103 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
Deploy Production / deploy (push) Successful in 37s
Test Suite / build-frontend (push) Successful in 8s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / playwright-tests (push) Successful in 26s
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
Deploy Development / deploy (push) Successful in 37s
Test Suite / build-frontend (push) Successful in 8s
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 / pytest-backend (push) Successful in 25s
Test Suite / playwright-tests (push) Successful in 23s
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
Deploy Production / deploy (push) Successful in 37s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / playwright-tests (push) Successful in 26s
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
Deploy Development / deploy (push) Successful in 40s
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 6s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / playwright-tests (push) Successful in 23s
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
Deploy Development / deploy (push) Successful in 40s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / playwright-tests (push) Successful in 23s
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
Deploy Development / deploy (push) Successful in 34s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / playwright-tests (push) Successful in 23s
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
Deploy Development / deploy (push) Successful in 41s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 30s
Test Suite / playwright-tests (push) Successful in 24s
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
Deploy Development / deploy (push) Successful in 36s
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 6s
Test Suite / pytest-backend (push) Successful in 30s
Test Suite / playwright-tests (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.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
Deploy Production / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / playwright-tests (push) Successful in 23s
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 / pytest-backend (push) Successful in 25s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 26s
- 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 / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 22s
- 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
Deploy Production / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 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
Deploy Development / deploy (push) Successful in 36s
Test Suite / build-frontend (push) Successful in 7s
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 / pytest-backend (push) Successful in 25s
Test Suite / playwright-tests (push) Successful in 23s
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
Deploy Development / deploy (push) Successful in 34s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / playwright-tests (push) Successful in 30s
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
Deploy Development / deploy (push) Successful in 33s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / playwright-tests (push) Successful in 27s
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
Deploy Development / deploy (push) Successful in 36s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / playwright-tests (push) Successful in 23s
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 / lint-backend (push) Successful in 0s
Test Suite / pytest-backend (push) Successful in 25s
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 / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Successful in 22s
- 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 / pytest-backend (push) Successful in 25s
Test Suite / playwright-tests (push) Successful in 23s
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
Deploy Development / deploy (push) Successful in 34s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / playwright-tests (push) Successful in 31s
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}
Deploy Development / deploy (push) Successful in 34s
Test Suite / build-frontend (push) Successful in 8s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / playwright-tests (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
Deploy Development / deploy (push) Successful in 34s
Test Suite / build-frontend (push) Successful in 8s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / playwright-tests (push) Successful in 23s
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
Deploy Development / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / playwright-tests (push) Successful in 23s
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
Deploy Development / deploy (push) Successful in 36s
Test Suite / build-frontend (push) Successful in 8s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / playwright-tests (push) Failing after 1m43s
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
Deploy Production / deploy (push) Successful in 36s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / playwright-tests (push) Successful in 23s
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
Deploy Development / deploy (push) Successful in 36s
Test Suite / build-frontend (push) Successful in 7s
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 / pytest-backend (push) Successful in 29s
Test Suite / playwright-tests (push) Successful in 30s
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 / pytest-backend (push) Successful in 24s
Test Suite / playwright-tests (push) Successful in 35s
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
Deploy Development / deploy (push) Successful in 34s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / playwright-tests (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
Deploy Development / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / playwright-tests (push) Successful in 30s
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
Deploy Production / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / playwright-tests (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
Deploy Development / deploy (push) Successful in 34s
Test Suite / build-frontend (push) Successful in 7s
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 / pytest-backend (push) Successful in 28s
Test Suite / playwright-tests (push) Successful in 39s
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 / pytest-backend (push) Successful in 23s
Test Suite / playwright-tests (push) Successful in 31s
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
Deploy Development / deploy (push) Successful in 36s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / playwright-tests (push) Successful in 23s
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
Deploy Development / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / playwright-tests (push) Successful in 22s
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
Deploy Development / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 28s
Test Suite / playwright-tests (push) Successful in 23s
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
Deploy Development / deploy (push) Successful in 33s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 23s
Test Suite / playwright-tests (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
Deploy Development / deploy (push) Successful in 34s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 23s
Test Suite / playwright-tests (push) Successful in 24s
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
Deploy Development / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / playwright-tests (push) Successful in 27s
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
Deploy Development / deploy (push) Successful in 36s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 23s
Test Suite / playwright-tests (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
Deploy Development / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 23s
Test Suite / playwright-tests (push) Successful in 27s
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 / pytest-backend (push) Successful in 23s
Test Suite / playwright-tests (push) Successful in 25s
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
Deploy Production / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 23s
Test Suite / pytest-backend (push) Successful in 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
Deploy Development / deploy (push) Successful in 34s
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 1s
Test Suite / build-frontend (pull_request) Successful in 6s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 26s
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
Deploy Development / deploy (push) Successful in 37s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 23s
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
Deploy Development / deploy (push) Successful in 34s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 23s
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
Deploy Development / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 24s
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
Deploy Production / deploy (push) Successful in 37s
Test Suite / build-frontend (push) Successful in 6s
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 / lint-backend (push) Successful in 0s
Test Suite / playwright-tests (pull_request) Failing after 28s
- 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
Deploy Development / deploy (push) Successful in 45s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 29s
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
Deploy Development / deploy (push) Successful in 40s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 27s
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
Deploy Development / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 27s
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
Deploy Development / deploy (push) Successful in 40s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 10s
Test Suite / playwright-tests (push) Failing after 29s
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
Deploy Development / deploy (push) Successful in 36s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 28s
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
Deploy Development / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 29s
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
Deploy Development / deploy (push) Successful in 36s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 7s
Test Suite / playwright-tests (push) Failing after 27s
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
Deploy Development / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 29s
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
Deploy Development / deploy (push) Successful in 33s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 28s
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
Deploy Development / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 7s
Test Suite / playwright-tests (push) Failing after 53s
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
Deploy Development / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 28s
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
Deploy Development / deploy (push) Successful in 34s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 22s
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
Deploy Development / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 23s
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
Deploy Development / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 23s
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
Deploy Development / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / playwright-tests (push) Successful in 30s
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
Deploy Development / deploy (push) Failing after 14s
Test Suite / build-frontend (push) Failing after 2s
Test Suite / pytest-backend (push) Successful in 5s
Test Suite / playwright-tests (push) Successful in 29s
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
Deploy Production / deploy (push) Successful in 37s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 11s
Test Suite / playwright-tests (push) Successful in 22s
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
Deploy Development / deploy (push) Successful in 36s
Test Suite / build-frontend (push) Successful in 6s
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 / pytest-backend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 44s
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
Deploy Development / deploy (push) Successful in 35s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Successful in 7s
Test Suite / playwright-tests (push) Failing after 37s
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
Deploy Development / deploy (push) Successful in 37s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / pytest-backend (push) Failing after 3s
Test Suite / playwright-tests (push) Failing after 34s
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
Deploy Development / deploy (push) Successful in 38s
Test Suite / build-frontend (push) Successful in 8s
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
139 changed files with 20136 additions and 2824 deletions

No files matched your search

+33 -19
View File
@@ -1,26 +1,33 @@
# Shinkan Jinkendo - Projekt-Status
**Stand:** 2026-05-05
**Version (Code):** 0.8.10 (`backend/version.py`, APP_VERSION)
**DB-Schema-Version:** `20260505037`
**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:** **Trainingsrahmenprogramm Bibliothek + Slot‑Blueprint** (DB **036–037**): Rahmenkopf nur als Vorlage mit Kontext‑Stammdaten; pro Slot genau eine **Blueprint‑`training_unit`** mit **`framework_unit_sections`/`_items`** wie die Planung; Kalenderliste blendet Blueprints aus; **`POST /api/training-units/from-framework-slot`** materialisiert Kopien mit **`origin_framework_slot_id`**. Parallel: **Progressionsgraph** (032–034) bleibt unterstützend (**`TRAINING_FRAMEWORK_SPEC.md`** §3–§4).
**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).
**Letzte dokumentierte Änderungen (Mai 2026):**
**Parallel weiter relevant:** **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
- ✅ Migration **036:** Rahmen nur Bibliothek; Fokus/Stil + M:N Trainingsarten/Zielgruppen; Entfall `plan_mode`/`group_id` am Kopf.
- ✅ Migration **037:** `training_units.framework_slot_id` / `origin_framework_slot_id`; Migration Entfall **`training_framework_slot_exercises`**.
- ✅ APIs: erweiterte Rahmen‑Hydration (`sections`, `exercises`, `blueprint_training_unit_id`); Planung siehe **`TRAINING_FRAMEWORK_SPEC.md`** §2.4.
- ✅ Frontend: `createTrainingUnitFromFrameworkSlot` in `api.js`.
**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)
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) · Rahmen/Graph: [`technical/TRAINING_FRAMEWORK_SPEC.md`](technical/TRAINING_FRAMEWORK_SPEC.md)
**Nächste Schritte — Medien & Archiv** (Stand 2026-05-08, für **neue Session**):
**Nächste Schritte (Auszug):**
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).
@@ -43,6 +50,7 @@
| **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 |
---
@@ -95,6 +103,11 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
### 🔲 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
@@ -125,7 +138,7 @@ Die exakten Zahlen hängen von der Umgebung ab (siehe Admin/DB). Die Skills/Übu
### Dev
Branch `develop`; Migrations bis mindestens **037** auf dem aktuellen Entwicklungsstand; Details in `backend/version.py`.
Branch `develop`; Migrations bis mindestens **046** auf dem aktuellen Entwicklungsstand; Details in `backend/version.py`.
### Prod
@@ -137,16 +150,17 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
| Dokument | Pfad | Stand | Status |
|----------|------|-------|--------|
| Lieferliste Q2 2026 | `library/FEATURES_DELIVERED_2026-Q2.md` | 2026-05-05 | ✅ Aktualisiert (u. a. 036–037) |
| 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-05 | ✅ Aktualisiert (037) |
| Domain Model | `functional/DOMAIN_MODEL.md` | 2026-05-05 | ✅ Aktualisiert |
| API Übungen | `technical/EXERCISES_API_SPEC.md` | 2026-04-30 | ✅ Ergänzt Progressions-API |
| 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-04-27 | ✅ Aktualisiert (Limits) |
| Projektstatus | `PROJECT_STATUS.md` | 2026-05-05 | ✅ Diese Datei |
| 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 |
---
@@ -157,4 +171,4 @@ Deployment der oben genannten Migrationen und Datenabgleich nach internem Prozes
---
**Letzte Aktualisierung:** 2026-05-05
**Letzte Aktualisierung:** 2026-05-08 (Inline-/Medien-Workflow 0.8.60–0.8.64 konsolidiert)
+12 -2
View File
@@ -1,7 +1,7 @@
# Shinkan Jinkendo - Fachliches Domänenmodell
**Version:** 0.4.3
**Stand:** 2026-05-05 (Migration **036–037:** Rahmen nur Bibliothek; Slot‑Inhalt über Blueprint‑`training_units` + Sektionen/Items wie Planung — siehe `TRAINING_FRAMEWORK_SPEC.md` §2)
**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
---
@@ -476,6 +476,16 @@ skill_level_definitions (
---
## 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)
**Prinzip:** Genau EINE Hauptmethode, optional weitere Nebenmethoden.
@@ -5,9 +5,10 @@ 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 (Abschnitt 11.2) |
| [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):** siehe [`../PROJECT_STATUS.md`](../PROJECT_STATUS.md) und [`../library/FEATURES_DELIVERED_2026-Q2.md`](../library/FEATURES_DELIVERED_2026-Q2.md).
**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.
@@ -1,9 +1,9 @@
# Gelieferte Features & technische Basis (Q2 2026)
**Stand:** 2026-05-05
**Referenz:** `backend/version.py` — **APP_VERSION 0.8.10**, **DB_SCHEMA_VERSION 20260505037**
**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**. Detail-Spezifikationen bleiben in den verlinkten Pfaden unter `.claude/docs/technical/` und `.claude/docs/functional/`.
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/`.
---
@@ -17,7 +17,7 @@ Dieses Dokument bündelt die in der Entwicklungsphase erreichten **lieferbaren**
| **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` |
| **037** | **`training_units.framework_slot_id`**, strukturierter Ablauf wie Planung; Entfall **`training_framework_slot_exercises`**; **`origin_framework_slot_id`** |
| **045–046** | **`media_assets`**, `platform_media_storage`, `exercise_media.media_asset_id`, ggf. **Tags/GIN** — siehe `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
---
@@ -79,7 +79,7 @@ Logik: `_upload_limit_bytes(session)` vor `read()`-Prüfung.
## 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** wie zuvor (Formularteil).
- **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).
@@ -123,16 +123,44 @@ Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Be
---
## 12. Nächste sinnvolle Schritte (nicht Lieferstand)
## 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“.
---
## 13. Verweise
## 14. Verweise
| Thema | Dokument |
|--------|----------|
@@ -140,5 +168,6 @@ Hinweis: Es gibt **keine** separaten Routen `/exercises/:id/variants/...` — Be
| API Übungen | `technical/EXERCISES_API_SPEC.md` |
| Domänenmodell | `functional/DOMAIN_MODEL.md` |
| Datenbank Überblick | `technical/DATABASE_SCHEMA.md` |
| Upload formal | `technical/MEDIA_UPLOAD_SPEC.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` |
@@ -1,7 +1,7 @@
# Einheitliche Zugriffsschicht & Governance – Umsetzungsplan
**Status:** verbindliche Umsetzungsreihenfolge (nachgelagert zum Zielbild in `MULTI_TENANCY_RBAC_ARCHITECTURE.md`)
**Stand:** 2026-05-05
**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.
@@ -101,7 +101,7 @@ Ausgangslage im Code: `private` \| `club` \| `official` (siehe `club_tenancy`).
| **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** | Phasen 1–4 dort größtenteils umgesetzt; **Gap-Analyse §3** im alten Dokument historisch lesen – fachlicher Zielabgleich bleibt dort, **operative Reihenfolge** hier. |
| **Beziehung zu MULTI_TENANCY-Doc** | Zielbild und Gap-Analyse §3 dort pflegen (**§3.0** = aktueller Umsetzungsstand); **operative Reihenfolge** hier. |
---
@@ -109,7 +109,7 @@ Ausgangslage im Code: `private` \| `club` \| `official` (siehe `club_tenancy`).
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 — erste rein-funktionale Tests unter `backend/tests/test_access_layer.py` (ohne DB); Integration folgt.
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`
@@ -118,8 +118,9 @@ Ausgangslage im Code: `private` \| `club` \| `official` (siehe `club_tenancy`).
## 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-05
**Letzte Aktualisierung:** 2026-05-07
+8 -7
View File
@@ -1,8 +1,8 @@
# Shinkan Jinkendo - Datenbank-Schema (Technisch)
**Version:** 0.5.2
**Stand:** 2026-05-05
**Hinweis:** Produktiver Deploy sollte mindestens bis Migration **037** (Rahmen‑Slot‑Blueprints in `training_units`; Entfall `training_framework_slot_exercises`) geführt sein — Details siehe `backend/version.py` (`DB_SCHEMA_VERSION`).
**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`**.
---
@@ -47,8 +47,7 @@ Dieses Dokument beschreibt die **technische Datenbankstruktur** von Shinkan Jink
| **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)
@@ -267,9 +266,11 @@ exercise_skills (
UNIQUE (exercise_id, skill_id) -- Migration 020
)
-- Varianten & Medien
-- 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, …)
```
### Trainingsrahmenprogramm Bibliothek (Migrationen **035–036**)
+13 -9
View File
@@ -1,10 +1,11 @@
# Exercises API Specification
**Version:** 1.4
**Datum:** 2026-04-30
**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
@@ -335,7 +336,8 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
### `PUT /exercises/{id}`
**Request Body:** Same as POST (all fields optional except 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)
@@ -459,7 +461,7 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
- `media_type` (enum, required) - `image | video | document | sketch`
- `title` (string, optional)
- `description` (string, optional)
- `context` (enum, optional) - `ablauf | detail | trainer_hint`
- `context` (enum, optional, legacy UI-Feld) - `ablauf | detail | trainer_hint`
**Entweder `file` ODER `embed_url` (nicht beides).**
@@ -505,11 +507,12 @@ Lightweight-Liste; bei `include_variants=true` zusätzlich z. B.:
{
"title": "Neuer Titel",
"description": "Neue Beschreibung",
"is_primary": true,
"context": "detail"
"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)
---
@@ -893,6 +896,7 @@ Trainer muss im Frontend aktiv übernehmen.
- 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
@@ -947,6 +951,6 @@ Trainer muss im Frontend aktiv übernehmen.
---
**Version:** 1.0
**Letzte Änderung:** 2026-04-24
**Status:** DRAFT - Awaiting Review
**Version:** 1.5
**Letzte Änderung:** 2026-05-08
**Status:** Living Spec
@@ -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
+7 -5
View File
@@ -1,10 +1,12 @@
# Media Upload & Embed Specification
**Version:** 1.1
**Datum:** 2026-04-27
**Status:** DRAFT - Awaiting Review
**Autor:** Claude Code
**Änderungen v1.1:** Rollenbasierte Server-Limits (`EXERCISE_MEDIA_*_MB`)
**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,7 +1,7 @@
# Multi-Tenancy, Vereins-Membership und Rollenmodell – Zielarchitektur & Umsetzungsplan
**Status:** verbindliche Zielrichtung (Architekturpapier)
**Stand:** 2026-05-05
**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**.
@@ -20,60 +20,68 @@ Dieses Dokument fasst den **Soll-Zustand** für Mandantenfähigkeit (Verein = Ma
|--------|-----------------------------------|-------------------------|
| `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; **technische Durchsetzung** ist noch lückenhaft |
| §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 bereits skizziert**. Es fehlt die **stringente technische Schicht**: Vereinszugehörigkeit, aktiver Vereinskontext, effektive Berechtigungen pro Anfrage und konsequente Filterung bei `club`-sichtbaren Objekten.
**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:** Dieser Abschnitt beschreibt den Ausgangspunkt vor Ausbauschritten (**Mitgliedschaften, gefilterte Vereinsliste, Teilen von Governance für Übungen/Rahmen/Planung** sind bereits angegangen). Verbindliche **offene Arbeit und Reihenfolge** sind im Dokument [`ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`](./ACCESS_LAYER_AND_GOVERNANCE_PLAN.md) festgehalten.
> **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`, …).
- **Keine** Tabelle für Vereinsmitgliedschaft mit **Mehrfachrollen pro Verein**.
- Sessions liefern nur `profile_id` + globale `role` (`auth.py` → `get_session`).
- *(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:** Mehrere Vereine mit unterschiedlichen Rollen pro User sind **nicht modelliert**; ein „Vereinsadmin“ kann nicht sauber von einem reinen Trainer unterschieden werden, sobald beides nur über `profiles.role` laufen soll.
**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
- `clubs`, `divisions`, `training_groups` existieren (`002_organization.sql`).
- `GET /api/clubs` listiert **alle** Vereine für jeden eingeloggten Nutzer.
- `POST /api/clubs` erlaubt Anlage für `trainer` und `user` – **nicht** nur Systemadmin.
- Sparten/Gruppen: Schreibzugriff über globale `admin`/`superadmin`, nicht über **Vereinsadmin** im Kontext „sein Verein“.
- *(Historisch)* Zu offene Vereinsliste und Club-Anlage für jeden Trainer/User.
- **Ist:** siehe **3.0** — gefilterte Liste, eingeschränktes Anlegen, kontextbezogene Organisationsrechte.
**Konsequenz:** Weder **Datenisolation** noch **Produktdifferenzierung** „nur Systemadmin legt Verein an“ sind umgesetzt.
**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 gruppenbasiert: Trainer/Co-Trainer der `training_groups`, plus `lead_trainer_profile_id` (Migration/Pfad `training_planning`).
- `_assert_club_visible_for_trainer` bindet Vereinssicht für Teile der Planung an „aktive Gruppe als Trainer/Co im Verein“ – **kein** generelles Mitgliedschaftsmodell.
- 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:** Planung ist **gruppenzentriert**, nicht **mitgliedschaftszentriert**; Vereinsweite Aufgaben des Vereinsadmins fehlen als konsistentes Recht.
**Konsequenz:** Vereinsweite oder „Administrations“-Planungsaufgaben können weiter ausgebaut werden (eigenes Produkt-Thema; nicht identisch mit Bibliotheks-Governance).
### 3.4 Governance / Sichtbarkeit (kritisch)
### 3.4 Governance / Sichtbarkeit (Bibliothek)
- Übungen (`list_exercises`): Bedingung sinngemäß „official OR club OR created_by = ich“ – **`club` gilt für alle Mandanten**, ohne Prüfung `exercise.club_id` ∈ Vereine des Nutzers.
- Detailzugriff `private`: nur Owner – **ok**.
- Rahmenprogramme (`training_framework_programs`): Lesen fremder Rahmen über `visibility=club` ist in `_framework_access` **nicht** gelöst (faktisch stark creator-basiert für Nicht-Admins).
- *(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:** **Cross-Tenant-Leaks** bei als `club` markierten Bibliotheksobjekten sind möglich bzw. Leselogik ist inkonsistent zwischen Modulen.
**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
- **Stand 2026-05:** `GET /api/profiles/me` liefert `clubs[]`, `active_club_id`; Frontend setzt `X-Active-Club-Id`. Details und Pflicht zur serverseitigen **TenantContext**-Validierung siehe `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md`.
- `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.
- Kein konzipiertes **`club_subscription` / `club_plan`** im Schema — bewusst nach ACCESS_LAYER-Plan zurückgestellt.
**Letzte Überarbeitung dieses Abschnitts (3.x):** 2026-05-06.
---
@@ -5,26 +5,45 @@ 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 | übrige geschützte `/api/exercises*` | ja | `get_tenant_context` | ja | |
| 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 | 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.
Letzte Änderung: 2026-05-05 — Cursor-Regel + Architektur-/Coding-Pflicht + Script `backend/scripts/check_access_layer_hints.py`; Katalog-Router im Audit als global dokumentiert.
**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`.
---
@@ -1,11 +1,14 @@
# Session Handover (Verweis)
**Dieses Dokument ist veraltet.** Der aktuelle Entwicklungsstand und die Handover-Basis stehen hier:
**Aktuelle Handover-Basis (Stand Implementierung + Medien):**
👉 **`docs/HANDOVER.md`** (Projektroot: `c:\Dev\shinkan-jinkendo\docs\HANDOVER.md`)
👉 **`docs/HANDOVER.md`** (Projektroot)
Dort: Fähigkeits-/Reifegrad-Stand (Bindings, Resolve, Export/Import, Matrix-Stack), Verweise auf `.claude/docs` für Anforderungen, und **nächste Priorität Übungen (UI/CRUD/Medien)**.
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`
---
*Historischer Inhalt aus April 2026 wurde durch `docs/HANDOVER.md` ersetzt.*
*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).
+2
View File
@@ -58,6 +58,8 @@ 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:
+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)
---
+10 -1
View File
@@ -12,6 +12,8 @@
# 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
@@ -20,6 +22,8 @@
# 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
@@ -46,7 +50,12 @@ APP_URL=https://shinkan.jinkendo.de
ALLOWED_ORIGINS=https://shinkan.jinkendo.de
ENVIRONMENT=production
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
+36 -1
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
@@ -172,7 +206,8 @@ jobs:
- 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/
+10 -3
View File
@@ -11,6 +11,8 @@
> | 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
@@ -56,7 +58,7 @@ backend/
└── routers/ # Router-Module
auth · profiles · clubs · groups · skills · methods
exercises · exercise_progression_graphs · training_units · training_programs
planning · import_wiki · admin · membership
planning · import_wiki · admin · membership · media_assets
frontend/src/
├── App.jsx # Root, Auth-Gates, Navigation
@@ -81,10 +83,11 @@ frontend/src/
**Siehe:** `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) und `.claude/docs/PROJECT_STATUS.md`.
Kurz (Stand 2026-05-05): App **0.8.10**, DB‑Schema‑Version **`20260505037`**; Kern: Übungen, Varianten, Medien, Planung mit Sektionen, **Trainingsrahmen Bibliothek + Slot‑Blueprint** (036–037), Progressionsgraph, Reifegrad/Matrix‑Stack — Details `PROJECT_STATUS.md` und `TRAINING_FRAMEWORK_SPEC.md` §2.
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).
### 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`.
@@ -105,7 +108,7 @@ Kurz (Stand 2026-05-05): App **0.8.10**, DB‑Schema‑Version **`20260505037`**
- `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 / Rahmen:**
- `training_plan_templates` + Sektionsvorlagen — Mikrovorlage pro Einheit (Migration **031**)
@@ -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
-2
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."""
+97 -23
View File
@@ -11,6 +11,10 @@ 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(
"""
@@ -52,6 +56,33 @@ def has_club_role(cur, profile_id: int, club_id: int, *role_codes: str) -> bool:
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):
@@ -60,7 +91,12 @@ def can_manage_club_org(cur, profile_id: int, club_id: int, global_role: Optiona
def can_plan_in_club(cur, profile_id: int, club_id: int, global_role: Optional[str]) -> bool:
"""Trainingsgruppen anlegen / planen: Admin-Rollen im Verein oder Plattform."""
"""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(
@@ -98,6 +134,24 @@ def memberships_with_roles(cur, profile_id: int, active_only: bool = True) -> Li
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"})
@@ -108,13 +162,13 @@ def assert_valid_governance_visibility(
visibility: str,
club_id: Optional[int],
) -> None:
"""Pflicht club_id bei visibility=club; Mitgliedschaft außer Plattform-Admin; official nur Plattform-Admin."""
"""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_platform_admin(role):
if visibility == "official" and not is_superadmin(role):
raise HTTPException(
status_code=403,
detail="Nur Plattform-Admins dürfen offizielle Inhalte setzen",
detail="Nur Superadmins dürfen offizielle Inhalte setzen",
)
if visibility == "club":
if club_id is None:
@@ -149,25 +203,45 @@ def exercise_visible_to_profile(
created_by: Optional[int],
global_role: Optional[str],
) -> bool:
"""Leserechte einer Übung. Für neue Codepfade lieber `library_content_visible_to_profile` verwenden."""
if is_platform_admin(global_role):
"""
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 visibility == "official":
if created_by is not None and int(created_by) == pid:
return True
if created_by is not None and created_by == profile_id:
return True
if visibility == "private":
if vis == "private":
return plat
if vis != "club":
return False
if visibility == "club":
if exercise_club_id is None:
return False
cur.execute(
"""
SELECT 1 FROM club_members
WHERE profile_id = %s AND club_id = %s AND status = 'active'
LIMIT 1
""",
(profile_id, exercise_club_id),
)
return cur.fetchone() is not None
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"
+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),
},
)
+54 -10
View File
@@ -6,7 +6,7 @@ Trainer- und Vereinsplattform für Kampfsport-Trainingsplanung
from pathlib import Path
from typing import Optional
from fastapi import FastAPI
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
@@ -18,7 +18,22 @@ from slowapi.errors import RateLimitExceeded
from version import APP_VERSION, BUILD_DATE, DB_SCHEMA_VERSION, MODULE_VERSIONS
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)")
@@ -39,11 +54,20 @@ else:
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,
)
# SlowAPI: Rate Limits auf /api/auth/* (Decorator in routers/auth.py)
@@ -62,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")
@@ -132,7 +162,7 @@ def health_ready():
migration_count = 0
complete = bool(err is None and all(tables.get(t) for t in REQUIRED))
return {
body = {
"status": "ready" if complete else "degraded",
"database": err is None,
"detail": err,
@@ -140,21 +170,30 @@ def health_ready():
"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, exercise_progression_graphs, clubs, club_memberships, club_join_requests, admin_users, skills, training_planning, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, admin_users, platform_media_storage, media_assets, skills, 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)
@@ -164,6 +203,8 @@ 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)
@@ -173,10 +214,13 @@ app.include_router(matrix_stack_bundle.router)
app.include_router(import_wiki.router)
app.include_router(import_wiki_admin.router)
# Lokale Medien (Übungen-Uploads) unter MEDIA_ROOT, ausliefern unter /media/...
# 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)
app.mount("/media", StaticFiles(directory=_media_dir), name="media")
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,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);
+9 -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
# ============================================================================
@@ -29,8 +29,10 @@ 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
@@ -41,6 +43,10 @@ class ProfileUpdate(BaseModel):
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)
+7
View File
@@ -1,3 +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).
+12 -21
View File
@@ -20,6 +20,11 @@ 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)
@@ -116,28 +121,14 @@ 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()))
app_base = (os.getenv("APP_URL") or "https://shinkan.jinkendo.de").rstrip("/")
reset_body = f"""Hallo {prof['name']},
Du hast einen Passwort-Reset angefordert.
Reset-Link: {app_base}/reset-password?token={token}
Der Link ist 1 Stunde gültig.
Falls du diese Anfrage nicht gestellt hast, ignoriere diese E-Mail.
Dein Shinkan Jinkendo Team
"""
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).")
+67 -1
View File
@@ -6,7 +6,7 @@ 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
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
@@ -106,6 +106,72 @@ def _response_one(cur, req_id: int, viewer_profile_id: int) -> Dict[str, Any]:
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
+85 -12
View File
@@ -50,6 +50,44 @@ def _club_exists(cur, club_id: int) -> bool:
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")
@@ -77,7 +115,8 @@ def list_club_members(
cur.execute(
f"""
SELECT cm.id AS membership_id, cm.profile_id, cm.status, cm.created_at, cm.updated_at,
p.email, p.name,
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[]
@@ -86,7 +125,7 @@ def list_club_members(
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
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,),
@@ -153,7 +192,8 @@ 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,
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[]
@@ -162,7 +202,7 @@ def _one_member(cur, club_id: int, profile_id: int) -> Dict[str, Any]:
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
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),
)
@@ -217,21 +257,50 @@ def update_club_member(
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:
st = body.status.strip().lower()
if st not in _ALLOWED_STATUS:
raise HTTPException(status_code=400, detail="status muss active oder inactive sein")
cur.execute(
"UPDATE club_members SET status = %s, updated_at = NOW() WHERE id = %s",
(st, cm_id),
(new_status, cm_id),
)
if body.roles is not None:
roles = _normalize_roles(body.roles)
if not roles:
raise HTTPException(status_code=400, detail="Mindestens eine Rolle angeben")
cur.execute("DELETE FROM club_member_roles WHERE club_member_id = %s", (cm_id,))
for rc in roles:
for rc in new_roles:
cur.execute(
"""
INSERT INTO club_member_roles (club_member_id, role_code)
@@ -258,6 +327,10 @@ def delete_club_member(
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),
+91 -29
View File
@@ -5,6 +5,7 @@ Handles CRUD operations for clubs, divisions, and training groups.
"""
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 tenant_context import TenantContext, get_tenant_context
@@ -19,6 +20,53 @@ from club_tenancy import (
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(
@@ -74,9 +122,10 @@ def public_club_directory():
return [r2d(r) for r in cur.fetchall()]
# ── Aktive Mitglieder für Trainer-/Co-Trainer-Auswahl (jeder Vereinsmitglied) ──
# ── 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:
@@ -96,7 +145,12 @@ def club_members_directory(club_id: int, tenant: TenantContext = Depends(get_ten
""",
(club_id,),
)
return [r2d(r) for r in cur.fetchall()]
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 ──────────────────────────────────────────────────────────
@@ -575,9 +629,15 @@ def create_training_group(data: dict, tenant: TenantContext = Depends(get_tenant
if not club_id or not name:
raise HTTPException(400, "club_id und name sind Pflichtfelder")
trainer_id = data.get("trainer_id")
if trainer_id in (None, "", 0) and role in ("trainer", "user"):
trainer_id = profile_id
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)
@@ -600,23 +660,23 @@ def create_training_group(data: dict, tenant: TenantContext = Depends(get_tenant
) 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"),
int(club_id),
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"),
_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,
data.get("co_trainer_ids"),
data.get("status", "active"),
co_json,
data.get("status") or "active",
),
)
@@ -656,6 +716,8 @@ def update_training_group(group_id: int, data: dict, tenant: TenantContext = Dep
if not allowed:
raise HTTPException(403, "Keine Berechtigung")
co_json = _co_trainer_ids_jsonb(data.get("co_trainer_ids"))
cur.execute(
"""
UPDATE training_groups SET
@@ -669,24 +731,24 @@ def update_training_group(group_id: int, data: dict, tenant: TenantContext = Dep
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"),
_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,
),
)
+16 -26
View File
@@ -206,32 +206,22 @@ def list_progression_graphs(tenant: TenantContext = Depends(get_tenant_context))
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
if is_platform_admin(role):
cur.execute(
"""
SELECT g.*,
(SELECT COUNT(*) FROM exercise_progression_edges e WHERE e.graph_id = g.id) AS edges_count
FROM exercise_progression_graphs g
ORDER BY g.updated_at DESC NULLS LAST, g.name
"""
)
else:
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,
)
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()]
+1639 -167
View File
File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -3,7 +3,8 @@ Reifegradmodelle / Fähigkeitsmatrix (kontextbezogen)
Kontext zu Fokusbereich, Stilrichtung, Zielgruppe: jeweils M:N (leer = gilt überall).
Lesen: alle authentifizierten Nutzer.
Lesen: Liste & resolve für alle authentifizierten Nutzer; GET eines Modells nach ID nur Portal-Admin (Admin-UI).
Schreiben: admin, superadmin.
"""
from datetime import datetime, timezone
@@ -534,6 +535,7 @@ def list_maturity_models(
@router.get("/maturity-models/{model_id}")
def get_maturity_model(model_id: int, session: dict = Depends(require_auth)):
_require_admin(session)
with get_db() as conn:
cur = get_cursor(conn)
return _load_full_model(cur, model_id)
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),
)
+225 -36
View File
@@ -3,34 +3,89 @@ 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 club_tenancy import assert_club_member, memberships_with_roles, is_platform_admin
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 ──────────────────────────────────────────────────────
@@ -39,7 +94,7 @@ 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; effective_club_id = aufgelöster Request-Kontext (Header vor Profilfeld)."""
"""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)
@@ -49,7 +104,7 @@ def get_current_profile(
raise HTTPException(404, "Profil nicht gefunden")
data = r2d(row)
data.pop("pin_hash", None)
clubs = memberships_with_roles(cur, profile_id)
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
@@ -87,17 +142,51 @@ def list_profiles(session=Depends(require_auth)):
@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))
def profile_document(pid: str) -> dict:
@@ -113,9 +202,75 @@ def profile_document(pid: str) -> dict:
return d
@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)):
"""Get profile by ID."""
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."""
@@ -220,6 +375,15 @@ def _run_profile_update(pid: str, p: ProfileUpdate, tenant: TenantContext) -> di
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":
@@ -249,32 +413,57 @@ def update_profile(pid: str, p: ProfileUpdate, tenant: TenantContext = Depends(g
@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)
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),
tenant: TenantContext = Depends(get_tenant_context),
):
"""Update current user's profile."""
pid = get_pid(x_profile_id)
"""Profil des eingeloggten Nutzers aktualisieren — dieselbe Quelle wie GET /profile."""
pid = str(tenant.profile_id)
return _run_profile_update(pid, p, tenant)
+11 -14
View File
@@ -350,21 +350,18 @@ def list_training_framework_programs(tenant: TenantContext = Depends(get_tenant_
LEFT JOIN focus_areas fa ON fa.id = fp.focus_area_id
LEFT JOIN style_directions sd ON sd.id = fp.style_direction_id
"""
if is_platform_admin(role):
cur.execute(base_sel + " ORDER BY fp.updated_at DESC NULLS LAST, fp.title")
else:
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})
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,
)
vis_params,
)
return [r2d(r) for r in cur.fetchall()]
+699 -87
View File
@@ -4,6 +4,7 @@ und wiederverwendbare Trainingsvorlagen (Sektions-Gliederung).
Governance: Sichtbarkeit wie Übungen (private / club / official); Schreiben nur Ersteller oder Plattform-Admin.
"""
from datetime import date, timedelta
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
@@ -12,6 +13,7 @@ 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,
can_manage_club_org,
is_platform_admin,
library_content_visible_to_profile,
)
@@ -53,7 +55,7 @@ def _validate_variant_for_exercise(cur, exercise_id: Optional[int], variant_id:
def _can_access_group_for_create(cur, group_id: int, profile_id: int, role: str) -> None:
cur.execute(
"SELECT trainer_id, co_trainer_ids FROM training_groups WHERE id = %s",
"SELECT trainer_id, co_trainer_ids, club_id FROM training_groups WHERE id = %s",
(group_id,),
)
group = cur.fetchone()
@@ -64,9 +66,83 @@ def _can_access_group_for_create(cur, group_id: int, profile_id: int, role: str)
raise HTTPException(status_code=403, detail="Nur Trainer dürfen Trainingseinheiten erstellen")
if role not in ["admin", "superadmin"]:
if group["trainer_id"] != profile_id and profile_id not in co_trainers:
raise HTTPException(
status_code=403, detail="Nur der zuständige Trainer darf für diese Gruppe planen"
)
if not can_manage_club_org(cur, profile_id, int(group["club_id"]), role):
raise HTTPException(
status_code=403, detail="Nur der zuständige Trainer darf für diese Gruppe planen"
)
def _profile_active_in_club(cur, club_id: int, profile_id: int) -> bool:
cur.execute(
"""
SELECT 1 FROM club_members
WHERE club_id = %s AND profile_id = %s AND status = 'active'
LIMIT 1
""",
(club_id, profile_id),
)
return cur.fetchone() is not None
def _caller_may_assign_session_trainers(
cur,
group_row: Dict[str, Any],
profile_id: int,
role: str,
unit_created_by: Optional[int],
) -> bool:
if is_platform_admin(role):
return True
cid = group_row.get("club_id")
if cid is not None and can_manage_club_org(cur, profile_id, int(cid), role):
return True
if unit_created_by is not None and unit_created_by == profile_id:
return True
if group_row.get("trainer_id") == profile_id:
return True
co = group_row.get("co_trainer_ids") or []
return profile_id in co
def _effective_co_trainer_ids_for_row(unit_row: Dict[str, Any]) -> List[int]:
"""Leseregel: Session-Co-Trainer überschreiben die Gruppe; NULL auf der Einheit = Gruppen-Standard."""
unit_asst = unit_row.get("assistant_trainer_profile_ids")
if unit_asst is not None:
src = unit_asst
else:
src = unit_row.get("co_trainer_ids") or []
seen: set = set()
out: List[int] = []
for x in src:
try:
i = int(x)
except (TypeError, ValueError):
continue
if i not in seen:
seen.add(i)
out.append(i)
return sorted(out)
def effective_co_trainer_profile_ids_for_merge(
unit_assistant: Any, group_co: Any
) -> List[int]:
"""Reine Hilfsfunktion (pytest): gleiche Semantik wie _effective_co_trainer_ids_for_row."""
if unit_assistant is not None:
src = unit_assistant
else:
src = group_co or []
seen: set = set()
out: List[int] = []
for x in src:
try:
i = int(x)
except (TypeError, ValueError):
continue
if i not in seen:
seen.add(i)
out.append(i)
return sorted(out)
def _training_unit_guard_row(cur, unit_id: int) -> Dict[str, Any]:
@@ -74,7 +150,8 @@ def _training_unit_guard_row(cur, unit_id: int) -> Dict[str, Any]:
"""
SELECT tu.id, tu.created_by, tu.group_id, tu.plan_template_id, tu.framework_slot_id,
tu.lead_trainer_profile_id,
tg.trainer_id, tg.co_trainer_ids,
tu.assistant_trainer_profile_ids,
tg.trainer_id, tg.co_trainer_ids, tg.club_id AS group_club_id,
fwp.created_by AS framework_created_by
FROM training_units tu
LEFT JOIN training_groups tg ON tu.group_id = tg.id
@@ -103,26 +180,53 @@ def _assert_training_unit_permission(
return
raise HTTPException(status_code=403, detail="Keine Berechtigung")
co_trainers = unit_row["co_trainer_ids"] or []
if role not in ["admin", "superadmin"]:
if (
unit_row["created_by"] != profile_id
and unit_row["trainer_id"] != profile_id
and profile_id not in co_trainers
and unit_row.get("lead_trainer_profile_id") != profile_id
):
raise HTTPException(status_code=403, detail="Keine Berechtigung")
def _assert_delete_training_unit(role: str, created_by: int, profile_id: int) -> None:
if role not in ["admin", "superadmin"] and created_by != profile_id:
co_eff = _effective_co_trainer_ids_for_row(unit_row)
if role in ["admin", "superadmin"]:
return
gcid = unit_row.get("group_club_id")
if gcid is not None and can_manage_club_org(cur, profile_id, int(gcid), role):
return
if (
unit_row["created_by"] != profile_id
and unit_row["trainer_id"] != profile_id
and profile_id not in co_eff
and unit_row.get("lead_trainer_profile_id") != profile_id
):
raise HTTPException(status_code=403, detail="Keine Berechtigung")
def _assert_delete_training_unit(
cur,
role: str,
created_by: int,
profile_id: int,
group_club_id: Optional[int],
) -> None:
if role in ["admin", "superadmin"]:
return
if created_by == profile_id:
return
if group_club_id is not None and can_manage_club_org(cur, profile_id, int(group_club_id), role):
return
raise HTTPException(status_code=403, detail="Keine Berechtigung")
def _assert_club_visible_for_trainer(cur, club_id: int, profile_id: int, role: str) -> None:
"""Nicht-Admin: mindestens eine aktive Gruppe im Verein als Trainer/Co-Trainer."""
"""Nicht-Admin: Vereinsbezug für Listen mit club_id (Mitglied genügt; Details filtert WHERE)."""
if role in ("admin", "superadmin"):
return
if can_manage_club_org(cur, profile_id, club_id, role):
return
cur.execute(
"""
SELECT 1 FROM club_members
WHERE club_id = %s AND profile_id = %s AND status = 'active'
LIMIT 1
""",
(club_id, profile_id),
)
if cur.fetchone():
return
cur.execute(
"""
SELECT 1 FROM training_groups g
@@ -145,8 +249,9 @@ def _normalize_lead_trainer_profile_id(
raw_lead: Any,
profile_id: int,
role: str,
unit_created_by: Optional[int],
) -> Optional[int]:
"""NULL = Vertretung aufheben; sonst Profil-ID mit Profil-Check und Gruppenkontext."""
"""NULL = Standard (Gruppen-Haupttrainer); sonst gültiges Profil i. d. R. mit Vereinsbezug."""
if raw_lead is None:
return None
if raw_lead in ("", []):
@@ -160,27 +265,130 @@ def _normalize_lead_trainer_profile_id(
cur.execute("SELECT 1 FROM profiles WHERE id = %s", (nid,))
if not cur.fetchone():
raise HTTPException(status_code=400, detail="Profil für Leitung nicht gefunden")
if role in ("admin", "superadmin"):
return nid
if nid == profile_id:
return nid
cur.execute(
"SELECT trainer_id, co_trainer_ids FROM training_groups WHERE id = %s",
"SELECT trainer_id, co_trainer_ids, club_id FROM training_groups WHERE id = %s",
(group_id,),
)
gr = cur.fetchone()
if not gr:
raise HTTPException(status_code=400, detail="Trainingsgruppe nicht gefunden")
eligible = {gr["trainer_id"]} if gr.get("trainer_id") else set()
for x in gr.get("co_trainer_ids") or []:
eligible.add(x)
if nid in eligible:
return nid
raise HTTPException(
status_code=403,
detail="Lead-Trainer kann nur eigene Person, Haupttrainer oder Co-Trainer der Gruppe sein",
)
grd = dict(gr)
cid = grd.get("club_id")
if cid is None:
raise HTTPException(status_code=400, detail="Trainingsgruppe nicht gefunden")
club_i = int(cid)
if is_platform_admin(role):
return nid
eligible = {grd["trainer_id"]} if grd.get("trainer_id") else set()
for x in grd.get("co_trainer_ids") or []:
try:
eligible.add(int(x))
except (TypeError, ValueError):
continue
if nid == profile_id:
if not _profile_active_in_club(cur, club_i, profile_id):
raise HTTPException(
status_code=403,
detail="Nur aktive Vereinsmitglieder können die Leitung dieser Einheit übernehmen",
)
return nid
if nid not in eligible:
if not _profile_active_in_club(cur, club_i, nid):
raise HTTPException(
status_code=400,
detail="Leitung nur für Profile mit aktiver Mitgliedschaft im Verein der Gruppe",
)
if not _caller_may_assign_session_trainers(cur, grd, profile_id, role, unit_created_by):
raise HTTPException(
status_code=403,
detail="Keine Berechtigung, die Leitung zuzuweisen",
)
return nid
if nid != profile_id and not _caller_may_assign_session_trainers(
cur, grd, profile_id, role, unit_created_by
):
raise HTTPException(status_code=403, detail="Keine Berechtigung, die Leitung anderen zuzuweisen")
return nid
def _normalize_assistant_trainer_profile_ids(
cur,
group_id: int,
raw_val: Any,
profile_id: int,
role: str,
unit_created_by: Optional[int],
lead_nid: Optional[int],
) -> Any:
"""
None = Vererbung aus training_groups.co_trainer_ids (SQL NULL);
Liste = Session-Co-Trainer (JSONB Array; leeres Array ausdrücklich ohne Co.)
"""
if raw_val is None:
return None
if not isinstance(raw_val, list):
raise HTTPException(status_code=400, detail="assistant_trainer_profile_ids muss Liste oder null sein")
ids_in: List[int] = []
for x in raw_val:
try:
i = int(x)
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="assistant_trainer_profile_ids ungültig")
if i < 1:
raise HTTPException(status_code=400, detail="assistant_trainer_profile_ids ungültig")
ids_in.append(i)
uniq = sorted(set(ids_in))
cur.execute(
"SELECT trainer_id, co_trainer_ids, club_id FROM training_groups WHERE id = %s",
(group_id,),
)
gr = cur.fetchone()
if not gr:
raise HTTPException(status_code=400, detail="Trainingsgruppe nicht gefunden")
grd = dict(gr)
cid = grd.get("club_id")
if cid is None:
raise HTTPException(status_code=400, detail="Trainingsgruppe nicht gefunden")
club_i = int(cid)
if not is_platform_admin(role) and not _caller_may_assign_session_trainers(
cur, grd, profile_id, role, unit_created_by
):
raise HTTPException(status_code=403, detail="Keine Berechtigung, Co-Trainer zuzuweisen")
eligible = {grd["trainer_id"]} if grd.get("trainer_id") else set()
for x in grd.get("co_trainer_ids") or []:
try:
eligible.add(int(x))
except (TypeError, ValueError):
continue
eff_lead = lead_nid if lead_nid is not None else (grd.get("trainer_id") or None)
for nid in uniq:
cur.execute("SELECT 1 FROM profiles WHERE id = %s", (nid,))
if not cur.fetchone():
raise HTTPException(status_code=400, detail="Profil für Co-Trainer nicht gefunden")
if eff_lead is not None and nid == eff_lead:
raise HTTPException(status_code=400, detail="Leitung und Co-Trainer dürfen sich nicht überschneiden")
if is_platform_admin(role):
continue
if nid in eligible:
continue
if not _profile_active_in_club(cur, club_i, nid):
raise HTTPException(
status_code=400,
detail="Co-Trainer nur mit aktiver Mitgliedschaft im Verein dieser Gruppe",
)
return uniq
# Nachverfolgbarkeit: Übernahmen aus Rahmenprogramm über origin_framework_slot_id
_ORIGIN_LINEAGE_JOIN = """
@@ -446,6 +654,129 @@ def _replace_unit_sections(cur, unit_id: int, sections_in: List[Any]):
_insert_section_items(cur, sid, sec.get("items"))
def _distinct_exercise_ids_in_unit(cur, unit_id: int) -> List[int]:
cur.execute(
"""
SELECT DISTINCT tusi.exercise_id
FROM training_unit_section_items tusi
INNER JOIN training_unit_sections tus ON tusi.section_id = tus.id
WHERE tus.training_unit_id = %s
AND tusi.item_type = 'exercise'
AND tusi.exercise_id IS NOT NULL
""",
(unit_id,),
)
rows = cur.fetchall() or []
out: List[int] = []
for r in rows:
try:
out.append(int(r["exercise_id"]))
except (TypeError, ValueError, KeyError):
continue
return out
def _group_club_id_for_scheduled_unit(cur, unit_id: int) -> Optional[int]:
"""Nur echte Gruppentermine (keine Rahmen-Blueprints ohne Gruppe)."""
cur.execute(
"""
SELECT tg.club_id
FROM training_units tu
INNER JOIN training_groups tg ON tu.group_id = tg.id
WHERE tu.id = %s AND tu.framework_slot_id IS NULL
""",
(unit_id,),
)
r = cur.fetchone()
if not r or r.get("club_id") is None:
return None
return int(r["club_id"])
def _exercise_needs_club_visibility_for_target(ex: Dict[str, Any], target_club_id: int) -> bool:
"""Übung für Mitglieder des Ziel-Vereins in der Durchführung sichtbar machen (Dashboard/Queue)."""
if str(ex.get("status") or "").strip().lower() == "archived":
return False
vis = (ex.get("visibility") or "private").strip().lower()
if vis == "official":
return False
if vis == "private":
return True
if vis == "club":
raw = ex.get("club_id")
if raw is None:
return True
try:
return int(raw) != int(target_club_id)
except (TypeError, ValueError):
return True
return False
def _caller_may_promote_exercise_to_club(
cur,
exercise_created_by: Optional[int],
profile_id: int,
role: str,
target_club_id: int,
) -> bool:
if is_platform_admin(role):
return True
if exercise_created_by is not None and int(exercise_created_by) == profile_id:
return True
if can_manage_club_org(cur, profile_id, target_club_id, role):
return True
return False
def _promote_private_exercises_used_in_unit(cur, unit_id: int, profile_id: int, role: str) -> None:
"""
Private Übungen in der Einheit auf visibility=club (Verein der Trainingsgruppe) setzen,
damit andere Trainer und Mitglieder sie in der Durchführung sehen.
"""
target_club_id = _group_club_id_for_scheduled_unit(cur, unit_id)
if not target_club_id:
return
if not (
is_platform_admin(role)
or _profile_active_in_club(cur, target_club_id, profile_id)
or can_manage_club_org(cur, profile_id, target_club_id, role)
):
return
for eid in _distinct_exercise_ids_in_unit(cur, unit_id):
cur.execute(
"""
SELECT id, created_by, visibility, club_id, COALESCE(status, '') AS status
FROM exercises WHERE id = %s
""",
(eid,),
)
row = cur.fetchone()
if not row:
continue
if str(row.get("status") or "").strip().lower() == "archived":
continue
vis = (row.get("visibility") or "private").strip().lower()
if vis == "official":
continue
if vis == "club":
continue
if vis != "private":
continue
cb = row.get("created_by")
if not _caller_may_promote_exercise_to_club(cur, cb, profile_id, role, target_club_id):
continue
cur.execute(
"""
UPDATE exercises
SET visibility = 'club', club_id = %s, updated_at = NOW()
WHERE id = %s AND LOWER(COALESCE(visibility, 'private')) = 'private'
""",
(target_club_id, eid),
)
def _insert_sections_from_legacy_exercises(cur, unit_id: int, exercises_in: List[Any]):
if not exercises_in:
return
@@ -565,25 +896,14 @@ def list_training_plan_templates(tenant: TenantContext = Depends(get_tenant_cont
role = tenant.global_role
with get_db() as conn:
cur = get_cursor(conn)
if is_platform_admin(role):
cur.execute(
"""
SELECT t.*,
(SELECT COUNT(*) FROM training_plan_template_sections s WHERE s.template_id = t.id)
AS sections_count
FROM training_plan_templates t
ORDER BY t.updated_at DESC NULLS LAST, t.name
"""
)
else:
vis_clause, vis_params = library_content_visibility_sql(
alias="t",
profile_id=profile_id,
role=role,
effective_club_id=tenant.effective_club_id,
)
cur.execute(
f"""
vis_clause, vis_params = library_content_visibility_sql(
alias="t",
profile_id=profile_id,
role=role,
effective_club_id=tenant.effective_club_id,
)
cur.execute(
f"""
SELECT t.*,
(SELECT COUNT(*) FROM training_plan_template_sections s WHERE s.template_id = t.id)
AS sections_count
@@ -591,8 +911,8 @@ def list_training_plan_templates(tenant: TenantContext = Depends(get_tenant_cont
WHERE ({vis_clause})
ORDER BY t.updated_at DESC NULLS LAST, t.name
""",
vis_params,
)
vis_params,
)
return [r2d(r) for r in cur.fetchall()]
@@ -755,6 +1075,10 @@ def list_training_units(
end_date: Optional[str] = Query(default=None),
status: Optional[str] = Query(default=None),
assigned_to_me: bool = Query(default=False),
debrief_pending: bool = Query(
default=False,
description="Nur abgeschlossene Einheiten ohne gesetzte Rückschau (debrief_completed_at IS NULL)",
),
sort: str = Query(default="desc"),
limit: Optional[int] = Query(default=None),
tenant: TenantContext = Depends(get_tenant_context),
@@ -775,14 +1099,18 @@ def list_training_units(
if gid and role not in ["admin", "superadmin"]:
cur.execute(
"SELECT trainer_id, co_trainer_ids FROM training_groups WHERE id = %s AND status = 'active'",
"SELECT trainer_id, co_trainer_ids, club_id FROM training_groups WHERE id = %s AND status = 'active'",
(gid,),
)
gr = cur.fetchone()
if not gr:
raise HTTPException(status_code=404, detail="Trainingsgruppe nicht gefunden")
cob = gr["co_trainer_ids"] or []
if gr["trainer_id"] != profile_id and profile_id not in cob:
gd = dict(gr)
cob = gd.get("co_trainer_ids") or []
ok_staff = gd.get("trainer_id") == profile_id or profile_id in cob
ok_org = can_manage_club_org(cur, profile_id, int(gd["club_id"]), role)
ok_member = _profile_active_in_club(cur, int(gd["club_id"]), profile_id)
if not (ok_staff or ok_org or ok_member):
raise HTTPException(status_code=403, detail="Keine Berechtigung für diese Gruppe")
order_dir = "ASC" if (sort or "").strip().lower() == "asc" else "DESC"
@@ -805,6 +1133,8 @@ def list_training_units(
p.name as trainer_name,
p.name as creator_name,
COALESCE(tu.lead_trainer_profile_id, tg.trainer_id) AS effective_lead_trainer_profile_id,
COALESCE(tu.assistant_trainer_profile_ids, tg.co_trainer_ids, '[]'::jsonb)
AS effective_assistant_trainer_profile_ids,
leadp.name AS lead_trainer_name
"""
query += "," + _ORIGIN_LINEAGE_FIELDS
@@ -820,12 +1150,27 @@ def list_training_units(
where = []
params = []
if role not in ["admin", "superadmin"]:
where.append(
"(tu.created_by = %s OR tg.trainer_id = %s OR "
"(tg.co_trainer_ids IS NOT NULL AND tg.co_trainer_ids @> jsonb_build_array(%s::int)))"
skip_involvement_filter = role in ("admin", "superadmin")
if not skip_involvement_filter and cid is not None:
if can_manage_club_org(cur, profile_id, cid, role):
skip_involvement_filter = True
if not skip_involvement_filter and gid is not None:
cur.execute(
"SELECT club_id FROM training_groups WHERE id = %s AND status = 'active'",
(gid,),
)
params.extend([profile_id, profile_id, profile_id])
gcx = cur.fetchone()
if gcx and gcx.get("club_id") is not None:
if can_manage_club_org(cur, profile_id, int(gcx["club_id"]), role):
skip_involvement_filter = True
if not skip_involvement_filter:
where.append(
"(tu.created_by = %s OR tg.trainer_id = %s OR tu.lead_trainer_profile_id = %s OR "
"COALESCE(tu.assistant_trainer_profile_ids, tg.co_trainer_ids, '[]'::jsonb) "
"@> jsonb_build_array(%s::int))"
)
params.extend([profile_id, profile_id, profile_id, profile_id])
where.append("tu.framework_slot_id IS NULL")
@@ -840,7 +1185,8 @@ def list_training_units(
if assigned_to_me:
where.append(
"(COALESCE(tu.lead_trainer_profile_id, tg.trainer_id) = %s OR "
"(tg.co_trainer_ids IS NOT NULL AND tg.co_trainer_ids @> jsonb_build_array(%s::int)))"
"COALESCE(tu.assistant_trainer_profile_ids, tg.co_trainer_ids, '[]'::jsonb) "
"@> jsonb_build_array(%s::int))"
)
params.extend([profile_id, profile_id])
@@ -852,7 +1198,11 @@ def list_training_units(
where.append("tu.planned_date <= %s")
params.append(end_date)
if status:
if debrief_pending:
where.append("tu.status = %s")
params.append("completed")
where.append("tu.debrief_completed_at IS NULL")
elif status:
where.append("tu.status = %s")
params.append(status)
@@ -869,6 +1219,163 @@ def list_training_units(
return [r2d(r) for r in rows]
@router.get("/training-units/exercises-club-visibility-queue")
def exercises_club_visibility_queue(
start_date: Optional[str] = Query(default=None),
end_date: Optional[str] = Query(default=None),
assigned_to_me: bool = Query(default=True),
limit_units: int = Query(default=80, ge=1, le=150),
tenant: TenantContext = Depends(get_tenant_context),
):
"""
Übungen in deinen Trainingseinheiten (Zeitfenster), die für den jeweiligen Verein der Gruppe
noch nicht vereinsweit sichtbar sind — für Dashboard & Freigabe-Workflow.
"""
profile_id = tenant.profile_id
role = tenant.global_role
if start_date is None:
start_date = (date.today() - timedelta(days=45)).isoformat()
if end_date is None:
end_date = (date.today() + timedelta(days=365)).isoformat()
units = list_training_units(
group_id=None,
club_id=None,
start_date=start_date,
end_date=end_date,
status=None,
assigned_to_me=assigned_to_me,
debrief_pending=False,
sort="asc",
limit=limit_units,
tenant=tenant,
)
unit_ids = [int(u["id"]) for u in units if u.get("id") is not None]
if not unit_ids:
return {"items": []}
placeholders = ",".join(["%s"] * len(unit_ids))
items: List[Dict[str, Any]] = []
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
f"""
SELECT DISTINCT tu.id AS unit_id,
tu.planned_date,
tg.name AS group_name,
tg.club_id AS target_club_id,
c.name AS target_club_name,
tusi.exercise_id AS exercise_id
FROM training_units tu
INNER JOIN training_groups tg ON tu.group_id = tg.id
LEFT JOIN clubs c ON c.id = tg.club_id
INNER JOIN training_unit_sections tus ON tus.training_unit_id = tu.id
INNER JOIN training_unit_section_items tusi ON tusi.section_id = tus.id
WHERE tu.id IN ({placeholders})
AND tu.framework_slot_id IS NULL
AND tusi.item_type = 'exercise'
AND tusi.exercise_id IS NOT NULL
""",
tuple(unit_ids),
)
pairs = [r2d(r) for r in cur.fetchall()]
if not pairs:
return {"items": []}
ex_ids = sorted(
{int(p["exercise_id"]) for p in pairs if p.get("exercise_id") is not None}
)
if not ex_ids:
return {"items": []}
exercises_map: Dict[int, Dict[str, Any]] = {}
ph = ",".join(["%s"] * len(ex_ids))
cur.execute(
f"""
SELECT id, title, visibility, club_id, created_by, status
FROM exercises
WHERE id IN ({ph})
""",
tuple(ex_ids),
)
for r in cur.fetchall():
d = r2d(r)
exercises_map[int(d["id"])] = d
agg: Dict[tuple, Dict[str, Any]] = {}
for p in pairs:
try:
ex_id = int(p["exercise_id"])
except (TypeError, ValueError):
continue
tc_raw = p.get("target_club_id")
if tc_raw is None:
continue
tc = int(tc_raw)
key = (ex_id, tc)
if key not in agg:
agg[key] = {
"exercise_id": ex_id,
"target_club_id": tc,
"target_club_name": (p.get("target_club_name") or "").strip(),
"units": [],
}
uid = p.get("unit_id")
if uid is None:
continue
agg[key]["units"].append(
{
"id": int(uid),
"planned_date": str(p["planned_date"]) if p.get("planned_date") is not None else "",
"group_name": (p.get("group_name") or "").strip(),
}
)
for _key, blob in agg.items():
ex_id = blob["exercise_id"]
tc = blob["target_club_id"]
ex = exercises_map.get(ex_id)
if not ex:
continue
if not _exercise_needs_club_visibility_for_target(ex, tc):
continue
uniq_units = {u["id"]: u for u in blob["units"]}.values()
ulist = sorted(
uniq_units,
key=lambda x: (x.get("planned_date") or "", x.get("id")),
)
cb = ex.get("created_by")
cb_int = int(cb) if cb is not None else None
can_promote = _caller_may_promote_exercise_to_club(cur, cb_int, profile_id, role, tc)
vis = (ex.get("visibility") or "private").strip().lower()
st = (ex.get("status") or "draft").strip().lower()
ecid = ex.get("club_id")
items.append(
{
"exercise_id": ex_id,
"title": (ex.get("title") or f"Übung #{ex_id}").strip() or f"Übung #{ex_id}",
"visibility": vis,
"status": st,
"club_id": int(ecid) if ecid is not None else None,
"created_by": cb_int,
"target_club_id": tc,
"target_club_name": blob.get("target_club_name") or "",
"can_promote": can_promote,
"units": ulist,
}
)
items.sort(
key=lambda x: (
(x["units"][0].get("planned_date") if x["units"] else ""),
x["title"],
)
)
return {"items": items}
@router.get("/training-units/{unit_id}")
def get_training_unit(unit_id: int, tenant: TenantContext = Depends(get_tenant_context)):
profile_id = tenant.profile_id
@@ -890,7 +1397,10 @@ def get_training_unit(unit_id: int, tenant: TenantContext = Depends(get_tenant_c
p.name as creator_name,
tg.trainer_id AS trainer_id,
tg.co_trainer_ids AS co_trainer_ids,
tg.club_id AS group_club_id,
COALESCE(tu.lead_trainer_profile_id, tg.trainer_id) AS effective_lead_trainer_profile_id,
COALESCE(tu.assistant_trainer_profile_ids, tg.co_trainer_ids, '[]'::jsonb)
AS effective_assistant_trainer_profile_ids,
leadp.name AS lead_trainer_name,
""" + _ORIGIN_LINEAGE_FIELDS.strip() + """
FROM training_units tu
@@ -957,27 +1467,77 @@ def create_training_unit(data: dict, tenant: TenantContext = Depends(get_tenant_
tpl_id_safe = plan_template_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
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""",
(
group_id,
planned_date,
data.get("planned_time_start"),
data.get("planned_time_end"),
data.get("planned_focus"),
data.get("status", "planned"),
data.get("notes"),
data.get("trainer_notes"),
profile_id,
tpl_id_safe,
),
"SELECT trainer_id FROM training_groups WHERE id = %s",
(int(group_id),),
)
g0 = cur.fetchone()
default_group_trainer = g0["trainer_id"] if g0 else None
lead_ins: Optional[int] = None
if "lead_trainer_profile_id" in data:
lead_ins = _normalize_lead_trainer_profile_id(
cur,
int(group_id),
data.get("lead_trainer_profile_id"),
profile_id,
role,
profile_id,
)
assistant_val: Any = None
assistant_set = False
if "assistant_trainer_profile_ids" in data:
assistant_set = True
eff_lead_for_co = lead_ins if lead_ins is not None else default_group_trainer
assistant_val = _normalize_assistant_trainer_profile_ids(
cur,
int(group_id),
data.get("assistant_trainer_profile_ids"),
profile_id,
role,
profile_id,
eff_lead_for_co,
)
base_params = (
group_id,
planned_date,
data.get("planned_time_start"),
data.get("planned_time_end"),
data.get("planned_focus"),
data.get("status", "planned"),
data.get("notes"),
data.get("trainer_notes"),
profile_id,
tpl_id_safe,
lead_ins,
)
if assistant_set:
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,
lead_trainer_profile_id,
assistant_trainer_profile_ids
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""",
base_params + (assistant_val,),
)
else:
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,
lead_trainer_profile_id
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""",
base_params,
)
unit_id = cur.fetchone()["id"]
@@ -991,6 +1551,8 @@ def create_training_unit(data: dict, tenant: TenantContext = Depends(get_tenant_
elif exercises_in is not None:
_insert_sections_from_legacy_exercises(cur, unit_id, exercises_in)
_promote_private_exercises_used_in_unit(cur, unit_id, profile_id, role)
conn.commit()
return get_training_unit(unit_id, tenant)
@@ -1066,8 +1628,13 @@ def update_training_unit(unit_id: int, data: dict, tenant: TenantContext = Depen
tuple(blueprint_params),
)
else:
cur_lead = unit_row.get("lead_trainer_profile_id")
base_tr = unit_row.get("trainer_id")
lead_sql = ""
lead_params: List[Any] = []
assist_sql = ""
assist_params: List[Any] = []
nl: Optional[int]
if "lead_trainer_profile_id" in data:
nl = _normalize_lead_trainer_profile_id(
cur,
@@ -1075,9 +1642,34 @@ def update_training_unit(unit_id: int, data: dict, tenant: TenantContext = Depen
data.get("lead_trainer_profile_id"),
profile_id,
role,
unit_row.get("created_by"),
)
lead_sql = ", lead_trainer_profile_id = %s"
lead_params.append(nl)
eff_lead_for_co = nl if nl is not None else base_tr
else:
nl = cur_lead if cur_lead is not None else base_tr
eff_lead_for_co = nl
if "assistant_trainer_profile_ids" in data:
na = _normalize_assistant_trainer_profile_ids(
cur,
unit_row["group_id"],
data.get("assistant_trainer_profile_ids"),
profile_id,
role,
unit_row.get("created_by"),
eff_lead_for_co,
)
assist_sql = ", assistant_trainer_profile_ids = %s"
assist_params.append(na)
debrief_frag = ""
if "debrief_completed" in data and not is_blueprint:
if data.get("debrief_completed") is True:
debrief_frag = ", debrief_completed_at = NOW()"
else:
debrief_frag = ", debrief_completed_at = NULL"
cur.execute(
f"""
@@ -1096,6 +1688,8 @@ def update_training_unit(unit_id: int, data: dict, tenant: TenantContext = Depen
plan_template_id = COALESCE(%s, plan_template_id),
updated_at = NOW()
{lead_sql}
{assist_sql}
{debrief_frag}
WHERE id = %s
""",
(
@@ -1113,6 +1707,7 @@ def update_training_unit(unit_id: int, data: dict, tenant: TenantContext = Depen
tpl_id_val,
)
+ tuple(lead_params)
+ tuple(assist_params)
+ (unit_id,),
)
@@ -1138,6 +1733,9 @@ def update_training_unit(unit_id: int, data: dict, tenant: TenantContext = Depen
cur.execute("DELETE FROM training_unit_sections WHERE training_unit_id = %s", (unit_id,))
_insert_sections_from_legacy_exercises(cur, unit_id, data["exercises"] or [])
if content_handled or "sections" in data or "exercises" in data:
_promote_private_exercises_used_in_unit(cur, unit_id, profile_id, role)
conn.commit()
return get_training_unit(unit_id, tenant)
@@ -1152,7 +1750,12 @@ def delete_training_unit(unit_id: int, tenant: TenantContext = Depends(get_tenan
cur = get_cursor(conn)
cur.execute(
"SELECT created_by, framework_slot_id FROM training_units WHERE id = %s",
"""
SELECT tu.created_by, tu.framework_slot_id, tg.club_id AS group_club_id
FROM training_units tu
LEFT JOIN training_groups tg ON tu.group_id = tg.id
WHERE tu.id = %s
""",
(unit_id,),
)
@@ -1167,7 +1770,13 @@ def delete_training_unit(unit_id: int, tenant: TenantContext = Depends(get_tenan
detail="Blueprint-Einheiten werden über das Rahmenprogramm verwaltet, nicht hier gelöscht.",
)
_assert_delete_training_unit(role, unit["created_by"], profile_id)
_assert_delete_training_unit(
cur,
role,
unit["created_by"],
profile_id,
unit.get("group_club_id"),
)
cur.execute("DELETE FROM training_units WHERE id = %s", (unit_id,))
conn.commit()
@@ -1238,6 +1847,8 @@ def create_training_unit_from_framework_slot(data: dict, tenant: TenantContext =
slot_id,
)
_promote_private_exercises_used_in_unit(cur, new_id, profile_id, role)
conn.commit()
return get_training_unit(new_id, tenant)
@@ -1310,6 +1921,7 @@ def quick_create_training_unit(data: dict, tenant: TenantContext = Depends(get_t
if tpl_id_safe:
_instantiate_from_template(cur, unit_id, tpl_id_safe)
_promote_private_exercises_used_in_unit(cur, unit_id, profile_id, role)
conn.commit()
+11 -2
View File
@@ -2,8 +2,17 @@
"""
Shinkan Jinkendo — Datenbank-Migrationen
**Idempotent** über `schema_migrations`: jede numerische Datei `migrations/*.sql` höchstens einmal
als „erfolgreich“ eingetragen; bei erneutem Start werden nur noch fehlende Dateien abgearbeitet.
**Deployment:** Beim Start importiert `main.py` dieses Modul und ruft `main()` auf, bevor FastAPI
die App lädt (`SKIP_DB_MIGRATE=1` nur für Tests oder ohne DB). Jeder Backend-Container-Start
wendet ausstehende Migrationen an — kein separater Deploy-Schritt nötig.
**Idempotent (Runner):** Über `schema_migrations` wird jede Datei `NNN_*.sql` höchstens einmal
als erfolgreich markiert; wiederholte Starts führen nur noch fehlende Dateien aus.
**Idempotent (SQL, empfohlen):** `IF NOT EXISTS`, `ADD COLUMN IF NOT EXISTS`, `CREATE INDEX IF NOT EXISTS`,
damit ein erneuter Lauf derselben Datei harmlos bleibt. Ohne diese Guards schützt nur der
`schema_migrations`-Eintrag; ältere Migrationen ohne IF NOT EXISTS können bei manuell gelöschtem
Eintrag und bestehenden Tabellen fehlschlagen.
**Reihenfolge:** Alle `NNN_*.sql` nach führender Zahl (001 vor 009 vor 010 …), bei gleicher Zahl
alphabetisch nach Dateinamen — nicht bloß String-Sortierung (vermeidet z. B. `10_` vor `9_`).
@@ -21,6 +21,7 @@ EXEMPT_ROUTERS: frozenset[str] = frozenset(
{
"auth.py",
"admin_users.py",
"platform_media_storage.py",
"catalogs.py",
"skills.py",
"maturity_models.py",
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
"""
Automatische Medien-Retention (Papierkorb Stufe 1→2, Purge wenn fällig).
Lauf z. B. täglich per Cron:
cd /path/to/backend && python scripts/media_retention_job.py
Umgebung wie Backend (DB_*), optional:
MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS (Default 30)
MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS (Default 90)
"""
from __future__ import annotations
import os
import sys
# Repo-Root: backend/scripts -> parents[1] == backend
_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if _ROOT not in sys.path:
sys.path.insert(0, _ROOT)
from db import get_db, get_cursor # noqa: E402
from media_lifecycle import run_retention_pass # noqa: E402
def main() -> int:
with get_db() as conn:
cur = get_cursor(conn)
summary = run_retention_pass(cur, conn)
print(summary)
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""
CI-Sicherheitschecks: schlanke pytest-Sammlung ohne Integrations-DB.
Repo-Root ist egal — arbeitet relativ zu diesem Script (backend/).
Usage (aus backend/):
python scripts/security_release_checks.py
"""
from __future__ import annotations
import subprocess
import sys
from pathlib import Path
def main() -> int:
root = Path(__file__).resolve().parents[1]
test_file = root / "tests" / "test_security_release.py"
cmd = [
sys.executable,
"-m",
"pytest",
str(test_file),
"-v",
"--tb=short",
]
return subprocess.run(cmd, cwd=str(root)).returncode
if __name__ == "__main__":
raise SystemExit(main())
+89 -20
View File
@@ -11,7 +11,7 @@ from typing import Any, Dict, List, Optional
from fastapi import Depends, Header, HTTPException
from auth import require_auth
from auth import require_auth, require_auth_flexible
from club_tenancy import is_platform_admin, memberships_with_roles
from db import get_db, get_cursor
@@ -21,6 +21,22 @@ def _club_exists(cur, club_id: int) -> bool:
return cur.fetchone() is not None
def memberships_for_tenant_resolution(
memberships: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""
Nur Zeilen mit aktivem Vereinszugang (cm.status = 'active').
Wird genutzt, wenn /profiles/me alle Mitgliedschaften inkl. inaktiver liefert.
"""
out: List[Dict[str, Any]] = []
for r in memberships:
st_raw = r.get("membership_status")
st = str(st_raw if st_raw is not None else "active").strip().lower()
if st == "active":
out.append(r)
return out
def parse_active_club_header(raw: Optional[str]) -> Optional[int]:
"""Parst X-Active-Club-Id; leer → None. Ungültig → HTTP 400."""
if raw is None:
@@ -45,21 +61,36 @@ def library_content_visibility_sql(
effective_club_id: Optional[int],
) -> tuple[str, List[Any]]:
"""
WHERE-Baustein für Bibliothekslisten (Übungen, Vorlagen, Rahmenprogramme):
official, eigene private, club nur im aktiven Vereinskontext (effective_club_id).
Plattform-Admin: keine Einschränkung (TRUE).
Ohne effective_club_id: kein club-Zweig (nur official + private).
WHERE-Baustein für Bibliothekslisten (Übungen, Vorlagen, Rahmenprogramme, …):
- official immer
- private: eigene (Norm) bzw. alle (Plattform-Admin/Superadmin)
- club: nur mit **aktivem** Vereinszugang; Existenz einer nur **inactive** Mitgliedschaft schließt
aus — auch bei Plattform-Rolle. Ist man **kein** Mitglied des Vereins, behalten Plattform-Admins
Zugriff (Audit).
Für Nicht-Plattform: club-Zweig nur mit effective_club_id (Mandantenfilter).
"""
if is_platform_admin(role):
return "TRUE", []
plat = is_platform_admin(role)
parts: List[str] = [f"{alias}.visibility = 'official'"]
params: List[Any] = []
parts: List[str] = [
f"{alias}.visibility = 'official'",
f"({alias}.visibility = 'private' AND {alias}.created_by = %s)",
]
params: List[Any] = [profile_id]
if plat:
parts.append(f"({alias}.visibility = 'private')")
else:
parts.append(f"({alias}.visibility = 'private' AND {alias}.created_by = %s)")
params.append(profile_id)
if effective_club_id is not None:
club_ok_plat = (
f"({alias}.visibility = 'club' AND {alias}.club_id IS NOT NULL AND ("
f"EXISTS (SELECT 1 FROM club_members cm WHERE cm.profile_id = %s AND cm.club_id = {alias}.club_id "
f"AND cm.status = 'active') OR NOT EXISTS (SELECT 1 FROM club_members cm2 WHERE cm2.profile_id = %s "
f"AND cm2.club_id = {alias}.club_id)))"
)
if plat:
parts.append(club_ok_plat)
params.extend([profile_id, profile_id])
elif effective_club_id is not None:
parts.append(
f"""(
{alias}.visibility = 'club'
@@ -80,7 +111,7 @@ def library_content_visibility_sql(
class TenantContext:
profile_id: int
global_role: str
# Header > gespeichertes Profil > Fallback; Plattform-Admin ohne Header oft None
# Header > gespeichertes Profil > Fallback; Plattform-Admin ohne Header: Profil-Verein wenn existent
effective_club_id: Optional[int]
club_ids: frozenset[int]
memberships: List[Dict[str, Any]]
@@ -97,10 +128,13 @@ def resolve_tenant_context(
invalid_header_policy: str = "reject",
) -> TenantContext:
"""
Mitgliedschaften: wenn nicht übergeben, wird aus der DB geladen (aktive Mitgliedschaften).
Mitgliedschaften: wenn nicht übergeben, lädt ``active_only=True`` aus der DB.
Übergabe z. B. von ``/profiles/me``: Liste darf auch **deaktivierte** Vereinszugänge
(`membership_status` = inactive) enthalten — für ``club_ids`` und Mandantenwahl werden nur aktive verwendet.
Auflösung effective_club_id:
- Plattform-Admin: Header setzt beliebigen existierenden Verein; ohne Header → None.
- Plattform-Admin: Header setzt beliebigen existierenden Verein; ohne Header → gespeichertes
active_club_id falls der Verein existiert, sonst None.
- Sonst: gültiger Header zwingend Mitgliedschaft — bei ``reject`` sonst 403, bei ``ignore`` wie ohne Header.
Ohne gültigen Header: gespeichertes active_club_id wenn Mitglied; sonst einziger Verein;
bei mehreren ohne gültige Vorgabe → min(club_ids) (Fallback).
@@ -109,15 +143,22 @@ def resolve_tenant_context(
header_cid = parse_active_club_header(header_raw)
if memberships is None:
memberships = memberships_with_roles(cur, profile_id, active_only=True)
membership_rows = memberships_with_roles(cur, profile_id, active_only=True)
else:
membership_rows = memberships_for_tenant_resolution(memberships)
club_ids = frozenset(int(r["id"]) for r in memberships if r.get("id") is not None)
club_ids = frozenset(int(r["id"]) for r in membership_rows if r.get("id") is not None)
if is_platform_admin(role_lc):
if header_cid is not None:
if not _club_exists(cur, header_cid):
raise HTTPException(status_code=400, detail="Verein nicht gefunden")
effective = header_cid
elif (
stored_active_club_id is not None
and _club_exists(cur, stored_active_club_id)
):
effective = stored_active_club_id
else:
effective = None
return TenantContext(
@@ -125,7 +166,7 @@ def resolve_tenant_context(
global_role=role_lc,
effective_club_id=effective,
club_ids=club_ids,
memberships=memberships,
memberships=membership_rows,
)
chosen_header = header_cid
@@ -153,7 +194,7 @@ def resolve_tenant_context(
global_role=role_lc,
effective_club_id=effective,
club_ids=club_ids,
memberships=memberships,
memberships=membership_rows,
)
@@ -183,6 +224,34 @@ def get_tenant_context(
)
def get_tenant_context_flexible(
session: dict = Depends(require_auth_flexible),
x_active_club_id: Optional[str] = Header(default=None, alias="X-Active-Club-Id"),
) -> TenantContext:
"""
Wie get_tenant_context, aber Auth per Header oder Query ?ssetoken (für <img>/<video> ohne Custom-Header).
"""
pid = int(session["profile_id"])
role = session.get("role") or ""
stored: Optional[int] = None
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT active_club_id FROM profiles WHERE id = %s", (pid,))
row = cur.fetchone()
if row is not None:
ac = row.get("active_club_id")
if ac is not None:
stored = int(ac)
return resolve_tenant_context(
cur,
profile_id=pid,
global_role=role,
header_raw=x_active_club_id,
memberships=None,
stored_active_club_id=stored,
)
def tenant_context_from_session_only(
cur,
session: dict,
+93 -7
View File
@@ -2,29 +2,30 @@
import pytest
from fastapi import HTTPException
from tenant_context import library_content_visibility_sql, parse_active_club_header
from tenant_context import library_content_visibility_sql, parse_active_club_header, resolve_tenant_context
def test_library_visibility_sql_platform_admin_no_filter():
def test_library_visibility_sql_platform_admin_restricts_club_by_membership():
sql, params = library_content_visibility_sql(
alias="e",
profile_id=1,
role="admin",
effective_club_id=None,
)
assert sql == "TRUE"
assert params == []
assert "e.visibility = 'official'" in sql
assert "club_members" in sql
assert params == [1, 1]
def test_library_visibility_sql_superadmin():
def test_library_visibility_sql_superadmin_uses_membership_clause_for_club_visibility():
sql, params = library_content_visibility_sql(
alias="fp",
profile_id=2,
role="superadmin",
effective_club_id=100,
)
assert sql == "TRUE"
assert params == []
assert "club_members" in sql
assert params == [2, 2]
def test_library_visibility_sql_trainer_without_active_club_no_shared_club_branch():
@@ -74,3 +75,88 @@ def test_parse_active_club_header_non_positive():
with pytest.raises(HTTPException) as exc:
parse_active_club_header("0")
assert exc.value.status_code == 400
def test_resolve_platform_admin_uses_stored_club_without_header(monkeypatch):
"""Ohne X-Active-Club-Id: effective wie gespeichertes Profil (Sync mit Dropdown/DB)."""
cur = object()
def fake_exists(c, cid):
return cid == 99
monkeypatch.setattr("tenant_context._club_exists", fake_exists)
ctx = resolve_tenant_context(
cur,
profile_id=1,
global_role="admin",
header_raw=None,
memberships=[{"id": 10}],
stored_active_club_id=99,
)
assert ctx.effective_club_id == 99
def test_resolve_platform_admin_header_overrides_stored(monkeypatch):
cur = object()
def fake_exists(c, cid):
return cid in (5, 99)
monkeypatch.setattr("tenant_context._club_exists", fake_exists)
ctx = resolve_tenant_context(
cur,
profile_id=1,
global_role="superadmin",
header_raw="5",
memberships=[{"id": 10}],
stored_active_club_id=99,
)
assert ctx.effective_club_id == 5
def test_resolve_platform_admin_no_header_stored_invalid(monkeypatch):
cur = object()
monkeypatch.setattr("tenant_context._club_exists", lambda c, cid: False)
ctx = resolve_tenant_context(
cur,
profile_id=1,
global_role="admin",
header_raw=None,
memberships=[{"id": 1}],
stored_active_club_id=123,
)
assert ctx.effective_club_id is None
def test_resolve_trainer_club_ids_excludes_inactive_memberships():
"""Nur aktive Vereinszugänge zählen für Mandant / Header-Validierung."""
cur = object()
ctx = resolve_tenant_context(
cur,
profile_id=9,
global_role="user",
header_raw=None,
memberships=[
{"id": 10, "membership_status": "inactive"},
{"id": 20, "membership_status": "active"},
],
stored_active_club_id=None,
invalid_header_policy="ignore",
)
assert ctx.club_ids == frozenset({20})
assert ctx.effective_club_id == 20
def test_resolve_all_memberships_inactive_no_effective_club():
cur = object()
ctx = resolve_tenant_context(
cur,
profile_id=9,
global_role="user",
header_raw=None,
memberships=[{"id": 10, "membership_status": "inactive"}],
stored_active_club_id=10,
invalid_header_policy="ignore",
)
assert ctx.club_ids == frozenset()
assert ctx.effective_club_id is None
@@ -0,0 +1,323 @@
"""
Cross-Tenant-Integrationstests (PostgreSQL).
Voraussetzungen:
- Migrierte Datenbank (wie lokaler Docker-Postgres).
- ACCESS_LAYER_INTEGRATION=1 oder true
- DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD passend setzen
(lokal z. B. DB_HOST=localhost DB_PORT=5434 bei docker-compose Port-Mapping).
Aufruf aus backend/:
set ACCESS_LAYER_INTEGRATION=1
pytest tests/test_access_layer_integration.py -v -m integration
main wird mit SKIP_DB_MIGRATE=1 importiert, damit beim Testlauf keine Migrationen erneut laufen.
"""
from __future__ import annotations
import os
import uuid
from dataclasses import dataclass
import pytest
from fastapi.testclient import TestClient
def _integration_enabled() -> bool:
return os.getenv("ACCESS_LAYER_INTEGRATION", "").strip().lower() in ("1", "true", "yes")
pytestmark = [
pytest.mark.integration,
pytest.mark.skipif(
not _integration_enabled(),
reason="ACCESS_LAYER_INTEGRATION=1 setzen und PostgreSQL (DB_*) konfigurieren",
),
]
def _db_ping() -> bool:
try:
from db import get_db, get_cursor
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT 1 AS ok")
row = cur.fetchone()
return row is not None and row.get("ok") == 1
except Exception:
return False
@pytest.fixture(scope="module")
def integration_app():
"""FastAPI-App ohne erneuten Migrationslauf beim Import."""
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
from main import app
return app
@pytest.fixture(scope="module")
def db_ready():
if not _db_ping():
pytest.skip("PostgreSQL nicht erreichbar (DB_HOST/DB_PORT/… prüfen)")
@dataclass
class CrossTenantFixture:
suffix: str
club_a_id: int
club_b_id: int
user_a_id: int
user_b_id: int
token_a: str
token_b: str
exercise_official_id: int
exercise_club_b_id: int
@pytest.fixture
def cross_tenant(integration_app, db_ready) -> CrossTenantFixture:
from auth import hash_pin, make_token
from db import get_db, get_cursor
suffix = uuid.uuid4().hex[:10]
email_a = f"access_layer_it_{suffix}_a@test.local"
email_b = f"access_layer_it_{suffix}_b@test.local"
name_a = f"Club A User {suffix}"
name_b = f"Club B User {suffix}"
club_a_name = f"access_layer_it_club_a_{suffix}"
club_b_name = f"access_layer_it_club_b_{suffix}"
token_a = f"it-token-a-{suffix}"
token_b = f"it-token-b-{suffix}"
pin_hash = hash_pin("integration-test-pin")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"INSERT INTO clubs (name, abbreviation, status) VALUES (%s, %s, %s) RETURNING id",
(club_a_name, "ITA", "active"),
)
club_a_id = int(cur.fetchone()["id"])
cur.execute(
"INSERT INTO clubs (name, abbreviation, status) VALUES (%s, %s, %s) RETURNING id",
(club_b_name, "ITB", "active"),
)
club_b_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO profiles (email, pin_hash, name, role, active_club_id)
VALUES (%s, %s, %s, %s, %s)
RETURNING id
""",
(email_a, pin_hash, name_a, "trainer", club_a_id),
)
user_a_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO profiles (email, pin_hash, name, role, active_club_id)
VALUES (%s, %s, %s, %s, %s)
RETURNING id
""",
(email_b, pin_hash, name_b, "trainer", club_b_id),
)
user_b_id = int(cur.fetchone()["id"])
cur.execute(
"INSERT INTO club_members (profile_id, club_id, status) VALUES (%s, %s, %s)",
(user_a_id, club_a_id, "active"),
)
cur.execute(
"INSERT INTO club_members (profile_id, club_id, status) VALUES (%s, %s, %s)",
(user_b_id, club_b_id, "active"),
)
cur.execute(
"""
INSERT INTO sessions (profile_id, token, expires_at)
VALUES (%s, %s, NOW() + INTERVAL '2 days')
""",
(user_a_id, token_a),
)
cur.execute(
"""
INSERT INTO sessions (profile_id, token, expires_at)
VALUES (%s, %s, NOW() + INTERVAL '2 days')
""",
(user_b_id, token_b),
)
title_official = f"access_layer_it_official_{suffix}"
title_club_b = f"access_layer_it_club_b_only_{suffix}"
cur.execute(
"""
INSERT INTO exercises
(title, summary, goal, execution, visibility, status, created_by, club_id)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""",
(
title_official,
None,
"Goal",
"Execution",
"official",
"approved",
user_b_id,
None,
),
)
exercise_official_id = int(cur.fetchone()["id"])
cur.execute(
"""
INSERT INTO exercises
(title, summary, goal, execution, visibility, status, created_by, club_id)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""",
(
title_club_b,
None,
"Goal",
"Execution",
"club",
"approved",
user_b_id,
club_b_id,
),
)
exercise_club_b_id = int(cur.fetchone()["id"])
conn.commit()
fx = CrossTenantFixture(
suffix=suffix,
club_a_id=club_a_id,
club_b_id=club_b_id,
user_a_id=user_a_id,
user_b_id=user_b_id,
token_a=token_a,
token_b=token_b,
exercise_official_id=exercise_official_id,
exercise_club_b_id=exercise_club_b_id,
)
try:
yield fx
finally:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"DELETE FROM exercises WHERE id IN (%s, %s)",
(exercise_official_id, exercise_club_b_id),
)
cur.execute("DELETE FROM sessions WHERE token IN (%s, %s)", (token_a, token_b))
cur.execute(
"DELETE FROM club_members WHERE profile_id IN (%s, %s)",
(user_a_id, user_b_id),
)
cur.execute("DELETE FROM profiles WHERE id IN (%s, %s)", (user_a_id, user_b_id))
cur.execute("DELETE FROM clubs WHERE id IN (%s, %s)", (club_a_id, club_b_id))
conn.commit()
def test_list_hides_foreign_club_exercise_same_active_header(
integration_app, cross_tenant: CrossTenantFixture
):
"""Nutzer nur Verein A sieht keine Vereins-Übung von Verein B (aktiver Header = A)."""
client = TestClient(integration_app)
r = client.get(
"/api/exercises",
params={"search": f"access_layer_it_club_b_only_{cross_tenant.suffix}", "limit": 50},
headers={
"X-Auth-Token": cross_tenant.token_a,
"X-Active-Club-Id": str(cross_tenant.club_a_id),
},
)
assert r.status_code == 200, r.text
ids = [row["id"] for row in r.json()]
assert cross_tenant.exercise_club_b_id not in ids
def test_list_shows_official_exercise_for_foreign_user(
integration_app, cross_tenant: CrossTenantFixture
):
"""Offizielle Übung ist für alle authentifizierten Nutzer sichtbar."""
client = TestClient(integration_app)
r = client.get(
"/api/exercises",
params={"search": f"access_layer_it_official_{cross_tenant.suffix}", "limit": 50},
headers={
"X-Auth-Token": cross_tenant.token_a,
"X-Active-Club-Id": str(cross_tenant.club_a_id),
},
)
assert r.status_code == 200, r.text
ids = [row["id"] for row in r.json()]
assert cross_tenant.exercise_official_id in ids
def test_detail_forbidden_foreign_club_exercise(
integration_app, cross_tenant: CrossTenantFixture
):
"""Detail: keine Mitgliedschaft im Übungs-Verein → 403."""
client = TestClient(integration_app)
r = client.get(
f"/api/exercises/{cross_tenant.exercise_club_b_id}",
headers={
"X-Auth-Token": cross_tenant.token_a,
"X-Active-Club-Id": str(cross_tenant.club_a_id),
},
)
assert r.status_code == 403
def test_member_club_b_can_read_own_club_exercise(
integration_app, cross_tenant: CrossTenantFixture
):
client = TestClient(integration_app)
r = client.get(
f"/api/exercises/{cross_tenant.exercise_club_b_id}",
headers={
"X-Auth-Token": cross_tenant.token_b,
"X-Active-Club-Id": str(cross_tenant.club_b_id),
},
)
assert r.status_code == 200
body = r.json()
assert body["id"] == cross_tenant.exercise_club_b_id
assert body["visibility"] == "club"
def test_get_profile_forbidden_other_user_integration(
integration_app, cross_tenant: CrossTenantFixture
):
"""GET /profiles/{id}: Fremdes Profil → 403 (PostgreSQL-Integration)."""
client = TestClient(integration_app)
r = client.get(
f"/api/profiles/{cross_tenant.user_b_id}",
headers={"X-Auth-Token": cross_tenant.token_a},
)
assert r.status_code == 403
def test_get_profile_ok_own_integration(
integration_app, cross_tenant: CrossTenantFixture
):
client = TestClient(integration_app)
r = client.get(
f"/api/profiles/{cross_tenant.user_a_id}",
headers={"X-Auth-Token": cross_tenant.token_a},
)
assert r.status_code == 200
body = r.json()
assert body["id"] == cross_tenant.user_a_id
assert "pin_hash" not in body
@@ -0,0 +1,108 @@
"""Vereins-Übung: Copyright-Pflicht für angehängte Archiv-Dateien."""
from __future__ import annotations
import pytest
from fastapi import HTTPException
import routers.exercises as exercises_mod
from routers.exercises import apply_club_exercise_media_copyright_rules
def test_apply_club_exercise_media_copyright_skips_non_club() -> None:
apply_club_exercise_media_copyright_rules(object(), 1, "private")
def test_apply_club_exercise_media_copyright_missing_copyright() -> None:
orig = exercises_mod._fetch_exercise_linked_file_assets
def mock_fetch(_cur, eid: int):
assert eid == 42
return [
{
"id": 10,
"visibility": "private",
"club_id": 1,
"lifecycle_state": "active",
"copyright_notice": "",
"original_filename": "x.jpg",
}
]
exercises_mod._fetch_exercise_linked_file_assets = mock_fetch
try:
with pytest.raises(HTTPException) as ei:
apply_club_exercise_media_copyright_rules(object(), 42, "club")
assert ei.value.status_code == 422
d = ei.value.detail
assert isinstance(d, dict)
assert d.get("code") == "CLUB_MEDIA_COPYRIGHT_REQUIRED"
finally:
exercises_mod._fetch_exercise_linked_file_assets = orig
def test_apply_club_exercise_media_copyright_ok() -> None:
orig = exercises_mod._fetch_exercise_linked_file_assets
def mock_fetch(_cur, _eid: int):
return [
{
"id": 10,
"visibility": "private",
"club_id": 1,
"lifecycle_state": "active",
"copyright_notice": "© Verein 2026",
"original_filename": "x.jpg",
}
]
exercises_mod._fetch_exercise_linked_file_assets = mock_fetch
try:
apply_club_exercise_media_copyright_rules(object(), 42, "club")
finally:
exercises_mod._fetch_exercise_linked_file_assets = orig
def test_apply_club_exercise_media_copyright_applies_default() -> None:
"""Nach Bestätigung setzt der Client default_club_media_copyright — Backend schreibt auf Assets."""
orig_fetch = exercises_mod._fetch_exercise_linked_file_assets
calls = {"n": 0}
def mock_fetch(_cur, _eid: int):
calls["n"] += 1
if calls["n"] == 1:
return [
{
"id": 10,
"visibility": "private",
"club_id": 1,
"lifecycle_state": "active",
"copyright_notice": "",
"original_filename": "x.jpg",
}
]
return [
{
"id": 10,
"visibility": "private",
"club_id": 1,
"lifecycle_state": "active",
"copyright_notice": "© Testverein",
"original_filename": "x.jpg",
}
]
class MockCur:
def execute(self, *args, **kwargs):
pass
exercises_mod._fetch_exercise_linked_file_assets = mock_fetch
try:
apply_club_exercise_media_copyright_rules(
MockCur(),
42,
"club",
default_club_media_copyright="© Testverein",
)
assert calls["n"] == 2
finally:
exercises_mod._fetch_exercise_linked_file_assets = orig_fetch
@@ -0,0 +1,51 @@
"""POST /api/exercises: keine Inline-Medien-Platzhalter beim ersten Anlegen (§11)."""
from __future__ import annotations
import os
import pytest
from fastapi.testclient import TestClient
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
from auth import require_auth
from main import app
from tenant_context import TenantContext, get_tenant_context
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
@pytest.fixture(autouse=True)
def _clear_overrides() -> None:
yield
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(get_tenant_context, None)
def test_post_exercise_rejects_inline_media_placeholder(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=1,
global_role="trainer",
effective_club_id=5,
club_ids=frozenset({5}),
memberships=[],
)
r = client.post(
"/api/exercises",
json={
"title": "Mit Inline",
"goal": "<p>Hallo {{exerciseMedia:7}}</p>",
"execution": "<p>Schritt</p>",
"visibility": "private",
"status": "draft",
},
headers={"X-Auth-Token": "x"},
)
assert r.status_code == 400
j = r.json()
assert j.get("detail", {}).get("code") == "INLINE_EXERCISE_MEDIA_ON_CREATE"
@@ -0,0 +1,75 @@
"""
Geschützte Übungs-Mediendatei: Auth + Governance (kein anonymes /media/).
"""
from __future__ import annotations
import os
from unittest.mock import MagicMock, patch
import pytest
from fastapi.testclient import TestClient
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
from auth import require_auth_flexible
from main import app
from tenant_context import TenantContext, get_tenant_context_flexible
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
@pytest.fixture(autouse=True)
def _clear_overrides():
yield
app.dependency_overrides.pop(require_auth_flexible, None)
app.dependency_overrides.pop(get_tenant_context_flexible, None)
def test_exercise_media_file_unauthenticated_401(client: TestClient) -> None:
r = client.get("/api/exercises/1/media/2/file")
assert r.status_code == 401
def test_exercise_media_file_forbidden_when_not_visible(client: TestClient) -> None:
app.dependency_overrides[get_tenant_context_flexible] = lambda: TenantContext(
profile_id=22,
global_role="trainer",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
mock_cm = MagicMock()
mock_conn = MagicMock()
mock_cm.__enter__.return_value = mock_conn
mock_cm.__exit__.return_value = False
mock_cur = MagicMock()
mock_cur.fetchone.return_value = {
"id": 3,
"visibility": "private",
"club_id": None,
"created_by": 99,
}
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
"routers.exercises.get_cursor", return_value=mock_cur
), patch("routers.exercises.library_content_visible_to_profile", return_value=False):
r = client.get("/api/exercises/3/media/2/file", headers={"X-Auth-Token": "t"})
assert r.status_code == 403
def test_get_maturity_model_requires_admin(client: TestClient) -> None:
from auth import require_auth
def _user() -> dict:
return {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[require_auth] = _user
try:
r = client.get("/api/maturity-models/1", headers={"X-Auth-Token": "x"})
assert r.status_code == 403
finally:
app.dependency_overrides.pop(require_auth, None)
+44
View File
@@ -0,0 +1,44 @@
"""exercise_rich_text: §11 Normalisierung und ID-Sammlung."""
from __future__ import annotations
import pytest
from fastapi import HTTPException
from unittest.mock import MagicMock
from exercise_rich_text import (
assert_no_inline_media_references_on_create,
collect_inline_exercise_media_ids,
normalize_inline_exercise_media_markup,
validate_inline_exercise_media_ids_for_exercise,
)
def test_normalize_curly_to_span() -> None:
s = '<p>Vor {{exerciseMedia: 42 }} nach</p>'
out = normalize_inline_exercise_media_markup(s)
assert 'data-shinkan-exercise-media="42"' in out
assert 'data-shinkan-exercise-media-size="medium"' in out
assert "{{" not in out
def test_collect_merges_braces_and_data_attr() -> None:
html = '{{ExercisemEDIA: 1}}\n<span data-shinkan-exercise-media="2"></span>'
assert collect_inline_exercise_media_ids(html) == {1, 2}
def test_assert_no_inline_on_create_raises() -> None:
with pytest.raises(HTTPException) as ei:
assert_no_inline_media_references_on_create({5})
assert ei.value.status_code == 400
body = ei.value.detail
assert isinstance(body, dict)
assert body["code"] == "INLINE_EXERCISE_MEDIA_ON_CREATE"
def test_validate_ids_sql_mock() -> None:
mock_cur = MagicMock()
mock_cur.fetchall.return_value = [{"id": 1}]
with pytest.raises(HTTPException) as ei:
validate_inline_exercise_media_ids_for_exercise(mock_cur, 100, {1, 99})
assert ei.value.detail["invalid_exercise_media_ids"] == [99]
@@ -0,0 +1,131 @@
"""
DELETE /api/exercises/{id}: Mandanten-/Rollenlogik und Verwendungsblock (409).
TestClient mit Overrides für Auth und TenantContext; DB via get_db/get_cursor gemockt.
"""
from __future__ import annotations
import os
from unittest.mock import MagicMock, patch
import pytest
from fastapi.testclient import TestClient
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
from auth import require_auth
from main import app
from tenant_context import TenantContext, get_tenant_context
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
@pytest.fixture(autouse=True)
def _clear_overrides() -> None:
yield
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(get_tenant_context, None)
def _mock_db_cm(mock_cur: MagicMock):
mock_conn = MagicMock()
mock_cm = MagicMock()
mock_cm.__enter__.return_value = mock_conn
mock_cm.__exit__.return_value = False
return mock_cm
def test_delete_trainer_private_own_ok(client: TestClient) -> None:
mock_cur = MagicMock()
mock_cur.fetchone.side_effect = [
{"id": 7, "created_by": 42, "visibility": "private", "club_id": None},
{"block_items": 0, "section_items": 0, "prog_edges": 0},
]
mock_cm = _mock_db_cm(mock_cur)
app.dependency_overrides[require_auth] = lambda: {"profile_id": 42, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=42,
global_role="trainer",
effective_club_id=5,
club_ids=frozenset({5}),
memberships=[],
)
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
"routers.exercises.get_cursor", return_value=mock_cur
):
r = client.delete("/api/exercises/7", headers={"X-Auth-Token": "dummy"})
assert r.status_code == 200
assert r.json().get("ok") is True
def test_delete_trainer_club_exercise_forbidden_without_club_admin(client: TestClient) -> None:
mock_cur = MagicMock()
mock_cur.fetchone.side_effect = [
{"id": 7, "created_by": 42, "visibility": "club", "club_id": 5},
]
mock_cm = _mock_db_cm(mock_cur)
app.dependency_overrides[require_auth] = lambda: {"profile_id": 42, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=42,
global_role="trainer",
effective_club_id=5,
club_ids=frozenset({5}),
memberships=[],
)
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
"routers.exercises.get_cursor", return_value=mock_cur
), patch("routers.exercises.has_club_role", return_value=False):
r = client.delete("/api/exercises/7", headers={"X-Auth-Token": "dummy"})
assert r.status_code == 403
def test_delete_usage_returns_409(client: TestClient) -> None:
mock_cur = MagicMock()
mock_cur.fetchone.side_effect = [
{"id": 7, "created_by": 42, "visibility": "private", "club_id": None},
{"block_items": 1, "section_items": 2, "prog_edges": 3},
]
mock_cm = _mock_db_cm(mock_cur)
app.dependency_overrides[require_auth] = lambda: {"profile_id": 42, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=42,
global_role="trainer",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
"routers.exercises.get_cursor", return_value=mock_cur
):
r = client.delete("/api/exercises/7", headers={"X-Auth-Token": "dummy"})
assert r.status_code == 409
detail = r.json().get("detail", "")
assert "Übungsblöcken" in detail or "Trainingsplänen" in detail
def test_delete_official_forbidden_non_platform_admin(client: TestClient) -> None:
mock_cur = MagicMock()
mock_cur.fetchone.side_effect = [
{"id": 99, "created_by": 1, "visibility": "official", "club_id": None},
]
mock_cm = _mock_db_cm(mock_cur)
app.dependency_overrides[require_auth] = lambda: {"profile_id": 42, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=42,
global_role="trainer",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
"routers.exercises.get_cursor", return_value=mock_cur
):
r = client.delete("/api/exercises/99", headers={"X-Auth-Token": "dummy"})
assert r.status_code == 403
+107
View File
@@ -0,0 +1,107 @@
"""library_storage_key: Mandantenpfade unter MEDIA_ROOT."""
from __future__ import annotations
import pytest
from media_storage import library_club_path_segment, library_media_kind_dir, library_storage_key
_HEX64 = "a" * 64
def test_library_media_kind_dir_mime_overrides_ext() -> None:
assert library_media_kind_dir("image/png", ".bin") == "image"
assert library_media_kind_dir("application/pdf", ".tmp") == "pdf"
def test_library_club_path_segment_slug_and_fallback() -> None:
assert library_club_path_segment(3, "Grün & Weiß / Dojo!") == "gruen-weiss-dojo-c3"
assert library_club_path_segment(3, None) == "verein-c3"
assert library_club_path_segment(3, " ") == "verein-c3"
assert library_club_path_segment(12, "東道場") == "verein-c12"
def test_library_club_path_segment_long_name_truncated() -> None:
long = "a" * 80
seg = library_club_path_segment(5, long)
assert seg == "a" * 48 + "-c5"
def test_library_storage_key_private_is_uploader_under_club() -> None:
assert (
library_storage_key(
"private", 7, _HEX64, ".jpg", uploader_profile_id=99, club_name="Ost Dojo München"
)
== f"library/ost-dojo-muenchen-c7/image/{_HEX64}.u99.jpg"
)
def test_library_storage_key_club_flat_under_club() -> None:
assert (
library_storage_key("club", 42, _HEX64, ".png", club_name="Demo-Verein")
== f"library/demo-verein-c42/image/{_HEX64}.png"
)
def test_library_storage_key_official() -> None:
assert (
library_storage_key("official", None, _HEX64, ".mp4", uploader_profile_id=1)
== f"library/official/video/{_HEX64}.mp4"
)
def test_library_storage_key_normalizes_visibility() -> None:
assert (
library_storage_key(" CLUB ", 1, _HEX64, "pdf", club_name="Alpha")
== f"library/alpha-c1/pdf/{_HEX64}.pdf"
)
def test_library_storage_key_other_bin() -> None:
assert (
library_storage_key("official", None, _HEX64, "", mime_type="application/octet-stream")
== f"library/official/other/{_HEX64}.bin"
)
def test_library_storage_key_private_requires_uploader() -> None:
with pytest.raises(ValueError, match="uploader_profile_id"):
library_storage_key("private", 1, _HEX64, ".jpg", club_name="V")
def test_library_storage_key_private_requires_club() -> None:
with pytest.raises(ValueError, match="Verein"):
library_storage_key("private", None, _HEX64, ".jpg", uploader_profile_id=1)
def test_library_storage_key_club_requires_id() -> None:
with pytest.raises(ValueError, match="Verein"):
library_storage_key("club", None, _HEX64, ".jpg", club_name="X")
def test_library_storage_key_club_id_positive() -> None:
with pytest.raises(ValueError, match="positiv"):
library_storage_key("club", 0, _HEX64, ".jpg", club_name="X")
def test_library_storage_key_invalid_visibility() -> None:
with pytest.raises(ValueError, match="Sichtbarkeit"):
library_storage_key("public", 1, _HEX64, ".jpg", club_name="X")
def test_library_storage_key_invalid_sha() -> None:
with pytest.raises(ValueError, match="64"):
library_storage_key("private", 1, "deadbeef", ".jpg", uploader_profile_id=1, club_name="X")
def test_library_storage_key_extension() -> None:
with pytest.raises(ValueError):
library_storage_key(
"private", 1, _HEX64, "../x", uploader_profile_id=1, club_name="X"
)
def test_library_storage_key_private_no_club_name_fallback() -> None:
assert (
library_storage_key("private", 2, _HEX64, ".jpg", uploader_profile_id=3)
== f"library/verein-c2/image/{_HEX64}.u3.jpg"
)
+506
View File
@@ -0,0 +1,506 @@
"""
Medienarchiv: GET /api/media-assets und POST /api/exercises/{id}/media/from-asset (gemockte DB).
"""
from __future__ import annotations
import os
from unittest.mock import MagicMock, patch
import pytest
from fastapi.testclient import TestClient
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
from auth import require_auth
from main import app
from tenant_context import TenantContext, get_tenant_context
# Gültige storage_key-Beispiele (64 Hex-Zeichen wie echter SHA-256)
_SK_OFF_A = f"library/official/image/{'a' * 64}.jpg"
_SK_OFF_B = f"library/official/image/{'b' * 64}.jpg"
_SK_PRIV_C = f"library/verein-c1/video/{'c' * 64}.u1.mp4"
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
@pytest.fixture(autouse=True)
def _clear_overrides() -> None:
yield
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(get_tenant_context, None)
def _mock_db(mock_cur: MagicMock) -> MagicMock:
mock_conn = MagicMock()
mock_cm = MagicMock()
mock_cm.__enter__.return_value = mock_conn
mock_cm.__exit__.return_value = False
return mock_cm
def test_list_media_assets_ok_mocked(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 10, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=10,
global_role="trainer",
effective_club_id=5,
club_ids=frozenset({5}),
memberships=[],
)
mock_cur = MagicMock()
mock_cur.fetchall.side_effect = [
[
{
"id": 1,
"mime_type": "image/png",
"byte_size": 100,
"original_filename": "a.png",
"visibility": "official",
"club_id": None,
"uploaded_by_profile_id": 2,
"lifecycle_state": "active",
"created_at": None,
"sha256": "a" * 64,
"copyright_notice": None,
"storage_key": "media/a.png",
"tags": ["demo"],
"uploader_name": None,
"uploader_email": None,
"club_name": None,
}
],
[],
]
mock_cm = _mock_db(mock_cur)
with patch("routers.media_assets.get_db", return_value=mock_cm), patch(
"routers.media_assets.get_cursor", return_value=mock_cur
), patch("routers.media_assets.club_ids_for_profile_with_roles", return_value=set()):
r = client.get("/api/media-assets?q=test", headers={"X-Auth-Token": "t"})
assert r.status_code == 200
body = r.json()
assert body["limit"] == 30
assert len(body["items"]) == 1
assert body["items"][0]["original_filename"] == "a.png"
assert body["items"][0]["usage"] == {"exercises": [], "training_units": []}
assert body["items"][0]["tags"] == ["demo"]
assert "viewer" in body
def test_list_media_assets_media_kind_image_ok_mocked(client: TestClient) -> None:
"""media_kind=image setzt %% in SQL — Regression gegen psycopg2-%-Platzhalter."""
app.dependency_overrides[require_auth] = lambda: {"profile_id": 10, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=10,
global_role="trainer",
effective_club_id=5,
club_ids=frozenset({5}),
memberships=[],
)
mock_cur = MagicMock()
mock_cur.fetchall.side_effect = [[], []]
mock_cm = _mock_db(mock_cur)
with patch("routers.media_assets.get_db", return_value=mock_cm), patch(
"routers.media_assets.get_cursor", return_value=mock_cur
), patch("routers.media_assets.club_ids_for_profile_with_roles", return_value=set()):
r = client.get("/api/media-assets?media_kind=image", headers={"X-Auth-Token": "t"})
assert r.status_code == 200
calls = [str(c) for c in mock_cur.execute.call_args_list]
joined = " ".join(calls)
assert "image/%%" in joined
def test_attach_from_asset_duplicate_returns_400(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=1,
global_role="trainer",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
mock_cur = MagicMock()
mock_cur.fetchone.side_effect = [
{"created_by": 1, "visibility": "private", "club_id": None},
{"c": 0},
{
"id": 5,
"mime_type": "image/jpeg",
"byte_size": 10,
"original_filename": "x.jpg",
"visibility": "official",
"club_id": None,
"uploaded_by_profile_id": 1,
"lifecycle_state": "active",
"storage_key": _SK_OFF_A,
},
{"id": 1},
]
mock_cm = _mock_db(mock_cur)
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
"routers.exercises.get_cursor", return_value=mock_cur
):
r = client.post(
"/api/exercises/3/media/from-asset",
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
json={
"media_asset_id": 5,
"title": "",
"description": "",
"context": "ablauf",
"is_primary": False,
},
)
assert r.status_code == 400
assert "bereits" in (r.json().get("detail") or "").lower()
def test_attach_from_asset_ok_mocked(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=1,
global_role="trainer",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
inserted = {
"id": 99,
"exercise_id": 3,
"media_type": "image",
"file_path": f"/media/{_SK_OFF_B}",
"file_size": 10,
"mime_type": "image/jpeg",
"original_filename": "h.jpg",
"embed_url": None,
"embed_platform": None,
"title": "h.jpg",
"description": None,
"sort_order": 1,
"is_primary": False,
"context": "ablauf",
"created_at": None,
"media_asset_id": 5,
}
mock_cur = MagicMock()
mock_cur.fetchone.side_effect = [
{"created_by": 1, "visibility": "private", "club_id": None},
{"c": 0},
{
"id": 5,
"mime_type": "image/jpeg",
"byte_size": 10,
"original_filename": "h.jpg",
"visibility": "official",
"club_id": None,
"uploaded_by_profile_id": 1,
"lifecycle_state": "active",
"storage_key": _SK_OFF_B,
},
None,
inserted,
]
mock_cm = _mock_db(mock_cur)
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
"routers.exercises.get_cursor", return_value=mock_cur
):
r = client.post(
"/api/exercises/3/media/from-asset",
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
json={
"media_asset_id": 5,
"context": "detail",
"is_primary": False,
},
)
assert r.status_code == 201
body = r.json()
assert body["id"] == 99
assert body["media_asset_id"] == 5
assert body["asset_lifecycle_state"] == "active"
def test_delete_exercise_media_returns_orphan_when_last_ref(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=1,
global_role="trainer",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
mock_cur = MagicMock()
mock_cur.fetchone.side_effect = [
{"created_by": 1, "visibility": "private", "club_id": None},
{"media_asset_id": 88},
{"c": 1},
]
mock_cm = _mock_db(mock_cur)
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
"routers.exercises.get_cursor", return_value=mock_cur
):
r = client.delete("/api/exercises/10/media/20", headers={"X-Auth-Token": "t"})
assert r.status_code == 200
body = r.json()
assert body["ok"] is True
assert body["orphan_media_asset_id"] == 88
def test_delete_exercise_media_no_orphan_when_shared(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=1,
global_role="trainer",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
mock_cur = MagicMock()
mock_cur.fetchone.side_effect = [
{"created_by": 1, "visibility": "private", "club_id": None},
{"media_asset_id": 88},
{"c": 2},
]
mock_cm = _mock_db(mock_cur)
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
"routers.exercises.get_cursor", return_value=mock_cur
):
r = client.delete("/api/exercises/10/media/20", headers={"X-Auth-Token": "t"})
assert r.status_code == 200
assert r.json()["orphan_media_asset_id"] is None
def test_delete_exercise_media_embed_row_no_orphan(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=1,
global_role="trainer",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
mock_cur = MagicMock()
mock_cur.fetchone.side_effect = [
{"created_by": 1, "visibility": "private", "club_id": None},
{"media_asset_id": None},
]
mock_cm = _mock_db(mock_cur)
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
"routers.exercises.get_cursor", return_value=mock_cur
):
r = client.delete("/api/exercises/10/media/21", headers={"X-Auth-Token": "t"})
assert r.status_code == 200
assert r.json() == {"ok": True, "orphan_media_asset_id": None}
def test_media_asset_lifecycle_reactivate_mocked(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=1,
global_role="trainer",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
mock_cur = MagicMock()
mock_cur.fetchone.side_effect = [
{
"id": 5,
"visibility": "private",
"club_id": 1,
"uploaded_by_profile_id": 1,
"lifecycle_state": "trash_soft",
"storage_key": _SK_PRIV_C,
"storage_backend": "local",
"trash_soft_at": None,
"trash_hidden_at": None,
"purge_after_at": None,
},
{"id": 5, "lifecycle_state": "active"},
]
mock_cm = _mock_db(mock_cur)
with patch("routers.media_assets.get_db", return_value=mock_cm), patch(
"routers.media_assets.get_cursor", return_value=mock_cur
):
r = client.post(
"/api/media-assets/5/lifecycle",
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
json={"action": "reactivate"},
)
assert r.status_code == 200
assert r.json()["lifecycle_state"] == "active"
def test_media_asset_lifecycle_purge_forbidden_for_non_superadmin(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "admin"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=1,
global_role="admin",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
mock_cur = MagicMock()
mock_cm = _mock_db(mock_cur)
fake_row = {
"id": 99,
"visibility": "official",
"club_id": None,
"uploaded_by_profile_id": 2,
"lifecycle_state": "trash_hidden",
"storage_key": "x",
"storage_backend": "local",
"trash_soft_at": None,
"trash_hidden_at": None,
"purge_after_at": None,
}
with patch("routers.media_assets.get_db", return_value=mock_cm), patch(
"routers.media_assets.get_cursor", return_value=mock_cur
), patch("routers.media_assets.fetch_media_asset_row", return_value=fake_row):
r = client.post(
"/api/media-assets/99/lifecycle",
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
json={"action": "purge"},
)
assert r.status_code == 403
assert "Superadmin" in (r.json().get("detail") or "")
def test_list_media_assets_lifecycle_trash_soft_mocked(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 10, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=10,
global_role="trainer",
effective_club_id=5,
club_ids=frozenset({5}),
memberships=[],
)
mock_cur = MagicMock()
mock_cur.fetchall.return_value = []
mock_cm = _mock_db(mock_cur)
with patch("routers.media_assets.get_db", return_value=mock_cm), patch(
"routers.media_assets.get_cursor", return_value=mock_cur
), patch("routers.media_assets.club_ids_for_profile_with_roles", return_value=set()):
r = client.get("/api/media-assets?lifecycle=trash_soft", headers={"X-Auth-Token": "t"})
assert r.status_code == 200
assert r.json()["lifecycle"] == "trash_soft"
list_sql_calls = [c[0][0] for c in mock_cur.execute.call_args_list if c[0] and "FROM media_assets ma" in str(c[0][0])]
assert list_sql_calls and "trash_soft" in list_sql_calls[0]
def test_list_media_assets_invalid_media_kind_400(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 10, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=10,
global_role="trainer",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
r = client.get("/api/media-assets?media_kind=movies", headers={"X-Auth-Token": "t"})
assert r.status_code == 400
def test_list_media_assets_club_filter_forbidden_non_superadmin(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 10, "role": "admin"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=10,
global_role="admin",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
r = client.get("/api/media-assets?club_id=3", headers={"X-Auth-Token": "t"})
assert r.status_code == 403
def test_list_media_assets_invalid_lifecycle_400(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 10, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=10,
global_role="trainer",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
r = client.get("/api/media-assets?lifecycle=invalid", headers={"X-Auth-Token": "t"})
assert r.status_code == 400
def test_patch_media_asset_copyright_mocked(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 10, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=10,
global_role="trainer",
effective_club_id=None,
club_ids=frozenset(),
memberships=[],
)
mock_cur = MagicMock()
mock_cur.fetchone.side_effect = [
{
"id": 9,
"visibility": "private",
"club_id": None,
"uploaded_by_profile_id": 10,
"lifecycle_state": "active",
"copyright_notice": "",
"original_filename": "x.png",
},
{
"id": 9,
"mime_type": "image/png",
"byte_size": 10,
"original_filename": "x.png",
"visibility": "private",
"club_id": None,
"uploaded_by_profile_id": 10,
"lifecycle_state": "active",
"created_at": None,
"sha256": "b" * 64,
"copyright_notice": "© HoldCo",
"tags": [],
},
]
mock_cm = _mock_db(mock_cur)
with patch("routers.media_assets.get_db", return_value=mock_cm), patch(
"routers.media_assets.get_cursor", return_value=mock_cur
), patch("media_lifecycle.assert_can_manage_media_asset_lifecycle", lambda *a, **k: None):
r = client.patch(
"/api/media-assets/9",
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
json={"copyright_notice": "© HoldCo"},
)
assert r.status_code == 200
assert r.json()["copyright_notice"] == "© HoldCo"
@@ -0,0 +1,107 @@
"""§4.2: apply_official_exercise_media_rules — Lifecycle, Sichtbarkeit, Copyright."""
from __future__ import annotations
import os
from unittest.mock import MagicMock
import pytest
from fastapi import HTTPException
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
from routers.exercises import apply_official_exercise_media_rules
def _row(
aid: int,
*,
vis: str = "private",
lifecycle: str = "active",
copyright_notice: str | None = "",
name: str = "f.bin",
) -> dict:
return {
"id": aid,
"visibility": vis,
"club_id": 1,
"lifecycle_state": lifecycle,
"copyright_notice": copyright_notice,
"original_filename": name,
}
def test_non_official_visibility_noop() -> None:
cur = MagicMock()
apply_official_exercise_media_rules(
cur,
1,
"private",
promote_attached_media=False,
default_official_media_copyright=None,
)
cur.execute.assert_not_called()
def test_lifecycle_not_active_422() -> None:
cur = MagicMock()
cur.fetchall.return_value = [_row(1, lifecycle="trash_soft", copyright_notice="abc")]
with pytest.raises(HTTPException) as ei:
apply_official_exercise_media_rules(
cur,
1,
"official",
promote_attached_media=False,
default_official_media_copyright=None,
)
assert ei.value.status_code == 422
assert ei.value.detail["code"] == "OFFICIAL_MEDIA_LIFECYCLE"
def test_visibility_promotion_confirm_422() -> None:
cur = MagicMock()
cur.fetchall.return_value = [_row(1, vis="club", copyright_notice="halten")]
with pytest.raises(HTTPException) as ei:
apply_official_exercise_media_rules(
cur,
1,
"official",
promote_attached_media=False,
default_official_media_copyright=None,
)
assert ei.value.status_code == 422
assert ei.value.detail["code"] == "OFFICIAL_MEDIA_CONFIRM_REQUIRED"
assert ei.value.detail["assets_need_visibility_promotion"]
def test_copyright_required_422() -> None:
cur = MagicMock()
cur.fetchall.return_value = [_row(1, vis="official", copyright_notice="")]
with pytest.raises(HTTPException) as ei:
apply_official_exercise_media_rules(
cur,
1,
"official",
promote_attached_media=True,
default_official_media_copyright=None,
)
assert ei.value.status_code == 422
assert ei.value.detail["code"] == "OFFICIAL_MEDIA_CONFIRM_REQUIRED"
assert ei.value.detail["assets_missing_copyright"]
def test_promote_and_fill_copyright_updates() -> None:
cur = MagicMock()
cur.fetchall.return_value = [_row(1, vis="private", copyright_notice=" ")]
apply_official_exercise_media_rules(
cur,
42,
"official",
promote_attached_media=True,
default_official_media_copyright="© Test Holding",
)
assert cur.execute.call_count == 3
sql1 = cur.execute.call_args_list[1][0][0]
sql2 = cur.execute.call_args_list[2][0][0]
assert "visibility = 'official'" in sql1
assert "copyright_notice" in sql2
@@ -0,0 +1,74 @@
"""GET/PUT /api/admin/platform-media-storage — Auth-Matrix (kein Live-DB nötig)."""
from __future__ import annotations
import os
from unittest.mock import MagicMock, patch
import pytest
from fastapi.testclient import TestClient
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
from auth import require_auth
from main import app
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
@pytest.fixture(autouse=True)
def _clear_overrides():
yield
app.dependency_overrides.pop(require_auth, None)
def test_platform_media_storage_get_requires_platform_admin(client: TestClient) -> None:
def _trainer():
return {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[require_auth] = _trainer
r = client.get("/api/admin/platform-media-storage", headers={"X-Auth-Token": "t"})
assert r.status_code == 403
def test_platform_media_storage_put_requires_superadmin(client: TestClient) -> None:
def _admin():
return {"profile_id": 1, "role": "admin"}
app.dependency_overrides[require_auth] = _admin
r = client.put(
"/api/admin/platform-media-storage",
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
json={"local_relative_root": "foo"},
)
assert r.status_code == 403
@patch("routers.platform_media_storage.get_effective_media_root", return_value=__import__("pathlib").Path("/tmp/media"))
def test_platform_media_storage_get_ok_for_admin(mock_root, client: TestClient) -> None:
def _admin():
return {"profile_id": 1, "role": "admin"}
app.dependency_overrides[require_auth] = _admin
mock_cm = MagicMock()
mock_conn = MagicMock()
mock_cm.__enter__.return_value = mock_conn
mock_cm.__exit__.return_value = False
mock_cur = MagicMock()
mock_cur.fetchone.return_value = {
"storage_backend": "local",
"local_relative_root": "nas",
}
with patch("routers.platform_media_storage.get_db", return_value=mock_cm), patch(
"routers.platform_media_storage.get_cursor", return_value=mock_cur
):
r = client.get("/api/admin/platform-media-storage", headers={"X-Auth-Token": "t"})
assert r.status_code == 200
body = r.json()
assert body["storage_backend"] == "local"
assert body["local_relative_root"] == "nas"
+193
View File
@@ -0,0 +1,193 @@
"""
Zugriffsrechte Profile: POST/GET/DELETE /api/profiles/{pid}.
TestClient + Dependency-Override für Sessions; GET mockt profile_document, DELETE/POST mocken DB,
damit keine echte Datenbank nötig ist.
"""
from __future__ import annotations
import os
import pytest
from unittest.mock import MagicMock, patch
from fastapi.testclient import TestClient
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
from auth import require_auth
from main import app
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
@pytest.fixture(autouse=True)
def _clear_auth_override():
yield
app.dependency_overrides.pop(require_auth, None)
def test_get_profile_forbidden_other_user(client: TestClient) -> None:
def auth_viewer() -> dict:
return {"profile_id": 42, "role": "trainer"}
app.dependency_overrides[require_auth] = auth_viewer
with patch("routers.profiles.profile_document") as pd_mock:
r = client.get("/api/profiles/99", headers={"X-Auth-Token": "dummy"})
assert r.status_code == 403
assert pd_mock.call_count == 0
def test_get_profile_ok_same_numeric_id(client: TestClient) -> None:
payload = {"id": 42, "name": "Self"}
def auth_self() -> dict:
return {"profile_id": 42, "role": "trainer"}
app.dependency_overrides[require_auth] = auth_self
with patch("routers.profiles.profile_document", return_value=payload) as pd_mock:
r = client.get("/api/profiles/42", headers={"X-Auth-Token": "dummy"})
assert r.status_code == 200
assert r.json() == payload
pd_mock.assert_called_once_with("42")
def test_get_profile_ok_same_string_session_id(client: TestClient) -> None:
"""Session liefert profile_id als String (Backward-Compatibility)."""
payload = {"id": 7, "name": "S"}
def auth_self_str() -> dict:
return {"profile_id": "7", "role": "user"}
app.dependency_overrides[require_auth] = auth_self_str
with patch("routers.profiles.profile_document", return_value=payload):
r = client.get("/api/profiles/7", headers={"X-Auth-Token": "dummy"})
assert r.status_code == 200
@pytest.mark.parametrize("admin_role", ["admin", "superadmin"])
def test_get_profile_ok_platform_admin_views_other(client: TestClient, admin_role: str) -> None:
payload = {"id": 99, "name": "Other"}
def auth_admin() -> dict:
return {"profile_id": 1, "role": admin_role}
app.dependency_overrides[require_auth] = auth_admin
with patch("routers.profiles.profile_document", return_value=payload) as pd_mock:
r = client.get("/api/profiles/99", headers={"X-Auth-Token": "dummy"})
assert r.status_code == 200
assert r.json() == payload
pd_mock.assert_called_once_with("99")
def test_delete_profile_forbidden_non_admin(client: TestClient) -> None:
def auth_trainer() -> dict:
return {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[require_auth] = auth_trainer
with patch("routers.profiles.get_db") as mock_get_db:
r = client.delete("/api/profiles/1", headers={"X-Auth-Token": "dummy"})
assert r.status_code == 403
mock_get_db.assert_not_called()
def test_delete_profile_admin_last_profile_protected(client: TestClient) -> None:
mock_conn = MagicMock()
mock_cm = MagicMock()
mock_cm.__enter__.return_value = mock_conn
mock_cm.__exit__.return_value = False
mock_cur = MagicMock()
mock_cur.fetchone.return_value = {"count": 1}
app.dependency_overrides[require_auth] = lambda: {"profile_id": 99, "role": "admin"}
with patch("routers.profiles.get_db", return_value=mock_cm), patch(
"routers.profiles.get_cursor", return_value=mock_cur
):
r = client.delete("/api/profiles/5", headers={"X-Auth-Token": "dummy"})
assert r.status_code == 400
def test_delete_profile_admin_ok_when_multiple_profiles(client: TestClient) -> None:
mock_conn = MagicMock()
mock_cm = MagicMock()
mock_cm.__enter__.return_value = mock_conn
mock_cm.__exit__.return_value = False
mock_cur = MagicMock()
mock_cur.fetchone.return_value = {"count": 4}
app.dependency_overrides[require_auth] = lambda: {"profile_id": 99, "role": "superadmin"}
with patch("routers.profiles.get_db", return_value=mock_cm), patch(
"routers.profiles.get_cursor", return_value=mock_cur
):
r = client.delete("/api/profiles/12", headers={"X-Auth-Token": "dummy"})
assert r.status_code == 200
assert r.json() == {"ok": True}
calls = mock_cur.execute.call_args_list
assert any(
args and "DELETE FROM profiles" in str(args[0][0]) for args in calls
)
def test_create_profile_forbidden_non_admin(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
with patch("routers.profiles.get_db") as mock_get_db:
r = client.post(
"/api/profiles",
json={"name": "Neu", "email": "neu@example.com"},
headers={"X-Auth-Token": "dummy"},
)
assert r.status_code == 403
mock_get_db.assert_not_called()
def test_create_profile_admin_duplicate_email(client: TestClient) -> None:
mock_cm = MagicMock()
mock_conn = MagicMock()
mock_cm.__enter__.return_value = mock_conn
mock_cm.__exit__.return_value = False
mock_cur = MagicMock()
mock_cur.fetchone.return_value = {"id": 99}
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "admin"}
with patch("routers.profiles.get_db", return_value=mock_cm), patch(
"routers.profiles.get_cursor", return_value=mock_cur
), patch("routers.profiles.hash_pin", return_value="hashed"):
r = client.post(
"/api/profiles",
json={"name": "Dup", "email": "dup@example.com"},
headers={"X-Auth-Token": "dummy"},
)
assert r.status_code == 409
def test_create_profile_admin_success(client: TestClient) -> None:
mock_cm = MagicMock()
mock_conn = MagicMock()
mock_cm.__enter__.return_value = mock_conn
mock_cm.__exit__.return_value = False
mock_cur = MagicMock()
mock_cur.fetchone.side_effect = [None, {"id": 501}]
doc = {"id": 501, "name": "Nu User", "email": "nu@example.com"}
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "superadmin"}
with patch("routers.profiles.get_db", return_value=mock_cm), patch(
"routers.profiles.get_cursor", return_value=mock_cur
), patch("routers.profiles.profile_document", return_value=doc), patch(
"routers.profiles.hash_pin", return_value="hashed"
):
r = client.post(
"/api/profiles",
json={"name": "Nu User", "email": "nu@example.com"},
headers={"X-Auth-Token": "dummy"},
)
assert r.status_code == 200
assert r.json() == doc
insert_calls = [
c.args[0] for c in mock_cur.execute.call_args_list if c.args and "INSERT INTO profiles" in str(c.args[0])
]
assert len(insert_calls) >= 1
+126
View File
@@ -0,0 +1,126 @@
"""
Sicherheits-Regression für Release-Konfiguration (OpenAPI, Health-Ready, Legacy-Routen).
Läuft ohne PostgreSQL, wo möglich (TestClient + Subprocess mit frischem Import).
CI: scripts/security_release_checks.py
"""
from __future__ import annotations
import os
import subprocess
import sys
from pathlib import Path
from unittest.mock import patch
import pytest
from fastapi.testclient import TestClient
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
from auth import require_auth
from main import app
BACKEND_ROOT = Path(__file__).resolve().parents[1]
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
@pytest.fixture(autouse=True)
def _clear_auth_override():
yield
app.dependency_overrides.pop(require_auth, None)
def test_legacy_get_profile_uses_session_only(client: TestClient) -> None:
"""SEC-01: /api/profile darf nur das Session-Profil liefern."""
def auth_user() -> dict:
return {"profile_id": 901, "role": "trainer"}
app.dependency_overrides[require_auth] = auth_user
with patch("routers.profiles.profile_document") as pd_mock:
pd_mock.return_value = {"id": 901, "name": "T"}
r = client.get("/api/profile", headers={"X-Auth-Token": "dummy"})
assert r.status_code == 200
pd_mock.assert_called_once_with("901")
def _run_fresh_import_int(code: str, env: dict) -> subprocess.CompletedProcess:
merged = {**os.environ, **env, "SKIP_DB_MIGRATE": "1"}
return subprocess.run(
[sys.executable, "-c", code],
cwd=str(BACKEND_ROOT),
env=merged,
capture_output=True,
text=True,
check=False,
)
@pytest.mark.parametrize(
"extra_env, expect_openapi",
[
({"ENVIRONMENT": "development"}, True),
({"ENVIRONMENT": "production"}, False),
({"ENVIRONMENT": "production", "PUBLIC_OPENAPI": "true"}, True),
],
)
def test_openapi_urls_match_environment(extra_env: dict, expect_openapi: bool) -> None:
snippet = f"""
from main import app
assert (app.openapi_url is not None) == {expect_openapi}
assert (app.docs_url is not None) == {expect_openapi}
"""
proc = _run_fresh_import_int(snippet, extra_env)
assert proc.returncode == 0, proc.stderr + proc.stdout
def test_health_ready_minimal_body_in_production() -> None:
snippet = """
from fastapi.testclient import TestClient
from main import app
c = TestClient(app)
r = c.get("/api/health/ready")
r.raise_for_status()
j = r.json()
assert "tables" not in j
assert "detail" not in j
assert "schema_migrations_count" not in j
assert "status" in j and "database" in j and "schema_complete" in j
"""
proc = _run_fresh_import_int(
snippet,
{"ENVIRONMENT": "production"},
)
assert proc.returncode == 0, proc.stderr + proc.stdout
def test_health_ready_full_detail_when_flag_in_production() -> None:
snippet = """
from fastapi.testclient import TestClient
from main import app
c = TestClient(app)
r = c.get("/api/health/ready")
r.raise_for_status()
j = r.json()
assert "tables" in j
assert "schema_migrations_count" in j
"""
proc = _run_fresh_import_int(
snippet,
{"ENVIRONMENT": "production", "HEALTH_READY_PUBLIC_DETAIL": "1"},
)
assert proc.returncode == 0, proc.stderr + proc.stdout
def test_api_attachments_x_content_type_options_nosniff(client: TestClient) -> None:
"""Globales Middleware: keine MIME-Sniffing-Heuristik für API/Health."""
r = client.get("/health")
assert r.status_code == 200
assert r.headers.get("x-content-type-options") == "nosniff"
r2 = client.get("/api/version")
assert r2.status_code == 200
assert r2.headers.get("x-content-type-options") == "nosniff"
@@ -0,0 +1,17 @@
"""Unit-Tests ohne DB: Zusammenführung Session-Co vs. Gruppe."""
import pytest
from routers.training_planning import effective_co_trainer_profile_ids_for_merge
@pytest.mark.parametrize(
"unit_side,group_side,expected",
[
(None, [10, 22], [10, 22]),
(None, None, []),
([], [10, 22], []),
([7, "8", 7], None, [7, 8]),
],
)
def test_effective_co_trainer_profile_ids_for_merge(unit_side, group_side, expected):
assert effective_co_trainer_profile_ids_for_merge(unit_side, group_side) == expected
+289 -7
View File
@@ -1,22 +1,24 @@
# Shinkan Jinkendo Version Information
APP_VERSION = "0.8.29"
BUILD_DATE = "2026-05-05"
DB_SCHEMA_VERSION = "20260505041"
APP_VERSION = "0.8.65"
BUILD_DATE = "2026-05-08"
DB_SCHEMA_VERSION = "20260508049"
MODULE_VERSIONS = {
"auth": "1.2.1", # Login-Rate-Limit 30/minute pro IP (vorher 5/minute)
"profiles": "1.4.1", # PUT /profiles*, Legacy /profile: Depends(get_tenant_context); profile_document für internes Laden
"tenant_context": "1.0.3", # pytest: backend/tests/test_access_layer.py (Visibility-SQL, Header)
"profiles": "1.7.0", # exercise_list_prefs JSONB (Standard Übungsfilter); Patch via ProfileUpdate + Json()
"tenant_context": "1.0.5", # Plattform-Admin: effective_club ohne Header aus Profil active_club_id wenn Verein existiert
"clubs": "0.4.1", # Alle geschützten Endpoints Depends(get_tenant_context); profile_id/role aus TenantContext
"club_memberships": "1.0.1", # Depends(get_tenant_context)
"club_join_requests": "1.0.1", # Depends(get_tenant_context)
"admin_users": "1.0.0", # GET /api/admin/users
"platform_media_storage": "1.0.0", # GET/PUT /api/admin/platform-media-storage (Superadmin-Pfad unter MEDIA_ROOT)
"media_assets": "1.12.1", # official: nur Superadmin Lifecycle/PATCH; UI Lesemodus; Superadmin Upload-Verein = aktiv
"groups": "0.1.0",
"skills": "0.1.0",
"methods": "0.1.0",
"exercises": "2.7.0", # PATCH /exercises/bulk-metadata — Massenänderung Sichtbarkeit/Status
"training_units": "0.1.0",
"exercises": "2.19.1", # Verein: PUT default_club_media_copyright + Prompt beim Speichern (fehlende File-Asset-Copyrights)
"training_units": "0.2.0",
"training_programs": "0.1.0",
"planning": "0.8.1", # Vorlagen Leseprüfung library_content_visible_to_profile
"import_wiki": "1.0.0",
@@ -27,6 +29,286 @@ MODULE_VERSIONS = {
}
CHANGELOG = [
{
"version": "0.8.65",
"date": "2026-05-08",
"changes": [
"Übung auf Verein: fehlende Copyrights an Datei-Assets wieder per Bestätigung + Eingabe beim Speichern setzbar (PUT default_club_media_copyright; Bulk-PATCH ebenfalls)",
],
},
{
"version": "0.8.64",
"date": "2026-05-08",
"changes": [
"Übung bearbeiten: Auto-Scroll beim Drag von Medien zu Textfeldern; Medien-Kacheln mehrspaltig; Sektion/Ablauf-Zuordnung an Medien entfernt (nur noch Titel bearbeiten); Picker: Video-Vorschau-Frame; Katalogvorschau ohne Anhangs-Medienliste; Ansehen mit Speichern-Hinweis + Zurück zur Bearbeitung von der Ansicht",
],
},
{
"version": "0.8.63",
"date": "2026-05-08",
"changes": [
"RTE/Übung Medien: Picker-Thumbnails; Dateiauswahl-Anzeige; bereits verknüpfte Archive-Medien ins Fließtext einfügen; Platzhalter-Caption data-shinkan-exercise-media-caption + Caret nach ZWSP; Lesemodus: Medienliste nur für nicht eingebettete Anhänge; bearbeiten: kompakte Kacheln mit Drag-and-Drop in Textfelder, Upload unter Medien entfällt",
],
},
{
"version": "0.8.62",
"date": "2026-05-08",
"changes": [
"RTE Inline-Medien: Modals Mediathek+Hochladen + „Embed im Text“; Darstellungsgröße small|medium|full (data-shinkan-exercise-media-size); Lesemodus begrenzt Bild/Video-Breite",
],
},
{
"version": "0.8.61",
"date": "2026-05-08",
"changes": [
"RTE „Bild/Video im Text“: eingebaute Hilfe (Caret + insertHTML/Fallback); sichtbarer 📎-Chip im Editor; Hinweis bei fehlgeschlagener Einfügung/Prompt-ID",
],
},
{
"version": "0.8.60",
"date": "2026-05-08",
"changes": [
"Inline-Medien im Übungs-Fließtext (MEDIA_SPEC §11): {{exerciseMedia:id}} → kanonisches span; nur exercise_media dieser Übung; create ohne Platzhalter",
"Frontend: ExerciseRichTextBlock mit Allowlist-Sanitize + Embed; Toolbar „Bild/Video im Text“ im RichTextEditor wenn Medien an der Übung; Detail/Katalog/Liste konsistent",
],
},
{
"version": "0.8.59",
"date": "2026-05-07",
"changes": [
"Aktiver Verein: Backend resolve_tenant_context für Plattform-Admin ohne X-Active-Club-Id nutzt gespeichertes active_club_id wenn der Verein existiert (kein effective=null nach hartem Reload mehr)",
"Frontend: Nach Vereinswechsel Profil neu laden; Dropdown-Wert aus effective_club_id / active_club_id / LocalStorage abgestimmt (getResolvedActiveClubIdForUi)",
],
},
{
"version": "0.8.58",
"date": "2026-05-07",
"changes": [
"Medienbibliothek offiziell: Ändern/Lifecycle nur Superadmin (nicht Plattform-Admin); Bearbeiten-Dialog für andere nur Lesemodus; Superadmin: Vereinsauswahl beim Archiv-Upload folgt aktiv/gesetzt effective_club_id",
],
},
{
"version": "0.8.57",
"date": "2026-05-07",
"changes": [
"Governance: visibility=official nur noch Superadmin (nicht Plattform-Admin)",
"Medienarchiv: private Uploads als Plattform-Admin erfordern explizites club_id; gleiche Ordnerstruktur wie „Verein“, private Kopien mit .u{Profil} vor Dateiendung",
"Übung visibility=Verein: angebundene Archiv-Dateien müssen aktiv sein und Copyright (≥3 Zeichen) haben; UI- und API-Fehlercodes CLUB_MEDIA_*",
"Frontend: „Offiziell“ nur Superadmin (Bibliothek, Übungsformular, Bulk-Sichtbarkeit, Progressionsgraphen)",
],
},
{
"version": "0.8.56",
"date": "2026-05-07",
"changes": [
"Medienbibliothek: Vereinsmedien unter library/{aus Name abgeleitet}-c{club_id}/ statt festem library/club/c{id}/; Sonderzeichen/Umlaute zu sicheren Ordnernamen; fehlender Name → verein-c{id}; Governance-Umzug liest aktuellen Vereinsnamen aus DB",
],
},
{
"version": "0.8.55",
"date": "2026-05-07",
"changes": [
"Medienbibliothek: Speicherpfad library/* mit Medientyp-Unterordnern (image, video, pdf, other) vor SHA-Dateinamen; Umzug bei Governance-PATCH nutzt mime_type aus DB",
],
},
{
"version": "0.8.54",
"date": "2026-05-08",
"changes": [
"Medienpfade: vereinsgeteilt (club) direkt unter library/club/c{id}/; private unter library/club/c{id}/u{profile}/ (kein Ordner „private“/„shared“); Dedupe private inkl. uploaded_by_profile_id",
],
},
{
"version": "0.8.53",
"date": "2026-05-08",
"changes": [
"Medienablage vereinsbezogen: private → library/club/c{id}/private, Vereinssichtbarkeit → …/shared, official unverändert; private Archiv-Upload: club_id oder X-Active-Club-Id; DB club_id bei private gesetzt; PATCH/Bulk: club_id für private nicht mehr blind auf NULL",
],
},
{
"version": "0.8.52",
"date": "2026-05-08",
"changes": [
"Neue lokale media_assets: hierarchische library/* Pfade; Dedupe nach sha+visibility+club_id; bei PATCH/Bulk-Patch Sichtbarkeit/Verein: Datei umziehen, exercise_media.file_path aktualisieren (Details siehe 0.8.53)",
],
},
{
"version": "0.8.51",
"date": "2026-05-07",
"changes": [
"Medienbibliothek GET: Verknüpfung zu Trainingseinheiten nur wenn Tabelle training_unit_exercises existiert (ältere/kaputte Schemas → keine 500, Einheiten-Liste leer)",
],
},
{
"version": "0.8.50",
"date": "2026-05-07",
"changes": [
"Medienbibliothek: DB 046 media_assets.tags (GIN); GET filter media_kind, club_id (Superadmin), uploaded_by; Suche über Copyright & Tags; Antwort usage exercises + training_units; PATCH/Bulk tags; UI volle Breite, Filterleiste, ©-Symbol auf Kacheln, Links zu Übungen/Planung, gleiche Sichtbarkeits-/Status-Symbole wie Übungsliste",
],
},
{
"version": "0.8.49",
"date": "2026-05-07",
"changes": [
"Medienbibliothek UI: Kacheln/Liste, Modal Bearbeiten, Video-First-Frame-Thumbs, Mobile/Safe-Area, Bulk; API: permissions pro Zeile, Uploader/Verein für Admin, PATCH Sichtbarkeit+Bezeichner, trash_soft nur Trainer-Eigenes-Privat / Vereinsorga / Plattform; purge nur Superadmin; superadmin_force_lifecycle + hard_delete; bulk-lifecycle, bulk-patch",
],
},
{
"version": "0.8.48",
"date": "2026-05-07",
"changes": [
"Medienbibliothek: GET /api/media-assets mit lifecycle (active|trash_soft|trash_hidden|all), copyright_notice in Liste; PATCH /api/media-assets/{id} (Copyright); GET …/file für Papierkorb wenn Lifecycle-Recht; Frontend /media + Admin-Nav + Link Übungsformular",
],
},
{
"version": "0.8.47",
"date": "2026-05-07",
"changes": [
"Übung „offiziell“ (§4.2): angehängte Datei-Assets müssen aktiv sein; Sichtbarkeit/Copyright per Bestätigung anheben; PUT /api/exercises/{id} + PATCH bulk-metadata: Felder promote_attached_media_for_official, default_official_media_copyright; Frontend Bestätigungsdialog",
],
},
{
"version": "0.8.46",
"date": "2026-05-07",
"changes": [
"Übung Medien-Upload: bei 409-Konflikt (Papierkorb-Dedupe) logger.warning mit exercise_id, profile_id, media_asset_id, lifecycle, visibility, club_id, sha256_prefix, Dateinamen",
"ExerciseFormPage: erklärende Medien-Hinweistexte in GUI entfernt (Kurzbeschreibung + Archiv-Dialog)",
],
},
{
"version": "0.8.45",
"date": "2026-05-07",
"changes": [
"Upload Übungsmedien: gleicher Inhalt (SHA-256) wie Papierkorb-Asset → 409 MEDIA_ASSET_IN_TRASH statt DB-Fehler; Lifecycle action reactivate (trash_soft/hidden → active)",
"Frontend: Dialog Reaktivieren + Verknüpfen; uploadExerciseMedia wertet strukturiertes 409 aus",
],
},
{
"version": "0.8.44",
"date": "2026-05-07",
"changes": [
"DELETE /api/exercises/{id}/media/{mid}: entfernt nur exercise_media; keine Datei-/media_assets-Löschung; Response orphan_media_asset_id wenn letzte Referenz",
"Übung bearbeiten: Video-Kachel (Erstframe), Dateiname; Papierkorb-Schalter entfernt; „Aus Übung entfernen“ + optional Papierkorb bei Waise",
],
},
{
"version": "0.8.43",
"date": "2026-05-07",
"changes": [
"Medienarchiv: GET /api/media-assets (Suche, nur aktive Assets, Bibliotheks-Sichtbarkeit); GET /api/media-assets/{id}/file (Thumbnails/Vorschau, ssetoken)",
"Übungen: POST /api/exercises/{id}/media/from-asset — bestehendes Archiv-Medium verknüpfen ohne Upload-Duplikat",
"Frontend Übung bearbeiten: „Aus Archiv verknüpfen…“, Medienvorschau-Modal, Kachel-Thumbnails in der Medienliste",
],
},
{
"version": "0.8.42",
"date": "2026-05-07",
"changes": [
"Medien-Papierkorb: POST /api/media-assets/{id}/lifecycle (trash_soft, trash_hidden, recover, purge); Retention-Job scripts/media_retention_job.py",
"Übungen: GET-Detail inkl. asset_lifecycle_state; Bearbeitungsrechte Erweiterung (Vereinsplanung); Frontend Übung bearbeiten: Reihenfolge, Papierkorb-Actions; Detail/Katalog: trash_hidden ausgeblendet, Hinweis trash_soft",
"Fix: ExerciseDetailPage zeigt „Hinweise für Trainer“ wieder an",
],
},
{
"version": "0.8.41",
"date": "2026-05-07",
"changes": [
"DB 045: media_assets, exercise_media.media_asset_id, platform_media_storage; Migration bestehender Medien; Upload-Dedupe pro sha256+visibility+club_id",
"Effektives Medien-Verzeichnis: MEDIA_ROOT + Superadmin local_relative_root (GET/PUT /api/admin/platform-media-storage)",
"Neue Uploads: storage_key exercises/{sha256}{ext}; Download/Delete nutzen media_assets",
"api.js: getPlatformMediaStorage, putPlatformMediaStorage",
],
},
{
"version": "0.8.40",
"date": "2026-05-06",
"changes": [
"Übungen Liste: Fokusfilter mit UND-+ (must_include) und UND-− (must_exclude), nur ohne Fokusbereich (focus_only_without); Frontend Dropdown + Mit / − Ohne",
],
},
{
"version": "0.8.39",
"date": "2026-05-06",
"changes": [
"Übungen DELETE: Nur eigene private / Vereinsadmin für Vereins-Übungen / Plattform für globale; keine harte Löschung bei Verwendung in Blöcken, Plan-Abschnitten oder Progressionskanten (409 → archivieren)",
"GET /api/exercises: Negativfilter (visibility_exclude_any, status_exclude_any), exclude_without_focus, include_archived; archivierte standardmäßig ausgeblendet",
"Profile exercise_list_prefs (JSONB, Migration 043): gespeicherte Standardfilter; Frontend Übungsliste Filterdialog + „Als Standard speichern“",
"Übungspicker: gleiche Negativfilter; Planung lädt archivierte Übungen immer mit (bestehende Zuordnungen)",
"pytest: tests/test_exercises_delete_policy.py",
],
},
{
"version": "0.8.38",
"date": "2026-05-06",
"changes": [
"Trainingsplanung: Vereinsadmins sehen alle Einheiten bei club_id-/Gruppenliste; GET/PUT Einheit & Löschen mit can_manage_club_org",
"Planung UI: „Trainer zuweisen“ in Vereins-Ansicht (Liste + Kalender) + eigener Modal; Mitgliederverzeichnis für Vereinsorganisation",
],
},
{
"version": "0.8.37",
"date": "2026-05-05",
"changes": [
"DB 042: training_units.assistant_trainer_profile_ids (Co-Trainer-Zuweisung je Termin; NULL = Gruppen-Standard)",
"Trainingseinheiten: POST/PUT lead_trainer_profile_id & assistant_trainer_profile_ids; Leitung für Vereinsmitglieder (Vertretung); GET-Listen inkl. Zuweisung für Sichtbarkeit/assigned_to_me",
"Frontend Trainingsplanung: Leitung/Co-Trainer pro Einheit; Dashboard-Text",
"pytest: tests/test_training_unit_assignments.py",
],
},
{
"version": "0.8.36",
"date": "2026-05-05",
"changes": [
"POST /api/profiles: nur Plattform-Admin; Anlage schema-konform (SERIAL, E-Mail, temporärer PIN-Hash); ProfileCreate mit Pflichtfeldern name + email",
"pytest: POST-Szenarien in test_profiles_read_access.py",
],
},
{
"version": "0.8.35",
"date": "2026-05-05",
"changes": [
"DELETE /api/profiles/{pid}: nur Plattform-Admin (403 sonst); Unit-Tests mit gemockter DB",
],
},
{
"version": "0.8.34",
"date": "2026-05-05",
"changes": [
"GET /api/profiles/{pid}: Zugriff nur eigenes Profil oder Plattform-Admin (403 sonst); Unit-Tests ohne DB; zwei Integrationstests mit PostgreSQL",
"Integration: zwei zusätzliche Profil-Lese-Tests in test_access_layer_integration",
],
},
{
"version": "0.8.33",
"date": "2026-05-05",
"changes": [
"CI pytest-backend wie Mitai-Jinkendo: docker compose exec backend (deployte Stacks shinkan / shinkan-dev); keine Runner-Python/Postgres-Service",
"pytest.ini: Marker smoke/slow, addopts/-q wie Schwesterprojekt; CI: -m \"not slow\", ACCESS_LAYER_STRICT + Integration im Container",
],
},
{
"version": "0.8.32",
"date": "2026-05-05",
"changes": [
"CI pytest-backend: kein setup-python — venv aus System-python3 (arm64/Debian Self-Host, Raspi)",
],
},
{
"version": "0.8.31",
"date": "2026-05-05",
"changes": [
"CI (Gitea): Job pytest-backend — Checkout, Postgres-Service, run_migrations, pytest (+ ACCESS_LAYER_INTEGRATION), ACCESS_LAYER_STRICT auf Router-Hinweis-Script",
"Workflow test.yml: pull_request auf main/develop zusätzlich zu push",
],
},
{
"version": "0.8.30",
"date": "2026-05-05",
"changes": [
"pytest: optionale PostgreSQL-Integration tests/test_access_layer_integration.py (Cross-Verein Übungen Liste/Detail; ACCESS_LAYER_INTEGRATION=1)",
"pytest.ini: Marker „integration“",
],
},
{
"version": "0.8.29",
"date": "2026-05-05",
+4 -3
View File
@@ -1,5 +1,6 @@
# Keine festen container_name — Compose-Namen haben Projektprefix (<projekt>-postgres-1).
# Gleiche Variablennamen wie docker-compose.yml; andere Werte in einer eigenen .env neben dieser Datei.
# Medien: In .env SHINKAN_MEDIA_HOST (Host-Pfad) und optional MEDIA_ROOT (Container-Pfad) setzen.
# Default Host /shinkan-media/dev — Verzeichnis ggf. anlegen oder Compose legt es an.
services:
postgres:
@@ -43,8 +44,9 @@ services:
MEDIAWIKI_CATEGORY_SKILLS: "${MEDIAWIKI_CATEGORY_SKILLS:-Fähigkeitsbeschreibung}"
MEDIAWIKI_CATEGORY_METHODS: "${MEDIAWIKI_CATEGORY_METHODS:-Methodenbeschreibung}"
MEDIAWIKI_CATEGORY_MODELS: "${MEDIAWIKI_CATEGORY_MODELS:-Reifegradmodelle}"
MEDIA_ROOT: "${MEDIA_ROOT:-/app/media}"
volumes:
- dev-shinkan-media:/app/media
- ${SHINKAN_MEDIA_HOST:-/shinkan-media/dev}:${MEDIA_ROOT:-/app/media}
ports:
- "8098:8000"
depends_on:
@@ -70,7 +72,6 @@ services:
volumes:
dev-shinkan-db-data:
dev-shinkan-media:
networks:
dev-shinkan-network:
+7 -3
View File
@@ -8,8 +8,9 @@ services:
POSTGRES_PASSWORD: ${DB_PASSWORD}
volumes:
- shinkan-db-data:/var/lib/postgresql/data
# Nur localhost: DB nicht im LAN exponieren (Beta/Prod). Entferne 127.0.0.1: nur wenn du bewusst remote willst.
ports:
- "5434:5432"
- "127.0.0.1:5434:5432"
restart: unless-stopped
networks:
- shinkan-network
@@ -51,8 +52,12 @@ services:
MEDIAWIKI_CATEGORY_SKILLS: "${MEDIAWIKI_CATEGORY_SKILLS:-Fähigkeitsbeschreibung}"
MEDIAWIKI_CATEGORY_METHODS: "${MEDIAWIKI_CATEGORY_METHODS:-Methodenbeschreibung}"
MEDIAWIKI_CATEGORY_MODELS: "${MEDIAWIKI_CATEGORY_MODELS:-Reifegradmodelle}"
# Medien: Host-Pfad SHINKAN_MEDIA_HOST (in .env), Ziel im Container MEDIA_ROOT.
MEDIA_ROOT: "${MEDIA_ROOT:-/app/media}"
# Bind-Mount: Verzeichnis muss auf dem Host existieren und chown für den Docker-Daemon
# zulassen (lokale Platte). Bei NFS/SMB oft "chown … operation not permitted" → anderen Pfad.
volumes:
- shinkan-media:/app/media
- ${SHINKAN_MEDIA_HOST:-/shinkan-media}:${MEDIA_ROOT:-/app/media}
ports:
- "8003:8000"
depends_on:
@@ -78,7 +83,6 @@ services:
volumes:
shinkan-db-data:
shinkan-media:
networks:
shinkan-network:
+75 -34
View File
@@ -1,9 +1,9 @@
# Shinkan Jinkendo – Entwicklungsstand & Handover
**Stand:** 2026-05-05
**App-Version / DB-Schema:** siehe `backend/version.py`
**Stand:** 2026-05-07
**App-Version / DB-Schema:** App **0.8.59**, DB-Schema siehe `backend/version.py` (`DB_SCHEMA_VERSION`)
Diese Datei ist die **Einstiegs-Doku für neue Chat-Sessions**: Anforderungen im Detail stehen in `.claude/docs/` (siehe unten); hier der **implementierte Stand** und **nächste Baustellen**.
Diese Datei ist die **Einstiegs-Doku für neue Chat-Sessions**: Anforderungen im Detail stehen in `.claude/docs/` (siehe unten); hier der **implementierte Stand**, **Medien-Meilenstein** und **sinnvolle nächste Schritte**.
### Produktion: `relation … does not exist` (z. B. `skill_main_categories`)
@@ -21,11 +21,17 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
| Thema | Pfad |
|--------|------|
| Projekt-Setup, Domain grob | `.claude/docs/working/SHINKAN_PROJECT_SETUP.md` |
| Projekt-Status (Skills, Wiki, Stats) | `.claude/docs/PROJECT_STATUS.md` |
| **Projekt-Status (aktuell)** | `.claude/docs/PROJECT_STATUS.md` |
| **Medien-Archiv, Lifecycle, Inline-Plan (§11)** | `.claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` |
| Übungen: API, DB, Architektur, Routing | `.claude/docs/technical/EXERCISES_API_SPEC.md`, `EXERCISES_DATABASE_FINAL.md`, `EXERCISES_ARCHITECTURE.md`, `EXERCISES_FRONTEND_ROUTING.md` |
| Media / Upload | `.claude/docs/technical/MEDIA_UPLOAD_SPEC.md` |
| Media / Upload-Limits / Embed | `.claude/docs/technical/MEDIA_UPLOAD_SPEC.md` |
| MediaWiki-Import | `.claude/docs/technical/MEDIAWIKI_IMPORT_SPEC.md` |
| Rahmenprogramm · Planung (`training_units` Blueprints), Progressionsgraph | `.claude/docs/technical/TRAINING_FRAMEWORK_SPEC.md`; Überblick DB → `.claude/docs/technical/DATABASE_SCHEMA.md`; Domäne → `.claude/docs/functional/DOMAIN_MODEL.md` |
| Zugriffsschicht, Mandant, Governance | `.claude/docs/technical/ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` |
| Tenant-Endpoints (Audit) | `.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md` |
| Rahmenprogramm · Planung | `.claude/docs/technical/TRAINING_FRAMEWORK_SPEC.md` |
| Überblick DB | `.claude/docs/technical/DATABASE_SCHEMA.md` |
| Domäne | `.claude/docs/functional/DOMAIN_MODEL.md` |
| **Lieferliste inkl. Medien** | `.claude/docs/library/FEATURES_DELIVERED_2026-Q2.md` §12 |
---
@@ -36,73 +42,108 @@ Das Schema ist gegenüber dem Code zurück: Migration **`022_skills_schema_compl
- **`maturity_models`**, **`model_levels`**, **`model_skills`**, **`model_skill_levels`**: Matrix-Inhalt pro Modell.
- **Kontext am Modell (Legacy, M:N):** `maturity_model_focus_areas`, `maturity_model_style_directions`, `maturity_model_target_groups` (Migration 025).
- **Hierarchische Kontext-Zuordnung (Resolve):** `maturity_model_context_bindings` mit optional `style_direction_id`, `training_type_id` (Migration 026, 027).
- **027:** u. a. `Fokus + Trainingsstil` ohne Stilrichtung (partielle Unique-Indizes).
- **027:** u. a. `Fokus + Trainingsstil` ohne Stilrichtung (partielle Unique-Indizes).
### 2.2 Resolve-Logik (Backend)
- **`GET /api/maturity-models/resolve`**: Bindings zum Fokus, die zur Anfrage passen; Merge nach Spezifität (weniger spezifisch zuerst); spezifischere Zeilen überschreiben Zelltexte.
- **Matching:** Gesetzte Spalten einer Binding-Zeile müssen mit der Anfrage übereinstimmen; `NULL` in der Zeile = Wildcard (z. B. Fokus+Trainingsstil gilt für alle Stilrichtungen, aber nur für diesen Trainingsstil).
- **Legacy-Fallback:** Nur wenn für den **Fokus keine einzige** Zeile in `maturity_model_context_bindings` existiert. Sonst bei fehlendem Treffer **`null`** (kein stilles Legacy mit falschem Trainingsstil).
- **Matching:** Gesetzte Spalten einer Binding-Zeile müssen mit der Anfrage übereinstimmen; `NULL` in der Zeile = Wildcard.
- **Legacy-Fallback:** Nur wenn für den **Fokus keine einzige** Zeile in `maturity_model_context_bindings` existiert.
### 2.3 Export / Import (einzelnes Modell & aufgelöst)
- **`GET /api/maturity-models/{id}/export`**: `shinkan.maturity_model.v1` inkl. `context_bindings_for_model` (IDs).
- **`GET /api/maturity-models/export-resolved`**: `shinkan.maturity_matrix_resolved.v1` (Query: `focus_area_id`, optional `style_direction_id`, `training_type_id`).
- **`POST /api/maturity-models/import`**: `create` | `replace`, optional `import_bindings` (nur bei `maturity_model.v1`).
- **`POST /api/maturity-models/import`**: `create` | `replace`, optional `import_bindings`.
### 2.4 Komplett-Stack Test → Prod
- **`GET /api/admin/matrix-stack/export`**: `shinkan.matrix_stack.v1` – Katalog (`skill_main_categories`, `skill_categories`, `skills`, `skill_level_definitions`) + alle Reifegradmodelle + Bindings mit **Namen** (Fokus/Stil/Trainingsstil).
- **`POST /api/admin/matrix-stack/import`**: Upsert Katalog per Slug; Skills per Kategorie+Name; Modelle neu anlegen; Bindings per Katalognamen. Optional **`replace_all_maturity_models`** + **`confirm_replace_all: "DELETE_MATURITY_STACK"`** (nur Superadmin).
- Router: `backend/routers/matrix_stack_bundle.py`, in `main.py` registriert.
- **`GET /api/admin/matrix-stack/export`**, **`POST /api/admin/matrix-stack/import`** — siehe `matrix_stack_bundle.py`.
### 2.5 Frontend (Admin)
- **`frontend/src/pages/AdminMaturityModelsPage.jsx`**: Tabs u. a. Katalog, Modelle, Kontext-Zuordnung, **Matrix-Ansicht und Export**.
- **`MaturityModelBindingsAdmin.jsx`**: Bindings CRUD, Erklärung Merge/Legacy.
- **`MaturityMatrixToolsAdmin.jsx`**: Kontext auflösen, hierarchische Matrix-Ansicht, Export einzelnes Modell / aufgelöst, Einzelmodell-Import; **Komplett-Stack** mit eigenem Export-Button und **eigenem Dateifeld für Stack-Import** (`POST /api/admin/matrix-stack/import`).
- **`frontend/src/utils/api.js`**: u. a. `exportMatrixStackBundle`, `importMatrixStackBundle`, Reifegrad-APIs.
- **`AdminMaturityModelsPage.jsx`**, **`MaturityModelBindingsAdmin.jsx`**, **`MaturityMatrixToolsAdmin.jsx`**; APIs in `api.js`.
---
## 3. Trainingsrahmenprogramm & Planungs‑Blueprint (kurz)
- **Migration 036:** Rahmenkopf nur Bibliothek (Kontext: Fokusbereich, Stilrichtung; M:N Trainingsarten/Zielgruppen); keine `plan_mode`/keine Kopf‑`group_id`.
- **Migration 037:** Pro Rahmen‑Slot eine **`training_units`‑Zeile mit `framework_slot_id`**; strukturierter Ablauf wie echte Einheiten (`training_unit_sections` / `training_unit_section_items`). Tabelle **`training_framework_slot_exercises`** entfällt.
- **API:** Rahmen unter **`/api/training-framework-programs`** (Slots liefern u. a. **`blueprint_training_unit_id`**, **`sections[]`**, **`exercises[]`**); Kalenderliste **`GET /api/training-units`** ohne Blueprints; Übernahme **`POST /api/training-units/from-framework-slot`**.
- **Code:** `backend/routers/training_framework_programs.py`, `training_planning.py`; Frontend **`TrainingFrameworkProgramEditPage.jsx`**; **`createTrainingUnitFromFrameworkSlot`** in `api.js`.
- **036 / 037:** Bibliotheks-Rahmen, Slot-Inhalt als **`training_units`** mit **`framework_slot_id`**; **`POST /api/training-units/from-framework-slot`**.
- **Code:** `training_framework_programs.py`, `training_planning.py`; Frontend **`TrainingFrameworkProgramEditPage.jsx`**, **`createTrainingUnitFromFrameworkSlot`** in `api.js`.
---
## 4. Stand: Übungen (Lücke für nächste Session)
## 4. Stand: Medien-Management (Ist, 2026-05-07)
**Ist (laut Projektdoku und aktuellem Produktziel):**
**Datenmodell (Kurz):**
- Backend: Übungen-CRUD, M:N, Suche, Blöcke, Medien-Struktur u. a. sind in `PROJECT_STATUS.md` als umgesetzt geführt; viele Übungen stammen aus **MediaWiki-Import** (Wiki-Tracking-Tabellen).
- **Soll / Nutzerfeedback:** In der Praxis fehlt oder ist unzureichend: **stabile Liste**, **gerenderte Detailansicht**, **Bearbeiten/Anlegen**, **Medien zuweisen/Upload** – konkrete Fehler (404, leere Liste, falsche Route) sind vor Ort zu verifizieren.
- **`media_assets`:** Physische oder logische Archiv-Datei (u. a. `sha256`, `visibility`, `club_id`, `lifecycle_state`, `copyright_notice`, Speicherpfad/`storage_key`, `tags` ab passender Migration).
- **`exercise_media`:** optional **`media_asset_id`**; weiterhin Embeds ohne Asset; Kontext/Sortierung/Titel wie bisher.
- **`platform_media_storage`:** Superadmin — relativer Unterpfad unter `MEDIA_ROOT`.
**Nächste Session sollte:**
**API (Auszug):**
1. Aktuelle Routen und Seiten prüfen (`App.jsx`, `EXERCISES_FRONTEND_ROUTING.md`).
2. `GET /api/exercises` (Filter, Auth) und eine Beispiel-Übung gegen die Dev-DB testen.
3. UI schrittweise: Liste → Detail → Formular → Medien (an Specs in `.claude/docs/technical/` ausrichten).
- **`GET /api/media-assets`**, Filter (Lifecycle, `media_kind`, Verein, Suche, Tags), Berechtigungen pro Zeile.
- **`PATCH /api/media-assets/{id}`** / Bulk-PATCH, **Lifecycle** (`POST …/lifecycle`, Bulk).
- **`GET …/media-assets/{id}/file`** (inkl. Kontext `ssetoken` wo vorgesehen).
- **`POST /api/exercises/{id}/media/from-asset`:** bestehendes Asset verknüpfen.
- Übungs-Uploads erzeugen/verknüpfen **`media_assets`**; Governance wie **`library_content_*`** / TenantContext.
**Frontend:**
- Route **`/media`** (Medienbibliothek): Kacheln/Liste, Filter, Copyright, Lifecycle-Actions (Rollen gemäß Spec; **`official`:** bearbeiten/Lifecycle im Wesentlichen **Superadmin**, andere Rollen **Lesemodus** im Bearbeiten-Dialog).
- Übungsformular: Archiv-Picker, Vorschau, Reaktivierung bei Dedupe-Konflikt (Papierkorb).
**Speicher & Pfade:**
- Struktur unter **`library/`** mit Vereinssegment (aus Vereinsname abgeleitet + `c{id}`), Unterordner nach Medienkind (`image`/`video`/`pdf`/`other`), Dateiname z. B. SHA-basiert — Details und Drift-Vermeidung in **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`**.
**Governance & Mandant:**
- **`visibility=official`** für Übungen: nur **Superadmin**; Medien **`official`:** Lifecycle/PATCH schwerpunktmäßig Superadmin (Plattform-Admin nicht gleich Superadmin).
- **Aktiver Verein:** `profiles.active_club_id`, Header **`X-Active-Club-Id`**, Response **`effective_club_id`** — nach **0.8.59** konsistent inkl. Plattform-Admin beim Reload (Backend **`tenant_context`**, Frontend **`getResolvedActiveClubIdForUi`** + Profil-Refresh nach Vereinswechsel).
---
## 5. Technische Referenz (kurz)
## 5. Geplant: Inline-Medienverlinkung (nicht umgesetzt)
**Ziel:** Mediendarstellung **innerhalb** von Fließtext-Feldern (Ablauf, Ziele, Trainerhinweise), konsistent mit derselben **`exercise_media`‑** bzw. Asset-Governance wie die Medienliste.
**Norm:** **`MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` §11** — u. a.:
- Verweis auf **`exercise_media.id`** (oder kanonisch übersetzte Markup-Syntax), **keine** zweite Sichtbarkeitslogik.
- **Ein** zentraler Render-/Sanitize-Pfad für Übungstexte; keine verstreuten „roh `dangerouslySetInnerHTML`“-Pfade.
- XSS/CSP: nur Allowlist-HTML und kontrollierte Player-Komponenten.
**Reihenfolge:** Archiv & aktuelle Governance gelten als Basis; Inline ist die **nächste** inhaltliche Ausbaustufe für Medien (siehe **`PROJECT_STATUS.md`** Nächste Schritte).
---
## 6. Nächste Session — sinnvolle Arbeitspakete
1. **Inline §11:** Syntax festlegen (z. B. `{{exerciseMedia:id}}` → kanonisches HTML), Server normalisieren bei Speichern, einen **`renderExerciseRichText()`**-Pfad im Frontend.
2. **Tests:** pytest für `media_assets`-Router (Leserechte, Lifecycle, `from-asset`); ggf. Snapshot der Pfad-Umzug-Logik.
3. **Retention:** Job-Dokumentation + Betrieb (ENV, Intervall); Dry-Run beschreiben.
4. **S3/Adapter:** Speicher-Abstraktion §7 — wenn Produkt es verlangt.
5. **Rahmen/UI:** Kalender „aus Rahmen übernehmen“ weiter anbinden (parallel, unabhängig von Medien).
---
## 7. Technische Referenz (kurz)
| Bereich | Einstieg |
|---------|----------|
| Backend API | `backend/main.py`; Router u. a. **`training_framework_programs.py`**, **`training_planning.py`**, `maturity_models.py`, `matrix_stack_bundle.py`, `exercises.py`, `catalogs.py`, `skills.py` |
| Migrationen | `backend/migrations/` (u. a. 024–027 Reifegrad/Bindings; **035–037** Rahmenprogramm / Slot‑Blueprint) |
| Backend API | `backend/main.py`; u. a. **`media_assets.py`**, **`exercises.py`**, **`profiles.py`**, **`training_framework_programs.py`**, `tenant_context.py` |
| Migrationen | `backend/migrations/` (040+ Mitgliedschaft/Governance; **045+** Medien-Stack) |
| Frontend API | `frontend/src/utils/api.js` |
| Aktiver Verein (UI) | `frontend/src/utils/activeClub.js`, `AuthContext.jsx` |
| Version / Changelog | `backend/version.py` |
---
## 6. Veraltete Hinweise
## 8. Veraltete Hinweise
Die Datei `.claude/docs/working/HANDOVER_NEXT_SESSION.md` (2026-04-22) ist **historisch**; für den aktuellen Stand gilt **`docs/HANDOVER.md`**.
`.claude/docs/working/HANDOVER_NEXT_SESSION.md` verweist auf **dieses** Dokument (`docs/HANDOVER.md`) als aktuelle Basis.
---
+24 -4
View File
@@ -4,13 +4,29 @@ server {
root /usr/share/nginx/html;
index index.html;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
# Docker-Embedded DNS: Hostname »backend« bei Container-Neustarts neu auflösen
# — verringert sporadische 502, wenn sich nur die Backend-Container-IP geändert hat.
resolver 127.0.0.11 valid=10s ipv6=off;
# Uploads (Übungsmedien) und API erreichen Clients unter derselben Host-URL wie die SPA —
# dafür muss Nginx zur FastAPI-Instanz im Compose-Netz weiterleiten.
client_max_body_size 64m;
# Uploads (Übungsmedien, Medienarchiv-Bulk) — Limit muss >= größte Einzeldatei und
# bei multipart ggf. Summe mehrerer Dateien sein (Backend praxis: bis 1024 MB Admin).
client_max_body_size 1024m;
# Medienbibliothek (React /media) — vor location ^~ /media/: sonst liefert ein Reload
# auf /media/ den FastAPI StaticFiles-Mount unter /media und der Browser zeigt {"detail":"Not Found"}.
location = /media {
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
try_files /index.html =404;
}
location = /media/ {
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
try_files /index.html =404;
}
location ^~ /api/ {
set $docker_backend_svc backend;
@@ -26,6 +42,8 @@ server {
}
location ^~ /media/ {
# Auslieferung Übungsdateien erfolgt geschützt über /api/exercises/.../media/.../file (?ssetoken).
# Optional: Backend mit ALLOW_PUBLIC_MEDIA_STATIC=1 → wieder /media/ ohne Auth.
set $docker_backend_svc backend;
proxy_pass http://$docker_backend_svc:8000$request_uri;
proxy_http_version 1.1;
@@ -42,8 +60,10 @@ server {
proxy_set_header Host $host;
}
# SPA routing - serve index.html for all routes
location / {
# Document-CSP für SPA/PWA — React nutzt häufig inline-styles; Mediendateien & API sind same-origin (Proxy).
# Bei separater API-Origin: connect-src hier erweitern oder nginx-Envsubst nutzen.
add_header Content-Security-Policy "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; media-src 'self' blob: data:; worker-src 'self' blob:; manifest-src 'self';" always;
try_files $uri $uri/ /index.html;
}
+71 -14
View File
@@ -9,16 +9,19 @@ import {
Outlet,
} from 'react-router-dom'
import { AuthProvider, useAuth } from './context/AuthContext'
import { OrgInboxProvider, useOrgInbox } from './context/OrgInboxContext'
import DesktopSidebar from './components/DesktopSidebar'
import { getMainNavItems } from './config/appNav'
import LoginPage from './pages/LoginPage'
import VerifyPage from './pages/VerifyPage'
import Dashboard from './pages/Dashboard'
import AccountSettingsPage from './pages/AccountSettingsPage'
import SettingsSystemInfoPage from './pages/SettingsSystemInfoPage'
import ExercisesListPage from './pages/ExercisesListPage'
import ExerciseDetailPage from './pages/ExerciseDetailPage'
import ExerciseFormPage from './pages/ExerciseFormPage'
import ClubsPage from './pages/ClubsPage'
import InboxPage from './pages/InboxPage'
import SkillsPage from './pages/SkillsPage'
import TrainingPlanningPage from './pages/TrainingPlanningPage'
import TrainingFrameworkProgramsListPage from './pages/TrainingFrameworkProgramsListPage'
@@ -31,12 +34,22 @@ import AdminMaturityModelsPage from './pages/AdminMaturityModelsPage'
import TrainerContextsPage from './pages/TrainerContextsPage'
import MediaWikiImportPage from './pages/MediaWikiImportPage'
import AdminUsersPage from './pages/AdminUsersPage'
import AdminHomeRedirect from './components/AdminHomeRedirect'
import PlatformAdminRoute from './components/PlatformAdminRoute'
import MediaLibraryPage from './pages/MediaLibraryPage'
import ActiveClubSwitcher from './components/ActiveClubSwitcher'
import InactiveMembershipBanner from './components/InactiveMembershipBanner'
import './app.css'
/** Shield „Admin“: nur Super-Admin (global). Vereinsorga: Vereine → Mitglieder. */
function computeShowAdminNav(currentUser) {
return currentUser?.role === 'superadmin'
}
// Bottom Navigation (Mobile)
function Nav({ isAdmin }) {
const items = getMainNavItems(isAdmin)
function Nav({ showAdminNav }) {
const { canAccessOrgInbox, inboxCount } = useOrgInbox()
const items = getMainNavItems(showAdminNav, { showInbox: canAccessOrgInbox })
const loc = useLocation()
const navItemActive = (pathname, item, routerIsActive) => {
@@ -55,7 +68,12 @@ function Nav({ isAdmin }) {
'nav-item' + (navItemActive(loc.pathname, item, isActive) ? ' active' : '')
}
>
<item.Icon size={20} strokeWidth={2} />
<item.Icon size={26} strokeWidth={2} />
{item.to === '/inbox' && inboxCount > 0 ? (
<span className="nav-item__badge" aria-label={`${inboxCount} offen`}>
{inboxCount > 99 ? '99+' : inboxCount}
</span>
) : null}
<span>{item.shortLabel || item.label}</span>
</NavLink>
))}
@@ -93,11 +111,11 @@ function ProtectedLayout() {
return <Navigate to="/login" replace />
}
const isAdmin = user?.role === 'admin' || user?.role === 'superadmin'
const showAdminNav = computeShowAdminNav(user)
return (
<>
<DesktopSidebar isAdmin={isAdmin} user={user} onLogout={handleLogout} />
<OrgInboxProvider user={user}>
<DesktopSidebar showAdminNav={showAdminNav} user={user} onLogout={handleLogout} />
<div className="app-shell">
<div className="app-shell__column">
<div className="app-header app-header--mobile app-header--mobile-stack">
@@ -107,12 +125,13 @@ function ProtectedLayout() {
<ActiveClubSwitcher variant="mobile" />
</div>
<div className="app-main">
<InactiveMembershipBanner />
<Outlet />
</div>
<Nav isAdmin={isAdmin} />
<Nav showAdminNav={showAdminNav} />
</div>
</div>
</>
</OrgInboxProvider>
)
}
@@ -156,6 +175,8 @@ function AppRoutes() {
<Route index element={<Dashboard />} />
<Route path="profile" element={<Navigate to="/settings" replace />} />
<Route path="settings" element={<AccountSettingsPage />} />
<Route path="settings/system" element={<SettingsSystemInfoPage />} />
<Route path="media" element={<MediaLibraryPage />} />
<Route path="exercises">
<Route index element={<ExercisesListPage />} />
<Route path="new" element={<ExerciseFormPage />} />
@@ -163,6 +184,7 @@ function AppRoutes() {
<Route path=":id" element={<ExerciseDetailPage />} />
</Route>
<Route path="clubs" element={<ClubsPage />} />
<Route path="inbox" element={<InboxPage />} />
<Route path="skills" element={<SkillsPage />} />
<Route path="planning/framework-programs/new" element={<TrainingFrameworkProgramEditPage />} />
<Route path="planning/framework-programs/:id" element={<TrainingFrameworkProgramEditPage />} />
@@ -170,12 +192,47 @@ function AppRoutes() {
<Route path="planning/run/:unitId/coach" element={<TrainingCoachPage />} />
<Route path="planning/run/:unitId" element={<TrainingUnitRunPage />} />
<Route path="planning" element={<TrainingPlanningPage />} />
<Route path="admin" element={<Navigate to="/admin/hierarchy" replace />} />
<Route path="admin/users" element={<AdminUsersPage />} />
<Route path="admin/hierarchy" element={<AdminHierarchyPage />} />
<Route path="admin/maturity-models" element={<AdminMaturityModelsPage />} />
<Route path="admin/catalogs" element={<AdminCatalogsPage />} />
<Route path="admin/mediawiki-import" element={<MediaWikiImportPage />} />
<Route path="admin" element={<AdminHomeRedirect />} />
<Route
path="admin/users"
element={
<PlatformAdminRoute>
<AdminUsersPage />
</PlatformAdminRoute>
}
/>
<Route
path="admin/hierarchy"
element={
<PlatformAdminRoute>
<AdminHierarchyPage />
</PlatformAdminRoute>
}
/>
<Route
path="admin/maturity-models"
element={
<PlatformAdminRoute>
<AdminMaturityModelsPage />
</PlatformAdminRoute>
}
/>
<Route
path="admin/catalogs"
element={
<PlatformAdminRoute>
<AdminCatalogsPage />
</PlatformAdminRoute>
}
/>
<Route
path="admin/mediawiki-import"
element={
<PlatformAdminRoute>
<MediaWikiImportPage />
</PlatformAdminRoute>
}
/>
<Route path="trainer-contexts" element={<TrainerContextsPage />} />
</Route>
+2846 -153
View File
File diff suppressed because it is too large. Load diff
@@ -1,4 +1,5 @@
import { useAuth } from '../context/AuthContext'
import { activeClubMemberships, getResolvedActiveClubIdForUi } from '../utils/activeClub'
/**
* Zeigt einen Vereins-Umschalter, wenn der Nutzer mehreren Vereinen zugeordnet ist.
@@ -6,13 +7,10 @@ import { useAuth } from '../context/AuthContext'
*/
export default function ActiveClubSwitcher({ variant = 'sidebar' }) {
const { user, setActiveClub } = useAuth()
const clubs = user?.clubs || []
const clubs = activeClubMemberships(user?.clubs)
if (clubs.length <= 1) return null
const selectClubId =
user?.active_club_id != null && clubs.some((c) => c.id === user.active_club_id)
? user.active_club_id
: clubs[0]?.id
const selectClubId = getResolvedActiveClubIdForUi(user)
const isMobile = variant === 'mobile'
@@ -0,0 +1,8 @@
import { Navigate } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
export default function AdminHomeRedirect() {
const { user } = useAuth()
const isSuper = user?.role === 'superadmin'
return <Navigate to={isSuper ? '/admin/hierarchy' : '/'} replace />
}
+9 -45
View File
@@ -1,67 +1,31 @@
import { NavLink, useLocation } from 'react-router-dom'
import { NavLink } from 'react-router-dom'
import { TreePine, FolderTree, Download, Grid3x3, Users } from 'lucide-react'
/**
* Admin-Seiten-Navigation (horizontal)
* Wechselt zwischen verschiedenen Admin-Seiten
* Admin-Seiten-Navigation (horizontal) — nur für Super-Admins (globaler Portal-Mandant).
*/
export default function AdminPageNav() {
const location = useLocation()
const pages = [
{ to: '/admin/hierarchy', label: 'Hierarchie', icon: TreePine },
{ to: '/admin/users', label: 'Nutzer', icon: Users },
{ to: '/admin/maturity-models', label: 'Fähigkeitsmatrix', icon: Grid3x3 },
{ to: '/admin/catalogs', label: 'Kataloge', icon: FolderTree },
{ to: '/admin/mediawiki-import', label: 'Wiki-Import', icon: Download }
{ to: '/admin/mediawiki-import', label: 'Wiki-Import', icon: Download },
]
return (
<nav style={{
display: 'flex',
gap: '8px',
borderBottom: '2px solid var(--border)',
marginBottom: '24px',
flexWrap: 'wrap'
}}>
{pages.map(page => {
<nav className="admin-top-nav" aria-label="Administration">
{pages.map((page) => {
const Icon = page.icon
const isActive = location.pathname === page.to
return (
<NavLink
key={page.to}
to={page.to}
style={{
padding: '12px 20px',
background: 'transparent',
border: 'none',
borderBottom: '3px solid transparent',
cursor: 'pointer',
fontSize: '16px',
fontWeight: 500,
color: isActive ? 'var(--accent)' : 'var(--text2)',
borderBottomColor: isActive ? 'var(--accent)' : 'transparent',
textDecoration: 'none',
display: 'flex',
alignItems: 'center',
gap: '8px',
transition: 'all 0.2s'
}}
onMouseEnter={(e) => {
if (!isActive) {
e.currentTarget.style.color = 'var(--text1)'
e.currentTarget.style.background = 'var(--surface2)'
}
}}
onMouseLeave={(e) => {
if (!isActive) {
e.currentTarget.style.color = 'var(--text2)'
e.currentTarget.style.background = 'transparent'
}
}}
className={({ isActive }) =>
'admin-top-nav__link' + (isActive ? ' admin-top-nav__link--active' : '')
}
>
<Icon size={18} />
<Icon size={18} strokeWidth={2} aria-hidden />
<span>{page.label}</span>
</NavLink>
)
@@ -0,0 +1,28 @@
import PageSectionNav from './PageSectionNav'
/**
* Sub-Navigation mit Icon-Chips: gleiche Darstellung wie Stammdaten / Vereine (PageSectionNav).
* „Sub-Sub“ (z. B. Editor) bleibt in den jeweiligen Feature-Layouts.
*/
export default function AppSubnavShell({
ariaLabel,
items,
value,
onChange,
children,
iconSize = 18,
}) {
return (
<div className="app-subnav-shell">
<PageSectionNav
ariaLabel={ariaLabel}
value={value}
onChange={onChange}
items={items}
iconSize={iconSize}
className="page-section-nav--wrap"
/>
<div className="app-subnav-shell__main">{children}</div>
</div>
)
}
@@ -0,0 +1,109 @@
import React, { useState } from 'react'
import { newCatalogRuleKey } from '../constants/exerciseListFilters'
/**
* Kompakte +/- Regeln für Katalogwerte (numerische IDs oder Slugs).
* Chips oben, schmales Dropdown, Schalter nur „+“ und „−“.
*/
export default function CatalogRulePicker({
label,
hint,
options = [],
rules = [],
rulesFieldName,
disabled = false,
placeholder = 'Auswählen …',
idKind = 'numeric',
onPatch,
}) {
const [pendingId, setPendingId] = useState('')
const labelFor = (id) => options.find((o) => String(o.id) === String(id))?.label ?? id
const addRule = (mode) => {
const raw = String(pendingId || '').trim()
if (!raw || disabled) return
if (idKind === 'numeric') {
const n = Number(raw)
if (!Number.isFinite(n) || n < 1) return
}
const dup = (rules || []).some((r) => String(r.id) === raw && r.mode === mode)
if (dup) return
onPatch({
[rulesFieldName]: [
...(rules || []),
{ key: newCatalogRuleKey(rulesFieldName), id: raw, mode },
],
})
setPendingId('')
}
const removeRule = (key) => {
onPatch({
[rulesFieldName]: (rules || []).filter((r) => r.key !== key),
})
}
return (
<div className={`catalog-rule-picker${disabled ? ' catalog-rule-picker--disabled' : ''}`}>
<label className="form-label catalog-rule-picker__label">{label}</label>
{hint ? (
<p className="muted catalog-rule-picker__hint" style={{ fontSize: '11px', marginTop: '2px', marginBottom: '6px' }}>
{hint}
</p>
) : null}
<div className="catalog-rule-picker__chips" aria-live="polite">
{(rules || []).map((r) => (
<span key={r.key} className="catalog-rule-chip">
<span className={`catalog-rule-chip__sign catalog-rule-chip__sign--${r.mode}`}>
{r.mode === 'forbid' ? '−' : '+'}
</span>
<span className="catalog-rule-chip__text">{labelFor(r.id)}</span>
<button
type="button"
className="catalog-rule-chip__x"
aria-label={`${label}: Regel entfernen`}
onClick={() => removeRule(r.key)}
>
×
</button>
</span>
))}
</div>
<div className="catalog-rule-picker__row">
<select
className="form-input catalog-rule-picker__select"
value={pendingId}
disabled={disabled}
onChange={(e) => setPendingId(e.target.value)}
aria-label={label}
>
<option value="">{placeholder}</option>
{options.map((o) => (
<option key={o.id} value={String(o.id)}>
{o.label || o.id}
</option>
))}
</select>
<button
type="button"
className="btn btn-secondary btn-small catalog-rule-picker__sign-btn"
disabled={disabled || !pendingId}
title="Muss zutreffen"
onClick={() => addRule('require')}
>
+
</button>
<button
type="button"
className="btn btn-secondary btn-small catalog-rule-picker__sign-btn"
disabled={disabled || !pendingId}
title="Darf nicht zutreffen"
onClick={() => addRule('forbid')}
>
−
</button>
</div>
</div>
)
}
@@ -0,0 +1,57 @@
import { Link } from 'react-router-dom'
import { Inbox } from 'lucide-react'
import { useOrgInbox } from '../context/OrgInboxContext'
/**
* Desktop-Dashboard: Hinweis auf offene Beitrittsanträge (nur ab 1024px sichtbar via CSS).
*/
export default function DashboardOrgInboxWidget() {
const { canAccessOrgInbox, inboxJoinRequests, inboxCount } = useOrgInbox()
if (!canAccessOrgInbox) return null
const preview = (inboxJoinRequests || []).slice(0, 5)
return (
<section
className="dashboard-org-inbox-widget"
aria-labelledby="dash-org-inbox-title"
>
<div className="dashboard-org-inbox-widget__inner card">
<div className="dashboard-org-inbox-widget__head">
<h2 id="dash-org-inbox-title" className="dashboard-org-inbox-widget__title">
<Inbox size={20} strokeWidth={2} aria-hidden className="dashboard-org-inbox-widget__icon" />
Posteingang
</h2>
{inboxCount > 0 ? (
<span className="dashboard-org-inbox-widget__badge" aria-live="polite">
{inboxCount}
</span>
) : null}
</div>
<p className="muted dashboard-org-inbox-widget__lead">
{inboxCount === 0
? 'Keine offenen Beitrittsanträge.'
: `${inboxCount} offene Beitrittsantrag${inboxCount === 1 ? '' : 'e'}.`}
</p>
{preview.length > 0 ? (
<ul className="dashboard-org-inbox-widget__list">
{preview.map((req) => (
<li key={`${req.club_id}-${req.id}`} className="dashboard-org-inbox-widget__item">
<span className="dashboard-org-inbox-widget__club">{req.club_name || 'Verein'}</span>
<span className="dashboard-org-inbox-widget__applicant">
{req.applicant_name || req.applicant_email || 'Bewerber/in'}
</span>
</li>
))}
</ul>
) : null}
<div className="dashboard-org-inbox-widget__footer">
<Link to="/inbox" className="btn btn-secondary" style={{ textDecoration: 'none' }}>
Zum Posteingang
</Link>
</div>
</div>
</section>
)
}
@@ -0,0 +1,347 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import { CalendarDays, ClipboardList } from 'lucide-react'
import api from '../utils/api'
const VIS_LABELS = { private: 'Privat', club: 'Verein', official: 'Offiziell' }
const STATUS_LABELS = {
draft: 'Entwurf',
in_review: 'Prüfung',
approved: 'Freigegeben',
archived: 'Archiv',
}
function rowKey(item) {
return `${item.exercise_id}-${item.target_club_id}`
}
function unitPlanTitle(u) {
const d = (u.planned_date || '').toString().slice(0, 10)
const g = (u.group_name || '').trim()
return [d, g].filter(Boolean).join(' · ') || `Einheit #${u.id}`
}
/**
* Dashboard: Übungen aus eigenen Trainingseinheiten, die für den Verein der Gruppe noch nicht freigegeben sind.
*/
export default function DashboardTrainingVisibilityWidget({ user }) {
const [items, setItems] = useState([])
const [loading, setLoading] = useState(true)
const [err, setErr] = useState(null)
const [selected, setSelected] = useState(() => new Set())
const [busy, setBusy] = useState(false)
const [msg, setMsg] = useState(null)
const load = useCallback(async () => {
if (!user?.id) return
setErr(null)
setLoading(true)
try {
const res = await api.getTrainingExerciseClubVisibilityQueue({ limit_units: 100 })
const list = Array.isArray(res?.items) ? res.items : []
setItems(list)
setSelected(new Set())
setMsg(null)
} catch (e) {
setErr(e?.message || String(e))
setItems([])
} finally {
setLoading(false)
}
}, [user?.id])
useEffect(() => {
load()
}, [load])
const promotableSelected = useMemo(() => {
const out = []
for (const k of selected) {
const it = items.find((x) => rowKey(x) === k)
if (it?.can_promote) out.push(it)
}
return out
}, [items, selected])
const toggle = (key) => {
setSelected((prev) => {
const n = new Set(prev)
if (n.has(key)) n.delete(key)
else n.add(key)
return n
})
}
const toggleAllPromotable = () => {
const keys = items.filter((i) => i.can_promote).map(rowKey)
setSelected((prev) => {
if (keys.length && keys.every((k) => prev.has(k))) {
return new Set()
}
return new Set(keys)
})
}
const promoteSelected = async () => {
if (!promotableSelected.length) return
setBusy(true)
setMsg(null)
try {
const byClub = new Map()
for (const it of promotableSelected) {
const cid = it.target_club_id
if (!byClub.has(cid)) byClub.set(cid, [])
byClub.get(cid).push(it.exercise_id)
}
let anyFail = false
for (const [clubId, ids] of byClub) {
const uniq = [...new Set(ids)]
const res = await api.bulkPatchExercisesMetadata({
exercise_ids: uniq,
visibility: 'club',
club_id: clubId,
})
if ((res?.failed || []).length) {
anyFail = true
const f = res.failed[0]
setMsg(f?.detail || 'Freigabe teilweise fehlgeschlagen')
}
}
if (!anyFail) setMsg(null)
await load()
} catch (e) {
setMsg(e?.message || String(e))
} finally {
setBusy(false)
}
}
if (!user?.id) return null
if (loading) {
return (
<div className="card dashboard-preview-card" style={{ marginTop: '1rem' }}>
<p className="muted" style={{ margin: 0 }}>
Vereinsfreigaben werden geladen…
</p>
</div>
)
}
if (err) {
return (
<div className="card dashboard-preview-card" style={{ marginTop: '1rem' }} role="alert">
<p style={{ margin: 0, color: 'var(--danger, #c0392b)' }}>{err}</p>
</div>
)
}
if (!items.length) {
return (
<div className="card dashboard-preview-card" style={{ marginTop: '1rem' }}>
<h3 className="dashboard-preview-card__title" style={{ marginTop: 0 }}>
Vereinssichtbarkeit in deinen Trainings
</h3>
<p className="dashboard-preview-card__empty" style={{ margin: 0 }}>
Keine Übungen in den abgefragten Einheiten, die noch auf Verein gestellt werden müssten.
</p>
</div>
)
}
const allPromo = items.filter((i) => i.can_promote)
const allSelected = allPromo.length > 0 && allPromo.every((i) => selected.has(rowKey(i)))
return (
<div className="card dashboard-preview-card dashboard-vis-queue" style={{ marginTop: '1rem' }}>
<div
style={{
display: 'flex',
flexWrap: 'wrap',
alignItems: 'flex-start',
justifyContent: 'space-between',
gap: '12px',
}}
>
<div>
<h3 className="dashboard-preview-card__title" style={{ marginTop: 0 }}>
Vereinssichtbarkeit in deinen Trainings
</h3>
<p
className="muted"
style={{ margin: '0.35rem 0 0', fontSize: '0.88rem', lineHeight: 1.45, maxWidth: '52rem' }}
>
Übungen in deinen Einheiten, die für den jeweiligen Verein noch nicht sichtbar sind — auf{' '}
<strong>Verein</strong> setzen oder zur Bearbeitung / Planung springen.
</p>
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', alignItems: 'center' }}>
{allPromo.length ? (
<button type="button" className="btn btn-secondary" onClick={toggleAllPromotable}>
{allSelected ? 'Auswahl leeren' : 'Alle wählbar'}
</button>
) : null}
<button
type="button"
className="btn btn-primary"
disabled={!promotableSelected.length || busy}
onClick={promoteSelected}
>
{busy ? 'Speichern…' : `Freigeben (${promotableSelected.length})`}
</button>
</div>
</div>
<div style={{ marginTop: '0.75rem', overflowX: 'auto' }}>
<table
className="dashboard-vis-queue__table"
style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.86rem' }}
>
<thead>
<tr
style={{
textAlign: 'left',
borderBottom: '1px solid var(--border2)',
color: 'var(--text3)',
fontSize: '0.78rem',
}}
>
<th style={{ width: 32, padding: '6px 4px' }} aria-label="Auswahl" />
<th style={{ padding: '6px 6px' }}>Übung</th>
<th style={{ padding: '6px 6px', whiteSpace: 'nowrap' }}>Sichtbarkeit</th>
<th style={{ padding: '6px 6px', whiteSpace: 'nowrap' }}>Status</th>
<th style={{ padding: '6px 6px' }}>Verein</th>
<th style={{ padding: '6px 4px', width: 76 }} title="Planung und Durchführung">
Kontext
</th>
</tr>
</thead>
<tbody>
{items.map((it) => {
const k = rowKey(it)
const on = selected.has(k)
const visL = VIS_LABELS[it.visibility] || it.visibility
const stL = STATUS_LABELS[it.status] || it.status
const first = it.units && it.units[0]
const restN = (it.units?.length || 0) - 1
const tool = (it.units || []).map(unitPlanTitle).join('\n')
const cn = (it.target_club_name || '').trim()
return (
<tr
key={k}
style={{ borderBottom: '1px solid var(--border2)' }}
title={restN > 0 ? tool : undefined}
>
<td style={{ padding: '6px 4px', verticalAlign: 'top' }}>
<input
type="checkbox"
checked={on}
disabled={!it.can_promote}
onChange={() => toggle(k)}
title={it.can_promote ? 'Zur Freigabe wählen' : 'Keine Berechtigung für diese Freigabe'}
aria-label={`${it.title} auswählen`}
/>
</td>
<td style={{ padding: '6px 6px', verticalAlign: 'top', minWidth: 140 }}>
<Link
to={`/exercises/${it.exercise_id}/edit`}
className="dashboard-preview-card__link"
style={{ fontWeight: 600 }}
>
{it.title}
</Link>
</td>
<td style={{ padding: '6px 6px', verticalAlign: 'top', whiteSpace: 'nowrap' }}>{visL}</td>
<td style={{ padding: '6px 6px', verticalAlign: 'top', whiteSpace: 'nowrap' }}>{stL}</td>
<td style={{ padding: '6px 6px', verticalAlign: 'top', maxWidth: 200 }}>
<span title={cn}>{cn.length > 28 ? `${cn.slice(0, 28)}…` : cn || '—'}</span>
</td>
<td style={{ padding: '6px 4px', verticalAlign: 'top' }}>
{first ? (
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 4,
flexWrap: 'wrap',
justifyContent: 'flex-end',
}}
>
<Link
to={`/planning?unit=${first.id}`}
className="btn-ghost"
style={{
padding: '2px 4px',
display: 'inline-flex',
borderRadius: 6,
textDecoration: 'none',
color: 'var(--text1)',
}}
title={
restN > 0
? `Planung (${unitPlanTitle(first)}; +${restN} weitere — siehe Tooltip ganze Zeile)`
: `Planung öffnen: ${unitPlanTitle(first)}`
}
aria-label="Planung öffnen"
>
<CalendarDays size={16} strokeWidth={2} aria-hidden />
</Link>
<Link
to={`/planning/run/${first.id}`}
className="btn-ghost"
style={{
padding: '2px 4px',
display: 'inline-flex',
borderRadius: 6,
textDecoration: 'none',
color: 'var(--text1)',
}}
title="Durchführung / Ablauf"
aria-label="Durchführung öffnen"
>
<ClipboardList size={16} strokeWidth={2} aria-hidden />
</Link>
{restN > 0 ? (
<span className="muted" style={{ fontSize: '0.72rem' }} title={tool}>
+{restN}
</span>
) : null}
</div>
) : (
'—'
)}
</td>
</tr>
)
})}
</tbody>
</table>
</div>
{items.some((i) => !i.can_promote) ? (
<p className="muted" style={{ margin: '0.5rem 0 0', fontSize: '0.82rem', lineHeight: 1.45 }}>
Ausgegraute Kästchen: keine direkte Freigabe-Berechtigung — Vereinsorga kontaktieren oder die Einheit in
der Planung speichern (dann ggf. automatische Vereinsfreigabe).
</p>
) : null}
<p className="muted" style={{ margin: '0.5rem 0 0', fontSize: '0.8rem', lineHeight: 1.45 }}>
Mehrere Termine: Kalender-Icon nutzt den frühesten; „+N“ listet alle Daten und Gruppen im Tooltip.
</p>
{msg ? (
<p
style={{ margin: '0.65rem 0 0', fontSize: '0.84rem', color: 'var(--danger, #c0392b)' }}
role="alert"
>
{msg}
</p>
) : null}
<p style={{ margin: '0.65rem 0 0', fontSize: '0.82rem' }}>
<Link to="/planning">Zur Trainingsplanung</Link>
<span className="muted"> · Zeitraum ca. 45 Tage zurück bis 1 Jahr voraus; bis zu 100 Einheiten.</span>
</p>
</div>
)
}
+9 -2
View File
@@ -1,6 +1,7 @@
import { NavLink, useLocation } from 'react-router-dom'
import { LogOut } from 'lucide-react'
import { getMainNavItems } from '../config/appNav'
import { useOrgInbox } from '../context/OrgInboxContext'
import ActiveClubSwitcher from './ActiveClubSwitcher'
function sidebarLinkActive(pathname, item, routerIsActive) {
@@ -12,12 +13,13 @@ function sidebarLinkActive(pathname, item, routerIsActive) {
* Desktop-Sidebar (≥1024px) — Sichtbarkeit via CSS (.desktop-sidebar).
*/
export default function DesktopSidebar({
isAdmin,
showAdminNav,
user,
onLogout
}) {
const loc = useLocation()
const items = getMainNavItems(isAdmin)
const { canAccessOrgInbox, inboxCount } = useOrgInbox()
const items = getMainNavItems(showAdminNav, { showInbox: canAccessOrgInbox })
const tier = user?.tier || ''
return (
@@ -42,6 +44,11 @@ export default function DesktopSidebar({
>
<item.Icon size={20} strokeWidth={2} />
<span>{item.label}</span>
{item.to === '/inbox' && inboxCount > 0 ? (
<span className="desktop-sidebar__badge" aria-label={`${inboxCount} offen`}>
{inboxCount > 99 ? '99+' : inboxCount}
</span>
) : null}
</NavLink>
))}
</nav>
@@ -0,0 +1,123 @@
/**
* Nur Medien, die noch nicht im Fließtext eingebettet sind — ohne Doppel-Darstellung.
*/
import React, { useMemo, useState } from 'react'
import ExerciseMediaEmbed from './ExerciseMediaEmbed'
import ExerciseMediaThumbTile from './ExerciseMediaThumbTile'
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
import {
collectInlineExerciseMediaIdsFromExercise,
} from '../utils/exerciseInlineMediaRefs'
function isTrashHidden(m) {
return String(m?.asset_lifecycle_state || 'active').toLowerCase() === 'trash_hidden'
}
export default function ExerciseAttachmentMediaStrip({ exerciseId, exercise }) {
const [preview, setPreview] = useState(null)
const inlineIds = useMemo(() => collectInlineExerciseMediaIdsFromExercise(exercise), [exercise])
const orphans = useMemo(() => {
const list = (exercise?.media || []).filter((m) => m && !isTrashHidden(m))
return list.filter((m) => !inlineIds.has(Number(m.id)))
}, [exercise, inlineIds])
if (!orphans.length || exerciseId == null) return null
return (
<section className="card exercise-detail-section exercise-attachment-media-strip">
<h2>Angehängte Medien</h2>
<p style={{ marginTop: '6px', color: 'var(--text2)', fontSize: '0.88rem' }}>
Hier erscheinen nur Verknüpfungen, die noch nicht im Fließtext eingebettet sind (reine Material-Anhänge).
</p>
<div className="exercise-orphan-media-grid">
{orphans.map((m) => {
const lc = String(m.asset_lifecycle_state || 'active').toLowerCase()
const caption = (m.title || '').trim() || (m.original_filename || '').trim() || `Medium #${m.id}`
return (
<article key={m.id} className="exercise-orphan-media-card">
<div className="exercise-orphan-media-card__head">
<ExerciseMediaThumbTile
exerciseId={exerciseId}
media={m}
onOpenPreview={setPreview}
size={88}
/>
<div className="exercise-orphan-media-card__meta">
<strong className="exercise-orphan-media-card__title">{caption}</strong>
<span className="exercise-orphan-media-card__sub">
#{m.id}
{m.embed_platform ? ` · ${m.embed_platform}` : ''}
{m.media_type ? ` · ${m.media_type}` : ''}
</span>
{lc === 'trash_soft' && (
<span className="exercise-orphan-media-card__warn">Papierkorb (Stufe 1)</span>
)}
</div>
</div>
<ExerciseMediaEmbed exerciseId={exerciseId} media={m} layoutSize="medium" />
</article>
)
})}
</div>
{preview && (
<div
role="dialog"
aria-modal="true"
aria-label="Medienvorschau"
style={{
position: 'fixed',
inset: 0,
background: 'rgba(0,0,0,0.55)',
zIndex: 1001,
overflow: 'auto',
padding: '16px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
onClick={() => setPreview(null)}
onKeyDown={(e) => e.key === 'Escape' && setPreview(null)}
>
<div
className="card"
style={{ maxWidth: 720, width: '100%', maxHeight: '90vh', overflow: 'auto' }}
onClick={(e) => e.stopPropagation()}
>
<h3 style={{ marginTop: 0, fontSize: '1.05rem' }}>Vorschau</h3>
{preview.embed_url ? (
<p style={{ fontSize: '14px', wordBreak: 'break-all' }}>
<a href={preview.embed_url} target="_blank" rel="noreferrer">
{preview.embed_url}
</a>
</p>
) : preview.mime_type?.startsWith('video/') || preview.media_type === 'video' ? (
<video
src={resolveExerciseMediaFileUrl(exerciseId, preview)}
controls
style={{ width: '100%', borderRadius: '8px', maxHeight: '70vh' }}
/>
) : preview.mime_type?.startsWith('image/') || preview.media_type === 'image' ? (
<img
alt=""
src={resolveExerciseMediaFileUrl(exerciseId, preview)}
style={{ maxWidth: '100%', borderRadius: '8px', maxHeight: '70vh', objectFit: 'contain' }}
/>
) : (
<p style={{ fontSize: '14px' }}>
<a href={resolveExerciseMediaFileUrl(exerciseId, preview)} target="_blank" rel="noreferrer">
Datei öffnen
</a>
</p>
)}
<div style={{ marginTop: '16px' }}>
<button type="button" className="btn btn-secondary" onClick={() => setPreview(null)}>
Schließen
</button>
</div>
</div>
</div>
)}
</section>
)
}
@@ -0,0 +1,64 @@
import React from 'react'
import CatalogRulePicker from './CatalogRulePicker'
/**
* Fokusbereiche inkl. „nur ohne Zuordnung“; Regeln über CatalogRulePicker (+/−).
*/
export default function ExerciseFocusRulePicker({
focusOptions,
focusRules,
focusOnlyWithout,
legacyFocusAreaIds = [],
onPatch,
}) {
const legacyWarning =
Array.isArray(legacyFocusAreaIds) && legacyFocusAreaIds.length > 0 && !focusOnlyWithout
const setFocusOnly = (on) => {
if (on) {
onPatch({
focus_only_without: true,
exclude_without_focus: false,
focus_rules: [],
focus_area_ids: [],
})
return
}
onPatch({ focus_only_without: false })
}
return (
<div className="exercise-focus-rule-picker">
<label style={{ display: 'flex', alignItems: 'center', gap: '10px', cursor: 'pointer', marginBottom: '10px' }}>
<input type="checkbox" checked={!!focusOnlyWithout} onChange={(e) => setFocusOnly(e.target.checked)} />
<span>
Nur Übungen <strong>ohne</strong> Fokusbereich (keine Zuordnung)
</span>
</label>
{!focusOnlyWithout ? (
<>
{legacyWarning ? (
<p className="muted" style={{ fontSize: '12px', marginTop: 0, marginBottom: '8px' }}>
Ältere ODER-Fokusliste aktiv — über die Chips auf der Übersicht entfernen.
</p>
) : null}
<CatalogRulePicker
label="Fokusbereiche"
hint="+ alle erforderlich (UND). − keine dieser Zuordnungen."
options={focusOptions}
rules={focusRules}
rulesFieldName="focus_rules"
idKind="numeric"
placeholder="Fokus …"
onPatch={onPatch}
/>
</>
) : (
<p className="muted" style={{ fontSize: '12px', marginTop: 0 }}>
Fokus-Regeln sind deaktiviert.
</p>
)}
</div>
)
}
@@ -3,60 +3,7 @@
*/
import React from 'react'
import { Link } from 'react-router-dom'
import { sanitizeTrainerHtml } from '../utils/htmlUtils'
const API_BASE = (import.meta.env.VITE_API_URL || '').replace(/\/$/, '')
function resolveMediaUrl(filePath) {
if (!filePath) return null
if (filePath.startsWith('http://') || filePath.startsWith('https://')) return filePath
const p = filePath.startsWith('/') ? filePath : `/${filePath}`
return `${API_BASE}${p}`
}
function HtmlBlock({ html, className = '' }) {
if (!html || !String(html).trim()) return null
const safe = sanitizeTrainerHtml(html)
return (
<div className={`rich-text-content ${className}`} dangerouslySetInnerHTML={{ __html: safe }} />
)
}
function MediaBlock({ media }) {
if (media.embed_url) {
return (
<div style={{ marginTop: '0.5rem' }}>
<a href={media.embed_url} target="_blank" rel="noreferrer">
{media.embed_url}
</a>
{media.embed_platform && (
<span style={{ color: 'var(--text2)', marginLeft: '0.5rem', fontSize: '0.8rem' }}>
({media.embed_platform})
</span>
)}
</div>
)
}
const src = resolveMediaUrl(media.file_path)
if (!src) return null
if (media.media_type === 'image' || (media.mime_type && media.mime_type.startsWith('image/'))) {
return (
<img
src={src}
alt={media.title || media.original_filename || ''}
style={{ maxWidth: '100%', borderRadius: '8px', marginTop: '0.5rem' }}
/>
)
}
if (media.media_type === 'video' || (media.mime_type && media.mime_type.startsWith('video/'))) {
return <video src={src} controls style={{ width: '100%', marginTop: '0.5rem', borderRadius: '8px' }} />
}
return (
<a href={src} target="_blank" rel="noreferrer" style={{ display: 'inline-block', marginTop: '0.5rem' }}>
{media.title || media.original_filename || 'Datei öffnen'}
</a>
)
}
import ExerciseRichTextBlock from './ExerciseRichTextBlock'
function TagRow({ exercise }) {
const tags = []
@@ -120,6 +67,7 @@ export default function ExerciseFullContent({ exercise, loading, error, exercise
}
if (!exercise) return null
const resolvedId = exercise.id ?? exerciseId
const meta = metaParts(exercise)
return (
@@ -136,13 +84,13 @@ export default function ExerciseFullContent({ exercise, loading, error, exercise
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px', letterSpacing: '0.04em' }}>
Kurzbeschreibung
</h3>
<HtmlBlock html={exercise.summary} />
<ExerciseRichTextBlock html={exercise.summary} exerciseId={resolvedId} media={exercise.media} />
</section>
)}
{exercise.goal && (
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>Ziel</h3>
<HtmlBlock html={exercise.goal} />
<ExerciseRichTextBlock html={exercise.goal} exerciseId={resolvedId} media={exercise.media} />
</section>
)}
{(exercise.equipment || []).length > 0 && (
@@ -160,27 +108,13 @@ export default function ExerciseFullContent({ exercise, loading, error, exercise
{exercise.preparation && (
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>Vorbereitung</h3>
<HtmlBlock html={exercise.preparation} />
<ExerciseRichTextBlock html={exercise.preparation} exerciseId={resolvedId} media={exercise.media} />
</section>
)}
{exercise.execution && (
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>Ablauf</h3>
<HtmlBlock html={exercise.execution} />
</section>
)}
{(exercise.media || []).length > 0 && (
<section className="card" style={{ marginTop: '10px', padding: '12px 14px' }}>
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>
Medien
</h3>
{exercise.media.map((m) => (
<div key={m.id} style={{ marginBottom: '12px' }}>
<strong style={{ fontSize: '0.9rem' }}>{m.title || m.original_filename || m.media_type}</strong>
{m.description && <p style={{ color: 'var(--text2)', fontSize: '0.82rem', marginTop: '4px' }}>{m.description}</p>}
<MediaBlock media={m} />
</div>
))}
<ExerciseRichTextBlock html={exercise.execution} exerciseId={resolvedId} media={exercise.media} />
</section>
)}
{exercise.trainer_notes && (
@@ -188,7 +122,7 @@ export default function ExerciseFullContent({ exercise, loading, error, exercise
<h3 style={{ fontSize: '0.78rem', textTransform: 'uppercase', color: 'var(--text3)', marginBottom: '8px' }}>
Hinweise Trainer (Katalog)
</h3>
<HtmlBlock html={exercise.trainer_notes} />
<ExerciseRichTextBlock html={exercise.trainer_notes} exerciseId={resolvedId} media={exercise.media} />
</section>
)}
{exerciseId != null && (
@@ -0,0 +1,132 @@
/**
* Modal: Embed-URL als exercise_media anlegen und §11-Platzhalter einfügen.
*/
import React, { useEffect, useState } from 'react'
import api from '../utils/api'
import {
INLINE_MEDIA_SIZES,
DEFAULT_INLINE_MEDIA_SIZE,
sanitizeInlineMediaSize,
} from '../constants/inlineExerciseMedia'
import { sanitizeInlineMediaCaption } from '../utils/inlineMediaCaption'
/**
* @param {{
* open: boolean,
* onClose: () => void,
* exerciseId: number,
* onMediaListChanged: () => Promise<void>,
* onInserted: (exerciseMediaId: number, displaySize: string, caption?: string) => void,
* }} props
*/
export default function ExerciseInlineEmbedModal({
open,
onClose,
exerciseId,
onMediaListChanged,
onInserted,
}) {
const [url, setUrl] = useState('')
const [title, setTitle] = useState('')
const [displaySize, setDisplaySize] = useState(DEFAULT_INLINE_MEDIA_SIZE)
const [busy, setBusy] = useState(false)
useEffect(() => {
if (!open) return
setUrl('')
setTitle('')
setDisplaySize(DEFAULT_INLINE_MEDIA_SIZE)
}, [open])
const submit = async () => {
const u = url.trim()
if (!u) {
alert('Bitte eine Embed-URL eingeben (https://…).')
return
}
const size = sanitizeInlineMediaSize(displaySize)
const fd = new FormData()
fd.append('embed_url', u)
fd.append('media_type', 'video')
fd.append('title', title.trim())
fd.append('description', '')
fd.append('context', 'ablauf')
fd.append('is_primary', 'false')
setBusy(true)
try {
const row = await api.uploadExerciseMedia(exerciseId, fd)
const mid = row?.id
if (mid == null) {
throw new Error('Antwort ohne exercise_media-ID')
}
await onMediaListChanged()
const cap = sanitizeInlineMediaCaption(
title.trim() || u.replace(/^https?:\/\//i, '').slice(0, 96),
)
onInserted(Number(mid), size, cap)
onClose()
} catch (e) {
alert(e.message || String(e))
} finally {
setBusy(false)
}
}
if (!open) return null
return (
<div className="admin-modal-backdrop" role="presentation" onClick={(e) => e.target === e.currentTarget && !busy && onClose()}>
<div
className="admin-modal-sheet"
role="dialog"
aria-modal="true"
aria-labelledby="rte-inline-embed-title"
style={{ maxWidth: '480px', width: '100%' }}
onClick={(e) => e.stopPropagation()}
>
<div className="admin-modal-sheet__header">
<h3 id="rte-inline-embed-title" className="admin-modal-sheet__title">
Embed im Textfeld
</h3>
<button type="button" className="btn btn-secondary admin-modal-sheet__close" disabled={busy} onClick={onClose}>
Schließen
</button>
</div>
<div style={{ padding: '14px 16px' }}>
<label className="form-label">Embed-URL</label>
<input
type="url"
className="form-input"
placeholder="https://…"
value={url}
onChange={(e) => setUrl(e.target.value)}
disabled={busy}
/>
<label className="form-label" style={{ marginTop: '12px' }}>
Titel (optional)
</label>
<input
type="text"
className="form-input"
value={title}
onChange={(e) => setTitle(e.target.value)}
disabled={busy}
/>
<label className="form-label" style={{ marginTop: '12px' }}>
Darstellung im Text
</label>
<select className="form-input" value={displaySize} onChange={(e) => setDisplaySize(e.target.value)} disabled={busy}>
{INLINE_MEDIA_SIZES.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
<button type="button" className="btn btn-primary btn-full" style={{ marginTop: '16px' }} disabled={busy} onClick={submit}>
{busy ? 'Speichern…' : 'Hinzufügen & in Text einfügen'}
</button>
</div>
</div>
</div>
)
}
@@ -0,0 +1,396 @@
/**
* Modal: Medium aus Archiv verknüpfen oder neue Datei hochladen, dann Inline-Platzhalter §11 einfügen.
*/
import React, { useEffect, useState, useCallback, useMemo } from 'react'
import api from '../utils/api'
import { resolveMediaAssetFileUrl } from '../utils/exerciseMediaUrl'
import {
INLINE_MEDIA_SIZES,
DEFAULT_INLINE_MEDIA_SIZE,
sanitizeInlineMediaSize,
} from '../constants/inlineExerciseMedia'
import { sanitizeInlineMediaCaption } from '../utils/inlineMediaCaption'
function RtePickerAssetThumb({ asset }) {
const id = asset.id
const src = resolveMediaAssetFileUrl(id)
const mt = (asset.mime_type || '').toLowerCase()
if (mt.startsWith('image/') && src) {
return <img alt="" src={src} className="rte-inline-asset-tile__thumb-img" />
}
if (mt.startsWith('video/') && src) {
return (
<video
key={`v-${id}`}
className="rte-inline-asset-tile__thumb-video"
src={src}
muted
playsInline
preload="metadata"
onLoadedMetadata={(e) => {
try {
const el = e.currentTarget
const d = el.duration
el.currentTime = Number.isFinite(d) && d > 0 ? Math.min(0.05, d * 0.01) : 0.05
} catch (_) {
/* ignore */
}
}}
/>
)
}
const nameLow = String(asset.original_filename || '').toLowerCase()
if (mt.includes('pdf') || nameLow.endsWith('.pdf')) {
return <span className="rte-inline-asset-tile__thumb-fallback">PDF</span>
}
return <span className="rte-inline-asset-tile__thumb-fallback">Datei</span>
}
/** MIME/Dateiname → Übungs-media_type */
function inferExerciseMediaType(file) {
if (!file) return 'image'
const mime = (file.type || '').toLowerCase()
if (mime.startsWith('image/')) return 'image'
if (mime.startsWith('video/')) return 'video'
if (mime === 'application/pdf' || mime.includes('pdf')) return 'document'
const name = (file.name || '').toLowerCase()
if (/\.(mp4|webm|mov|mkv|avi|m4v|mpeg|mpg)$/.test(name)) return 'video'
if (/\.(jpg|jpeg|png|gif|webp|bmp|svg)$/.test(name)) return 'image'
if (/\.pdf$/.test(name)) return 'document'
return 'image'
}
/**
* @param {{
* open: boolean,
* onClose: () => void,
* exerciseId: number,
* linkedExerciseMedia?: object[],
* onMediaListChanged: () => Promise<void>,
* onInserted: (exerciseMediaId: number, displaySize: string, caption?: string) => void,
* }} props
*/
export default function ExerciseInlineFileMediaModal({
open,
onClose,
exerciseId,
linkedExerciseMedia = [],
onMediaListChanged,
onInserted,
}) {
const [tab, setTab] = useState('library')
const [q, setQ] = useState('')
const [loading, setLoading] = useState(false)
const [items, setItems] = useState([])
const [err, setErr] = useState(null)
const [selectedAssetId, setSelectedAssetId] = useState(null)
const [busy, setBusy] = useState(false)
const [uploadFile, setUploadFile] = useState(null)
const [uploadTitle, setUploadTitle] = useState('')
const [displaySize, setDisplaySize] = useState(DEFAULT_INLINE_MEDIA_SIZE)
const [uploadInputKey, setUploadInputKey] = useState(0)
const assetToExerciseMedia = useMemo(() => {
const m = new Map()
for (const row of linkedExerciseMedia || []) {
const aid = row?.media_asset_id
if (aid != null) m.set(Number(aid), row)
}
return m
}, [linkedExerciseMedia])
const loadAssets = useCallback(async () => {
setLoading(true)
setErr(null)
try {
const res = await api.listMediaAssets({
q: q.trim() || undefined,
limit: 48,
lifecycle: 'active',
})
setItems(Array.isArray(res.items) ? res.items : [])
} catch (e) {
setErr(e.message || String(e))
setItems([])
} finally {
setLoading(false)
}
}, [q])
useEffect(() => {
if (!open) return undefined
setTab('library')
setSelectedAssetId(null)
setUploadFile(null)
setUploadTitle('')
setUploadInputKey((k) => k + 1)
setDisplaySize(DEFAULT_INLINE_MEDIA_SIZE)
setErr(null)
const t = setTimeout(loadAssets, 280)
return () => clearTimeout(t)
}, [open])
useEffect(() => {
if (!open || tab !== 'library') return undefined
const t = setTimeout(loadAssets, 300)
return () => clearTimeout(t)
}, [q, open, tab, loadAssets])
const handleLinkSelected = async () => {
if (!selectedAssetId) {
alert('Bitte ein Archiv-Medium auswählen.')
return
}
const size = sanitizeInlineMediaSize(displaySize)
const assetMeta = items.find((x) => x.id === selectedAssetId)
const capFromExisting = (row) =>
sanitizeInlineMediaCaption(row?.original_filename || row?.title || assetMeta?.original_filename || '')
const existing = assetToExerciseMedia.get(Number(selectedAssetId))
if (existing?.id != null) {
onInserted(Number(existing.id), size, capFromExisting(existing))
onClose()
return
}
setBusy(true)
setErr(null)
try {
const row = await api.attachExerciseMediaFromAsset(exerciseId, {
media_asset_id: selectedAssetId,
title: '',
description: '',
context: 'ablauf',
is_primary: false,
})
const mid = row?.id
if (mid == null) {
throw new Error('Antwort ohne exercise_media-ID')
}
await onMediaListChanged()
onInserted(
Number(mid),
size,
sanitizeInlineMediaCaption(assetMeta?.original_filename || ''),
)
onClose()
} catch (e) {
const msg = e.message || String(e)
setErr(msg)
} finally {
setBusy(false)
}
}
const handleUploadAndInsert = async () => {
if (!uploadFile) {
alert('Bitte eine Datei wählen.')
return
}
const size = sanitizeInlineMediaSize(displaySize)
const inferred = inferExerciseMediaType(uploadFile)
const fd = new FormData()
fd.append('file', uploadFile)
fd.append('media_type', inferred)
fd.append('title', uploadTitle.trim())
fd.append('description', '')
fd.append('context', 'ablauf')
fd.append('is_primary', 'false')
setBusy(true)
setErr(null)
try {
const row = await api.uploadExerciseMedia(exerciseId, fd)
const mid = row?.id
if (mid == null) {
throw new Error('Antwort ohne exercise_media-ID')
}
await onMediaListChanged()
const cap = sanitizeInlineMediaCaption(
uploadTitle.trim() || uploadFile.name || '',
)
onInserted(Number(mid), size, cap)
setUploadFile(null)
setUploadTitle('')
setUploadInputKey((k) => k + 1)
onClose()
} catch (e) {
if (e.code === 'MEDIA_ASSET_IN_TRASH' && e.payload?.media_asset_id != null) {
alert(
'Dieselbe Datei existiert bereits im Papierkorb — bitte in der Medienbibliothek reaktivieren oder eine andere Datei wählen.',
)
} else {
alert(e.message || String(e))
}
setErr(e.message || String(e))
} finally {
setBusy(false)
}
}
const selectedLinked = selectedAssetId != null && assetToExerciseMedia.has(Number(selectedAssetId))
if (!open) return null
return (
<div className="admin-modal-backdrop" role="presentation" onClick={(e) => e.target === e.currentTarget && !busy && onClose()}>
<div
className="admin-modal-sheet rte-inline-media-modal"
role="dialog"
aria-modal="true"
aria-labelledby="rte-inline-file-title"
style={{
maxWidth: '560px',
width: '100%',
maxHeight: '90vh',
display: 'flex',
flexDirection: 'column',
}}
onClick={(e) => e.stopPropagation()}
>
<div className="admin-modal-sheet__header">
<h3 id="rte-inline-file-title" className="admin-modal-sheet__title">
Medium im Textfeld
</h3>
<button type="button" className="btn btn-secondary admin-modal-sheet__close" disabled={busy} onClick={onClose}>
Schließen
</button>
</div>
<div style={{ padding: '10px 12px', borderBottom: '1px solid var(--border)', display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
<button
type="button"
className={`btn btn-secondary ${tab === 'library' ? 'rte-tab--active' : ''}`}
style={{ fontSize: '13px' }}
onClick={() => setTab('library')}
disabled={busy}
>
Aus Mediathek
</button>
<button
type="button"
className={`btn btn-secondary ${tab === 'upload' ? 'rte-tab--active' : ''}`}
style={{ fontSize: '13px' }}
onClick={() => setTab('upload')}
disabled={busy}
>
Neu hochladen
</button>
</div>
<div style={{ overflowY: 'auto', flex: 1, padding: '12px 14px' }}>
{err && !loading ? (
<p style={{ color: 'var(--danger)', marginTop: '0', marginBottom: '12px', fontSize: '0.9rem' }}>{err}</p>
) : null}
{tab === 'library' && (
<>
<label className="form-label">Suche in der Bibliothek</label>
<input
className="form-input"
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder="Name, Tag, © …"
disabled={busy}
/>
{loading ? <p style={{ color: 'var(--text3)', marginTop: '12px' }}>Laden…</p> : null}
<div className="rte-inline-asset-grid" style={{ marginTop: '14px' }}>
{items.map((it) => {
const id = it.id
const selected = selectedAssetId === id
const label = it.original_filename || it.copyright_notice || `Archiv #${id}`
const linked = assetToExerciseMedia.has(Number(id))
return (
<button
key={id}
type="button"
className={`rte-inline-asset-tile${selected ? ' rte-inline-asset-tile--selected' : ''}`}
onClick={() => setSelectedAssetId(id)}
disabled={busy}
>
<div className="rte-inline-asset-tile__thumb" aria-hidden>
<RtePickerAssetThumb asset={it} />
</div>
{linked ? (
<span className="rte-inline-asset-tile__badge">Bereits verknüpft</span>
) : null}
<span className="rte-inline-asset-tile__meta">
{(it.mime_type || '').split('/')[0] || 'datei'}
</span>
<span className="rte-inline-asset-tile__name">{label}</span>
</button>
)
})}
</div>
{!loading && items.length === 0 ? (
<p style={{ color: 'var(--text3)', marginTop: '12px' }}>Keine Treffer — Suche anpassen oder „Neu hochladen“.</p>
) : null}
</>
)}
{tab === 'upload' && (
<>
<label className="form-label">Datei</label>
<div className="rte-inline-file-row">
<input
key={uploadInputKey}
id="rte-inline-file-upload-input"
type="file"
accept="image/*,video/*,application/pdf"
className="rte-inline-file-input-hidden"
disabled={busy}
onChange={(e) => {
const f = e.target.files?.[0] || null
setUploadFile(f)
}}
/>
<label htmlFor="rte-inline-file-upload-input" className="btn btn-secondary rte-inline-file-pick-btn">
Datei auswählen
</label>
<span className="rte-inline-file-name" title={uploadFile?.name || ''}>
{uploadFile ? uploadFile.name : 'Keine Datei ausgewählt'}
</span>
</div>
<label className="form-label" style={{ marginTop: '12px' }}>
Titel (optional)
</label>
<input
className="form-input"
value={uploadTitle}
onChange={(e) => setUploadTitle(e.target.value)}
disabled={busy}
/>
</>
)}
</div>
<div style={{ padding: '12px 14px', borderTop: '1px solid var(--border)', flexShrink: 0 }}>
<div className="form-row" style={{ marginBottom: '12px' }}>
<label className="form-label" style={{ marginBottom: '4px' }}>
Darstellung im Text
</label>
<select className="form-input" value={displaySize} onChange={(e) => setDisplaySize(e.target.value)} disabled={busy}>
{INLINE_MEDIA_SIZES.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
</div>
{tab === 'library' ? (
<button
type="button"
className="btn btn-primary btn-full"
disabled={busy || !selectedAssetId}
onClick={handleLinkSelected}
>
{busy ? 'Bitte warten…' : selectedLinked ? 'In Text einfügen (bereits verknüpft)' : 'Verknüpfen & in Text einfügen'}
</button>
) : (
<button type="button" className="btn btn-primary btn-full" disabled={busy || !uploadFile} onClick={handleUploadAndInsert}>
{busy ? 'Hochladen…' : 'Hochladen & in Text einfügen'}
</button>
)}
</div>
</div>
</div>
)
}
@@ -0,0 +1,71 @@
import React from 'react'
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
import { sanitizeInlineMediaSize } from '../constants/inlineExerciseMedia'
/**
* Ein ausgeliefertes exercise_media für Übungslisten (Liste + Inline gleiche Darstellung).
* @param {{ media: object, exerciseId: number, layoutSize?: string }} props
*/
export default function ExerciseMediaEmbed({ exerciseId, media, layoutSize = 'medium' }) {
const sz = sanitizeInlineMediaSize(layoutSize)
const box =
sz === 'small'
? { maxWidth: 'min(280px, 33vw)', marginTop: '0.5rem' }
: sz === 'full'
? { maxWidth: '100%', marginTop: '0.5rem' }
: { maxWidth: 'min(560px, 85vw)', marginTop: '0.5rem' }
if (!media || exerciseId == null) return null
if (media.embed_url) {
return (
<div
style={{
...box,
wordBreak: 'break-word',
overflowWrap: 'anywhere',
fontSize: sz === 'small' ? '0.88rem' : undefined,
}}
>
<a href={media.embed_url} target="_blank" rel="noreferrer">
{media.title?.trim() || media.embed_url}
</a>
{media.embed_platform && (
<span style={{ color: 'var(--text2)', marginLeft: '0.35rem', fontSize: '0.82rem', display: 'inline' }}>
({media.embed_platform})
</span>
)}
</div>
)
}
const src = resolveExerciseMediaFileUrl(exerciseId, media)
if (!src) return null
if (media.media_type === 'image' || (media.mime_type && media.mime_type.startsWith('image/'))) {
return (
<div style={box}>
<img
src={src}
alt={media.title || media.original_filename || ''}
style={{ width: '100%', maxWidth: '100%', height: 'auto', borderRadius: '8px', display: 'block' }}
/>
</div>
)
}
if (media.media_type === 'video' || (media.mime_type && media.mime_type.startsWith('video/'))) {
return (
<div style={box}>
<video
src={src}
controls
style={{ width: '100%', maxWidth: '100%', borderRadius: '8px', verticalAlign: 'top' }}
/>
</div>
)
}
return (
<div style={box}>
<a href={src} target="_blank" rel="noreferrer" style={{ display: 'inline-block', marginTop: '0.25rem' }}>
{media.title || media.original_filename || 'Datei öffnen'}
</a>
</div>
)
}
@@ -0,0 +1,68 @@
/**
* Kachelvorschau: Video nutzt ersten Frame (metadata), Bild = img, Embed = Label.
*/
import React from 'react'
import { resolveExerciseMediaFileUrl } from '../utils/exerciseMediaUrl'
export default function ExerciseMediaThumbTile({ exerciseId, media, onOpenPreview, size = 72 }) {
const src = !media.embed_url ? resolveExerciseMediaFileUrl(exerciseId, media) : null
const commonStyle = {
width: '100%',
height: '100%',
objectFit: 'cover',
}
return (
<div
role="button"
tabIndex={0}
title="Vorschau"
onClick={() => onOpenPreview(media)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
onOpenPreview(media)
}
}}
style={{
width: size,
height: size,
flexShrink: 0,
borderRadius: '8px',
overflow: 'hidden',
background: 'var(--surface2, rgba(127,127,127,0.12))',
border: '1px solid var(--border)',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
{media.embed_url ? (
<span style={{ fontSize: '11px', padding: '4px', color: 'var(--text2)', textAlign: 'center' }}>
{media.embed_platform || 'Embed'}
</span>
) : (media.mime_type?.startsWith('image/') || media.media_type === 'image') && src ? (
<img alt="" src={src} style={commonStyle} />
) : (media.mime_type?.startsWith('video/') || media.media_type === 'video') && src ? (
<video
src={src}
muted
playsInline
preload="metadata"
style={{ ...commonStyle, pointerEvents: 'none' }}
onLoadedMetadata={(e) => {
try {
const el = e.currentTarget
const d = el.duration
el.currentTime = Number.isFinite(d) && d > 0 ? Math.min(0.05, d * 0.01) : 0.05
} catch {
/* ignore */
}
}}
/>
) : (
<span style={{ fontSize: '11px', color: 'var(--text2)' }}>Datei</span>
)}
</div>
)
}
+8 -16
View File
@@ -4,15 +4,7 @@
import React, { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import api from '../utils/api'
import { sanitizeTrainerHtml } from '../utils/htmlUtils'
function HtmlBlock({ html, className = '' }) {
if (!html || !String(html).trim()) return null
const safe = sanitizeTrainerHtml(html)
return (
<div className={`rich-text-content ${className}`} dangerouslySetInnerHTML={{ __html: safe }} />
)
}
import ExerciseRichTextBlock from './ExerciseRichTextBlock'
function TagMini({ exercise }) {
const parts = []
@@ -129,7 +121,7 @@ export default function ExercisePeekModal({
</div>
{variant.description ? (
<div style={{ marginTop: 8, fontSize: '0.9rem', color: 'var(--text2)' }}>
<HtmlBlock html={variant.description} />
<ExerciseRichTextBlock html={variant.description} exerciseId={exercise.id} media={exercise.media} />
</div>
) : null}
{variant.execution_changes ? (
@@ -137,14 +129,14 @@ export default function ExercisePeekModal({
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', marginBottom: 6 }}>
Durchführung (Variante)
</h4>
<HtmlBlock html={variant.execution_changes} />
<ExerciseRichTextBlock html={variant.execution_changes} exerciseId={exercise.id} media={exercise.media} />
</div>
) : null}
</div>
) : null}
{exercise.summary && (
<div style={{ fontSize: '0.95rem', color: 'var(--text2)' }}>
<HtmlBlock html={exercise.summary} />
<ExerciseRichTextBlock html={exercise.summary} exerciseId={exercise.id} media={exercise.media} />
</div>
)}
<TagMini exercise={exercise} />
@@ -154,25 +146,25 @@ export default function ExercisePeekModal({
{exercise.goal && (
<>
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', marginBottom: 6 }}>Ziel</h4>
<HtmlBlock html={exercise.goal} />
<ExerciseRichTextBlock html={exercise.goal} exerciseId={exercise.id} media={exercise.media} />
</>
)}
{exercise.preparation && (
<>
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', margin: '14px 0 6px' }}>Vorbereitung</h4>
<HtmlBlock html={exercise.preparation} />
<ExerciseRichTextBlock html={exercise.preparation} exerciseId={exercise.id} media={exercise.media} />
</>
)}
{exercise.execution && (
<>
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', margin: '14px 0 6px' }}>Ablauf</h4>
<HtmlBlock html={exercise.execution} />
<ExerciseRichTextBlock html={exercise.execution} exerciseId={exercise.id} media={exercise.media} />
</>
)}
{exercise.trainer_notes && (
<>
<h4 style={{ fontSize: '0.85rem', color: 'var(--text3)', margin: '14px 0 6px' }}>Trainer-Hinweise</h4>
<HtmlBlock html={exercise.trainer_notes} />
<ExerciseRichTextBlock html={exercise.trainer_notes} exerciseId={exercise.id} media={exercise.media} />
</>
)}
</>
+258 -76
View File
@@ -4,23 +4,26 @@
*/
import React, { useState, useEffect, useMemo, useCallback } from 'react'
import api from '../utils/api'
import { useAuth } from '../context/AuthContext'
import { SKILL_LEVEL_OPTIONS } from '../constants/skillLevels'
import {
INITIAL_EXERCISE_LIST_FILTERS,
mergeExerciseListPrefsFromApi,
splitMnCatalogRules,
splitScalarCatalogRules,
} from '../constants/exerciseListFilters'
import MultiSelectCombo from './MultiSelectCombo'
import ExerciseFocusRulePicker from './ExerciseFocusRulePicker'
import CatalogRulePicker from './CatalogRulePicker'
const PAGE_SIZE = 100
const LEVEL_FILTER_OPTS = SKILL_LEVEL_OPTIONS.filter((o) => o.level != null)
const INITIAL_FILTERS = {
focus_area_ids: [],
style_direction_ids: [],
training_type_ids: [],
target_group_ids: [],
skill_ids: [],
skill_min_level: '',
skill_max_level: '',
visibility_any: [],
status_any: [],
}
const INITIAL_FILTERS = { ...INITIAL_EXERCISE_LIST_FILTERS }
/** Stub-Ziel für API-Validator (mind. Ziel oder Durchführung); Nutzer ergänzt Details in der Übungsbearbeitung. */
const QUICK_CREATE_GOAL_PLACEHOLDER =
'Aus der Trainingsplanung angelegt — bitte Ziel und Durchführung in der Übungsbearbeitung ergänzen.'
export default function ExercisePickerModal({
open,
@@ -28,7 +31,9 @@ export default function ExercisePickerModal({
onSelectExercise,
multiSelect = false,
onSelectExercises = null,
enableQuickCreateDraft = false,
}) {
const { user } = useAuth()
const [catalogs, setCatalogs] = useState({
focusAreas: [],
styleDirections: [],
@@ -49,6 +54,10 @@ export default function ExercisePickerModal({
const [offset, setOffset] = useState(0)
const [hasMore, setHasMore] = useState(false)
const [multiPicked, setMultiPicked] = useState([])
const [quickOpen, setQuickOpen] = useState(false)
const [quickTitle, setQuickTitle] = useState('')
const [quickSummary, setQuickSummary] = useState('')
const [quickSaving, setQuickSaving] = useState(false)
const toggleMultiPick = (ex) => {
setMultiPicked((prev) =>
@@ -110,8 +119,14 @@ export default function ExercisePickerModal({
setOffset(0)
setHasMore(false)
setMultiPicked([])
setQuickOpen(false)
setQuickTitle('')
setQuickSummary('')
setQuickSaving(false)
return
}
}, [open])
setFilters(mergeExerciseListPrefsFromApi(user?.exercise_list_prefs))
}, [open, user?.exercise_list_prefs])
const focusOptions = useMemo(
() => catalogs.focusAreas.map((fa) => ({ id: fa.id, label: `${fa.icon || ''} ${fa.name || ''}`.trim() })),
@@ -156,20 +171,46 @@ export default function ExercisePickerModal({
const n = (v) => (v === '' || v == null ? undefined : Number(v))
const ids = (arr) =>
Array.isArray(arr) && arr.length ? arr.map((x) => Number(x)).filter((x) => !Number.isNaN(x)) : undefined
const fMn = splitMnCatalogRules(filters.focus_rules)
if (fMn.includeIds.length) q.focus_area_must_include_ids = fMn.includeIds
if (fMn.excludeIds.length) q.focus_area_must_exclude_ids = fMn.excludeIds
if (filters.focus_only_without) q.focus_only_without_focus_areas = true
const fa = ids(filters.focus_area_ids)
if (fa?.length) q.focus_area_ids = fa
const sd = ids(filters.style_direction_ids)
if (sd?.length) q.style_direction_ids = sd
const tt = ids(filters.training_type_ids)
if (tt?.length) q.training_type_ids = tt
const tg = ids(filters.target_group_ids)
if (tg?.length) q.target_group_ids = tg
const sdMn = splitMnCatalogRules(filters.style_direction_rules)
if (sdMn.includeIds.length) q.style_direction_must_include_ids = sdMn.includeIds
if (sdMn.excludeIds.length) q.style_direction_must_exclude_ids = sdMn.excludeIds
const sdLegacy = ids(filters.style_direction_ids)
if (sdLegacy?.length) q.style_direction_ids = sdLegacy
const ttMn = splitMnCatalogRules(filters.training_type_rules)
if (ttMn.includeIds.length) q.training_type_must_include_ids = ttMn.includeIds
if (ttMn.excludeIds.length) q.training_type_must_exclude_ids = ttMn.excludeIds
const ttLegacy = ids(filters.training_type_ids)
if (ttLegacy?.length) q.training_type_ids = ttLegacy
const tgMn = splitMnCatalogRules(filters.target_group_rules)
if (tgMn.includeIds.length) q.target_group_must_include_ids = tgMn.includeIds
if (tgMn.excludeIds.length) q.target_group_must_exclude_ids = tgMn.excludeIds
const tgLegacy = ids(filters.target_group_ids)
if (tgLegacy?.length) q.target_group_ids = tgLegacy
const visMn = splitScalarCatalogRules(filters.visibility_rules)
if (visMn.includeVals.length) q.visibility_any = visMn.includeVals
if (visMn.excludeVals.length) q.visibility_exclude_any = visMn.excludeVals
const stMn = splitScalarCatalogRules(filters.status_rules)
if (stMn.includeVals.length) q.status_any = stMn.includeVals
if (stMn.excludeVals.length) q.status_exclude_any = stMn.excludeVals
const sk = ids(filters.skill_ids)
if (sk?.length) q.skill_ids = sk
if (filters.skill_min_level) q.skill_min_level = n(filters.skill_min_level)
if (filters.skill_max_level) q.skill_max_level = n(filters.skill_max_level)
if (filters.visibility_any?.length) q.visibility_any = [...filters.visibility_any]
if (filters.status_any?.length) q.status_any = [...filters.status_any]
if (filters.exclude_without_focus) q.exclude_without_focus = true
if (filters.include_archived) q.include_archived = true
if (debouncedSearch) q.search = debouncedSearch
if (debouncedAi) q.ai_search = debouncedAi
return q
@@ -182,6 +223,7 @@ export default function ExercisePickerModal({
try {
const batch = await api.listExercises({
...queryBase,
include_archived: true,
include_variants: true,
limit: PAGE_SIZE,
offset: 0,
@@ -209,6 +251,7 @@ export default function ExercisePickerModal({
try {
const batch = await api.listExercises({
...queryBase,
include_archived: true,
include_variants: true,
limit: PAGE_SIZE,
offset,
@@ -226,6 +269,48 @@ export default function ExercisePickerModal({
const resetFilters = () => setFilters({ ...INITIAL_FILTERS })
const submitQuickCreate = async () => {
const title = (quickTitle || '').trim()
if (title.length < 3) {
alert('Titel: mindestens 3 Zeichen.')
return
}
const summaryRaw = (quickSummary || '').trim()
setQuickSaving(true)
try {
const created = await api.createExercise({
title,
summary: summaryRaw || null,
goal: QUICK_CREATE_GOAL_PLACEHOLDER,
execution: null,
visibility: 'private',
status: 'draft',
equipment: [],
focus_areas_multi: [],
training_styles_multi: [],
training_types_multi: [],
target_groups_multi: [],
age_groups: [],
skills: [],
club_id: null,
})
if (!created?.id) {
throw new Error('Anlegen fehlgeschlagen')
}
if (multiSelect && typeof onSelectExercises === 'function') {
await Promise.resolve(onSelectExercises([created]))
} else if (typeof onSelectExercise === 'function') {
await Promise.resolve(onSelectExercise(created))
}
onClose()
} catch (e) {
console.error(e)
alert(e.message || 'Übung konnte nicht angelegt werden')
} finally {
setQuickSaving(false)
}
}
if (!open) return null
return (
@@ -252,6 +337,75 @@ export default function ExercisePickerModal({
</button>
</div>
{enableQuickCreateDraft ? (
<div
style={{
padding: '10px 1rem 12px',
borderBottom: '1px solid var(--border)',
flexShrink: 0,
background: 'var(--surface2)',
}}
>
<button
type="button"
className="btn btn-secondary"
style={{ width: '100%' }}
onClick={() => setQuickOpen((v) => !v)}
aria-expanded={quickOpen}
>
{quickOpen ? 'Neue Übung ausblenden' : 'Neue Übung anlegen (Entwurf, privat)'}
</button>
{quickOpen ? (
<div style={{ marginTop: '12px', display: 'grid', gap: '10px' }}>
<p style={{ margin: 0, fontSize: '13px', color: 'var(--text2)', lineHeight: 1.45 }}>
Wird mit Sichtbarkeit <strong>privat</strong> und Status <strong>Entwurf</strong> gespeichert und
erscheint auf dem Dashboard zum Weiterbearbeiten. Nach dem Speichern wird die Übung direkt in den
Ablauf übernommen.
</p>
<div>
<label className="form-label" htmlFor="ex-picker-quick-title">
Titel
</label>
<input
id="ex-picker-quick-title"
type="text"
className="form-input"
value={quickTitle}
onChange={(e) => setQuickTitle(e.target.value)}
autoComplete="off"
minLength={3}
maxLength={300}
placeholder="z. B. Partnerübung Abwehr"
/>
</div>
<div>
<label className="form-label" htmlFor="ex-picker-quick-summary">
Kurzbeschreibung
</label>
<textarea
id="ex-picker-quick-summary"
className="form-input"
rows={3}
value={quickSummary}
onChange={(e) => setQuickSummary(e.target.value)}
placeholder="Optional: grobe Idee, Kontext aus der Planung …"
/>
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', justifyContent: 'flex-end' }}>
<button
type="button"
className="btn btn-primary"
disabled={quickSaving || (quickTitle || '').trim().length < 3}
onClick={submitQuickCreate}
>
{quickSaving ? 'Wird angelegt…' : 'Entwurf anlegen und übernehmen'}
</button>
</div>
</div>
) : null}
</div>
) : null}
<div style={{ padding: '0 1rem 0.75rem', borderBottom: '1px solid var(--border)', flexShrink: 0 }}>
<div style={{ display: 'grid', gap: '0.65rem' }}>
<div>
@@ -292,45 +446,44 @@ export default function ExercisePickerModal({
{filterOpen && (
<div style={{ marginTop: '0.35rem', fontSize: '13px', color: 'var(--text2)' }}>
<p style={{ margin: '0 0 12px 0' }}>
Zwischen den Bereichen gilt <strong>UND</strong>, innerhalb ODER wie in der Übungsübersicht.
Felder gelten mit <strong>UND</strong>. Kataloge: mehrere „+“ = alle zutreffend; „−“ schließt aus.
Sichtbarkeit/Status: mehrere „+“ = eine davon (ODER); „−“ blendet aus.
</p>
<div className="exercise-filters-modal-grid">
<div>
<label className="form-label">Fokus</label>
<MultiSelectCombo
value={filters.focus_area_ids}
onChange={(v) => setFilters((f) => ({ ...f, focus_area_ids: v }))}
options={focusOptions}
placeholder="Fokus …"
/>
</div>
<div>
<label className="form-label">Stilrichtung</label>
<MultiSelectCombo
value={filters.style_direction_ids}
onChange={(v) => setFilters((f) => ({ ...f, style_direction_ids: v }))}
options={styleOptions}
placeholder="Stilrichtung …"
/>
</div>
<div>
<label className="form-label">Trainingsstil</label>
<MultiSelectCombo
value={filters.training_type_ids}
onChange={(v) => setFilters((f) => ({ ...f, training_type_ids: v }))}
options={trainingTypeOptions}
placeholder="Trainingsstil …"
/>
</div>
<div>
<label className="form-label">Zielgruppe</label>
<MultiSelectCombo
value={filters.target_group_ids}
onChange={(v) => setFilters((f) => ({ ...f, target_group_ids: v }))}
options={targetGroupOptions}
placeholder="Zielgruppe …"
/>
</div>
<ExerciseFocusRulePicker
focusOptions={focusOptions}
focusRules={filters.focus_rules}
focusOnlyWithout={filters.focus_only_without}
legacyFocusAreaIds={filters.focus_area_ids}
onPatch={(patch) => setFilters((f) => ({ ...f, ...patch }))}
/>
<div className="exercise-filters-modal-grid exercise-filters-modal-grid--catalog" style={{ marginTop: 12 }}>
<CatalogRulePicker
label="Stilrichtung"
hint="+ alle nötig (UND). − verbietet Zuordnung."
options={styleOptions}
rules={filters.style_direction_rules}
rulesFieldName="style_direction_rules"
placeholder="Stil …"
onPatch={(patch) => setFilters((f) => ({ ...f, ...patch }))}
/>
<CatalogRulePicker
label="Trainingsstil"
hint="+ alle nötig (UND). − verbietet Zuordnung."
options={trainingTypeOptions}
rules={filters.training_type_rules}
rulesFieldName="training_type_rules"
placeholder="Trainingsstil …"
onPatch={(patch) => setFilters((f) => ({ ...f, ...patch }))}
/>
<CatalogRulePicker
label="Zielgruppe"
hint="+ alle nötig (UND). − verbietet Zuordnung."
options={targetGroupOptions}
rules={filters.target_group_rules}
rulesFieldName="target_group_rules"
placeholder="Gruppe …"
onPatch={(patch) => setFilters((f) => ({ ...f, ...patch }))}
/>
</div>
<div style={{ marginTop: 12 }}>
<label className="form-label">Fähigkeit</label>
@@ -369,25 +522,54 @@ export default function ExercisePickerModal({
</select>
</div>
</div>
<div className="exercise-filters-modal-grid exercise-filters-modal-grid--two" style={{ marginTop: 12 }}>
<div>
<label className="form-label">Sichtbarkeit</label>
<MultiSelectCombo
value={filters.visibility_any}
onChange={(v) => setFilters((f) => ({ ...f, visibility_any: v }))}
options={visibilityOptions}
placeholder="Sichtbarkeit …"
<div className="exercise-filters-modal-grid exercise-filters-modal-grid--two exercise-filters-modal-grid--catalog" style={{ marginTop: 12 }}>
<CatalogRulePicker
label="Sichtbarkeit"
options={visibilityOptions}
rules={filters.visibility_rules}
rulesFieldName="visibility_rules"
idKind="string"
placeholder="Sichtbarkeit …"
onPatch={(patch) => setFilters((f) => ({ ...f, ...patch }))}
/>
<CatalogRulePicker
label="Status"
options={statusOptions}
rules={filters.status_rules}
rulesFieldName="status_rules"
idKind="string"
placeholder="Status …"
onPatch={(patch) => setFilters((f) => ({ ...f, ...patch }))}
/>
</div>
<div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 10 }}>
<label
style={{
display: 'flex',
alignItems: 'center',
gap: 8,
cursor: filters.focus_only_without ? 'not-allowed' : 'pointer',
opacity: filters.focus_only_without ? 0.55 : 1,
}}
>
<input
type="checkbox"
disabled={!!filters.focus_only_without}
checked={!!filters.exclude_without_focus}
onChange={(e) =>
setFilters((f) => ({
...f,
exclude_without_focus: e.target.checked,
...(e.target.checked ? { focus_only_without: false } : {}),
}))
}
/>
</div>
<div>
<label className="form-label">Status</label>
<MultiSelectCombo
value={filters.status_any}
onChange={(v) => setFilters((f) => ({ ...f, status_any: v }))}
options={statusOptions}
placeholder="Status …"
/>
</div>
<span>Ohne Fokus ausblenden</span>
</label>
<p style={{ margin: 0, fontSize: '12px', color: 'var(--text2)' }}>
Hinweis: Für die Planung werden archivierte Übungen bei der Suche immer mit eingeschlossen (bestehende
Zuordnungen).
</p>
</div>
</div>
)}
@@ -5,6 +5,7 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import api from '../utils/api'
import { useAuth } from '../context/AuthContext'
import ExercisePickerModal from './ExercisePickerModal'
const VIS_OPTIONS = [
@@ -99,6 +100,13 @@ export default function ExerciseProgressionGraphPanel({
anchorExerciseId = null,
anchorTitle = null,
}) {
const { user } = useAuth()
const isSuperadmin = user?.role === 'superadmin'
const filteredGraphVisOptions = useMemo(
() => VIS_OPTIONS.filter((o) => o.value !== 'official' || isSuperadmin),
[isSuperadmin],
)
const [graphs, setGraphs] = useState([])
const [selectedGraphId, setSelectedGraphId] = useState(null)
const [edges, setEdges] = useState([])
@@ -566,7 +574,7 @@ export default function ExerciseProgressionGraphPanel({
value={newGraphVisibility}
onChange={(e) => setNewGraphVisibility(e.target.value)}
>
{VIS_OPTIONS.map((o) => (
{filteredGraphVisOptions.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
@@ -599,7 +607,7 @@ export default function ExerciseProgressionGraphPanel({
<div className="form-row">
<label className="form-label">Sichtbarkeit</label>
<select className="form-input" value={metaVisibility} onChange={(e) => setMetaVisibility(e.target.value)}>
{VIS_OPTIONS.map((o) => (
{filteredGraphVisOptions.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
@@ -0,0 +1,107 @@
import React, { useMemo } from 'react'
import { sanitizeExerciseRichDisplayHtml } from '../utils/exerciseRichTextSanitize'
import ExerciseMediaEmbed from './ExerciseMediaEmbed'
function isTrashHidden(m) {
return String(m?.asset_lifecycle_state || 'active').toLowerCase() === 'trash_hidden'
}
function buildVisibleMediaMap(mediaList) {
const map = new Map()
for (const m of mediaList || []) {
if (!m || m.id == null || isTrashHidden(m)) continue
map.set(Number(m.id), m)
}
return map
}
function domToReactNodes(node, exerciseId, mediaById, path) {
if (node.nodeType === Node.TEXT_NODE) {
const t = node.textContent
return t ? t : null
}
if (node.nodeType !== Node.ELEMENT_NODE) return null
const el = node
const tag = el.tagName.toLowerCase()
const key = path.join('.')
if (tag === 'span' && el.getAttribute('data-shinkan-exercise-media')) {
const raw = el.getAttribute('data-shinkan-exercise-media')
const mid = parseInt(raw, 10)
if (!Number.isFinite(mid) || mid < 1) {
return (
<span key={key} className="shinkan-inline-media-missing" style={{ color: 'var(--text3)', fontSize: '0.9em' }}>
[Ungültiger Medienverweis]
</span>
)
}
const media = mediaById.get(mid)
if (!media) {
return (
<span key={key} className="shinkan-inline-media-missing" style={{ color: 'var(--text3)', fontSize: '0.9em' }}>
[Medium nicht verfügbar]
</span>
)
}
const rawSize = (el.getAttribute('data-shinkan-exercise-media-size') || 'medium').toLowerCase().trim()
const layoutSize = rawSize === 'small' || rawSize === 'full' ? rawSize : 'medium'
const wrapClass =
layoutSize === 'small'
? 'shinkan-inline-media-wrap shinkan-inline-media-wrap--sm'
: layoutSize === 'full'
? 'shinkan-inline-media-wrap shinkan-inline-media-wrap--full'
: 'shinkan-inline-media-wrap shinkan-inline-media-wrap--md'
const lc = String(media.asset_lifecycle_state || 'active').toLowerCase()
return (
<span key={key} className={wrapClass} style={{ display: 'inline-block', verticalAlign: 'top' }}>
{lc === 'trash_soft' && (
<span style={{ fontSize: '0.75rem', color: 'var(--danger)', display: 'block', marginBottom: '4px' }}>
Dieses Medium ist im Papierkorb.
</span>
)}
<ExerciseMediaEmbed exerciseId={exerciseId} media={media} layoutSize={layoutSize} />
</span>
)
}
const children = []
const childNodes = Array.from(el.childNodes)
childNodes.forEach((ch, i) => {
const sub = domToReactNodes(ch, exerciseId, mediaById, [...path, String(i)])
if (sub != null && sub !== false) children.push(sub)
})
const props = { key }
if (tag === 'a' && el.getAttribute('href')) {
props.href = el.getAttribute('href')
props.target = '_blank'
props.rel = 'noreferrer'
}
return React.createElement(tag, props, children.length ? children : null)
}
/**
* Zentraler Anzeige-Pfad für Übungs-Rich-Text inkl. §11 Inline-Medien.
* @param {{ html?: string|null, exerciseId?: number|null, media?: object[]|null, className?: string }} props
*/
export default function ExerciseRichTextBlock({ html, exerciseId, media, className = '' }) {
const safe = useMemo(() => sanitizeExerciseRichDisplayHtml(html), [html])
const mediaById = useMemo(() => buildVisibleMediaMap(media), [media])
const body = useMemo(() => {
if (!safe.trim()) return null
const tpl = document.createElement('template')
tpl.innerHTML = safe
const nodes = []
Array.from(tpl.content.childNodes).forEach((ch, i) => {
const r = domToReactNodes(ch, exerciseId, mediaById, [String(i)])
if (r != null) nodes.push(r)
})
return nodes
}, [safe, exerciseId, mediaById])
if (!body || body.length === 0) return null
return <div className={`rich-text-content ${className}`.trim()}>{body}</div>
}
@@ -0,0 +1,39 @@
import { useAuth } from '../context/AuthContext'
/**
* Hinweis, wenn der Vereinszugang (Mitgliedschaft) deaktiviert wurde — Login bleibt möglich.
*/
export default function InactiveMembershipBanner() {
const { user } = useAuth()
const inactive = (user?.clubs || []).filter(
(c) => (c.membership_status || '').toString().trim().toLowerCase() === 'inactive'
)
if (!inactive.length) return null
const names = inactive.map((c) => c.name || `Verein #${c.id}`).join(', ')
return (
<div
role="status"
className="inactive-membership-banner"
style={{
marginBottom: '0.75rem',
padding: '0.65rem 0.85rem',
borderRadius: '8px',
background: 'var(--surface2, #2a2a2a)',
border: '1px solid color-mix(in srgb, var(--warning, #d4a012) 45%, transparent)',
color: 'var(--text1)',
fontSize: '0.88rem',
lineHeight: 1.45,
}}
>
<strong>Vereinszugang vorübergehend deaktiviert</strong>
<span style={{ display: 'block', marginTop: '0.35rem' }}>
Für {inactive.length === 1 ? 'den Verein' : 'die Vereine'}{' '}
<strong>{names}</strong>{' '}
ist der Zugang zu Vereinsinhalten ausgesetzt — du kannst dich weiterhin anmelden und z.&nbsp;B.
öffentliche Inhalte oder andere Vereine nutzen. Bei Fragen wende dich an eine:n Vereinsadministrator:in.
</span>
</div>
)
}
+3 -5
View File
@@ -1,16 +1,14 @@
import { Link, useLocation, useNavigate } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import { getResolvedActiveClubIdForUi, activeClubMemberships } from '../utils/activeClub'
function Navigation() {
const location = useLocation()
const navigate = useNavigate()
const { user, logout, setActiveClub } = useAuth()
const clubs = user?.clubs || []
const selectClubId =
user?.active_club_id != null && clubs.some((c) => c.id === user.active_club_id)
? user.active_club_id
: clubs[0]?.id
const clubs = activeClubMemberships(user?.clubs)
const selectClubId = getResolvedActiveClubIdForUi(user)
const handleLogout = async () => {
await logout()
@@ -0,0 +1,50 @@
/**
* Einheitliche Sektions-Navigation: Chip-Zeile wie Admin-Stammdaten (.admin-page-subtabs).
* Für „Tabs“ (role=tablist) oder kompakte Umschalter (aria-pressed, role=group).
*/
export default function PageSectionNav({
ariaLabel,
value,
onChange,
items,
className = '',
iconSize = 16,
semantics = 'tabs',
}) {
const isToggle = semantics === 'toggle'
return (
<div
className={`admin-page-subtabs page-section-nav ${className}`.trim()}
role={isToggle ? 'group' : 'tablist'}
aria-label={ariaLabel}
>
{items.map((item) => {
const Icon = item.icon
const active = value === item.id
const disabled = Boolean(item.disabled)
return (
<button
key={item.id}
type="button"
role={isToggle ? undefined : 'tab'}
aria-selected={isToggle ? undefined : active}
aria-pressed={isToggle ? active : undefined}
disabled={disabled}
className={
'admin-page-subtabs__btn' +
(active ? ' admin-page-subtabs__btn--active' : '')
}
onClick={() => {
if (!disabled) onChange(item.id)
}}
>
{Icon ? (
<Icon size={iconSize} strokeWidth={2} className="page-section-nav__icon" aria-hidden />
) : null}
<span>{item.label}</span>
</button>
)
})}
</div>
)
}
@@ -0,0 +1,10 @@
import { Navigate } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
/** Nur Super-Admins; andere Nutzer → Startseite. */
export default function PlatformAdminRoute({ children }) {
const { user } = useAuth()
const ok = user?.role === 'superadmin'
if (!ok) return <Navigate to="/" replace />
return children
}
+305 -2
View File
@@ -1,4 +1,12 @@
import React, { useRef, useEffect, useState, useCallback } from 'react'
import ExerciseInlineFileMediaModal from './ExerciseInlineFileMediaModal'
import ExerciseInlineEmbedModal from './ExerciseInlineEmbedModal'
import { sanitizeInlineMediaCaption } from '../utils/inlineMediaCaption'
import {
SHINKAN_EXERCISE_MEDIA_DRAG_MIME,
parseExerciseMediaDragPayload,
} from '../utils/exerciseInlineMediaRefs'
import { autoScrollForDragNearEdges } from '../utils/dragAutoScroll'
function exec(cmd, value = null) {
try {
@@ -45,12 +53,140 @@ function normalText() {
formatBlock('p')
}
function escapeHtmlAttr(s) {
return String(s)
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/</g, '&lt;')
}
function buildInlineExerciseMediaHtml(mediaId, displaySize = 'medium', caption = '') {
const sid = parseInt(String(mediaId), 10)
if (!Number.isFinite(sid) || sid < 1) return null
const sz = ['small', 'medium', 'full'].includes(displaySize) ? displaySize : 'medium'
const cap = sanitizeInlineMediaCaption(caption)
let attrs = `data-shinkan-exercise-media="${sid}" data-shinkan-exercise-media-size="${sz}" class="shinkan-inline-media"`
if (cap) attrs += ` data-shinkan-exercise-media-caption="${escapeHtmlAttr(cap)}"`
return `<span ${attrs}>\u2060</span>`
}
function patchExitGlyphAfterPlaceholder(editorEl, mediaId, sel) {
const sid = String(parseInt(String(mediaId), 10))
const hits = editorEl.querySelectorAll(`span.shinkan-inline-media[data-shinkan-exercise-media="${sid}"]`)
const span = hits[hits.length - 1]
if (!span?.parentNode || !sel) return
let n = span.nextSibling
if (!n || n.nodeType !== Node.TEXT_NODE || !n.textContent.includes('\u200B')) {
const zn = document.createTextNode('\u200B')
span.parentNode.insertBefore(zn, span.nextSibling)
n = zn
}
try {
const r = document.createRange()
r.setStart(n, n.textContent.length)
r.collapse(true)
sel.removeAllRanges()
sel.addRange(r)
} catch {
/* noop */
}
}
function insertExerciseMediaPlaceholder(editorEl, mediaId, displaySize = 'medium', caption = '') {
if (!editorEl || mediaId == null) return false
const html = buildInlineExerciseMediaHtml(mediaId, displaySize, caption)
if (!html) return false
editorEl.focus()
const sel = window.getSelection()
if (!sel) return false
let caretInside = false
if (sel.rangeCount > 0) {
try {
const r0 = sel.getRangeAt(0)
caretInside = editorEl.contains(r0.commonAncestorContainer)
} catch {
caretInside = false
}
}
if (!caretInside) {
const anchor = document.createRange()
try {
anchor.selectNodeContents(editorEl)
anchor.collapse(false)
} catch {
return false
}
sel.removeAllRanges()
sel.addRange(anchor)
}
let inserted = false
try {
inserted = document.execCommand('insertHTML', false, html)
} catch {
inserted = false
}
if (inserted) {
patchExitGlyphAfterPlaceholder(editorEl, mediaId, sel)
return true
}
let range = null
try {
range = sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null
} catch {
range = null
}
if (!range || !editorEl.contains(range.commonAncestorContainer)) {
range = document.createRange()
range.selectNodeContents(editorEl)
range.collapse(false)
sel.removeAllRanges()
sel.addRange(range)
}
try {
const tpl = document.createElement('template')
tpl.innerHTML = html
const span = tpl.content.firstChild
if (!span) return false
range.deleteContents()
range.insertNode(span)
const zn = document.createTextNode('\u200B')
span.parentNode.insertBefore(zn, span.nextSibling)
range.setStart(zn, zn.textContent.length)
range.collapse(true)
sel.removeAllRanges()
sel.addRange(range)
return true
} catch {
return false
}
}
/**
* Leichter WYSIWYG (contenteditable). Wert kommt von außen zuverlässig ins DOM (Edit-Modus).
* Leichter WYSIWYG (contenteditable).
* @param {{
* linkedExerciseMedia?: object[],
* }} [extra]
*/
export default function RichTextEditor({ value, onChange, placeholder, minHeight = '140px' }) {
export default function RichTextEditor({
value,
onChange,
placeholder,
minHeight = '140px',
inlineExerciseId = null,
linkedExerciseMedia = [],
onExerciseMediaListChanged,
}) {
const ref = useRef(null)
const pendingRangeRef = useRef(null)
const [focused, setFocused] = useState(false)
const [fileModalOpen, setFileModalOpen] = useState(false)
const [embedModalOpen, setEmbedModalOpen] = useState(false)
const showInlineToolbar = inlineExerciseId != null && Number(inlineExerciseId) > 0
useEffect(() => {
const el = ref.current
@@ -66,6 +202,129 @@ export default function RichTextEditor({ value, onChange, placeholder, minHeight
onChange(ref.current.innerHTML)
}, [onChange])
const refreshExerciseMedia = useCallback(async () => {
if (onExerciseMediaListChanged) {
await onExerciseMediaListChanged()
}
}, [onExerciseMediaListChanged])
const stashRangeAndOpen = useCallback((openFn) => (e) => {
e.preventDefault()
e.stopPropagation()
const el = ref.current
pendingRangeRef.current = el ? saveSelectionInside(el) : null
openFn()
}, [])
const finalizeInsertFromModal = useCallback(
(mediaId, displaySize, caption) => {
queueMicrotask(() => {
const shell = ref.current
if (!shell) return
shell.focus()
restoreSelection(pendingRangeRef.current)
const ok = insertExerciseMediaPlaceholder(shell, mediaId, displaySize, caption)
if (!ok) {
alert(
'Einfügen ist fehlgeschlagen — bitte Cursor ins Textfeld setzen und den Schalter erneut verwenden.',
)
return
}
sync()
shell.focus()
})
},
[sync],
)
const onEditorKeyDown = useCallback(
(e) => {
const el = ref.current
if (!el || e.key !== 'Enter') return
const sel = window.getSelection()
if (!sel || sel.rangeCount === 0 || !el.contains(sel.focusNode)) return
let node = sel.focusNode
let elNode = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement
const host = elNode?.closest?.('.shinkan-inline-media')
if (!host || !el.contains(host)) return
e.preventDefault()
patchExitGlyphAfterPlaceholder(el, host.getAttribute('data-shinkan-exercise-media'), sel)
try {
exec('insertParagraph')
} catch {
exec('insertLineBreak')
}
sync()
},
[sync],
)
const onEditorDragOver = useCallback(
(e) => {
if (!showInlineToolbar) return
const types = e.dataTransfer?.types ? Array.from(e.dataTransfer.types) : []
if (types.includes(SHINKAN_EXERCISE_MEDIA_DRAG_MIME)) {
e.preventDefault()
e.dataTransfer.dropEffect = 'copy'
autoScrollForDragNearEdges(e)
}
},
[showInlineToolbar],
)
const onEditorDrop = useCallback(
(e) => {
const el = ref.current
if (!el || !showInlineToolbar) return
const raw = e.dataTransfer?.getData(SHINKAN_EXERCISE_MEDIA_DRAG_MIME)
const parsed = parseExerciseMediaDragPayload(raw)
if (!parsed) return
e.preventDefault()
el.focus()
const sel = window.getSelection()
if (!sel) return
let r = null
try {
if (document.caretRangeFromPoint) {
r = document.caretRangeFromPoint(e.clientX, e.clientY)
}
} catch {
r = null
}
if (!r) {
try {
const p = document.caretPositionFromPoint?.(e.clientX, e.clientY)
if (p?.offsetNode) {
const nr = document.createRange()
nr.setStart(p.offsetNode, p.offset)
nr.collapse(true)
r = nr
}
} catch {
r = null
}
}
if (r && el.contains(r.commonAncestorContainer)) {
sel.removeAllRanges()
sel.addRange(r)
} else {
const anchor = document.createRange()
try {
anchor.selectNodeContents(el)
anchor.collapse(false)
} catch {
return
}
sel.removeAllRanges()
sel.addRange(anchor)
}
insertExerciseMediaPlaceholder(el, parsed.exerciseMediaId, 'medium', parsed.caption)
sync()
el.focus()
},
[sync, showInlineToolbar],
)
const run = (fn) => (e) => {
e.preventDefault()
e.stopPropagation()
@@ -133,6 +392,26 @@ export default function RichTextEditor({ value, onChange, placeholder, minHeight
<button type="button" className="rte-btn" title="Link einfügen" onMouseDown={onLink}>
Link
</button>
{showInlineToolbar ? (
<>
<button
type="button"
className="rte-btn"
title="Datei aus Mediathek oder neu hochladen, in den Text einfügen"
onMouseDown={stashRangeAndOpen(() => setFileModalOpen(true))}
>
Medien im Text
</button>
<button
type="button"
className="rte-btn"
title="Embed-URL hinzufügen und im Text einfügen"
onMouseDown={stashRangeAndOpen(() => setEmbedModalOpen(true))}
>
Embed im Text
</button>
</>
) : null}
<button
type="button"
className="rte-btn"
@@ -158,7 +437,31 @@ export default function RichTextEditor({ value, onChange, placeholder, minHeight
sync()
}}
onInput={sync}
onKeyDown={onEditorKeyDown}
onDragEnter={onEditorDragOver}
onDragOver={onEditorDragOver}
onDrop={onEditorDrop}
/>
{showInlineToolbar ? (
<ExerciseInlineFileMediaModal
open={fileModalOpen}
onClose={() => setFileModalOpen(false)}
exerciseId={Number(inlineExerciseId)}
linkedExerciseMedia={linkedExerciseMedia}
onMediaListChanged={refreshExerciseMedia}
onInserted={(mid, sz, cap) => finalizeInsertFromModal(mid, sz, cap)}
/>
) : null}
{showInlineToolbar ? (
<ExerciseInlineEmbedModal
open={embedModalOpen}
onClose={() => setEmbedModalOpen(false)}
exerciseId={Number(inlineExerciseId)}
onMediaListChanged={refreshExerciseMedia}
onInserted={(mid, sz, cap) => finalizeInsertFromModal(mid, sz, cap)}
/>
) : null}
</div>
)
}
@@ -0,0 +1,281 @@
import React, { useCallback, useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import api from '../utils/api'
import { activeClubMemberships } from '../utils/activeClub'
const VIS_LABELS = {
private: 'Privat',
club: 'Verein',
official: 'Offiziell',
}
function collectExerciseRows(sections) {
const map = new Map()
for (const sec of sections || []) {
for (const it of sec.items || []) {
if (it.item_type === 'note') continue
const id = Number(it.exercise_id)
if (!Number.isFinite(id) || id < 1) continue
if (!map.has(id)) {
map.set(id, it)
}
}
}
return [...map.entries()].map(([id, it]) => ({
id,
title: it.exercise_title || `Übung #${id}`,
visibility: it.exercise_visibility,
clubId: it.exercise_club_id != null ? Number(it.exercise_club_id) : null,
createdBy: it.exercise_created_by != null ? Number(it.exercise_created_by) : null,
status: it.exercise_status,
}))
}
function needsClubForTarget(row, targetClubId) {
if (targetClubId == null || !Number.isFinite(Number(targetClubId))) return false
const vis = String(row.visibility || 'private').toLowerCase()
if (vis === 'official') return false
const tc = Number(targetClubId)
if (vis === 'private') return true
if (vis === 'club') {
if (row.clubId == null) return true
return row.clubId !== tc
}
return false
}
function userMayPromote(user, targetClubId, createdBy) {
if (!user || targetClubId == null) return false
const role = String(user.role || '').toLowerCase()
if (role === 'admin' || role === 'superadmin') return true
if (createdBy != null && Number(createdBy) === Number(user.id)) return true
const row = activeClubMemberships(user?.clubs).find((c) => Number(c.id) === Number(targetClubId))
if (!row || !Array.isArray(row.roles)) return false
return row.roles.includes('club_admin')
}
/**
* Listen-Panel im Trainingsplan: Übungen, die für die gewählte Gruppe noch nicht vereinsweit sichtbar sind,
* und Freigabe auf „Verein“ (API: PUT / bulk-metadata).
*/
export default function TrainingPlanExerciseVisibilityPanel({
sections,
targetClubId,
user,
onMetaRefresh,
}) {
const [busyId, setBusyId] = useState(null)
const [bulkBusy, setBulkBusy] = useState(false)
const [message, setMessage] = useState(null)
const rows = useMemo(() => collectExerciseRows(sections), [sections])
const { pending, okCount } = useMemo(() => {
if (targetClubId == null || !Number.isFinite(Number(targetClubId))) {
return { pending: [], okCount: 0 }
}
const pending = []
let okCount = 0
for (const r of rows) {
if (needsClubForTarget(r, targetClubId)) pending.push(r)
else okCount += 1
}
return { pending, okCount }
}, [rows, targetClubId])
const promotableIds = useMemo(
() => pending.filter((r) => userMayPromote(user, targetClubId, r.createdBy)).map((r) => r.id),
[pending, targetClubId, user]
)
const applyClubVisibility = useCallback(
async (exerciseIds) => {
if (!exerciseIds.length || targetClubId == null) return
setMessage(null)
const res = await api.bulkPatchExercisesMetadata({
exercise_ids: exerciseIds,
visibility: 'club',
club_id: targetClubId,
})
const failed = res?.failed || []
const updatedN = Number(res?.updated_count || 0)
if (updatedN > 0 && onMetaRefresh) {
await onMetaRefresh()
}
if (failed.length) {
const first = failed[0]?.detail || 'Unbekannter Fehler'
setMessage(
failed.length === 1
? String(first)
: `${failed.length} Übungen nicht geändert: ${first}`
)
}
},
[targetClubId, onMetaRefresh]
)
const onPromoteOne = useCallback(
async (id) => {
setBusyId(id)
setMessage(null)
try {
await applyClubVisibility([id])
} catch (e) {
setMessage(e?.message || String(e))
} finally {
setBusyId(null)
}
},
[applyClubVisibility]
)
const onPromoteAll = useCallback(async () => {
if (!promotableIds.length) return
setBulkBusy(true)
setMessage(null)
try {
await applyClubVisibility(promotableIds)
} catch (e) {
setMessage(e?.message || String(e))
} finally {
setBulkBusy(false)
}
}, [applyClubVisibility, promotableIds])
if (!rows.length) return null
return (
<div
className="training-planning-template-panel training-plan-visibility-panel no-print"
style={{ marginBottom: '1.15rem' }}
>
<span className="training-planning-template-panel__label">Sichtbarkeit für den Verein</span>
<p className="training-planning-template-panel__help" style={{ marginTop: 0 }}>
Übungen mit Sichtbarkeit „Privat“ oder einem anderen Verein sieht das Team bei der Durchführung
nicht. Hier können Sie sie auf <strong>Verein</strong> setzen (gleiche Logik wie beim Speichern der
Einheit).
</p>
{targetClubId == null || !Number.isFinite(Number(targetClubId)) ? (
<p style={{ margin: '0.35rem 0 0', fontSize: '0.82rem', color: 'var(--text3)', lineHeight: 1.45 }}>
Wählen Sie eine Trainingsgruppe, um passende Freigaben anzuzeigen.
</p>
) : null}
{targetClubId != null && Number.isFinite(Number(targetClubId)) && !pending.length && rows.length ? (
<p
style={{
margin: '0.5rem 0 0',
fontSize: '0.88rem',
color: 'var(--text2)',
lineHeight: 1.45,
}}
>
Alle {rows.length} {rows.length === 1 ? 'Übung ist' : 'Übungen sind'} für diesen Verein in der
Durchführung sichtbar (oder offiziell).
</p>
) : null}
{targetClubId != null && Number.isFinite(Number(targetClubId)) && pending.length ? (
<>
<div
style={{
display: 'flex',
flexWrap: 'wrap',
alignItems: 'center',
gap: '10px',
marginTop: '0.65rem',
}}
>
<button
type="button"
className="btn btn-secondary"
disabled={!promotableIds.length || bulkBusy}
onClick={onPromoteAll}
>
{bulkBusy ? 'Speichern…' : `Alle auf Verein (${promotableIds.length})`}
</button>
{okCount > 0 ? (
<span style={{ fontSize: '0.82rem', color: 'var(--text3)' }}>
{okCount} weitere {okCount === 1 ? 'Übung' : 'Übungen'} bereits passend
</span>
) : null}
</div>
<ul
style={{
listStyle: 'none',
margin: '0.75rem 0 0',
padding: 0,
display: 'flex',
flexDirection: 'column',
gap: '8px',
}}
>
{pending.map((r) => {
const vis = String(r.visibility || 'private').toLowerCase()
const visLabel = VIS_LABELS[vis] || vis
const may = userMayPromote(user, targetClubId, r.createdBy)
const loading = busyId === r.id
return (
<li
key={r.id}
style={{
display: 'flex',
flexWrap: 'wrap',
alignItems: 'center',
gap: '10px',
padding: '10px 12px',
borderRadius: '10px',
border: '1px solid var(--border2)',
background: 'var(--surface)',
}}
>
<div style={{ flex: '1 1 160px', minWidth: 0 }}>
<Link to={`/exercises/${r.id}`} style={{ fontWeight: 600, fontSize: '0.9rem' }}>
{r.title}
</Link>
<div style={{ fontSize: '0.78rem', color: 'var(--text3)', marginTop: '4px' }}>
Aktuell: {visLabel}
{vis === 'club' && r.clubId != null && r.clubId !== Number(targetClubId)
? ` · anderer Verein (#${r.clubId})`
: ''}
</div>
</div>
<button
type="button"
className="btn btn-primary"
disabled={!may || loading || bulkBusy}
title={
may
? 'Sichtbarkeit auf Verein setzen'
: 'Nur Ersteller, Plattform-Admin oder Vereinsorga (Admin im Verein)'
}
onClick={() => onPromoteOne(r.id)}
>
{loading ? '…' : 'Auf Verein'}
</button>
</li>
)
})}
</ul>
{pending.some((r) => !userMayPromote(user, targetClubId, r.createdBy)) ? (
<p className="training-planning-template-panel__help" style={{ marginTop: '0.65rem' }}>
Einige Einträge können Sie nicht selbst freigeben: Denken Sie an die Vereinsorga oder speichern Sie
die Einheit — bei ausreichender Berechtigung werden private Übungen dann automatisch mitgeführt.
</p>
) : null}
</>
) : null}
{message ? (
<p
role="alert"
style={{
margin: '0.65rem 0 0',
fontSize: '0.84rem',
color: 'var(--danger, #c0392b)',
lineHeight: 1.45,
}}
>
{message}
</p>
) : null}
</div>
)
}
@@ -763,30 +763,34 @@ export default function TrainingUnitSectionsEditor({
</div>
{showExecutionExtras ? (
<label className="tu-ex-run-block form-label">
Ist-Dauer / Anpassungen
<span className="tu-ex-run-block__controls">
<div className="tu-ex-debrief">
<div className="tu-ex-debrief__grow">
<span className="tu-item-row__meta-label">Abweichungen beim Durchführen</span>
<textarea
className="form-input tu-ex-debrief__textarea"
rows={3}
value={it.modifications || ''}
onChange={(e) =>
updateItem(sIdx, iIdx, 'modifications', e.target.value)
}
placeholder="Was lief anders? Anpassungen für spätere Planung…"
/>
</div>
<div className="tu-ex-debrief__ist">
<span className="tu-item-row__meta-label">Ist (Min)</span>
<input
type="number"
className="form-input"
className="form-input tu-ex-duration"
min={1}
value={it.actual_duration_min}
onChange={(e) =>
updateItem(sIdx, iIdx, 'actual_duration_min', e.target.value)
}
placeholder="IST min"
placeholder="IST"
title="Tatsächliche Dauer (Minuten); dieselbe Spaltenbreite wie „Min“ (Plan) oben"
/>
<textarea
className="form-input"
rows={2}
value={it.modifications || ''}
onChange={(e) =>
updateItem(sIdx, iIdx, 'modifications', e.target.value)
}
placeholder="Abweichungen beim Durchführen"
/>
</span>
</label>
</div>
</div>
) : null}
</div>
)
@@ -5,22 +5,24 @@ function AssignmentsTab({ styleDirections, targetGroups, assignments, loading, e
const [saving, setSaving] = useState(false)
if (loading) {
return <div style={{ textAlign: 'center', padding: '40px' }}><div className="spinner"></div></div>
return (
<div className="empty-state" style={{ padding: '2.5rem' }}>
<div className="spinner" />
</div>
)
}
async function toggleAssignment(styleDirectionId, targetGroupId, currentlyAssigned) {
setSaving(true)
try {
if (currentlyAssigned) {
// Find and delete the assignment
const assignment = assignments.find(
a => a.style_direction_id === styleDirectionId && a.target_group_id === targetGroupId
(a) => a.style_direction_id === styleDirectionId && a.target_group_id === targetGroupId
)
if (assignment) {
await api.deleteStyleDirectionTargetGroup(assignment.id)
}
} else {
// Create new assignment
await api.createStyleDirectionTargetGroup({
style_direction_id: styleDirectionId,
target_group_id: targetGroupId,
@@ -37,11 +39,10 @@ function AssignmentsTab({ styleDirections, targetGroups, assignments, loading, e
function isAssigned(styleDirectionId, targetGroupId) {
return assignments.some(
a => a.style_direction_id === styleDirectionId && a.target_group_id === targetGroupId
(a) => a.style_direction_id === styleDirectionId && a.target_group_id === targetGroupId
)
}
// Group style directions by focus area
const groupedStyles = styleDirections.reduce((acc, sd) => {
const key = sd.focus_area_name || 'Ohne Fokusbereich'
if (!acc[key]) acc[key] = []
@@ -50,30 +51,30 @@ function AssignmentsTab({ styleDirections, targetGroups, assignments, loading, e
}, {})
return (
<div style={{ background: 'var(--surface)', borderRadius: '12px', padding: '20px' }}>
<h2 style={{ marginTop: 0 }}>Zuordnungen: Stilrichtungen ↔ Zielgruppen</h2>
{error && <div style={{ color: 'var(--danger)', padding: '16px', background: 'var(--surface2)', borderRadius: '8px', marginBottom: '16px' }}>{error}</div>}
<div className="admin-assignments-wrap">
<h2 className="admin-assignments-wrap__title">Zuordnungen: Stilrichtungen ↔ Zielgruppen</h2>
{error && <div className="admin-matrix-alert">{error}</div>}
{targetGroups.length === 0 && (
<div style={{ textAlign: 'center', color: 'var(--text3)', padding: '40px' }}>
Keine Zielgruppen vorhanden. Bitte erst im Tab "Kataloge" anlegen.
<div className="empty-state" style={{ padding: '2rem 1rem' }}>
Keine Zielgruppen vorhanden. Bitte zuerst unter <strong>Kataloge</strong> anlegen.
</div>
)}
{styleDirections.length === 0 && (
<div style={{ textAlign: 'center', color: 'var(--text3)', padding: '40px' }}>
Keine Stilrichtungen vorhanden. Bitte erst im Tab "Hierarchie" anlegen.
<div className="empty-state" style={{ padding: '2rem 1rem' }}>
Keine Stilrichtungen vorhanden. Bitte zuerst unter <strong>Hierarchie</strong> anlegen.
</div>
)}
{targetGroups.length > 0 && styleDirections.length > 0 && (
<div className="assignment-matrix-container">
<table className="assignment-matrix">
<div className="admin-assignments-matrix-container">
<table className="admin-assignments-matrix">
<thead>
<tr>
<th style={{ position: 'sticky', left: 0, background: 'var(--surface)', zIndex: 2 }}>Stilrichtung</th>
{targetGroups.map(tg => (
<th key={tg.id} style={{ textAlign: 'center', padding: '12px' }}>
<th className="admin-assignments-matrix__corner">Stilrichtung</th>
{targetGroups.map((tg) => (
<th key={tg.id} className="admin-assignments-matrix__th-narrow">
{tg.name}
</th>
))}
@@ -82,17 +83,18 @@ function AssignmentsTab({ styleDirections, targetGroups, assignments, loading, e
<tbody>
{Object.entries(groupedStyles).map(([focusAreaName, styles]) => (
<React.Fragment key={focusAreaName}>
<tr className="focus-area-header">
<td colSpan={targetGroups.length + 1} style={{ background: 'var(--surface2)', padding: '8px 12px', fontWeight: 600, color: 'var(--text2)' }}>
<tr>
<td
className="admin-assignments-matrix__focus-header"
colSpan={targetGroups.length + 1}
>
{focusAreaName}
</td>
</tr>
{styles.map(sd => (
{styles.map((sd) => (
<tr key={sd.id}>
<td style={{ position: 'sticky', left: 0, background: 'var(--surface)', zIndex: 1, padding: '12px', fontWeight: 500 }}>
{sd.name}
</td>
{targetGroups.map(tg => {
<td className="admin-assignments-matrix__row-label">{sd.name}</td>
{targetGroups.map((tg) => {
const assigned = isAssigned(sd.id, tg.id)
return (
<td key={tg.id} style={{ textAlign: 'center', padding: '12px' }}>
@@ -101,7 +103,8 @@ function AssignmentsTab({ styleDirections, targetGroups, assignments, loading, e
checked={assigned}
onChange={() => toggleAssignment(sd.id, tg.id, assigned)}
disabled={saving}
style={{ width: '20px', height: '20px', cursor: 'pointer' }}
aria-label={`${sd.name} — ${tg.name}`}
style={{ width: '20px', height: '20px', cursor: 'pointer', accentColor: 'var(--accent)' }}
/>
</td>
)
@@ -114,45 +117,6 @@ function AssignmentsTab({ styleDirections, targetGroups, assignments, loading, e
</table>
</div>
)}
<style>{`
.assignment-matrix-container {
overflow-x: auto;
margin-top: 20px;
}
.assignment-matrix {
width: 100%;
border-collapse: collapse;
min-width: 600px;
}
.assignment-matrix th,
.assignment-matrix td {
border: 1px solid var(--border);
padding: 12px;
}
.assignment-matrix th {
background: var(--surface2);
font-weight: 600;
color: var(--text1);
}
.assignment-matrix tbody tr:hover {
background: var(--surface2);
}
@media (max-width: 768px) {
.assignment-matrix {
font-size: 14px;
}
.assignment-matrix th,
.assignment-matrix td {
padding: 8px;
}
}
`}</style>
</div>
)
}
+88 -42
View File
@@ -1,18 +1,23 @@
import React, { useState } from 'react'
import { Target, Tags, Dumbbell } from 'lucide-react'
import { api } from '../../utils/api'
function CatalogsTab({ targetGroups, skillCategories, trainingCharacters, loading, error, onUpdate }) {
if (loading) {
return <div style={{ textAlign: 'center', padding: '40px' }}><div className="spinner"></div></div>
return (
<div className="empty-state" style={{ padding: '2.5rem' }}>
<div className="spinner" />
</div>
)
}
return (
<div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '24px' }}>
{error && <div style={{ color: 'var(--danger)', padding: '16px', background: 'var(--surface)', borderRadius: '8px' }}>{error}</div>}
<div className="admin-catalog-stack">
{error && <div className="admin-matrix-alert">{error}</div>}
<CatalogSection
title="Zielgruppen"
icon="🎯"
Icon={Target}
items={targetGroups}
onUpdate={onUpdate}
createFn={api.createTargetGroup}
@@ -28,7 +33,7 @@ function CatalogsTab({ targetGroups, skillCategories, trainingCharacters, loadin
<CatalogSection
title="Fähigkeitskategorien"
icon="⚡"
Icon={Tags}
items={skillCategories}
onUpdate={onUpdate}
createFn={api.createSkillCategory}
@@ -42,7 +47,7 @@ function CatalogsTab({ targetGroups, skillCategories, trainingCharacters, loadin
<CatalogSection
title="Trainingscharakter"
icon="💪"
Icon={Dumbbell}
items={trainingCharacters}
onUpdate={onUpdate}
createFn={api.createTrainingCharacter}
@@ -57,27 +62,27 @@ function CatalogsTab({ targetGroups, skillCategories, trainingCharacters, loadin
)
}
function CatalogSection({ title, icon, items, onUpdate, createFn, updateFn, deleteFn, fields }) {
function CatalogSection({ title, Icon, items, onUpdate, createFn, updateFn, deleteFn, fields }) {
const [creating, setCreating] = useState(false)
const [editing, setEditing] = useState(null)
const [form, setForm] = useState({})
function startCreate() {
const emptyForm = {}
fields.forEach(f => { emptyForm[f.key] = '' })
fields.forEach((f) => { emptyForm[f.key] = '' })
setForm(emptyForm)
setCreating(true)
}
function startEdit(item) {
const editForm = {}
fields.forEach(f => { editForm[f.key] = item[f.key] || '' })
fields.forEach((f) => { editForm[f.key] = item[f.key] || '' })
setEditing(item.id)
setForm(editForm)
}
async function handleCreate() {
const required = fields.filter(f => f.required)
const required = fields.filter((f) => f.required)
for (const field of required) {
if (!form[field.key]) {
alert(`${field.label} ist erforderlich`)
@@ -116,75 +121,116 @@ function CatalogSection({ title, icon, items, onUpdate, createFn, updateFn, dele
}
return (
<div style={{ background: 'var(--surface)', borderRadius: '12px', padding: '20px' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
<h3 style={{ margin: 0 }}>{icon} {title}</h3>
<button className="btn btn-primary" onClick={startCreate}>+ Neu</button>
<div className="admin-catalog-section">
<div className="admin-catalog-section__head">
<h3 className="admin-catalog-section__title">
{Icon ? (
<Icon className="admin-catalog-section__icon" size={20} strokeWidth={2} aria-hidden />
) : null}
{title}
</h3>
<button type="button" className="btn btn-primary btn-small" onClick={startCreate}>
+ Neu
</button>
</div>
{creating && (
<div style={{ marginBottom: '20px', padding: '16px', background: 'var(--surface2)', borderRadius: '8px' }}>
<h4 style={{ marginTop: 0 }}>Neu erstellen</h4>
{fields.map(field => (
<div className="admin-catalog-inline-form">
<h4>Neu erstellen</h4>
{fields.map((field) => (
<div key={field.key} className="form-row">
<label className="form-label">{field.label} {field.required && '*'}</label>
<label className="form-label">
{field.label} {field.required && '*'}
</label>
{field.type === 'textarea' ? (
<textarea className="form-input" value={form[field.key] || ''} onChange={e => setForm({ ...form, [field.key]: e.target.value })} rows={3} />
<textarea
className="form-input"
value={form[field.key] || ''}
onChange={(e) => setForm({ ...form, [field.key]: e.target.value })}
rows={3}
/>
) : (
<input className="form-input" type={field.type} value={form[field.key] || ''} onChange={e => setForm({ ...form, [field.key]: e.target.value })} />
<input
className="form-input"
type={field.type}
value={form[field.key] || ''}
onChange={(e) => setForm({ ...form, [field.key]: e.target.value })}
/>
)}
</div>
))}
<div style={{ display: 'flex', gap: '8px', marginTop: '12px' }}>
<button className="btn btn-primary" onClick={handleCreate}>Erstellen</button>
<button className="btn" onClick={() => setCreating(false)}>Abbrechen</button>
<div className="admin-catalog-actions">
<button type="button" className="btn btn-primary" onClick={handleCreate}>
Erstellen
</button>
<button type="button" className="btn btn-secondary" onClick={() => setCreating(false)}>
Abbrechen
</button>
</div>
</div>
)}
<div style={{ display: 'grid', gap: '12px' }}>
{items.map(item => (
<div key={item.id} style={{ padding: '12px', background: 'var(--surface2)', borderRadius: '8px' }}>
<div className="admin-catalog-list">
{items.map((item) => (
<div key={item.id} className="admin-catalog-item">
{editing === item.id ? (
<div>
{fields.map(field => (
{fields.map((field) => (
<div key={field.key} className="form-row">
<label className="form-label">{field.label}</label>
{field.type === 'textarea' ? (
<textarea className="form-input" value={form[field.key] || ''} onChange={e => setForm({ ...form, [field.key]: e.target.value })} rows={3} />
<textarea
className="form-input"
value={form[field.key] || ''}
onChange={(e) => setForm({ ...form, [field.key]: e.target.value })}
rows={3}
/>
) : (
<input className="form-input" type={field.type} value={form[field.key] || ''} onChange={e => setForm({ ...form, [field.key]: e.target.value })} />
<input
className="form-input"
type={field.type}
value={form[field.key] || ''}
onChange={(e) => setForm({ ...form, [field.key]: e.target.value })}
/>
)}
</div>
))}
<div style={{ display: 'flex', gap: '8px', marginTop: '12px' }}>
<button className="btn btn-primary" onClick={() => handleUpdate(item.id)}>Speichern</button>
<button className="btn" onClick={() => setEditing(null)}>Abbrechen</button>
<div className="admin-catalog-actions">
<button type="button" className="btn btn-primary" onClick={() => handleUpdate(item.id)}>
Speichern
</button>
<button type="button" className="btn btn-secondary" onClick={() => setEditing(null)}>
Abbrechen
</button>
</div>
</div>
) : (
<div>
<div style={{ marginBottom: '8px' }}>
<div className="admin-catalog-item__name-row">
<strong>{item.name}</strong>
{item.min_age !== null && item.max_age !== null && (
<span style={{ marginLeft: '12px', color: 'var(--text3)', fontSize: '14px' }}>
{item.min_age != null && item.max_age != null && (
<span className="admin-catalog-meta">
Alter: {item.min_age}-{item.max_age}
</span>
)}
</div>
{item.description && <p style={{ color: 'var(--text2)', fontSize: '14px', margin: '8px 0' }}>{item.description}</p>}
<div style={{ display: 'flex', gap: '8px', marginTop: '8px' }}>
<button className="btn" onClick={() => startEdit(item)}>Bearbeiten</button>
<button className="btn" onClick={() => handleDelete(item.id, item.name)}>Löschen</button>
{item.description ? (
<p className="admin-catalog-desc">{item.description}</p>
) : null}
<div className="admin-catalog-actions">
<button type="button" className="btn btn-secondary btn-small" onClick={() => startEdit(item)}>
Bearbeiten
</button>
<button type="button" className="btn btn-danger btn-small" onClick={() => handleDelete(item.id, item.name)}>
Löschen
</button>
</div>
</div>
)}
</div>
))}
{items.length === 0 && !creating && (
<div style={{ textAlign: 'center', color: 'var(--text3)', padding: '20px' }}>
Noch keine Einträge vorhanden
</div>
<div className="admin-catalog-empty">Noch keine Einträge vorhanden</div>
)}
</div>
</div>
+16 -16
View File
@@ -20,7 +20,7 @@ function DetailPanel({ item, onUpdate, focusAreas }) {
return <TrainingTypeDetail item={item} onUpdate={onUpdate} focusAreas={focusAreas} />
}
return <div style={{ padding: '20px', color: 'var(--text3)' }}>Unbekannter Typ: {type}</div>
return <div className="detail-panel__unknown">Unbekannter Typ: {type}</div>
}
function FocusAreaDetail({ item, onUpdate }) {
@@ -57,7 +57,7 @@ function FocusAreaDetail({ item, onUpdate }) {
return (
<div>
<h2 style={{ marginTop: 0 }}>Fokusbereich bearbeiten</h2>
<h2 className="detail-panel__title">Fokusbereich bearbeiten</h2>
<div className="form-row">
<label className="form-label">Name *</label>
<input className="form-input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
@@ -81,11 +81,11 @@ function FocusAreaDetail({ item, onUpdate }) {
<option value="inactive">Inaktiv</option>
</select>
</div>
<div style={{ display: 'flex', gap: '8px', marginTop: '20px' }}>
<div className="detail-panel__actions">
<button className="btn btn-primary" onClick={handleSave} disabled={saving || !form.name}>
{saving ? 'Speichert...' : 'Speichern'}
</button>
<button className="btn" onClick={handleDelete}>Löschen</button>
<button type="button" className="btn btn-danger" onClick={handleDelete}>Löschen</button>
</div>
</div>
)
@@ -130,7 +130,7 @@ function StyleDirectionDetail({ item, onUpdate, focusAreas }) {
return (
<div>
<h2 style={{ marginTop: 0 }}>Stilrichtung bearbeiten</h2>
<h2 className="detail-panel__title">Stilrichtung bearbeiten</h2>
<div className="form-row">
<label className="form-label">Name *</label>
<input className="form-input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
@@ -163,11 +163,11 @@ function StyleDirectionDetail({ item, onUpdate, focusAreas }) {
<option value="inactive">Inaktiv</option>
</select>
</div>
<div style={{ display: 'flex', gap: '8px', marginTop: '20px' }}>
<div className="detail-panel__actions">
<button className="btn btn-primary" onClick={handleSave} disabled={saving || !form.name || !form.focus_area_id}>
{saving ? 'Speichert...' : 'Speichern'}
</button>
<button className="btn" onClick={handleDelete}>Löschen</button>
<button type="button" className="btn btn-danger" onClick={handleDelete}>Löschen</button>
</div>
</div>
)
@@ -212,7 +212,7 @@ function TrainingTypeDetail({ item, onUpdate, focusAreas }) {
return (
<div>
<h2 style={{ marginTop: 0 }}>Trainingstyp bearbeiten</h2>
<h2 className="detail-panel__title">Trainingstyp bearbeiten</h2>
<div className="form-row">
<label className="form-label">Name *</label>
<input className="form-input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
@@ -245,11 +245,11 @@ function TrainingTypeDetail({ item, onUpdate, focusAreas }) {
<option value="inactive">Inaktiv</option>
</select>
</div>
<div style={{ display: 'flex', gap: '8px', marginTop: '20px' }}>
<div className="detail-panel__actions">
<button className="btn btn-primary" onClick={handleSave} disabled={saving || !form.name || !form.focus_area_id}>
{saving ? 'Speichert...' : 'Speichern'}
</button>
<button className="btn" onClick={handleDelete}>Löschen</button>
<button type="button" className="btn btn-danger" onClick={handleDelete}>Löschen</button>
</div>
</div>
)
@@ -284,8 +284,8 @@ function CreateStyleDirectionForm({ item, onUpdate }) {
return (
<div>
<h2 style={{ marginTop: 0 }}>Neue Stilrichtung erstellen</h2>
<div style={{ padding: '12px', background: 'var(--surface2)', borderRadius: '8px', marginBottom: '20px', color: 'var(--text2)' }}>
<h2 className="detail-panel__title">Neue Stilrichtung erstellen</h2>
<div className="detail-panel__context">
Fokusbereich: <strong>{item.focus_area_name}</strong>
</div>
<div className="form-row">
@@ -304,7 +304,7 @@ function CreateStyleDirectionForm({ item, onUpdate }) {
<label className="form-label">Sortierung</label>
<input className="form-input" type="number" value={form.sort_order} onChange={e => setForm({ ...form, sort_order: parseInt(e.target.value) || 0 })} />
</div>
<div style={{ display: 'flex', gap: '8px', marginTop: '20px' }}>
<div className="detail-panel__actions">
<button className="btn btn-primary" onClick={handleCreate} disabled={saving || !form.name}>
{saving ? 'Erstellt...' : 'Erstellen'}
</button>
@@ -342,8 +342,8 @@ function CreateTrainingTypeForm({ item, onUpdate }) {
return (
<div>
<h2 style={{ marginTop: 0 }}>Neuen Trainingstyp erstellen</h2>
<div style={{ padding: '12px', background: 'var(--surface2)', borderRadius: '8px', marginBottom: '20px', color: 'var(--text2)' }}>
<h2 className="detail-panel__title">Neuen Trainingstyp erstellen</h2>
<div className="detail-panel__context">
Fokusbereich: <strong>{item.focus_area_name}</strong>
</div>
<div className="form-row">
@@ -362,7 +362,7 @@ function CreateTrainingTypeForm({ item, onUpdate }) {
<label className="form-label">Sortierung</label>
<input className="form-input" type="number" value={form.sort_order} onChange={e => setForm({ ...form, sort_order: parseInt(e.target.value) || 0 })} />
</div>
<div style={{ display: 'flex', gap: '8px', marginTop: '20px' }}>
<div className="detail-panel__actions">
<button className="btn btn-primary" onClick={handleCreate} disabled={saving || !form.name}>
{saving ? 'Erstellt...' : 'Erstellen'}
</button>
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff. Show more