Author SHA1 Message Date
Lars 09439ad1a5 Merge pull request 'Indvidual Dashboard V0.9' (#67) from develop into main
Deploy Production / deploy (push) Successful in 1m0s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
Reviewed-on: #67
2026-04-08 10:56:02 +02:00
Lars 365ce49c6a feat: Introduce admin dashboard product standard management
Deploy Development / deploy (push) Successful in 57s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 17s
- Added new API endpoints for managing the product dashboard standard, including retrieval, update, and deletion functionalities.
- Enhanced the DashboardConfigurePage to support admin mode for configuring the product dashboard standard.
- Updated the admin navigation to include a link for the product dashboard standard configuration.
- Refactored the dashboard layout logic to utilize the new product standard management features.
- Bumped app_dashboard version to 1.10.0 to reflect these enhancements and changes.
2026-04-08 10:32:18 +02:00
Lars ff95ef63c7 feat: Enhance DashboardConfigurePage with drag-and-drop functionality and improved widget search
Deploy Development / deploy (push) Successful in 50s
Build Test / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 0s
- Added drag-and-drop support for widget reordering in the dashboard configuration.
- Introduced a new search input for filtering widgets, enhancing user experience.
- Updated layout editor with a new function to move widgets between indices.
- Improved responsiveness by implementing viewport detection for drag-and-drop features.
- Refactored state management for better handling of widget visibility and search functionality.
2026-04-08 07:58:52 +02:00
Lars e4e2f23d7f feat: Enhance dashboard layout and widget configuration
Deploy Development / deploy (push) Successful in 48s
Build Test / build-frontend (push) Successful in 17s
Build Test / lint-backend (push) Successful in 0s
- Updated dashboard layout schema to introduce separate default layouts for product and lab dashboards.
- Added new functions for managing product and lab default layouts, improving user customization options.
- Updated app_dashboard version to 1.9.0 to reflect the introduction of product vs lab layout defaults and new API fields for dashboard configuration.
- Enhanced tests to validate new layout functionalities and ensure proper widget visibility based on user settings.
2026-04-08 07:41:16 +02:00
Lars 9bc0cf70da feat: Update widget catalog and enhance dashboard layout features
Deploy Development / deploy (push) Successful in 49s
Build Test / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 0s
- Added new "Dashboard-Lab-Widgets" entry to the documentation for better guidance on widget configuration.
- Updated the app_dashboard version to 1.8.0 to reflect the introduction of widget catalog features and layout entitlements.
- Enhanced widget catalog entries to include optional feature requirements for better visibility and access control.
- Improved the DashboardLabPage to manage widget visibility based on feature entitlements, ensuring a more tailored user experience.
2026-04-08 07:21:49 +02:00
Lars bc91396885 feat: Add new widgets and enhance configuration validation
Deploy Development / deploy (push) Successful in 48s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
- Introduced "nutrition_detail_charts", "recovery_charts_panel", and "progress_photos" widgets to the dashboard.
- Updated widget configuration validation to support new widgets, including chart days for nutrition and recovery charts.
- Enhanced the widget catalog and dashboard layout to include the new features.
- Bumped app_dashboard version to 1.7.0 to reflect these additions and improvements.
2026-04-07 20:58:44 +02:00
Lars 7f833b2cb1 feat: Introduce quick capture widget configuration and validation
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- Added support for the "quick_capture" widget, allowing users to configure visibility for weight and baseline vitals (resting HR, HRV, VO₂max).
- Implemented validation logic to ensure correct configuration input and prevent errors.
- Updated the widget catalog and dashboard layout to reflect the new quick capture features.
- Removed the "training_type_distribution" widget from the catalog as part of the refactor.
- Bumped app_dashboard version to 1.6.2 to incorporate these enhancements.
2026-04-07 18:02:18 +02:00
Lars 3d498d03c1 feat: Enhance dashboard widget configuration and introduce new widgets
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- Updated the dashboard layout schema to include new widgets: DashboardGreeting, QuickWeightToday, BodyStatStrip, StatusPills, ProfileGoalsProgress, TrendKcalWeight, NutritionActivitySummary, RecoverySleepRest, and TrainingTypeDistribution.
- Improved widget configuration validation to support new features, including chart days for trend and distribution widgets.
- Refactored the default lab layout to align with the updated widget catalog and ensure proper default activation.
- Bumped app_dashboard version to 1.6.0 to reflect the addition of new widgets and configuration enhancements.
2026-04-07 14:19:45 +02:00
Lars c0c512e942 feat: Revamp KPI board configuration and validation
Deploy Development / deploy (push) Successful in 53s
Build Test / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 0s
- Enhanced the KPI board widget to support tile configuration, allowing users to select and order tiles.
- Updated validation logic to ensure proper handling of tile IDs and configuration fields.
- Removed legacy chart_days support, transitioning to a fixed analysis window for KPI metrics.
- Improved the DashboardLabPage to integrate the new KpiBoardConfigEditor for managing tile selections.
- Bumped app_dashboard version to 1.5.0 to reflect these significant changes.
2026-04-07 12:46:18 +02:00
Lars 096d896166 fix: Correct syntax error in PilotKpiBoard component
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
- Fixed a syntax error in the recentNutr filter function by adding a closing parenthesis.
- Ensured proper calculation of kcal based on recent nutrition data.
2026-04-07 12:39:41 +02:00
Lars de99856a28 feat: Extend widget configuration for KPI board and enhance validation
Deploy Development / deploy (push) Failing after 44s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
- Added support for the "kpi_board" widget in the dashboard configuration, allowing for chart_days validation.
- Updated the widget catalog description to reflect the new configuration options for KPI tiles.
- Enhanced the DashboardLabPage to manage chart_days input for the KPI board, improving user experience.
- Introduced normalization functions for KPI kcal window days to maintain consistent behavior.
- Bumped app_dashboard version to 1.4.0 to reflect these enhancements.
2026-04-07 12:37:04 +02:00
Lars 97f9aa696e feat: Enhance activity API feat: Enhance sleep data import functionality with support for multiple CSV formats and improved data parsing
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
- Added functions to handle Apple Health sleep data in both segment and summary formats.
- Implemented robust error handling for date parsing and data conversion.
- Updated documentation to reflect new CSV format support and data aggregation logic.
- Bumped version in version.py to reflect the changes in the activity module.
2026-04-07 12:28:59 +02:00
Lars b617212145 feat: Extend widget configuration for activity overview and improve validation
Deploy Development / deploy (push) Successful in 55s
Build Test / build-frontend (push) Successful in 16s
Build Test / lint-backend (push) Successful in 1s
- Added support for the "activity_overview" widget in the dashboard configuration, allowing for chart_days validation.
- Refactored validation logic to streamline error handling for both "body_overview" and "activity_overview" widgets.
- Updated the widget catalog description to reflect the new configuration options.
- Enhanced the DashboardLabPage to manage chart_days input for both widgets, improving user experience.
- Bumped app_dashboard version to 1.3.0 to reflect these enhancements.
2026-04-07 12:20:23 +02:00
Lars 4493b140bd feat: Improve body chart days configuration in DashboardLabPage
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
- Introduced a draft state for body chart days input to allow for temporary edits without immediate clamping.
- Updated input handling to support numeric input mode and improved accessibility with aria-label.
- Enhanced save and reset functionalities to manage the new draft state effectively.
- Refactored layout normalization to accommodate changes in body chart days configuration.
2026-04-07 12:05:05 +02:00
Lars 87c4cbc4b4 feat: Enhance Dashboard widget configuration and layout management
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
- Added validation for widget configuration in the DashboardWidgetEntry model to ensure proper data structure.
- Updated the DashboardLayoutPayload to include widget configuration in the serialized output.
- Improved the PilotBodySection and DashboardLabPage components to support dynamic chart days configuration for the body overview widget.
- Refactored layout editor functions to normalize widget configurations for better handling.
- Bumped app_dashboard version to 1.2.0 to reflect the new features and improvements.
2026-04-07 11:58:07 +02:00
Lars f6c5f96768 feat: Enhance Dashboard-Lab with widget catalog integration and layout updates
Deploy Development / deploy (push) Successful in 46s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
- Integrated a new API endpoint for fetching the widget catalog in the Dashboard-Lab.
- Updated the dashboard layout schema to utilize the widget catalog for dynamic widget management.
- Refactored DashboardLabPage and PilotVizPage to leverage the new widget rendering system.
- Removed deprecated widget metadata from the frontend, streamlining the widget management process.
- Bumped app_dashboard version to 1.1.0 to reflect the new features and improvements.
2026-04-07 11:47:16 +02:00
Lars e5f6e6c10d feat: Integrate Dashboard-Lab layout and enhance settings navigation
Deploy Development / deploy (push) Successful in 49s
Build Test / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 0s
- Added new routes and API endpoints for the Dashboard-Lab layout in the app.
- Updated main.py to include the app_dashboard router for backend integration.
- Enhanced App.jsx to include a route for the DashboardLabPage.
- Modified SettingsPage to add a link to the new Dashboard-Lab layout, improving user access to dashboard features.
- Updated version.py to reflect the new app_dashboard module version.
2026-04-07 11:38:35 +02:00
Lars c0cb995a7b feat: Remove deprecated pilot widgets and layout management
Deploy Development / deploy (push) Successful in 56s
Build Test / build-frontend (push) Successful in 23s
Build Test / lint-backend (push) Successful in 0s
- Deleted unused components: GoalsSnapshotWidget, ReferenceValuesSummaryWidget, WeightKpiWidget, and PilotVizAdminCard.
- Removed associated layout storage and widget registry logic to streamline the pilot visualization module.
- Updated PilotVizPage to integrate new components for improved user experience and functionality.
2026-04-07 11:07:33 +02:00
Lars 8c8f595385 feat: Refactor PilotVizPage and widget registry for improved layout and rendering
Deploy Development / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
- Replaced the previous widget retrieval method with a new layout-based approach in PilotVizPage.
- Introduced a PilotVizAdminCard for layout configuration and management.
- Updated widget definitions in the registry to include new components and default order.
- Enhanced user feedback for widget visibility with a message when no widgets are active.
2026-04-07 10:21:11 +02:00
Lars 932bceb1e1 feat: Update reference values and introduce pilot visualization module
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 23s
- Bumped version of reference_values module to 1.3.0.
- Added new imports and functionality for reference values in the backend, enhancing data retrieval.
- Introduced a new PilotVizPage in the frontend for visualizing data, linked from the SettingsPage for easy access.
- Updated routing in App.jsx to include the new pilot visualization route.
2026-04-07 10:15:13 +02:00
Lars 3e916c082c feat: Add profile reference values summary endpoint and UI enhancements
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
- Introduced a new API endpoint for fetching a summary of profile reference values, providing the latest and previous entries for each reference type.
- Updated ProfileReferenceValuesPage to display summary tiles with trend indicators for better user insights.
- Enhanced CSS for responsive layout of reference value tiles, improving the overall user experience on different screen sizes.
- Implemented trend calculation logic to visually represent changes between the latest and previous reference values.
2026-04-07 06:30:22 +02:00
Lars c152721fe8 feat: Refactor settings navigation and enhance profile reference values display
Deploy Development / deploy (push) Successful in 47s
Build Test / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 0s
- Introduced a new SettingsShell layout for improved navigation within the settings section.
- Updated ProfileReferenceValuesPage to display the latest entry with enhanced styling and information.
- Removed the direct link to settings from ProfileReferenceValuesPage for a cleaner UI.
- Adjusted SettingsPage to streamline the layout and focus on essential settings options.
2026-04-07 06:24:47 +02:00
Lars 296e79c3b3 feat: Implement reference value types reordering and confidence level sorting
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
- Added a new API endpoint for reordering reference value types based on user-defined order.
- Updated the AdminReferenceValueTypesPage to allow users to reorder types using up/down buttons.
- Introduced a consistent confidence level sorting mechanism across the application.
- Refactored related components to remove unused sort order fields and improve user experience.
2026-04-06 21:40:55 +02:00
Lars 45e4e64f15 feat: Enhance reference value types management with validation rules and metadata
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
- Updated the backend to include new fields for validation rules and metadata in reference value types.
- Enhanced the AdminReferenceValueTypesPage to support new validation rules for different data types.
- Improved the ProfileReferenceValuesPage to handle validation and metadata for profile reference values.
- Added API endpoint for fetching reference value metadata enums to support frontend validation.
- Refactored frontend forms to incorporate new fields and validation logic for a better user experience.
2026-04-06 21:25:42 +02:00
Lars f04318f76a - Updated the AdminReferenceValueTypesPage to enhance text alignment and styling for form fields.
Deploy Development / deploy (push) Successful in 56s
Build Test / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 0s
- Refactored ProfileReferenceValuesPage to apply consistent styling for form elements and improve layout.
- Adjusted button styles for better visual consistency across the forms.
2026-04-06 20:01:23 +02:00
Lars ab616ba044 feat: Introduce admin reference value types management in API and UI
Deploy Development / deploy (push) Successful in 54s
Build Test / build-frontend (push) Successful in 16s
Build Test / lint-backend (push) Successful in 0s
- Added new routes and API endpoints for managing reference value types in the admin section.
- Updated the frontend to include navigation and components for reference value types management.
- Enhanced the backend to support the new reference value types in the data layer and versioning.
2026-04-06 19:51:23 +02:00
Lars f0e6fd04fb feat: Add personal reference values management in settings and API
Deploy Development / deploy (push) Successful in 50s
Build Test / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 0s
- Introduced new routes and API endpoints for managing personal reference values.
- Updated the SettingsPage to include a section for reference values with navigation to manage them.
- Enhanced the backend to support reference values in the data layer and versioning.
- Added necessary imports and UI components for a seamless user experience.
2026-04-06 19:45:06 +02:00
Lars e7dedd527f feat: Implement focus area usage types management in API and UI
Deploy Development / deploy (push) Successful in 51s
Build Test / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 0s
- Added endpoints for listing and updating focus area usage types in the backend.
- Enhanced the AdminFocusAreasPage to display and manage allowed usage types for focus areas.
- Introduced a new state for usage types catalog and integrated it into the focus area editing process.
- Updated API utility functions to support new usage types operations.
2026-04-06 07:28:19 +02:00
Lars 75736dadec Merge pull request 'feat: Integrate caliper data enrichment and weight loading in API responses' (#64) from develop into main
Deploy Production / deploy (push) Successful in 57s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Reviewed-on: #64
2026-04-06 06:10:39 +02:00
Lars 49e9c9c214 feat: Integrate caliper data enrichment and weight loading in API responses
Deploy Development / deploy (push) Successful in 1m0s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- Enhanced the caliper listing and export functionalities to include enriched data from weight logs.
- Updated the upsert and update operations to utilize new composition functions for body composition calculations.
- Refactored the CaliperScreen component to streamline payload construction by removing unnecessary parameters.
2026-04-06 06:08:37 +02:00
Lars 8d56c352fc Merge pull request 'Bug Fixes' (#63) from develop into main
Deploy Production / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
Reviewed-on: #63
2026-04-05 17:54:00 +02:00
Lars 00437a92ab feat: Enhance sleep module with CSV import functionality and date parsing improvements
Deploy Development / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
2026-04-05 17:35:48 +02:00
Lars 24f60c0a6d feat: Update documentation for GUI, Admin navigation, and responsive UI integration
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
2026-04-05 12:25:28 +02:00
Lars fdaf4471da feat: Adjust navigation height and padding for improved layout and responsiveness
Deploy Development / deploy (push) Successful in 54s
Build Test / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 0s
2026-04-05 12:16:24 +02:00
Lars 6e952f9277 feat: Enhance navigation and dashboard with goals integration and UI improvements
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
2026-04-05 12:07:11 +02:00
Lars 952cb90973 feat: Update deployment scripts to use git fetch and reset for more reliable state management
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
2026-04-05 11:39:15 +02:00
Lars ebea9946a7 Merge pull request 'feat: Add admin access denial alert to Dashboard with timeout handling' (#62) from develop into main
Build Test / build-frontend (push) Successful in 13s
Deploy Production / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Reviewed-on: #62
2026-04-05 11:29:03 +02:00
Lars bd694b30a6 feat: Add admin access denial alert to Dashboard with timeout handling
Deploy Development / deploy (push) Successful in 52s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
2026-04-05 11:28:33 +02:00
Lars 9fb04af7df Merge pull request 'Responsive Gui - partially Workflow' (#61) from develop into main
Deploy Production / deploy (push) Failing after 1s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Reviewed-on: #61
2026-04-05 11:27:43 +02:00
Lars 430a928df6 feat: Update settings page layout with improved field structure and accessibility
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
2026-04-05 11:19:35 +02:00
Lars c63ec5f700 feat: Enhance profile update functionality with email validation and improved error handling
Deploy Development / deploy (push) Successful in 51s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
2026-04-05 11:14:01 +02:00
Lars b7f2e2adbe feat: Add Admin Group Hub page and update navigation structure for improved admin management
Deploy Development / deploy (push) Successful in 53s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
2026-04-05 11:05:45 +02:00
Lars bbc59457ac feat: Refactor admin settings and user management
Deploy Development / deploy (push) Successful in 53s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 1s
- Removed Admin Panel from SettingsPage and adjusted related logic.
- Added EmailSettings component for SMTP configuration and testing.
- Created admin navigation structure in adminNav.js for better organization.
- Implemented AdminShell layout for consistent admin UI.
- Added RequireAdmin component to protect admin routes.
- Developed AdminHomePage for admin dashboard with navigation links.
- Created AdminSystemPage for SMTP settings and placeholder metadata export.
- Implemented AdminUsersPage for user management, including profile creation and editing.
2026-04-05 10:32:43 +02:00
Lars 190c0dd7fa feat: Standardize capture page layout to a unified content width across all relevant pages
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
2026-04-05 10:21:06 +02:00
Lars a4376d1cd8 feat: Implement CaptureShell layout with sub-navigation for capture section
Deploy Development / deploy (push) Successful in 46s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 1s
2026-04-05 10:17:47 +02:00
Lars a639d08037 feat: Update capture page layout for improved responsiveness and organization across multiple screens
Deploy Development / deploy (push) Successful in 46s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
2026-04-05 10:14:07 +02:00
Lars 630a3de88a feat: Refactor analysis navigation to use category-based grouping and update state management
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
2026-04-05 10:06:29 +02:00
Lars 6d0e2de66d Gruppierung Analysen
Deploy Development / deploy (push) Successful in 59s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
2026-04-05 09:04:08 +02:00
Lars 1fa0edb3b5 feat: Implement responsive analysis page layout with horizontal navigation for mobile and vertical navigation for desktop
Deploy Development / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
2026-04-05 08:52:40 +02:00
Lars ac31c5e014 feat: Implement responsive history page layout with horizontal tabs for mobile and vertical tabs for desktop
Deploy Development / deploy (push) Successful in 48s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
2026-04-05 08:46:37 +02:00
Lars 422a117026 feat: Refactor dashboard layout with new DashboardSection and DashboardTile components for improved responsiveness and organization
Deploy Development / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
2026-04-05 08:42:07 +02:00
Lars d51bfd3daa feat: Update dashboard layout to use grid for responsive stat cards
Deploy Development / deploy (push) Successful in 55s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
2026-04-05 08:12:10 +02:00
Lars c2b2c71ccd feat: Enhance Dashboard layout with responsive greeting and metrics display
Deploy Development / deploy (push) Successful in 50s
Build Test / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 0s
2026-04-05 08:03:53 +02:00
Lars 7e8422cbd7 feat: Implement responsive desktop sidebar navigation and update app structure
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
2026-04-05 07:58:38 +02:00
Lars 3f5b9b8b58 Merge pull request 'Platzhaltersystem für Ernährung, Körper und Aktivity' (#60) from develop into main
Deploy Production / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
Reviewed-on: #60
2026-04-03 09:28:13 +02:00
Lars 5bbea036c2 Merge pull request 'develop' (#59) from develop into main
Deploy Production / deploy (push) Successful in 53s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Reviewed-on: #59
2026-04-03 08:23:48 +02:00
Lars c762495b6f Merge pull request 'Goals -System refactored - Platzhaltersystem enhanced (als draft)' (#53) from develop into main
Deploy Production / deploy (push) Successful in 51s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
Reviewed-on: #53
2026-03-31 11:46:47 +02:00
Lars 979e734bd9 Merge pull request 'Bug Fix' (#52) from develop into main
Deploy Production / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
Reviewed-on: #52
2026-03-27 22:16:18 +01:00
Lars 79cb3e0100 Merge pull request 'V 0.9h dynamic focus area system' (#51) from develop into main
Deploy Production / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Reviewed-on: #51
2026-03-27 21:14:40 +01:00
Lars 9d22e7e8af Merge pull request 'Goalsystem V1' (#50) from develop into main
Deploy Production / deploy (push) Successful in 49s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
Reviewed-on: #50
2026-03-27 17:40:50 +01:00
Lars f46c367c27 Merge pull request 'Flexibles KI Prompt System' (#48) from develop into main
Deploy Production / deploy (push) Successful in 50s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
Reviewed-on: #48
2026-03-26 14:49:47 +01:00
Lars ac4c6760d7 Merge pull request 'globaler Filter für Qualitätsgates von Trainings' (#41) from develop into main
Deploy Production / deploy (push) Successful in 52s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 1s
Reviewed-on: #41
2026-03-24 08:44:22 +01:00
Lars 5a6a140dfd Merge pull request 'Bugfixes: Vitals Import (German columns + decimal values)' (#23) from develop into main
Deploy Production / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
2026-03-23 16:52:27 +01:00
Lars 931012c16b Merge pull request 'v9d Phase 2d: Vitals Module Refactoring (Baseline + Blood Pressure)' (#22) from develop into main
Deploy Production / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
2026-03-23 16:27:03 +01:00
Lars 03f4b871a9 Merge pull request 'Production Release: RestDays Widget + Trainingstyp Fix' (#16) from develop into main
Deploy Production / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Merge pull request #16: Production Release
2026-03-23 09:24:17 +01:00
Lars 601fc80178 Merge pull request 'WP 9c Phase 1' (#12) from develop into main
Deploy Production / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Reviewed-on: #12
2026-03-22 14:14:34 +01:00
Lars 3ff2a1bf45 Merge pull request 'Abschluss 9c' (#11) from develop into main
Deploy Production / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Reviewed-on: #11
2026-03-21 21:20:10 +01:00
Lars 51aa57f304 Merge pull request 'Final Feature 9c' (#10) from develop into main
Deploy Production / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Reviewed-on: #10
2026-03-21 12:41:41 +01:00
Lars ca4411f30f Merge pull request 'fix: update version string to v9c' (#9) from develop into main
Deploy Production / deploy (push) Successful in 49s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Reviewed-on: #9
2026-03-21 09:00:55 +01:00
Lars b551365fb5 Merge pull request 'Membership-System und Bug Fixing (inkl. Nutrition)' (#8) from develop into main
Deploy Production / deploy (push) Failing after 1s
Build Test / build-frontend (push) Successful in 12s
Build Test / lint-backend (push) Successful in 0s
Reviewed-on: #8
2026-03-21 08:48:56 +01:00
Lars 272c123952 Merge pull request '9c Phase 2' (#6) from develop into main
Deploy Production / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Reviewed-on: #6
2026-03-19 14:59:25 +01:00
Lars 9387670a7b Merge pull request '9c datatables' (#5) from develop into main
Deploy Production / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Reviewed-on: #5
2026-03-19 13:00:31 +01:00
Lars d4a8401a6a Merge pull request 'Refactored Main.py' (#4) from develop into main
Deploy Production / deploy (push) Successful in 48s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Reviewed-on: #4
2026-03-19 11:44:32 +01:00
Lars aaf88a6f12 Merge pull request 'fix: Migration-Fehler - meas_id Spalte in ai_insights' (#3) from develop into main
Deploy Production / deploy (push) Successful in 49s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Reviewed-on: #3
2026-03-19 08:41:13 +01:00
Lars b789c1bd44 Merge pull request 'bug Fix Login' (#2) from develop into main
Deploy Production / deploy (push) Successful in 55s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 1s
Reviewed-on: #2
2026-03-19 08:29:48 +01:00
Lars 5062aa8068 docker-compose.yml aktualisiert
Deploy Production / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
2026-03-19 08:21:12 +01:00
Lars 8a042589e7 docker-compose.yml aktualisiert
Deploy Production / deploy (push) Failing after 1s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 12s
2026-03-19 08:19:19 +01:00
Lars 3898b5ad45 docker-compose.yml aktualisiert
Deploy Production / deploy (push) Failing after 38s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
2026-03-19 08:06:02 +01:00
Lars 9d15336144 Merge pull request 'Version 9b' (#1) from develop into main
Deploy Production / deploy (push) Failing after 42s
Build Test / build-frontend (push) Successful in 12s
Build Test / lint-backend (push) Successful in 0s
Reviewed-on: #1
2026-03-19 08:04:01 +01:00
139 changed files with 12519 additions and 1466 deletions

No files matched your search

+2 -1
View File
@@ -13,7 +13,8 @@ jobs:
set -e
echo "=== Deploying to DEVELOPMENT ==="
cd /home/lars/docker/bodytrack-dev
git pull origin develop
git fetch origin develop
git reset --hard origin/develop
docker compose -f docker-compose.dev-env.yml build --no-cache
docker compose -f docker-compose.dev-env.yml up -d
sleep 5
+3 -1
View File
@@ -13,7 +13,9 @@ jobs:
set -e
echo "=== Deploying to PRODUCTION ==="
cd /home/lars/docker/bodytrack
git pull origin main
# Arbeitskopie = exakt origin/main (vermeidet Abbruch bei lokalem package-lock o. ä.)
git fetch origin main
git reset --hard origin/main
docker compose -f docker-compose.yml build --no-cache
docker compose -f docker-compose.yml up -d
sleep 5
+2 -1
View File
@@ -64,4 +64,5 @@ tmp/
# Cursor MCP mit Secrets (Example: .cursor/mcp.json.example)
.cursor/mcp.json
.claude/settings.local.jsonfrontend/package-lock.json
.claude/settings.local.json
frontend/package-lock.json
+10
View File
@@ -6,6 +6,8 @@
> | Architektur-Regeln | `.claude/rules/ARCHITECTURE.md` |
> | Coding-Regeln | `.claude/rules/CODING_RULES.md` |
> | Lessons Learned | `.claude/rules/LESSONS_LEARNED.md` |
> | **GUI / IA / Admin / Nav / PWA-Leiste** | **`docs/issues/GUI_IA_ADMIN_NAV_2026-04-05.md`** |
> | **Dashboard-Lab-Widgets** (Katalog, Registrierung, `config`) | **`.claude/docs/technical/DASHBOARD_WIDGETS_AGENT_GUIDE.md`** |
## Claude Code Verantwortlichkeiten
@@ -16,6 +18,7 @@
- ✅ Bestehende Issues aktualisieren (Status, Beschreibung)
- ✅ Issues bei Fertigstellung schließen
- 🎯 Gitea: http://192.168.2.144:3000/Lars/mitai-jinkendo/issues
- Gitea **MCP** vs **CLI**: kurze Lese-/Kommentar-/PATCH-Vorgänge im Agent über MCP (`gitea_*`); **Beschreibung aus Datei**, sehr lange Bodies oder Skripte → `python scripts/gitea/gitea_api.py issues edit … --body-file` — `scripts/gitea/README.md`
**Dokumentation:**
- Code-Änderungen in CLAUDE.md dokumentieren
@@ -69,6 +72,8 @@ backend/
frontend/src/
├── App.jsx # Root, Auth-Gates, Navigation
├── app.css # CSS-Variablen + globale Styles
├── config/ # appNav.js · adminNav.js (Single Source für Main/Admin-Nav)
├── layouts/ # AdminShell · RequireAdmin
├── context/ # AuthContext · ProfileContext
├── pages/ # Alle Screens
└── utils/
@@ -90,6 +95,10 @@ frontend/src/
**Branch:** develop
**Nächster Schritt:** Frontend Chart Integration → Testing → Prod Deploy v0.9i
### GUI / Informationsarchitektur (Abnahme dieser Iteration, 2026-04-05)
Admin-Bereich (`AdminShell`, Hub-Routen), Hauptnavigation inkl. **Ziele** (`config/appNav.js`), Einstellungen nur aktives Profil + E-Mail, KI-Analyse Ergebnis in rechter Spalte, **PWA** Bottom-Nav inkl. iOS Safe Area. Zentrale Agent-Doku: **`docs/issues/GUI_IA_ADMIN_NAV_2026-04-05.md`**. Responsive-Epic **Gitea #30:** Phasenplan `docs/issues/PHASE_PLAN_RESPONSIVE_UI.md` — **P7 Kern erledigt**, **P8** (Regression/Abnahme) ausstehend; Issue bewusst **nicht** geschlossen.
### Updates (28.03.2026 - Phase 0c Multi-Layer Architecture Complete) 🆕
#### Phase 0c: Multi-Layer Data Architecture ✅ **COMPLETED**
@@ -834,6 +843,7 @@ Bottom-Padding Mobile: 80px (Navigation)
|Auth-Flow|`.claude/library/AUTH.md`|Sicherheit + Sessions|
|API-Referenz|`.claude/library/API\_REFERENCE.md`|Alle Endpoints|
|Datenbankschema|`.claude/library/DATABASE.md`|Tabellen + Beziehungen|
|Dashboard-Lab-Widgets|`.claude/docs/technical/DASHBOARD_WIDGETS_AGENT_GUIDE.md`|Katalog, Validierung, Frontend-Registry, konfigurierbare `config`|
> Library-Dateien werden mit `/document` generiert und nach größeren
> Änderungen aktualisiert.
+111
View File
@@ -0,0 +1,111 @@
"""Derive lean_mass and fat_mass from weight_log + body_fat_pct for caliper entries."""
from datetime import date, datetime
from decimal import Decimal
from typing import Any, Dict, List, Optional, Tuple
from db import get_cursor, r2d
def as_date(d: Any) -> Optional[date]:
if d is None:
return None
if isinstance(d, datetime):
return d.date()
if isinstance(d, date):
return d
if isinstance(d, str) and len(d) >= 10:
return datetime.strptime(d[:10], "%Y-%m-%d").date()
return None
def _floaty(x: Any) -> float:
if isinstance(x, Decimal):
return float(x)
return float(x)
def load_weight_rows(conn: Any, profile_id: str) -> List[Dict[str, Any]]:
cur = get_cursor(conn)
cur.execute(
"SELECT date, weight FROM weight_log WHERE profile_id=%s ORDER BY date",
(profile_id,),
)
return [r2d(r) for r in cur.fetchall()]
def nearest_weight_kg(weight_rows: List[Dict[str, Any]], caliper_date: Any) -> Optional[float]:
td = as_date(caliper_date)
if td is None or not weight_rows:
return None
best: Optional[float] = None
best_delta: Optional[int] = None
for row in weight_rows:
wd = as_date(row.get("date"))
if wd is None:
continue
wraw = row.get("weight")
if wraw is None:
continue
delta = abs((wd - td).days)
if best_delta is None or delta < best_delta:
best_delta = delta
best = _floaty(wraw)
return best
def nearest_weight_kg_from_map(wlog: Dict[Any, Any], target_date: Any) -> Optional[float]:
if not wlog:
return None
td = as_date(target_date)
if td is None:
return None
best_w: Optional[float] = None
best_delta: Optional[int] = None
for wd, wval in wlog.items():
if wval is None:
continue
wdate = as_date(wd)
if wdate is None:
continue
delta = abs((wdate - td).days)
if best_delta is None or delta < best_delta:
best_delta = delta
best_w = _floaty(wval)
return best_w
def compute_lean_fat_kg(weight_kg: float, body_fat_pct: float) -> Tuple[float, float]:
lean = round(weight_kg - (weight_kg * body_fat_pct / 100.0), 2)
fat = round(weight_kg * body_fat_pct / 100.0, 2)
return lean, fat
def fill_caliper_body_comp(d: Dict[str, Any], conn: Any, profile_id: str) -> None:
"""Mutate caliper API payload (model_dump) before INSERT/UPDATE."""
bf = d.get("body_fat_pct")
if bf is None:
return
if d.get("lean_mass") is not None and d.get("fat_mass") is not None:
return
rows = load_weight_rows(conn, profile_id)
w = nearest_weight_kg(rows, d.get("date"))
if w is None:
return
lean, fat = compute_lean_fat_kg(w, _floaty(bf))
d["lean_mass"] = lean
d["fat_mass"] = fat
def enrich_caliper_row_for_response(row: Dict[str, Any], weight_rows: List[Dict[str, Any]]) -> None:
"""Fill missing lean_mass / fat_mass for API responses (read path)."""
bf = row.get("body_fat_pct")
if bf is None:
return
if row.get("lean_mass") is not None and row.get("fat_mass") is not None:
return
w = nearest_weight_kg(weight_rows, row.get("date"))
if w is None:
return
lean, fat = compute_lean_fat_kg(w, _floaty(bf))
row["lean_mass"] = lean
row["fat_mass"] = fat
+127
View File
@@ -0,0 +1,127 @@
"""
Dashboard-Layout v1: Validierung, Produkt-Standard (Übersicht) und Lab-Standard.
Erlaubte Widget-IDs und Reihenfolge: widget_catalog.WIDGET_CATALOG.
"""
from __future__ import annotations
from typing import Any, Literal
from pydantic import BaseModel, Field, field_validator, model_validator
from dashboard_widget_config import validate_widget_entry_config
from widget_catalog import (
ALLOWED_WIDGET_IDS,
DEFAULT_LAB_WIDGET_IDS,
DEFAULT_PRODUCT_DASHBOARD_WIDGET_IDS,
WIDGET_CATALOG,
)
# Abwärtskompatibel (Tests importieren weiterhin aus diesem Modul)
__all__ = [
"ALLOWED_WIDGET_IDS",
"DashboardLayoutPayload",
"DashboardWidgetEntry",
"coalesce_effective_layout",
"default_layout_dict",
"lab_default_layout_dict",
"product_default_layout_dict",
]
def lab_default_layout_dict() -> dict[str, Any]:
"""Standard für Dashboard-Lab (Experimentier-Widgets)."""
on = DEFAULT_LAB_WIDGET_IDS
return {
"version": 1,
"widgets": [{"id": e["id"], "enabled": e["id"] in on} for e in WIDGET_CATALOG],
}
def product_default_layout_dict() -> dict[str, Any]:
"""Code-Fallback für die Produkt-Übersicht; live-Standard ggf. system_config (siehe get_product_default_base_dict)."""
on = DEFAULT_PRODUCT_DASHBOARD_WIDGET_IDS
return {
"version": 1,
"widgets": [{"id": e["id"], "enabled": e["id"] in on} for e in WIDGET_CATALOG],
}
def default_layout_dict() -> dict[str, Any]:
"""Alias: Produkt-Standard (coalesce, Reset). Lab nutzt lab_default_layout_dict()."""
return product_default_layout_dict()
class DashboardWidgetEntry(BaseModel):
id: str = Field(min_length=1, max_length=64)
enabled: bool = True
config: dict[str, Any] = Field(default_factory=dict)
@field_validator("config", mode="before")
@classmethod
def _config_coerce(cls, v: Any) -> dict[str, Any]:
if v is None:
return {}
if not isinstance(v, dict):
raise ValueError("config muss Objekt sein")
return v
@model_validator(mode="after")
def _normalize_widget_config(self) -> DashboardWidgetEntry:
normalized = validate_widget_entry_config(self.id, self.config)
return self.model_copy(update={"config": normalized})
class DashboardLayoutPayload(BaseModel):
version: Literal[1] = 1
widgets: list[DashboardWidgetEntry] = Field(min_length=1, max_length=32)
@model_validator(mode="after")
def _validate_widgets(self) -> DashboardLayoutPayload:
ids = [w.id for w in self.widgets]
if len(ids) != len(set(ids)):
raise ValueError("Doppelte widget id")
bad = [i for i in ids if i not in ALLOWED_WIDGET_IDS]
if bad:
raise ValueError(f"Unbekannte Widget-IDs: {bad}")
if not any(w.enabled for w in self.widgets):
raise ValueError("Mindestens ein Widget muss aktiv sein")
return self
def to_stored_dict(self) -> dict[str, Any]:
out_widgets: list[dict[str, Any]] = []
for w in self.widgets:
d: dict[str, Any] = {"id": w.id, "enabled": w.enabled}
if w.config:
d["config"] = dict(w.config)
out_widgets.append(d)
return {"version": self.version, "widgets": out_widgets}
def coalesce_effective_layout(raw: Any) -> tuple[bool, dict[str, Any]]:
"""
Returns (has_custom, effective_layout).
has_custom=True nur wenn DB-Wert vorhanden und gültig (v1).
"""
if raw is None:
return False, default_layout_dict()
parsed_obj: Any = raw
if isinstance(raw, str):
import json
try:
parsed_obj = json.loads(raw)
except json.JSONDecodeError:
return False, default_layout_dict()
if not isinstance(parsed_obj, dict):
return False, default_layout_dict()
try:
parsed = DashboardLayoutPayload.model_validate(
{
"version": parsed_obj.get("version", 1),
"widgets": parsed_obj.get("widgets", []),
}
)
return True, parsed.to_stored_dict()
except Exception:
return False, default_layout_dict()
+165
View File
@@ -0,0 +1,165 @@
"""
Pro-Widget-Konfiguration im Dashboard-Layout (v1).
Nur ausgewählte Widget-IDs dürfen nicht-leere config haben; bekannte Keys werden validiert.
"""
from __future__ import annotations
import json
import math
import re
from typing import Any
MAX_WIDGET_CONFIG_JSON_BYTES = 3072
WIDGETS_ALLOWING_CONFIG: frozenset[str] = frozenset({
"body_overview",
"activity_overview",
"kpi_board",
"quick_capture",
"trend_kcal_weight",
"nutrition_detail_charts",
"recovery_charts_panel",
})
_QUICK_CAPTURE_KEYS: frozenset[str] = frozenset({
"show_weight",
"show_resting_hr",
"show_hrv",
"show_vo2_max",
})
_KPI_TILE_FIXED: frozenset[str] = frozenset({"body_fat", "avg_kcal"})
_KPI_REF_TILE_RE = re.compile(r"^ref:[a-z0-9_]{1,64}$")
def _config_json_size_bytes(config: dict[str, Any]) -> int:
return len(json.dumps(config, sort_keys=True, ensure_ascii=False).encode("utf-8"))
def validate_widget_entry_config(widget_id: str, raw: Any) -> dict[str, Any]:
if raw is None:
return {}
if not isinstance(raw, dict):
raise ValueError(f"Widget {widget_id}: config muss ein Objekt sein")
if _config_json_size_bytes(raw) > MAX_WIDGET_CONFIG_JSON_BYTES:
raise ValueError(f"Widget {widget_id}: config zu groß (max. {MAX_WIDGET_CONFIG_JSON_BYTES} Byte JSON)")
if not raw:
return {}
if widget_id not in WIDGETS_ALLOWING_CONFIG:
raise ValueError(f"Widget {widget_id}: keine Konfiguration unterstützt")
if widget_id == "body_overview":
return _validate_chart_days_only(raw, label="body_overview")
if widget_id == "activity_overview":
return _validate_chart_days_only(raw, label="activity_overview")
if widget_id == "kpi_board":
return _validate_kpi_board_config(raw)
if widget_id == "quick_capture":
return _validate_quick_capture_config(raw)
if widget_id == "trend_kcal_weight":
return _validate_chart_days_only(raw, label="trend_kcal_weight")
if widget_id == "nutrition_detail_charts":
return _validate_chart_days_only(raw, label="nutrition_detail_charts")
if widget_id == "recovery_charts_panel":
return _validate_chart_days_only(raw, label="recovery_charts_panel")
raise ValueError(f"Widget {widget_id}: keine Konfiguration unterstützt")
def _validate_quick_capture_config(raw: dict[str, Any]) -> dict[str, Any]:
label = "quick_capture"
unknown = set(raw) - _QUICK_CAPTURE_KEYS
if unknown:
raise ValueError(f"{label}: unbekannte config-Felder: {sorted(unknown)}")
out: dict[str, bool] = {}
for k in _QUICK_CAPTURE_KEYS:
if k not in raw:
continue
v = raw[k]
if not isinstance(v, bool):
raise ValueError(f"{label}: {k} muss boolean sein")
out[k] = v
merged = {k: True for k in _QUICK_CAPTURE_KEYS}
merged.update(out)
if not any(merged.values()):
raise ValueError(f"{label}: mindestens ein Bereich muss sichtbar sein (show_*)")
return out
def _kpi_tile_id_valid(tid: str) -> bool:
if tid in _KPI_TILE_FIXED:
return True
return bool(_KPI_REF_TILE_RE.match(tid))
def _normalize_kpi_tile_entry(item: Any) -> str:
if isinstance(item, str):
tid = item.strip()
elif isinstance(item, dict) and "id" in item:
tid = str(item["id"]).strip()
else:
raise ValueError("kpi_board: jedes tiles-Element braucht eine id (String oder Objekt mit id)")
if not tid:
raise ValueError("kpi_board: leere Kachel-id")
if not _kpi_tile_id_valid(tid):
raise ValueError(f"kpi_board: ungültige Kachel-id {tid!r} (z. B. body_fat, avg_kcal, ref:typ_key)")
return tid
def _validate_kpi_board_config(raw: dict[str, Any]) -> dict[str, Any]:
if not raw:
return {}
# Legacy nur chart_days → entfallen, automatische Kachelwahl
if set(raw.keys()) <= frozenset({"chart_days"}):
return {}
allowed = frozenset({"tiles"})
unknown = set(raw) - allowed
if unknown:
raise ValueError(f"kpi_board: unbekannte config-Felder: {sorted(unknown)}")
tiles_raw = raw.get("tiles")
if tiles_raw is None:
return {}
if not isinstance(tiles_raw, list):
raise ValueError("kpi_board: tiles muss eine Liste sein")
if len(tiles_raw) > 9:
raise ValueError("kpi_board: maximal 9 Kacheln")
seen: set[str] = set()
out: list[dict[str, str]] = []
for item in tiles_raw:
tid = _normalize_kpi_tile_entry(item)
if tid in seen:
raise ValueError(f"kpi_board: doppelte Kachel-id {tid}")
seen.add(tid)
out.append({"id": tid})
return {"tiles": out}
def _parse_chart_days(v: Any, label: str) -> int:
if isinstance(v, bool):
raise ValueError(f"{label}: chart_days muss ganze Zahl sein")
if isinstance(v, float):
if not math.isfinite(v):
raise ValueError(f"{label}: chart_days muss ganze Zahl sein")
if abs(v - round(v)) > 1e-9:
raise ValueError(f"{label}: chart_days muss ganze Zahl sein")
return int(round(v))
if isinstance(v, int):
return v
raise ValueError(f"{label}: chart_days muss ganze Zahl sein")
def _validate_chart_days_only(raw: dict[str, Any], *, label: str) -> dict[str, Any]:
allowed = frozenset({"chart_days"})
unknown = set(raw) - allowed
if unknown:
raise ValueError(f"{label}: unbekannte config-Felder: {sorted(unknown)}")
if "chart_days" not in raw:
return {}
v = _parse_chart_days(raw["chart_days"], label)
if v < 7 or v > 90:
raise ValueError(f"{label}: chart_days muss zwischen 7 und 90 liegen")
return {"chart_days": v}
+87
View File
@@ -0,0 +1,87 @@
"""
Dashboard-Widgets × Feature-System: Sichtbarkeit aus check_feature_access.
Katalog-Einträge optional `requires_feature` (features.id). Fehlt der Key → immer erlaubt.
"""
from __future__ import annotations
import copy
from typing import Any
from widget_catalog import WIDGET_CATALOG
def _check_feature_access(profile_id: str, feature_id: str, conn) -> dict:
"""Indirection für Tests (monkeypatch) und spätes Laden von auth (bcrypt)."""
from auth import check_feature_access
return check_feature_access(profile_id, feature_id, conn)
_WIDGET_ENTRY_BY_ID: dict[str, dict[str, Any]] = {e["id"]: e for e in WIDGET_CATALOG}
def widget_id_allowed(widget_id: str, profile_id: str, conn) -> bool:
entry = _WIDGET_ENTRY_BY_ID.get(widget_id)
if entry is None:
return False
fid = entry.get("requires_feature")
if not fid:
return True
return bool(_check_feature_access(profile_id, fid, conn)["allowed"])
def _public_row(entry: dict[str, Any], *, allowed: bool) -> dict[str, Any]:
return {
"id": entry["id"],
"title": entry["title"],
"description": entry["description"],
"allowed": allowed,
}
def widgets_catalog_for_profile(profile_id: str, conn) -> list[dict[str, Any]]:
"""Zeilen für GET /api/app/widgets/catalog (ohne internes requires_feature-Feld)."""
out: list[dict[str, Any]] = []
for e in WIDGET_CATALOG:
fid = e.get("requires_feature")
allowed = True
if fid:
allowed = bool(_check_feature_access(profile_id, fid, conn)["allowed"])
out.append(_public_row(e, allowed=allowed))
return out
def widgets_catalog_payload(profile_id: str, conn) -> dict[str, Any]:
return {
"catalog_version": 1,
"widgets": widgets_catalog_for_profile(profile_id, conn),
}
def widgets_catalog_admin_payload() -> dict[str, Any]:
"""Admin: alle Widgets als auswählbar (ohne Feature-Filter)."""
return {
"catalog_version": 1,
"widgets": [_public_row(e, allowed=True) for e in WIDGET_CATALOG],
}
def apply_entitlements_to_layout_dict(layout: dict[str, Any], profile_id: str, conn) -> dict[str, Any]:
"""
Setzt enabled=False für Widgets ohne Berechtigung. Mindestens ein Widget bleibt aktiv (welcome).
"""
out = copy.deepcopy(layout)
widgets = out.get("widgets") or []
for w in widgets:
wid = w.get("id")
if not wid:
continue
if w.get("enabled") and not widget_id_allowed(wid, profile_id, conn):
w["enabled"] = False
if not any(w.get("enabled") for w in widgets):
for w in widgets:
if w.get("id") == "welcome":
w["enabled"] = True
break
return out
+4
View File
@@ -19,6 +19,10 @@ Modules:
- goals: Active goals, progress, projections
- correlations: Lag-analysis, plateau detection
- utils: Shared functions (confidence, baseline, outliers)
- training_profile: Template-based training evaluation scaffold (Layer 1)
Import: ``from data_layer.training_profile import resolve_training_evaluation``
- reference_values: Profile reference value reads + summary (Layer 1)
Import: ``from data_layer import reference_values`` or submodule imports
Phase 0c: Multi-Layer Architecture
Version: 1.0
+179
View File
@@ -0,0 +1,179 @@
"""
Reference values — Layer 1 (read paths + structured rows)
Structured retrieval for profile reference values and the active type catalog.
Mutations (INSERT/UPDATE/DELETE) stay in routers/reference_values.py with validation.
Dates are normalized to ISO strings; Decimals to float — suitable for JSON/API layers.
"""
from __future__ import annotations
from decimal import Decimal
from typing import Any, Optional
from db import get_cursor, get_db, r2d
def normalize_reference_row(d: Optional[dict[str, Any]]) -> dict[str, Any]:
"""Normalize DB row dict for JSON (dates → ISO, Decimal → float)."""
if not d:
return d
out = dict(d)
for k in ("effective_date", "created_at", "updated_at"):
v = out.get(k)
if v is not None and hasattr(v, "isoformat"):
out[k] = v.isoformat()
vn = out.get("value_numeric")
if vn is not None and isinstance(vn, Decimal):
out["value_numeric"] = float(vn)
return out
def fetch_reference_type_by_key(cur, key: str, require_active: bool = True) -> Optional[dict[str, Any]]:
"""Single type row by key; for use inside router transactions (shared cursor)."""
q = (
"SELECT id, key, label, description, default_unit, active, category, "
"value_data_type, validation_rules, metadata "
"FROM reference_value_types WHERE key = %s "
)
if require_active:
q += "AND active = TRUE "
cur.execute(q, (key,))
row = cur.fetchone()
return r2d(row) if row else None
def list_active_reference_value_types_data() -> list[dict[str, Any]]:
"""All active reference_value_types rows, catalog sort order."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT
id, key, label, description, default_unit, sort_order, active,
category, value_data_type, validation_rules, metadata, created_at
FROM reference_value_types
WHERE active = TRUE
ORDER BY sort_order ASC, id ASC
"""
)
return [normalize_reference_row(r2d(r)) for r in cur.fetchall()]
def list_profile_reference_values_for_type(
profile_id: str, type_key: str
) -> Optional[list[dict[str, Any]]]:
"""
Historical entries for one type, newest first.
Returns None if type_key does not resolve to an active type.
"""
with get_db() as conn:
cur = get_cursor(conn)
t = fetch_reference_type_by_key(cur, type_key, require_active=True)
if not t:
return None
cur.execute(
"""
SELECT
v.id,
v.profile_id,
v.reference_value_type_id,
v.effective_date,
v.value_numeric,
v.value_text,
v.unit,
v.source,
v.confidence,
v.method,
v.notes,
v.extra,
v.created_at,
v.updated_at,
rt.key AS type_key,
rt.label AS type_label
FROM profile_reference_values v
JOIN reference_value_types rt ON rt.id = v.reference_value_type_id
WHERE v.profile_id = %s AND rt.key = %s
ORDER BY v.effective_date DESC, v.created_at DESC
""",
(profile_id, t["key"]),
)
return [normalize_reference_row(r2d(r)) for r in cur.fetchall()]
def build_summary_tiles_from_ranked_rows(raw_rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""
Build /summary.tile payloads from SQL rows (rn 1..2 per type).
Each row still contains rn, type_sort_order, value_data_type before stripping.
"""
by_key: dict[str, dict[str, Any]] = {}
skip_cols = frozenset({"rn", "type_sort_order", "value_data_type"})
for row in raw_rows:
rn = int(row.get("rn") or 0)
key = row["type_key"]
if key not in by_key:
by_key[key] = {
"type_key": key,
"type_label": row.get("type_label") or key,
"value_data_type": (row.get("value_data_type") or "decimal").strip().lower(),
"sort_key": (row.get("type_sort_order") or 0, key),
"latest": None,
"previous": None,
}
entry = {k: v for k, v in row.items() if k not in skip_cols}
api_entry = normalize_reference_row(entry)
if rn == 1:
by_key[key]["latest"] = api_entry
elif rn == 2:
by_key[key]["previous"] = api_entry
tiles = sorted(by_key.values(), key=lambda t: t["sort_key"])
for t in tiles:
t.pop("sort_key", None)
return tiles
def get_profile_reference_values_summary(profile_id: str) -> dict[str, Any]:
"""latest + previous entry per type (active types only), tiles sorted like catalog."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
WITH ranked AS (
SELECT
v.id,
v.profile_id,
v.reference_value_type_id,
v.effective_date,
v.value_numeric,
v.value_text,
v.unit,
v.source,
v.confidence,
v.method,
v.notes,
v.extra,
v.created_at,
v.updated_at,
rt.key AS type_key,
rt.label AS type_label,
rt.sort_order AS type_sort_order,
rt.value_data_type,
ROW_NUMBER() OVER (
PARTITION BY v.reference_value_type_id
ORDER BY v.effective_date DESC, v.created_at DESC
) AS rn
FROM profile_reference_values v
JOIN reference_value_types rt ON rt.id = v.reference_value_type_id
WHERE v.profile_id = %s AND rt.active = TRUE
)
SELECT * FROM ranked WHERE rn <= 2
ORDER BY type_sort_order ASC, type_key ASC, rn ASC
""",
(profile_id,),
)
raw_rows = [r2d(r) for r in cur.fetchall()]
tiles = build_summary_tiles_from_ranked_rows(raw_rows)
return {"tiles": tiles}
@@ -0,0 +1,36 @@
"""
Training profile resolver (Layer 1 scaffold).
Template-driven multi-dimensional evaluation with built-in algorithms and
Focus Area contribution aggregation. Import explicitly from this package.
Public API:
- resolve_training_evaluation
- resolve_for_base_profile
- models: CalculationTemplate, TrainingEvaluationResult, ...
- registries: templates, profiles, algorithms
"""
from data_layer.training_profile.models import (
CalculationTemplate,
DimensionResult,
DimensionSpec,
FocusAreaMapping,
TrainingBaseProfile,
TrainingEvaluationResult,
)
from data_layer.training_profile.resolver import (
resolve_for_base_profile,
resolve_training_evaluation,
)
__all__ = [
"CalculationTemplate",
"DimensionResult",
"DimensionSpec",
"FocusAreaMapping",
"TrainingBaseProfile",
"TrainingEvaluationResult",
"resolve_for_base_profile",
"resolve_training_evaluation",
]
@@ -0,0 +1,13 @@
"""Built-in training evaluation algorithms (code-defined only)."""
from .registry import (
get_algorithm,
list_algorithm_ids,
register_algorithm,
)
__all__ = [
"get_algorithm",
"list_algorithm_ids",
"register_algorithm",
]
@@ -0,0 +1,23 @@
"""
Algorithm protocol: fixed implementations selected by id from declarative templates.
"""
from __future__ import annotations
from typing import Any, Dict, Mapping, Protocol
from data_layer.training_profile.models import AlgorithmRunResult
class TrainingAlgorithm(Protocol):
"""Built-in algorithm callable shape."""
id: str
def __call__(
self,
*,
inputs: Mapping[str, Any],
params: Mapping[str, Any],
) -> AlgorithmRunResult:
...
@@ -0,0 +1,6 @@
"""Example built-in algorithms (threshold bands, linear range mapping)."""
from .linear_range import linear_range_score
from .threshold_band import threshold_band_score
__all__ = ["linear_range_score", "threshold_band_score"]
@@ -0,0 +1,69 @@
"""
linear_range: map a value linearly from [min_value, max_value] to [0, 1], clamped.
params:
value_key: str
min_value: float
max_value: float
invert: bool (optional) — if True, high values map to 0
Missing value → score 0 and missing_inputs.
"""
from __future__ import annotations
from typing import Any, Mapping
from data_layer.training_profile.models import AlgorithmRunResult
from data_layer.utils import safe_float
ALGORITHM_ID = "linear_range"
def linear_range_score(
*,
inputs: Mapping[str, Any],
params: Mapping[str, Any],
) -> AlgorithmRunResult:
value_key = str(params.get("value_key", ""))
if not value_key:
return AlgorithmRunResult(
raw_score=0.0,
normalized_score=0.0,
missing_inputs=["__param_value_key__"],
detail={"error": "params.value_key required"},
)
if value_key not in inputs or inputs[value_key] is None:
return AlgorithmRunResult(
raw_score=0.0,
normalized_score=0.0,
missing_inputs=[value_key],
detail={"value_key": value_key},
)
raw = safe_float(inputs[value_key])
lo = safe_float(params.get("min_value"))
hi = safe_float(params.get("max_value"))
invert = bool(params.get("invert", False))
if hi <= lo:
return AlgorithmRunResult(
raw_score=raw,
normalized_score=0.0,
missing_inputs=[],
detail={"error": "max_value must be > min_value", "min": lo, "max": hi},
)
t = (raw - lo) / (hi - lo)
t = max(0.0, min(1.0, t))
if invert:
t = 1.0 - t
return AlgorithmRunResult(
raw_score=raw,
normalized_score=t,
missing_inputs=[],
detail={"value_key": value_key, "min": lo, "max": hi, "invert": invert},
)
@@ -0,0 +1,75 @@
"""
threshold_band: map a numeric value into a score using ordered upper bounds.
params:
value_key: str — key in inputs to read
bands: list of { "max": float | null, "score": float } — ascending max; null = +inf
Missing value_key → normalized_score 0, missing_inputs lists value_key.
"""
from __future__ import annotations
from typing import Any, List, Mapping
from data_layer.training_profile.models import AlgorithmRunResult
from data_layer.utils import safe_float
ALGORITHM_ID = "threshold_band"
def threshold_band_score(
*,
inputs: Mapping[str, Any],
params: Mapping[str, Any],
) -> AlgorithmRunResult:
value_key = str(params.get("value_key", ""))
if not value_key:
return AlgorithmRunResult(
raw_score=0.0,
normalized_score=0.0,
missing_inputs=["__param_value_key__"],
detail={"error": "params.value_key required"},
)
if value_key not in inputs or inputs[value_key] is None:
return AlgorithmRunResult(
raw_score=0.0,
normalized_score=0.0,
missing_inputs=[value_key],
detail={"value_key": value_key},
)
raw = safe_float(inputs[value_key])
bands = params.get("bands") or []
if not isinstance(bands, list) or not bands:
return AlgorithmRunResult(
raw_score=raw,
normalized_score=0.0,
missing_inputs=[],
detail={"error": "params.bands must be a non-empty list", "raw": raw},
)
score = 0.0
for band in bands:
if not isinstance(band, dict):
continue
max_v = band.get("max")
s = safe_float(band.get("score"))
if max_v is None:
score = s
break
if raw <= safe_float(max_v):
score = s
break
else:
score = safe_float(bands[-1].get("score")) if isinstance(bands[-1], dict) else 0.0
norm = max(0.0, min(1.0, score))
return AlgorithmRunResult(
raw_score=raw,
normalized_score=norm,
missing_inputs=[],
detail={"value_key": value_key, "bands_applied": True, "band_score": score},
)
@@ -0,0 +1,47 @@
"""
Registry for built-in algorithm ids → callables.
Only code registers algorithms; templates reference ids declared here.
"""
from __future__ import annotations
from typing import Any, Callable, Dict, Mapping
from data_layer.training_profile.algorithms.builtin.linear_range import (
ALGORITHM_ID as LINEAR_RANGE_ID,
linear_range_score,
)
from data_layer.training_profile.algorithms.builtin.threshold_band import (
ALGORITHM_ID as THRESHOLD_BAND_ID,
threshold_band_score,
)
from data_layer.training_profile.models import AlgorithmRunResult
AlgorithmFn = Callable[..., AlgorithmRunResult]
_REGISTRY: Dict[str, AlgorithmFn] = {}
def register_algorithm(algorithm_id: str, fn: AlgorithmFn) -> None:
if algorithm_id in _REGISTRY:
raise ValueError(f"Algorithm already registered: {algorithm_id}")
_REGISTRY[algorithm_id] = fn
def get_algorithm(algorithm_id: str) -> AlgorithmFn:
if algorithm_id not in _REGISTRY:
raise KeyError(f"Unknown algorithm_id: {algorithm_id}")
return _REGISTRY[algorithm_id]
def list_algorithm_ids() -> tuple[str, ...]:
return tuple(sorted(_REGISTRY.keys()))
def _register_defaults() -> None:
register_algorithm(THRESHOLD_BAND_ID, threshold_band_score)
register_algorithm(LINEAR_RANGE_ID, linear_range_score)
_register_defaults()
@@ -0,0 +1,121 @@
"""
Declarative schemas for template-based training evaluation (Layer 1 scaffold).
Templates select built-in algorithms by id and pass parameters; they do not embed
executable logic. See resolver and algorithm registry.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List, Mapping, Optional
@dataclass(frozen=True)
class FocusAreaMapping:
"""Maps a share of one dimension's score to a Focus Area (by stable key)."""
focus_area_key: str
weight: float
@dataclass(frozen=True)
class DimensionSpec:
"""
One evaluation dimension: algorithm + inputs + params + FA mapping.
inputs: names of keys expected in the flat activity_inputs dict passed to the resolver.
"""
key: str
algorithm_id: str
inputs: tuple[str, ...]
params: Mapping[str, Any]
maps_to: tuple[FocusAreaMapping, ...]
@dataclass(frozen=True)
class CalculationTemplate:
"""Declarative multi-dimensional calculation template (in-code registry)."""
id: str
version: str
label: str
dimensions: tuple[DimensionSpec, ...]
@dataclass(frozen=True)
class TrainingBaseProfile:
"""
Conceptual base profile: links a training context to a default template.
allowed_dimension_keys: if set, dimensions not listed are skipped at resolve time.
"""
key: str
label: str
default_template_id: str
allowed_dimension_keys: Optional[frozenset[str]] = None
@dataclass
class AlgorithmRunResult:
"""Output of a single built-in algorithm execution."""
raw_score: float
normalized_score: float
missing_inputs: List[str]
detail: Dict[str, Any] = field(default_factory=dict)
@dataclass
class DimensionResult:
"""Per-dimension result after resolution."""
dimension_key: str
algorithm_id: str
raw_score: float
normalized_score: float
missing_inputs: List[str]
evidence: Dict[str, Any] = field(default_factory=dict)
@dataclass
class TrainingEvaluationResult:
"""
Stable structured result for Layer 2 (KI, charts, APIs, future persistence).
focus_area_contributions: aggregated contribution per focus_area key (additive).
"""
template_id: str
template_version: str
base_profile_key: Optional[str]
dimension_results: List[DimensionResult]
focus_area_contributions: Dict[str, float]
confidence: str
evidence: Dict[str, Any]
trace: Optional[Dict[str, Any]] = None
def to_serializable(self) -> Dict[str, Any]:
"""JSON-compatible dict (for APIs / storage)."""
return {
"template_id": self.template_id,
"template_version": self.template_version,
"base_profile_key": self.base_profile_key,
"dimension_results": [
{
"dimension_key": d.dimension_key,
"algorithm_id": d.algorithm_id,
"raw_score": d.raw_score,
"normalized_score": d.normalized_score,
"missing_inputs": d.missing_inputs,
"evidence": d.evidence,
}
for d in self.dimension_results
],
"focus_area_contributions": dict(self.focus_area_contributions),
"confidence": self.confidence,
"evidence": self.evidence,
"trace": self.trace,
}
@@ -0,0 +1,13 @@
"""Training base profile registrations (scaffold, in-code)."""
from .registry import (
get_training_base_profile,
list_training_base_profile_keys,
try_get_training_base_profile,
)
__all__ = [
"get_training_base_profile",
"list_training_base_profile_keys",
"try_get_training_base_profile",
]
@@ -0,0 +1,52 @@
"""
Example training base profiles — point to default templates and optional dimension filters.
Future: DB-backed training types may reference profile keys; this registry is code-only.
"""
from __future__ import annotations
from typing import Dict, Optional
from data_layer.training_profile.models import TrainingBaseProfile
_PROFILES: Dict[str, TrainingBaseProfile] = {}
def _register(p: TrainingBaseProfile) -> None:
if p.key in _PROFILES:
raise ValueError(f"Duplicate training base profile key: {p.key}")
_PROFILES[p.key] = p
def get_training_base_profile(key: str) -> TrainingBaseProfile:
if key not in _PROFILES:
raise KeyError(f"Unknown training base profile: {key}")
return _PROFILES[key]
def try_get_training_base_profile(key: str) -> Optional[TrainingBaseProfile]:
return _PROFILES.get(key)
def list_training_base_profile_keys() -> tuple[str, ...]:
return tuple(sorted(_PROFILES.keys()))
_register(
TrainingBaseProfile(
key="scaffold_aerobic_base",
label="Scaffold: aerobic base profile",
default_template_id="scaffold_example_aerobic_v1",
allowed_dimension_keys=None,
)
)
_register(
TrainingBaseProfile(
key="scaffold_strength_base",
label="Scaffold: strength base profile",
default_template_id="scaffold_example_strength_v1",
allowed_dimension_keys=frozenset({"effort"}),
)
)
@@ -0,0 +1,160 @@
"""
Layer 1 entry: resolve a multi-dimensional training evaluation from a template.
Pure calculation orchestration — no DB, no HTTP, no formatting for KI/charts.
"""
from __future__ import annotations
from collections import defaultdict
from typing import Any, Dict, List, Mapping, Optional
from data_layer.training_profile.algorithms.registry import get_algorithm
from data_layer.training_profile.models import (
CalculationTemplate,
DimensionResult,
DimensionSpec,
TrainingBaseProfile,
TrainingEvaluationResult,
)
def _required_inputs_present(
activity_inputs: Mapping[str, Any], keys: tuple[str, ...]
) -> tuple[bool, List[str]]:
missing: List[str] = []
for k in keys:
if k not in activity_inputs or activity_inputs[k] is None:
missing.append(k)
return (len(missing) == 0, missing)
def _confidence_level(total_dims: int, dims_with_any_missing: int) -> str:
if total_dims == 0:
return "insufficient"
if dims_with_any_missing == 0:
return "high"
if dims_with_any_missing >= total_dims:
return "insufficient"
if dims_with_any_missing == 1:
return "medium"
return "low"
def _filter_dimensions(
template: CalculationTemplate, base_profile: Optional[TrainingBaseProfile]
) -> tuple[DimensionSpec, ...]:
if base_profile is None or base_profile.allowed_dimension_keys is None:
return template.dimensions
allowed = base_profile.allowed_dimension_keys
return tuple(d for d in template.dimensions if d.key in allowed)
def resolve_training_evaluation(
*,
activity_inputs: Mapping[str, Any],
template: CalculationTemplate,
base_profile: Optional[TrainingBaseProfile] = None,
include_trace: bool = False,
) -> TrainingEvaluationResult:
"""
Run all template dimensions, aggregate Focus Area contributions, attach evidence.
activity_inputs: flat dict (e.g. avg_hr, duration_min, distance_km) supplied by caller.
"""
dimensions = _filter_dimensions(template, base_profile)
dimension_results: List[DimensionResult] = []
contributions: Dict[str, float] = defaultdict(float)
evidence: Dict[str, Any] = {
"dimensions_total": len(dimensions),
"inputs_keys": sorted(activity_inputs.keys()),
}
trace: Optional[Dict[str, Any]] = {} if include_trace else None
dims_with_missing = 0
for spec in dimensions:
ok, missing = _required_inputs_present(activity_inputs, spec.inputs)
if not ok:
dims_with_missing += 1
dimension_results.append(
DimensionResult(
dimension_key=spec.key,
algorithm_id=spec.algorithm_id,
raw_score=0.0,
normalized_score=0.0,
missing_inputs=list(missing),
evidence={"skipped": True, "reason": "required_inputs_missing"},
)
)
if trace is not None:
trace[spec.key] = {"skipped": True, "missing": missing}
continue
algo = get_algorithm(spec.algorithm_id)
slice_inputs = {k: activity_inputs[k] for k in spec.inputs}
run = algo(inputs=slice_inputs, params=dict(spec.params))
if run.missing_inputs:
dims_with_missing += 1
dimension_results.append(
DimensionResult(
dimension_key=spec.key,
algorithm_id=spec.algorithm_id,
raw_score=run.raw_score,
normalized_score=run.normalized_score,
missing_inputs=list(run.missing_inputs),
evidence={"algorithm_detail": run.detail},
)
)
for m in spec.maps_to:
contributions[m.focus_area_key] += run.normalized_score * m.weight
if trace is not None:
trace[spec.key] = {
"inputs": dict(slice_inputs),
"params": dict(spec.params),
"run": {
"raw_score": run.raw_score,
"normalized_score": run.normalized_score,
"missing_inputs": run.missing_inputs,
"detail": run.detail,
},
"maps_to": [(x.focus_area_key, x.weight) for x in spec.maps_to],
}
conf = _confidence_level(len(dimensions), dims_with_missing)
evidence["dimensions_with_missing_or_failed"] = dims_with_missing
return TrainingEvaluationResult(
template_id=template.id,
template_version=template.version,
base_profile_key=base_profile.key if base_profile else None,
dimension_results=dimension_results,
focus_area_contributions=dict(contributions),
confidence=conf,
evidence=evidence,
trace=trace,
)
def resolve_for_base_profile(
*,
activity_inputs: Mapping[str, Any],
base_profile_key: str,
include_trace: bool = False,
) -> TrainingEvaluationResult:
"""Convenience: load profile + default template from registries."""
from data_layer.training_profile.profiles.registry import get_training_base_profile
from data_layer.training_profile.templates.registry import get_calculation_template
profile = get_training_base_profile(base_profile_key)
template = get_calculation_template(profile.default_template_id)
return resolve_training_evaluation(
activity_inputs=activity_inputs,
template=template,
base_profile=profile,
include_trace=include_trace,
)
@@ -0,0 +1,5 @@
"""Declarative calculation templates (in-code registry, scaffold)."""
from .registry import get_calculation_template, list_calculation_template_ids
__all__ = ["get_calculation_template", "list_calculation_template_ids"]
@@ -0,0 +1,96 @@
"""
Example calculation templates — declarative only; algorithms are referenced by id.
These are scaffolding examples, not production coaching rules.
"""
from __future__ import annotations
from typing import Dict
from data_layer.training_profile.models import CalculationTemplate, DimensionSpec, FocusAreaMapping
_TEMPLATES: Dict[str, CalculationTemplate] = {}
def _register(t: CalculationTemplate) -> None:
if t.id in _TEMPLATES:
raise ValueError(f"Duplicate template id: {t.id}")
_TEMPLATES[t.id] = t
def get_calculation_template(template_id: str) -> CalculationTemplate:
if template_id not in _TEMPLATES:
raise KeyError(f"Unknown calculation template: {template_id}")
return _TEMPLATES[template_id]
def list_calculation_template_ids() -> tuple[str, ...]:
return tuple(sorted(_TEMPLATES.keys()))
# --- Example templates (illustrative) ---
_example_aerobic = CalculationTemplate(
id="scaffold_example_aerobic_v1",
version="1",
label="Scaffold: aerobic-style intensity + volume (example)",
dimensions=(
DimensionSpec(
key="intensity",
algorithm_id="threshold_band",
inputs=("avg_hr", "duration_min"),
params={
"value_key": "avg_hr",
"bands": [
{"max": 120, "score": 0.25},
{"max": 140, "score": 0.55},
{"max": 160, "score": 0.85},
{"max": None, "score": 1.0},
],
},
maps_to=(
FocusAreaMapping("aerobic_endurance", 0.7),
FocusAreaMapping("cardiovascular_health", 0.3),
),
),
DimensionSpec(
key="volume",
algorithm_id="linear_range",
inputs=("duration_min", "distance_km"),
params={
"value_key": "duration_min",
"min_value": 10.0,
"max_value": 90.0,
"invert": False,
},
maps_to=(FocusAreaMapping("aerobic_endurance", 0.8),),
),
),
)
_example_strength = CalculationTemplate(
id="scaffold_example_strength_v1",
version="1",
label="Scaffold: strength session load (example)",
dimensions=(
DimensionSpec(
key="effort",
algorithm_id="linear_range",
inputs=("duration_min",),
params={
"value_key": "duration_min",
"min_value": 20.0,
"max_value": 75.0,
"invert": False,
},
maps_to=(
FocusAreaMapping("strength", 0.9),
FocusAreaMapping("strength_endurance", 0.1),
),
),
),
)
_register(_example_aerobic)
_register(_example_strength)
+20
View File
@@ -0,0 +1,20 @@
"""Kleine Helfer für Focus-Area-Nutzungstypen (ohne Router-/Auth-Abhängigkeiten)."""
from __future__ import annotations
import json
from typing import Any, List
def coerce_usage_type_keys(raw: Any) -> List[str]:
"""json_agg / JSON-Spalte zu list[str] normalisieren."""
if raw is None:
return []
if isinstance(raw, list):
return [str(x) for x in raw]
if isinstance(raw, str):
try:
data = json.loads(raw)
return [str(x) for x in data] if isinstance(data, list) else []
except json.JSONDecodeError:
return []
return []
+6
View File
@@ -28,6 +28,9 @@ from routers import goal_types, goal_progress, training_phases, fitness_tests #
from routers import charts # Phase 0c Multi-Layer Architecture
from routers import workflow_questions # Phase 1 Workflow Engine - Question Catalog
from routers import workflows # Phase 2 Workflow Engine - Execution
from routers import reference_values # Persönliche Referenzwerte (Profil)
from routers import admin_reference_value_types # Admin: Referenzwert-Typen
from routers import app_dashboard # Geschützter App-Bereich: Dashboard-Lab Layout
# ── App Configuration ─────────────────────────────────────────────────────────
DATA_DIR = Path(os.getenv("DATA_DIR", "./data"))
@@ -115,6 +118,9 @@ app.include_router(charts.router) # /api/charts/* (Phase 0c Charts
# Phase 1-2 Workflow Engine
app.include_router(workflow_questions.router) # /api/workflow/questions/* (Phase 1 Question Catalog)
app.include_router(workflows.router) # /api/workflows/* (Phase 2 Execution)
app.include_router(reference_values.router) # /api/reference-value-types, /api/profile-reference-values
app.include_router(admin_reference_value_types.router) # /api/admin/reference-value-types
app.include_router(app_dashboard.router) # /api/app/dashboard-layout
# ── Health Check ──────────────────────────────────────────────────────────────
@app.get("/")
@@ -0,0 +1,24 @@
-- Migration 035: Backfill caliper lean_mass / fat_mass from nearest weight_log row
-- Date: 2026-04-06
UPDATE caliper_log c
SET
lean_mass = sub.lean_mass,
fat_mass = sub.fat_mass
FROM (
SELECT
c2.id,
round((wl.weight::numeric - (wl.weight::numeric * c2.body_fat_pct::numeric / 100.0))::numeric, 2) AS lean_mass,
round((wl.weight::numeric * c2.body_fat_pct::numeric / 100.0)::numeric, 2) AS fat_mass
FROM caliper_log c2
CROSS JOIN LATERAL (
SELECT w.weight
FROM weight_log w
WHERE w.profile_id = c2.profile_id
ORDER BY abs(w.date - c2.date) ASC
LIMIT 1
) wl
WHERE c2.body_fat_pct IS NOT NULL
AND (c2.lean_mass IS NULL OR c2.fat_mass IS NULL)
) sub
WHERE c.id = sub.id;
@@ -0,0 +1,36 @@
-- Migration 036: Focus Area — erlaubte Nutzungstypen (Referenz + M:N)
-- Date: 2026-04-06
-- Purpose: System-seeded usage types; optional Zuordnung pro Focus Area (kein Auto-Backfill)
-- Referenztabelle: feste, systemdefinierte Nutzungstypen
CREATE TABLE IF NOT EXISTS focus_area_usage_types (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
key VARCHAR(64) UNIQUE NOT NULL,
label_de VARCHAR(160),
sort_order INT NOT NULL DEFAULT 0,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
COMMENT ON TABLE focus_area_usage_types IS
'Systemdefinierte Nutzungsarten für Focus Areas (kein Admin-CRUD in v1)';
-- M:N: welche Nutzungstypen für eine Focus Area erlaubt sind (leer = noch nicht klassifiziert)
CREATE TABLE IF NOT EXISTS focus_area_definition_usage_types (
focus_area_id UUID NOT NULL REFERENCES focus_area_definitions(id) ON DELETE CASCADE,
usage_type_id UUID NOT NULL REFERENCES focus_area_usage_types(id) ON DELETE CASCADE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
PRIMARY KEY (focus_area_id, usage_type_id)
);
CREATE INDEX IF NOT EXISTS idx_fadut_focus_area ON focus_area_definition_usage_types(focus_area_id);
CREATE INDEX IF NOT EXISTS idx_fadut_usage_type ON focus_area_definition_usage_types(usage_type_id);
COMMENT ON TABLE focus_area_definition_usage_types IS
'Zuordnung Focus Area → erlaubte Nutzungstypen (kein automatisches Befüllen bestehender Areas)';
-- Seed: nur die drei Typen — keine Zeilen in der Junction-Tabelle
INSERT INTO focus_area_usage_types (key, label_de, sort_order) VALUES
('goal_priority', 'Ziele / Prioritäten', 1),
('expected_training_effect', 'Erwartetes Trainingseffekt-Profil', 2),
('concrete_training_contribution', 'Konkrete Trainings-Beiträge / Belastungsausprägung', 3)
ON CONFLICT (key) DO NOTHING;
@@ -0,0 +1,99 @@
-- Migration 037: Persönliche Referenzwerte (Typkatalog + historische Werte pro Profil)
-- Date: 2026-04-06
-- Purpose: System-definierte Referenztyp-Schlüssel; Nutzer pflegt nur historische Einträge.
CREATE TABLE IF NOT EXISTS reference_value_types (
id SERIAL PRIMARY KEY,
key VARCHAR(64) NOT NULL UNIQUE,
label VARCHAR(200) NOT NULL,
description TEXT,
default_unit VARCHAR(32),
sort_order INT NOT NULL DEFAULT 0,
active BOOLEAN NOT NULL DEFAULT TRUE,
metadata JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
COMMENT ON TABLE reference_value_types IS
'Systemdefinierte Typen persönlicher Referenzwerte (kein Nutzer-CRUD auf Typen)';
CREATE TABLE IF NOT EXISTS profile_reference_values (
id BIGSERIAL PRIMARY KEY,
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
reference_value_type_id INT NOT NULL REFERENCES reference_value_types(id) ON DELETE RESTRICT,
effective_date DATE NOT NULL,
value_numeric NUMERIC(18, 6),
value_text TEXT,
unit VARCHAR(32) NOT NULL,
source TEXT,
confidence NUMERIC(5, 2),
method TEXT,
notes TEXT,
extra JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
CONSTRAINT profile_reference_values_value_ck CHECK (
value_numeric IS NOT NULL OR (value_text IS NOT NULL AND length(trim(value_text)) > 0)
)
);
COMMENT ON TABLE profile_reference_values IS
'Historische Referenzwerte pro Profil (kein Überschreiben eines Einzel-»aktuellen« Werts)';
CREATE INDEX IF NOT EXISTS idx_prv_profile_type_date
ON profile_reference_values (profile_id, reference_value_type_id, effective_date DESC);
CREATE INDEX IF NOT EXISTS idx_prv_profile
ON profile_reference_values (profile_id);
-- Seed: nur Typdefinitionen, keine Benutzerwerte
INSERT INTO reference_value_types (key, label, description, default_unit, sort_order, active) VALUES
(
'max_heart_rate',
'Maximale Herzfrequenz',
'Individuelle HRmax (z. B. aus Leistungstest oder geschätzt).',
'bpm',
10,
TRUE
),
(
'anaerobic_threshold_hr',
'Anaerober Schwellenwert (Herzfrequenz)',
'Laktatschwelle / anaerober Schwellenpuls.',
'bpm',
20,
TRUE
),
(
'aerobic_threshold_hr',
'Aerober Schwellenwert (Herzfrequenz)',
'Erster aerobet/schwellenanaloger Trainingsbereich (GA2).',
'bpm',
30,
TRUE
),
(
'training_frequency_weekly',
'Trainingshäufigkeit',
'Geplante oder beobachtete Einheiten pro Woche.',
'Sessions/Woche',
40,
TRUE
),
(
'fitness_level',
'Fitnesslevel',
'Subjektive oder normierte Einstufung (Zahl oder Kurzbeschreibung im Freitextfeld).',
'Stufe',
50,
TRUE
),
(
'resting_heart_rate',
'Ruhepuls (Referenz)',
'Ruheherzfrequenz als persönliche Referenz (z. B. morgens).',
'bpm',
15,
TRUE
)
ON CONFLICT (key) DO NOTHING;
@@ -0,0 +1,54 @@
-- Migration 038: Referenzwert-Typen — Kategorie, Datentyp, Plausibilisierung; confidence als Diskretwert
-- Date: 2026-04-06
ALTER TABLE reference_value_types ADD COLUMN IF NOT EXISTS category TEXT;
ALTER TABLE reference_value_types ADD COLUMN IF NOT EXISTS value_data_type VARCHAR(32) NOT NULL DEFAULT 'decimal';
ALTER TABLE reference_value_types ADD COLUMN IF NOT EXISTS validation_rules JSONB NOT NULL DEFAULT '{}';
ALTER TABLE reference_value_types DROP CONSTRAINT IF EXISTS rvt_value_data_type_chk;
ALTER TABLE reference_value_types ADD CONSTRAINT rvt_value_data_type_chk CHECK (
value_data_type IN ('integer', 'decimal', 'percentage', 'text', 'enum')
);
COMMENT ON COLUMN reference_value_types.category IS 'Freitext-Kategorie (UI/Admin)';
COMMENT ON COLUMN reference_value_types.value_data_type IS 'Logischer Wert-Typ für Erfassung & Validierung';
COMMENT ON COLUMN reference_value_types.validation_rules IS 'JSON: min, max, positive_only, max_length, not_empty, allowed_values[]';
-- Bestehende Seeds mit sinnvollen Defaults
UPDATE reference_value_types SET
value_data_type = 'integer',
validation_rules = '{"min": 40, "max": 240, "positive_only": true}'::jsonb
WHERE key IN ('max_heart_rate', 'resting_heart_rate');
UPDATE reference_value_types SET
value_data_type = 'integer',
validation_rules = '{"min": 80, "max": 210, "positive_only": true}'::jsonb
WHERE key IN ('anaerobic_threshold_hr', 'aerobic_threshold_hr');
UPDATE reference_value_types SET
value_data_type = 'integer',
validation_rules = '{"min": 0, "max": 21, "positive_only": false}'::jsonb
WHERE key = 'training_frequency_weekly';
UPDATE reference_value_types SET
value_data_type = 'text',
validation_rules = '{"max_length": 200, "not_empty": true}'::jsonb
WHERE key = 'fitness_level';
-- profile_reference_values.confidence: von NUMERIC auf diskrete Stufen
ALTER TABLE profile_reference_values ALTER COLUMN confidence DROP DEFAULT;
ALTER TABLE profile_reference_values
ALTER COLUMN confidence TYPE VARCHAR(32)
USING (NULL::varchar(32));
COMMENT ON COLUMN profile_reference_values.confidence IS 'high | medium | low | unknown';
-- Optionaler leerer Text (not_empty=false): leere Zeichenkette statt „kein Wert“
ALTER TABLE profile_reference_values DROP CONSTRAINT IF EXISTS profile_reference_values_value_ck;
ALTER TABLE profile_reference_values ADD CONSTRAINT profile_reference_values_value_ck CHECK (
value_numeric IS NOT NULL OR value_text IS NOT NULL
);
@@ -0,0 +1,5 @@
-- Nutzer-Dashboard: Layout (JSONB) für geschützten App-Lab-Bereich (Issue #65, Phase 1)
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS dashboard_layout JSONB DEFAULT NULL;
COMMENT ON COLUMN profiles.dashboard_layout IS
'Optional: konfigurierbare Dashboard-Widget-Reihenfolge/Sichtbarkeit (v1 JSON). NULL = Standard.';
+8
View File
@@ -0,0 +1,8 @@
-- Globale System-Konfiguration (Key/Value, JSONB)
CREATE TABLE IF NOT EXISTS system_config (
key VARCHAR(64) PRIMARY KEY,
value JSONB NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_system_config_updated_at ON system_config (updated_at);
+1
View File
@@ -28,6 +28,7 @@ class ProfileUpdate(BaseModel):
goal_weight: Optional[float] = None
goal_bf_pct: Optional[float] = None
quality_filter_level: Optional[str] = None # Issue #31: Global quality filter
email: Optional[str] = None # Self-service; leer = entfernen; Änderung setzt Verifikation zurück
# ── Tracking Models ───────────────────────────────────────────────────────────
+170
View File
@@ -0,0 +1,170 @@
"""
Validierung & Konstanten für persönliche Referenzwerte.
"""
from __future__ import annotations
from typing import Any, Optional
from fastapi import HTTPException
REF_VALUE_SOURCES = frozenset(
{
"manual_user",
"manual_admin",
"import_device",
"import_app",
"derived_system",
"estimated_system",
"test_entry",
}
)
REF_VALUE_METHODS = frozenset(
{
"direct_measurement",
"lab_test",
"field_test",
"questionnaire",
"formula_estimation",
"trend_analysis",
"device_algorithm",
"manual_assessment",
"imported_external",
"unknown",
}
)
REF_VALUE_CONFIDENCE = frozenset({"high", "medium", "low", "unknown"})
# Anzeigereihenfolge (nicht alphabetisch)
REF_VALUE_CONFIDENCE_ORDER = ("high", "medium", "low", "unknown")
VALUE_DATA_TYPES = frozenset({"integer", "decimal", "percentage", "text", "enum"})
def _rules_dict(raw: Any) -> dict:
if not raw:
return {}
if isinstance(raw, dict):
return raw
return {}
def validate_meta_source(source: Optional[str]) -> str:
if not source or not str(source).strip():
raise HTTPException(400, "Quelle (source) ist erforderlich.")
s = str(source).strip()
if s not in REF_VALUE_SOURCES:
raise HTTPException(400, f"Ungültige Quelle: {s}")
return s
def validate_meta_method(method: Optional[str]) -> str:
if not method or not str(method).strip():
raise HTTPException(400, "Methode (method) ist erforderlich.")
m = str(method).strip()
if m not in REF_VALUE_METHODS:
raise HTTPException(400, f"Ungültige Methode: {m}")
return m
def validate_meta_confidence(confidence: Optional[str]) -> str:
if not confidence or not str(confidence).strip():
raise HTTPException(400, "Vertrauensgrad (confidence) ist erforderlich.")
c = str(confidence).strip().lower()
if c not in REF_VALUE_CONFIDENCE:
raise HTTPException(400, f"Ungültiger Vertrauensgrad: {c}")
return c
def resolve_unit_from_type(default_unit: Optional[str]) -> str:
u = (default_unit or "").strip()
if not u:
raise HTTPException(
400,
"Für diesen Kennwert-Typ ist keine Einheit hinterlegt. Bitte im Admin einen Standard unter „Standard-Einheit“ setzen.",
)
return u
def validate_value_for_data_type(
value_data_type: str,
validation_rules_raw: Any,
value_numeric: Optional[float],
value_text: Optional[str],
) -> tuple[Optional[float], Optional[str]]:
"""
Je nach value_data_type den Wert prüfen und (value_numeric, value_text) für die DB liefern.
"""
vdt = (value_data_type or "decimal").strip().lower()
if vdt not in VALUE_DATA_TYPES:
raise HTTPException(400, f"Ungültiger interner Datentyp: {vdt}")
rules = _rules_dict(validation_rules_raw)
if vdt in ("integer", "decimal", "percentage"):
if value_numeric is None:
raise HTTPException(400, "Bitte einen numerischen Wert eingeben.")
v = float(value_numeric)
if vdt == "integer":
if abs(v - round(v)) > 1e-9:
raise HTTPException(400, "Der Wert muss eine ganze Zahl sein.")
v = float(int(round(v)))
pos = bool(rules.get("positive_only"))
mn = rules.get("min")
mx = rules.get("max")
if mn is not None:
mn = float(mn)
if mx is not None:
mx = float(mx)
if vdt == "percentage":
gmn = float(mn) if mn is not None else 0.0
gmx = float(mx) if mx is not None else 100.0
gmn = max(gmn, 0.0)
gmx = min(gmx, 100.0)
if gmn > gmx:
raise HTTPException(500, "Ungültige Plausibilisierung: min > max (Prozent).")
if v < gmn or v > gmx:
raise HTTPException(
400,
f"Prozentwert muss zwischen {gmn} und {gmx} liegen.",
)
if pos and v <= 0:
raise HTTPException(400, "Prozentwert muss positiv sein (laut Konfiguration).")
else:
if pos and v <= 0:
raise HTTPException(400, "Der Wert muss positiv sein (laut Konfiguration).")
if mn is not None and v < mn:
raise HTTPException(400, f"Der Wert muss mindestens {mn} sein.")
if mx is not None and v > mx:
raise HTTPException(400, f"Der Wert darf höchstens {mx} sein.")
return v, None
# text / enum
s = (value_text or "").strip() if value_text is not None else ""
if vdt == "text" and not s and not rules.get("not_empty"):
return None, ""
if rules.get("not_empty") and not s:
raise HTTPException(400, "Der Text darf nicht leer sein.")
ml = rules.get("max_length")
if ml is not None:
try:
ml_int = int(ml)
except (TypeError, ValueError):
ml_int = None
if ml_int is not None and len(s) > ml_int:
raise HTTPException(400, f"Text zu lang (max. {ml_int} Zeichen).")
if vdt == "enum":
allowed = rules.get("allowed_values") or []
if not isinstance(allowed, list):
allowed = []
allowed_str = [str(x).strip() for x in allowed if str(x).strip()]
if not allowed_str:
raise HTTPException(500, "ENUM-Typ ohne erlaubte Werte (Admin-Konfiguration).")
if s not in allowed_str:
raise HTTPException(
400,
f"Ungültiger Wert. Erlaubt: {', '.join(allowed_str)}",
)
return None, s
+32 -11
View File
@@ -9,7 +9,7 @@ import uuid
import logging
from typing import Optional
from fastapi import APIRouter, HTTPException, UploadFile, File, Header, Depends
from fastapi import APIRouter, HTTPException, UploadFile, File, Header, Depends, Query
from db import get_db, get_cursor, r2d
from auth import require_auth, check_feature_access, increment_feature_usage
@@ -32,24 +32,45 @@ logger = logging.getLogger(__name__)
@router.get("")
def list_activity(limit: int=200, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get activity entries for current profile."""
def list_activity(
limit: int = Query(200, ge=1, le=50_000),
days: Optional[int] = Query(None, ge=1, le=4000, description="Nur Einträge mit date >= HEUTE − days (Kalendertage)"),
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth),
):
"""Get activity entries for current profile. Optional *days* filter by calendar window (not the same as *limit*)."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
# Issue #31: Apply global quality filter
# Issue #31: Apply global quality filter (profile from DB = saved level)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
profile = r2d(cur.fetchone())
quality_filter = get_quality_filter_sql(profile)
cur.execute(f"""
SELECT * FROM activity_log
WHERE profile_id=%s
{quality_filter}
ORDER BY date DESC, start_time DESC
LIMIT %s
""", (pid, limit))
if days is not None:
cur.execute(
f"""
SELECT * FROM activity_log
WHERE profile_id=%s
{quality_filter}
AND date >= (CURRENT_DATE - %s::integer)
ORDER BY date DESC, start_time DESC
LIMIT %s
""",
(pid, days, limit),
)
else:
cur.execute(
f"""
SELECT * FROM activity_log
WHERE profile_id=%s
{quality_filter}
ORDER BY date DESC, start_time DESC
LIMIT %s
""",
(pid, limit),
)
return [r2d(r) for r in cur.fetchall()]
+58
View File
@@ -7,12 +7,21 @@ import os
import smtplib
from email.mime.text import MIMEText
from datetime import datetime
from typing import Any
from fastapi import APIRouter, HTTPException, Depends
from db import get_db, get_cursor, r2d
from auth import require_admin, hash_pin
from models import AdminProfileUpdate
from dashboard_layout_schema import DashboardLayoutPayload, product_default_layout_dict
from dashboard_widget_entitlements import widgets_catalog_admin_payload
from system_dashboard_product_default import (
delete_product_default_override,
get_product_default_base_dict,
get_stored_product_default_validated,
upsert_product_default_base,
)
router = APIRouter(prefix="/api/admin", tags=["admin"])
@@ -155,3 +164,52 @@ def admin_test_email(data: dict, session: dict=Depends(require_admin)):
return {"ok": True, "message": f"Test-E-Mail an {email} gesendet"}
except Exception as e:
raise HTTPException(500, f"Fehler beim Senden: {str(e)}")
@router.get("/widgets/catalog-full")
def admin_widgets_catalog_full(session: dict = Depends(require_admin)):
"""Dashboard-Widget-Katalog ohne Feature-Filter (Konfiguration des Produkt-Standards)."""
_ = session
return widgets_catalog_admin_payload()
@router.get("/dashboard-product-default")
def admin_get_dashboard_product_default(session: dict = Depends(require_admin)):
"""Aktueller Produkt-Dashboard-Standard (DB oder Code)."""
_ = session
with get_db() as conn:
layout = get_product_default_base_dict(conn)
from_database = get_stored_product_default_validated(conn) is not None
code_ref = product_default_layout_dict()
return {
"from_database": from_database,
"layout": layout,
"code_reference": code_ref,
}
@router.put("/dashboard-product-default")
def admin_put_dashboard_product_default(
body: dict[str, Any],
session: dict = Depends(require_admin),
):
"""System-Standard persistieren (JSON wie Nutzer-Layout v1)."""
_ = session
try:
payload = DashboardLayoutPayload.model_validate(body)
except Exception as e:
raise HTTPException(422, str(e)) from e
stored = payload.to_stored_dict()
with get_db() as conn:
upsert_product_default_base(conn, stored)
return {"ok": True, "layout": stored, "from_database": True}
@router.delete("/dashboard-product-default")
def admin_delete_dashboard_product_default(session: dict = Depends(require_admin)):
"""DB-Override entfernen; App fällt auf Code-Standard zurück."""
_ = session
with get_db() as conn:
delete_product_default_override(conn)
layout = get_product_default_base_dict(conn)
return {"ok": True, "layout": layout, "from_database": False}
@@ -0,0 +1,282 @@
"""
Admin: Referenzwert-Typen (Katalog für persönliche Referenzwerte).
Nur Admins; Nutzer sehen nur aktive Typen über /api/reference-value-types.
"""
import re
from typing import Any, Optional
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from psycopg2 import errors as pg_errors
from psycopg2.extras import Json
from auth import require_admin
from db import get_db, get_cursor, r2d
from reference_value_validation import VALUE_DATA_TYPES
router = APIRouter(prefix="/api/admin/reference-value-types", tags=["admin", "reference-value-types"])
KEY_PATTERN = re.compile(r"^[a-z][a-z0-9_]{0,62}$")
def _serialize_type(row: dict[str, Any]) -> dict[str, Any]:
if not row:
return row
out = dict(row)
ca = out.get("created_at")
if ca is not None and hasattr(ca, "isoformat"):
out["created_at"] = ca.isoformat()
return out
def _normalize_value_data_type(v: str) -> str:
s = (v or "decimal").strip().lower()
if s not in VALUE_DATA_TYPES:
raise HTTPException(
400,
f"Ungültiger Datentyp: {s}. Erlaubt: {', '.join(sorted(VALUE_DATA_TYPES))}",
)
return s
class ReferenceValueTypeAdminCreate(BaseModel):
key: str = Field(..., min_length=1, max_length=64)
label: str = Field(..., min_length=1, max_length=200)
description: Optional[str] = None
category: Optional[str] = None
default_unit: Optional[str] = Field(None, max_length=32)
value_data_type: str = "decimal"
validation_rules: Optional[dict] = None
active: bool = True
metadata: Optional[dict] = None
class ReferenceValueTypeAdminUpdate(BaseModel):
label: Optional[str] = Field(None, min_length=1, max_length=200)
description: Optional[str] = None
category: Optional[str] = None
default_unit: Optional[str] = Field(None, max_length=32)
value_data_type: Optional[str] = None
validation_rules: Optional[dict] = None
active: Optional[bool] = None
metadata: Optional[dict] = None
class ReferenceValueTypesReorderBody(BaseModel):
ordered_ids: list[int] = Field(..., min_length=1)
def _normalize_key(key: str) -> str:
k = key.strip().lower()
if not KEY_PATTERN.match(k):
raise HTTPException(
400,
"Ungültiger Schlüssel: nur Kleinbuchstaben, Ziffern, Unterstriche; muss mit Buchstabe beginnen.",
)
return k
def _unit_or_none(u: Optional[str]) -> Optional[str]:
if u is None:
return None
s = u.strip()
return s if s else None
def _cat_or_none(c: Optional[str]) -> Optional[str]:
if c is None:
return None
s = c.strip()
return s if s else None
@router.get("")
def admin_list_reference_value_types(session: dict = Depends(require_admin)):
"""Alle Typen inkl. inaktiver (Admin-Übersicht)."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT
id, key, label, description, category, default_unit, value_data_type,
validation_rules, sort_order, active, metadata, created_at
FROM reference_value_types
ORDER BY sort_order ASC, id ASC
"""
)
return [_serialize_type(r2d(r)) for r in cur.fetchall()]
@router.post("/reorder")
def admin_reorder_reference_value_types(
body: ReferenceValueTypesReorderBody,
session: dict = Depends(require_admin),
):
"""Globale Reihenfolge setzen (sort_order = 10, 20, …). Liste muss alle Typ-IDs genau einmal enthalten."""
ids = body.ordered_ids
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT id FROM reference_value_types")
all_ids = sorted([r["id"] for r in cur.fetchall()])
if len(ids) != len(all_ids):
raise HTTPException(
400,
f"Erwartet {len(all_ids)} Einträge, erhalten {len(ids)}.",
)
if sorted(ids) != all_ids:
raise HTTPException(400, "Die ID-Liste muss alle Kennwert-Typen exakt einmal enthalten (keine Duplikate).")
if len(set(ids)) != len(ids):
raise HTTPException(400, "Doppelte IDs sind nicht erlaubt.")
with get_db() as conn:
cur = get_cursor(conn)
for idx, tid in enumerate(ids):
cur.execute(
"UPDATE reference_value_types SET sort_order = %s WHERE id = %s",
((idx + 1) * 10, tid),
)
return {"ok": True}
@router.get("/{type_id}")
def admin_get_reference_value_type(type_id: int, session: dict = Depends(require_admin)):
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT
id, key, label, description, category, default_unit, value_data_type,
validation_rules, sort_order, active, metadata, created_at
FROM reference_value_types WHERE id = %s
""",
(type_id,),
)
row = cur.fetchone()
if not row:
raise HTTPException(404, "Typ nicht gefunden")
return _serialize_type(r2d(row))
@router.post("")
def admin_create_reference_value_type(
body: ReferenceValueTypeAdminCreate,
session: dict = Depends(require_admin),
):
key = _normalize_key(body.key)
vdt = _normalize_value_data_type(body.value_data_type)
if not _unit_or_none(body.default_unit):
raise HTTPException(400, "Standard-Einheit ist erforderlich (wird bei der Erfassung fix verwendet).")
meta = body.metadata if body.metadata is not None else {}
rules = body.validation_rules if body.validation_rules is not None else {}
if vdt == "enum":
av = rules.get("allowed_values") if isinstance(rules, dict) else []
if not isinstance(av, list) or not [x for x in av if str(x).strip()]:
raise HTTPException(
400,
"Datentyp ENUM erfordert unter Plausibilisierung eine nicht-leere Liste „Erlaubte Werte“.",
)
du = _unit_or_none(body.default_unit)
with get_db() as conn:
cur = get_cursor(conn)
try:
cur.execute("SELECT COALESCE(MAX(sort_order), 0) AS m FROM reference_value_types")
next_sort = int(cur.fetchone()["m"]) + 10
cur.execute(
"""
INSERT INTO reference_value_types
(key, label, description, category, default_unit, value_data_type,
validation_rules, sort_order, active, metadata)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING
id, key, label, description, category, default_unit, value_data_type,
validation_rules, sort_order, active, metadata, created_at
""",
(
key,
body.label.strip(),
body.description.strip() if body.description else None,
_cat_or_none(body.category),
du,
vdt,
Json(rules),
next_sort,
body.active,
Json(meta),
),
)
return _serialize_type(r2d(cur.fetchone()))
except pg_errors.UniqueViolation:
raise HTTPException(409, "Ein Typ mit diesem Schlüssel existiert bereits.")
@router.put("/{type_id}")
def admin_update_reference_value_type(
type_id: int,
body: ReferenceValueTypeAdminUpdate,
session: dict = Depends(require_admin),
):
patch = body.model_dump(exclude_unset=True)
if not patch:
raise HTTPException(400, "Keine Felder zum Aktualisieren")
if "value_data_type" in patch and patch["value_data_type"] is not None:
patch["value_data_type"] = _normalize_value_data_type(patch["value_data_type"])
if "default_unit" in patch:
patch["default_unit"] = _unit_or_none(patch.get("default_unit"))
if patch["default_unit"] is None:
raise HTTPException(400, "Standard-Einheit darf nicht leer werden.")
if "description" in patch and patch["description"] is not None:
patch["description"] = patch["description"].strip() or None
if "category" in patch:
patch["category"] = _cat_or_none(patch.get("category"))
if "metadata" in patch:
patch["metadata"] = Json(patch["metadata"] if patch["metadata"] is not None else {})
if "validation_rules" in patch:
patch["validation_rules"] = Json(patch["validation_rules"] if patch["validation_rules"] is not None else {})
cols = []
vals = []
for k, v in patch.items():
cols.append(f"{k} = %s")
vals.append(v)
vals.append(type_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
f"""
UPDATE reference_value_types SET {", ".join(cols)}
WHERE id = %s
RETURNING
id, key, label, description, category, default_unit, value_data_type,
validation_rules, sort_order, active, metadata, created_at
""",
tuple(vals),
)
row = cur.fetchone()
if not row:
raise HTTPException(404, "Typ nicht gefunden")
return _serialize_type(r2d(row))
@router.delete("/{type_id}")
def admin_delete_reference_value_type(type_id: int, session: dict = Depends(require_admin)):
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT COUNT(*) AS c FROM profile_reference_values WHERE reference_value_type_id = %s",
(type_id,),
)
n = cur.fetchone()["c"]
if n > 0:
raise HTTPException(
409,
f"Es gibt noch {n} gespeicherte Referenzwert(e) zu diesem Typ. "
"Bitte zuerst löschen oder den Typ deaktivieren (active = aus).",
)
cur.execute("DELETE FROM reference_value_types WHERE id = %s RETURNING id", (type_id,))
if not cur.fetchone():
raise HTTPException(404, "Typ nicht gefunden")
return {"ok": True}
+115
View File
@@ -0,0 +1,115 @@
"""
Geschützter App-Bereich: Dashboard-Lab Layout (kein Produktiv-Dashboard).
/api/app/dashboard-layout — nur mit Session + aktivem Profil (X-Profile-Id).
"""
from typing import Any, Optional
from fastapi import APIRouter, Depends, Header, HTTPException
from psycopg2.extras import Json
from auth import require_auth
from dashboard_layout_schema import (
DashboardLayoutPayload,
coalesce_effective_layout,
lab_default_layout_dict,
)
from dashboard_widget_entitlements import apply_entitlements_to_layout_dict, widgets_catalog_payload
from db import get_cursor, get_db
from routers.profiles import get_pid
from system_dashboard_product_default import get_product_default_base_dict
router = APIRouter(prefix="/api/app", tags=["app-dashboard-lab"])
@router.get("/widgets/catalog")
def get_widgets_catalog(
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth),
) -> dict[str, Any]:
"""Katalog inkl. allowed pro Widget (Feature / Subscription, effektiver Tier)."""
_ = session
pid = get_pid(x_profile_id)
with get_db() as conn:
return widgets_catalog_payload(pid, conn)
@router.get("/dashboard-layout")
def get_dashboard_layout(
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth),
) -> dict[str, Any]:
_ = session
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT dashboard_layout FROM profiles WHERE id = %s",
(pid,),
)
row = cur.fetchone()
raw = row["dashboard_layout"] if row else None
custom, effective = coalesce_effective_layout(raw)
with get_db() as conn:
base_product = get_product_default_base_dict(conn)
if not custom:
effective = base_product
effective = apply_entitlements_to_layout_dict(effective, pid, conn)
product_adj = apply_entitlements_to_layout_dict(base_product, pid, conn)
lab_adj = apply_entitlements_to_layout_dict(lab_default_layout_dict(), pid, conn)
return {
"custom": custom,
"layout": effective,
"product_default_layout": product_adj,
"lab_default_layout": lab_adj,
}
@router.put("/dashboard-layout")
def put_dashboard_layout(
body: dict[str, Any],
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth),
) -> dict[str, Any]:
_ = session
pid = get_pid(x_profile_id)
try:
payload = DashboardLayoutPayload.model_validate(body)
except Exception as e:
raise HTTPException(422, str(e)) from e
with get_db() as conn:
adjusted = apply_entitlements_to_layout_dict(payload.to_stored_dict(), pid, conn)
try:
payload = DashboardLayoutPayload.model_validate(adjusted)
except Exception as e:
raise HTTPException(422, str(e)) from e
stored = payload.to_stored_dict()
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"UPDATE profiles SET dashboard_layout = %s WHERE id = %s",
(Json(stored), pid),
)
if cur.rowcount == 0:
raise HTTPException(404, "Profil nicht gefunden")
return {"ok": True, "layout": stored}
@router.post("/dashboard-layout/reset")
def reset_dashboard_layout(
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth),
) -> dict[str, Any]:
_ = session
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"UPDATE profiles SET dashboard_layout = NULL WHERE id = %s",
(pid,),
)
if cur.rowcount == 0:
raise HTTPException(404, "Profil nicht gefunden")
base = get_product_default_base_dict(conn)
cleared = apply_entitlements_to_layout_dict(base, pid, conn)
return {"ok": True, "layout": cleared}
+8 -1
View File
@@ -14,6 +14,7 @@ from auth import require_auth, check_feature_access, increment_feature_usage
from models import CaliperEntry
from routers.profiles import get_pid
from feature_logger import log_feature_usage
from caliper_composition import enrich_caliper_row_for_response, fill_caliper_body_comp, load_weight_rows
router = APIRouter(prefix="/api/caliper", tags=["caliper"])
logger = logging.getLogger(__name__)
@@ -27,7 +28,11 @@ def list_caliper(limit: int=100, x_profile_id: Optional[str]=Header(default=None
cur = get_cursor(conn)
cur.execute(
"SELECT * FROM caliper_log WHERE profile_id=%s ORDER BY date DESC LIMIT %s", (pid,limit))
return [r2d(r) for r in cur.fetchall()]
rows = [r2d(r) for r in cur.fetchall()]
weight_rows = load_weight_rows(conn, pid)
for row in rows:
enrich_caliper_row_for_response(row, weight_rows)
return rows
@router.post("")
@@ -55,6 +60,7 @@ def upsert_caliper(e: CaliperEntry, x_profile_id: Optional[str]=Header(default=N
cur.execute("SELECT id FROM caliper_log WHERE profile_id=%s AND date=%s", (pid,e.date))
ex = cur.fetchone()
d = e.model_dump()
fill_caliper_body_comp(d, conn, pid)
is_new_entry = not ex
if ex:
@@ -86,6 +92,7 @@ def update_caliper(eid: str, e: CaliperEntry, x_profile_id: Optional[str]=Header
pid = get_pid(x_profile_id)
with get_db() as conn:
d = e.model_dump()
fill_caliper_body_comp(d, conn, pid)
cur = get_cursor(conn)
cur.execute(f"UPDATE caliper_log SET {', '.join(f'{k}=%s' for k in d)} WHERE id=%s AND profile_id=%s",
list(d.values())+[eid,pid])
+20 -4
View File
@@ -21,6 +21,7 @@ from db import get_db, get_cursor, r2d
from auth import require_auth, check_feature_access, increment_feature_usage
from routers.profiles import get_pid
from feature_logger import log_feature_usage
from caliper_composition import enrich_caliper_row_for_response, load_weight_rows
router = APIRouter(prefix="/api/export", tags=["export"])
logger = logging.getLogger(__name__)
@@ -68,10 +69,21 @@ def export_csv(x_profile_id: Optional[str]=Header(default=None), session: dict=D
details = f"Taille:{float(r['c_waist'])}cm Bauch:{float(r['c_belly'])}cm Hüfte:{float(r['c_hip'])}cm"
writer.writerow(["Umfänge", r['date'], "", details])
# Caliper
cur.execute("SELECT date, body_fat_pct, lean_mass FROM caliper_log WHERE profile_id=%s ORDER BY date", (pid,))
for r in cur.fetchall():
writer.writerow(["Caliper", r['date'], f"{float(r['body_fat_pct'])}%", f"Magermasse:{float(r['lean_mass'])}kg"])
# Caliper (Magermasse aus Gewicht + KF% nachziehen wenn in DB leer)
cur.execute(
"SELECT date, body_fat_pct, lean_mass, fat_mass FROM caliper_log WHERE profile_id=%s ORDER BY date",
(pid,),
)
cal_rows = [r2d(r) for r in cur.fetchall()]
weight_rows = load_weight_rows(conn, pid)
for r in cal_rows:
enrich_caliper_row_for_response(r, weight_rows)
if r.get("body_fat_pct") is None:
continue
bf = float(r["body_fat_pct"])
lm = r.get("lean_mass")
details = f"Magermasse:{float(lm)}kg" if lm is not None else ""
writer.writerow(["Caliper", r["date"], f"{bf}%", details])
# Nutrition
cur.execute("SELECT date, kcal, protein_g FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,))
@@ -141,6 +153,10 @@ def export_json(x_profile_id: Optional[str]=Header(default=None), session: dict=
cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,))
data['insights'] = [r2d(r) for r in cur.fetchall()]
w_rows = [{'date': x['date'], 'weight': x['weight']} for x in data.get('weight', [])]
for row in data.get('caliper', []):
enrich_caliper_row_for_response(row, w_rows)
def decimal_handler(obj):
if isinstance(obj, Decimal):
return float(obj)
+112 -3
View File
@@ -3,10 +3,11 @@ Focus Areas Router
Manages dynamic focus area definitions and user preferences
"""
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
from pydantic import BaseModel, Field
from typing import Optional, List
from db import get_db, get_cursor, r2d
from auth import require_auth
from focus_area_usage_helpers import coerce_usage_type_keys
router = APIRouter(prefix="/api/focus-areas", tags=["focus-areas"])
@@ -36,6 +37,11 @@ class UserFocusPreferences(BaseModel):
"""User's focus area weightings (dynamic)"""
preferences: dict # {focus_area_id: weight_pct}
class FocusAreaUsageTypesUpdate(BaseModel):
"""Replace all usage-type assignments for one focus area (admin)."""
usage_type_keys: List[str] = Field(default_factory=list)
# ============================================================================
# Focus Area Definitions (Admin)
# ============================================================================
@@ -58,14 +64,27 @@ def list_focus_area_definitions(
query = """
SELECT id, key, name_de, name_en, icon, description, category, is_active,
created_at, updated_at
created_at, updated_at,
COALESCE(
(
SELECT json_agg(faut.key ORDER BY faut.sort_order, faut.key)
FROM focus_area_definition_usage_types fadut
JOIN focus_area_usage_types faut ON faut.id = fadut.usage_type_id
WHERE fadut.focus_area_id = focus_area_definitions.id
),
'[]'::json
) AS allowed_usage_type_keys
FROM focus_area_definitions
WHERE is_active = true OR %s
ORDER BY category, name_de
"""
cur.execute(query, (include_inactive,))
areas = [r2d(row) for row in cur.fetchall()]
areas = []
for row in cur.fetchall():
d = r2d(row)
d['allowed_usage_type_keys'] = coerce_usage_type_keys(d.get('allowed_usage_type_keys'))
areas.append(d)
# Group by category
grouped = {}
@@ -75,6 +94,10 @@ def list_focus_area_definitions(
grouped[cat] = []
grouped[cat].append(area)
if session.get('role') != 'admin':
for area in areas:
area.pop('allowed_usage_type_keys', None)
return {
"areas": areas,
"grouped": grouped,
@@ -226,6 +249,92 @@ def delete_focus_area_definition(
return {"message": "Focus Area gelöscht"}
@router.get("/usage-types")
def list_focus_area_usage_types(session: dict = Depends(require_auth)):
"""
Liste aller systemdefinierten Nutzungstypen (Admin, Konfigurations-UI).
Keine freie Anlage neuer Typen über die API.
"""
if session.get('role') != 'admin':
raise HTTPException(status_code=403, detail="Admin-Rechte erforderlich")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT id, key, label_de, sort_order
FROM focus_area_usage_types
ORDER BY sort_order, key
""")
rows = [r2d(r) for r in cur.fetchall()]
return {"usage_types": rows, "total": len(rows)}
@router.put("/definitions/{area_id}/usage-types")
def replace_focus_area_usage_types(
area_id: str,
data: FocusAreaUsageTypesUpdate,
session: dict = Depends(require_auth),
):
"""
Ersetzt die Nutzungstyp-Zuweisungen einer Focus Area (Admin).
Leere Liste entfernt alle Zuordnungen. Unbekannte Keys → 400.
"""
if session.get('role') != 'admin':
raise HTTPException(status_code=403, detail="Admin-Rechte erforderlich")
keys = list(dict.fromkeys(data.usage_type_keys)) # dedupe, preserve order
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT id FROM focus_area_definitions WHERE id = %s",
(area_id,),
)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Focus Area nicht gefunden")
if not keys:
cur.execute(
"DELETE FROM focus_area_definition_usage_types WHERE focus_area_id = %s",
(area_id,),
)
return {"message": "Nutzungstyp-Zuweisungen entfernt", "usage_type_keys": []}
placeholders = ','.join(['%s'] * len(keys))
cur.execute(
f"""
SELECT id, key FROM focus_area_usage_types
WHERE key IN ({placeholders})
""",
keys,
)
found = {row['key']: row['id'] for row in cur.fetchall()}
missing = [k for k in keys if k not in found]
if missing:
raise HTTPException(
status_code=400,
detail=f"Unbekannte Nutzungstyp-Keys: {', '.join(missing)}",
)
cur.execute(
"DELETE FROM focus_area_definition_usage_types WHERE focus_area_id = %s",
(area_id,),
)
for k in keys:
ut_id = found[k]
cur.execute(
"""
INSERT INTO focus_area_definition_usage_types (focus_area_id, usage_type_id)
VALUES (%s, %s)
ON CONFLICT (focus_area_id, usage_type_id) DO NOTHING
""",
(area_id, ut_id),
)
return {"message": "Nutzungstyp-Zuweisungen aktualisiert", "usage_type_keys": keys}
# ============================================================================
# User Focus Preferences
# ============================================================================
+7 -2
View File
@@ -16,6 +16,7 @@ from db import get_db, get_cursor, r2d
from auth import require_auth, check_feature_access, increment_feature_usage
from routers.profiles import get_pid
from feature_logger import log_feature_usage
from caliper_composition import compute_lean_fat_kg, nearest_weight_kg_from_map
router = APIRouter(prefix="/api/nutrition", tags=["nutrition"])
logger = logging.getLogger(__name__)
@@ -202,8 +203,12 @@ def nutrition_correlations(x_profile_id: Optional[str]=Header(default=None), ses
if d in cal_by_date:
lm = cal_by_date[d].get('lean_mass')
bf = cal_by_date[d].get('body_fat_pct')
row['lean_mass']=float(lm) if lm is not None else None
row['body_fat_pct']=float(bf) if bf is not None else None
if bf is not None and lm is None:
wkg = nearest_weight_kg_from_map(wlog, d)
if wkg is not None:
lm, _fat = compute_lean_fat_kg(wkg, float(bf))
row['lean_mass'] = float(lm) if lm is not None else None
row['body_fat_pct'] = float(bf) if bf is not None else None
result.append(row)
return result
+54 -5
View File
@@ -68,13 +68,62 @@ def get_profile(pid: str, session=Depends(require_auth)):
@router.put("/profiles/{pid}")
def update_profile(pid: str, p: ProfileUpdate, session=Depends(require_auth)):
"""Update profile by ID (admin)."""
"""Update profile by ID."""
with get_db() as conn:
data = {k:v for k,v in p.model_dump().items() if v is not None}
data['updated'] = datetime.now().isoformat()
cur = get_cursor(conn)
cur.execute(f"UPDATE profiles SET {', '.join(f'{k}=%s' for k in data)} WHERE id=%s",
list(data.values())+[pid])
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
row = cur.fetchone()
if not row:
raise HTTPException(404, "Profil nicht gefunden")
rowd = r2d(row)
cur_email_norm = (rowd.get("email") or "").strip().lower()
patch = p.model_dump(exclude_unset=True)
data = {}
if "email" in patch:
ev = patch["email"]
if ev is None or (isinstance(ev, str) and ev.strip() == ""):
if rowd.get("email") is not None:
data["email"] = None
data["email_verified"] = False
data["verification_token"] = None
data["verification_expires"] = None
else:
email_norm = ev.strip().lower()
if "@" not in email_norm or len(email_norm) < 5:
raise HTTPException(400, "Ungültige E-Mail-Adresse")
cur.execute(
"""
SELECT id FROM profiles
WHERE email IS NOT NULL AND lower(trim(email)) = %s AND id <> %s
""",
(email_norm, pid),
)
if cur.fetchone():
raise HTTPException(409, "E-Mail wird bereits verwendet")
data["email"] = email_norm
if email_norm != cur_email_norm:
data["email_verified"] = False
data["verification_token"] = None
data["verification_expires"] = None
nullable_keys = {"goal_weight", "goal_bf_pct", "dob"}
for k, v in patch.items():
if k == "email":
continue
if v is None and k in nullable_keys:
data[k] = None
elif v is not None:
data[k] = v
if not data:
return get_profile(pid, session)
data["updated"] = datetime.now().isoformat()
cols = ", ".join(f"{k}=%s" for k in data)
vals = list(data.values()) + [pid]
cur.execute(f"UPDATE profiles SET {cols} WHERE id=%s", vals)
return get_profile(pid, session)
+320
View File
@@ -0,0 +1,320 @@
"""
Persönliche Referenzwerte (profilorientiert)
Typkatalog system-seeded; Nutzer pflegt historische Einträge pro aktivem Profil.
Einheit immer aus dem Typ; Wert je value_data_type validiert.
Reads (Liste, Summary, Katalog) → data_layer.reference_values (Layer 1).
"""
from __future__ import annotations
from datetime import datetime
from decimal import Decimal
from typing import Any, Optional
from fastapi import APIRouter, Depends, Header, HTTPException, Query
from pydantic import BaseModel, Field
from psycopg2.extras import Json
from auth import require_auth
from data_layer.reference_values import (
fetch_reference_type_by_key,
get_profile_reference_values_summary,
list_active_reference_value_types_data,
list_profile_reference_values_for_type,
normalize_reference_row,
)
from db import get_db, get_cursor, r2d
from reference_value_validation import (
REF_VALUE_CONFIDENCE,
REF_VALUE_CONFIDENCE_ORDER,
REF_VALUE_METHODS,
REF_VALUE_SOURCES,
validate_meta_confidence,
validate_meta_method,
validate_meta_source,
validate_value_for_data_type,
resolve_unit_from_type,
)
from routers.profiles import get_pid
router = APIRouter(prefix="/api", tags=["reference-values"])
class ProfileReferenceValueCreate(BaseModel):
reference_value_type_key: str = Field(..., min_length=1, max_length=64)
effective_date: str
value_numeric: Optional[float] = None
value_text: Optional[str] = None
source: str = Field(..., min_length=1)
method: str = Field(..., min_length=1)
confidence: str = Field(..., min_length=1)
notes: Optional[str] = None
extra: Optional[dict] = None
class ProfileReferenceValueUpdate(BaseModel):
effective_date: Optional[str] = None
value_numeric: Optional[float] = None
value_text: Optional[str] = None
source: Optional[str] = None
method: Optional[str] = None
confidence: Optional[str] = None
notes: Optional[str] = None
extra: Optional[dict] = None
@router.get("/reference-value-types")
def list_reference_value_types(session: dict = Depends(require_auth)):
"""Alle aktiven Referenztyp-Definitionen (dynamische UI inkl. Validierungsmetadaten)."""
return list_active_reference_value_types_data()
@router.get("/reference-value-meta/enums")
def list_reference_value_meta_enums(session: dict = Depends(require_auth)):
"""Erlaubte Werte für Quelle, Methode, Vertrauensgrad (Erfassungsdialog)."""
return {
"sources": sorted(REF_VALUE_SOURCES),
"methods": sorted(REF_VALUE_METHODS),
"confidence_levels": [x for x in REF_VALUE_CONFIDENCE_ORDER if x in REF_VALUE_CONFIDENCE],
}
@router.get("/profile-reference-values/summary")
def profile_reference_values_summary(
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth),
):
"""
Für das aktive Profil: je Referenztyp mit mindestens einem Eintrag der jüngste Wert
plus der unmittelbar vorherige (gleiche Sortierung wie Liste), für Tendenz-Anzeigen.
"""
pid = get_pid(x_profile_id)
return get_profile_reference_values_summary(pid)
@router.get("/profile-reference-values")
def list_profile_reference_values(
type_key: str = Query(..., description="Schlüssel aus reference_value_types.key"),
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth),
):
"""Historische Einträge eines Typs für das aktive Profil (neueste zuerst)."""
pid = get_pid(x_profile_id)
rows = list_profile_reference_values_for_type(pid, type_key)
if rows is None:
raise HTTPException(404, "Referenztyp nicht gefunden")
return rows
@router.post("/profile-reference-values")
def create_profile_reference_value(
body: ProfileReferenceValueCreate,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth),
):
pid = get_pid(x_profile_id)
try:
datetime.strptime(body.effective_date, "%Y-%m-%d")
except ValueError:
raise HTTPException(400, "Ungültiges Datum. Format: YYYY-MM-DD")
src = validate_meta_source(body.source)
meth = validate_meta_method(body.method)
conf = validate_meta_confidence(body.confidence)
with get_db() as conn:
cur = get_cursor(conn)
t = fetch_reference_type_by_key(cur, body.reference_value_type_key.strip(), require_active=True)
if not t:
raise HTTPException(404, "Referenztyp nicht gefunden")
vdt = (t.get("value_data_type") or "decimal").strip().lower()
rules = t.get("validation_rules") or {}
vnum, vtxt = validate_value_for_data_type(vdt, rules, body.value_numeric, body.value_text)
unit = resolve_unit_from_type(t.get("default_unit"))
extra = body.extra if body.extra is not None else {}
cur.execute(
"""
INSERT INTO profile_reference_values (
profile_id, reference_value_type_id, effective_date,
value_numeric, value_text, unit, source, confidence, method, notes, extra
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""",
(
pid,
t["id"],
body.effective_date,
vnum,
vtxt,
unit,
src,
conf,
meth,
body.notes,
Json(extra),
),
)
new_id = cur.fetchone()["id"]
cur.execute(
"""
SELECT
v.id,
v.profile_id,
v.reference_value_type_id,
v.effective_date,
v.value_numeric,
v.value_text,
v.unit,
v.source,
v.confidence,
v.method,
v.notes,
v.extra,
v.created_at,
v.updated_at,
rt.key AS type_key,
rt.label AS type_label
FROM profile_reference_values v
JOIN reference_value_types rt ON rt.id = v.reference_value_type_id
WHERE v.id = %s AND v.profile_id = %s
""",
(new_id, pid),
)
return normalize_reference_row(r2d(cur.fetchone()))
@router.put("/profile-reference-values/{entry_id}")
def update_profile_reference_value(
entry_id: int,
body: ProfileReferenceValueUpdate,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth),
):
pid = get_pid(x_profile_id)
patch = body.model_dump(exclude_unset=True)
if not patch:
raise HTTPException(400, "Keine Felder zum Aktualisieren")
if patch.get("effective_date"):
try:
datetime.strptime(patch["effective_date"], "%Y-%m-%d")
except ValueError:
raise HTTPException(400, "Ungültiges Datum. Format: YYYY-MM-DD")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT v.*, rt.default_unit, rt.value_data_type, rt.validation_rules
FROM profile_reference_values v
JOIN reference_value_types rt ON rt.id = v.reference_value_type_id
WHERE v.id = %s AND v.profile_id = %s
""",
(entry_id, pid),
)
row = cur.fetchone()
if not row:
raise HTTPException(404, "Eintrag nicht gefunden")
cur_row = r2d(row)
vdt = (cur_row.get("value_data_type") or "decimal").strip().lower()
rules = cur_row.get("validation_rules") or {}
new_ed = patch.get("effective_date", cur_row["effective_date"])
if hasattr(new_ed, "isoformat"):
new_ed = new_ed.isoformat()
vn = patch["value_numeric"] if "value_numeric" in patch else cur_row.get("value_numeric")
vt_raw = patch["value_text"] if "value_text" in patch else cur_row.get("value_text")
if vn is not None and isinstance(vn, Decimal):
vn = float(vn)
vnum, vtxt = validate_value_for_data_type(vdt, rules, vn, vt_raw)
unit = resolve_unit_from_type(cur_row.get("default_unit"))
if "source" in patch:
src = validate_meta_source(patch["source"])
else:
src = validate_meta_source(cur_row.get("source"))
if "method" in patch:
meth = validate_meta_method(patch["method"])
else:
meth = validate_meta_method(cur_row.get("method"))
if "confidence" in patch:
conf = validate_meta_confidence(patch["confidence"])
else:
conf = validate_meta_confidence(cur_row.get("confidence"))
updates: dict[str, Any] = {
"effective_date": new_ed,
"value_numeric": vnum,
"value_text": vtxt,
"unit": unit,
"source": src,
"method": meth,
"confidence": conf,
}
if "notes" in patch:
updates["notes"] = patch["notes"]
if "extra" in patch:
updates["extra"] = Json(patch["extra"] if patch["extra"] is not None else {})
set_parts = [f"{k} = %s" for k in updates]
vals = list(updates.values()) + [entry_id, pid]
cur.execute(
f"""
UPDATE profile_reference_values SET {", ".join(set_parts)}, updated_at = NOW()
WHERE id = %s AND profile_id = %s
""",
tuple(vals),
)
cur.execute(
"""
SELECT
v.id,
v.profile_id,
v.reference_value_type_id,
v.effective_date,
v.value_numeric,
v.value_text,
v.unit,
v.source,
v.confidence,
v.method,
v.notes,
v.extra,
v.created_at,
v.updated_at,
rt.key AS type_key,
rt.label AS type_label
FROM profile_reference_values v
JOIN reference_value_types rt ON rt.id = v.reference_value_type_id
WHERE v.id = %s AND v.profile_id = %s
""",
(entry_id, pid),
)
return normalize_reference_row(r2d(cur.fetchone()))
@router.delete("/profile-reference-values/{entry_id}")
def delete_profile_reference_value(
entry_id: int,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth),
):
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"DELETE FROM profile_reference_values WHERE id = %s AND profile_id = %s RETURNING id",
(entry_id, pid),
)
if not cur.fetchone():
raise HTTPException(404, "Eintrag nicht gefunden")
return {"ok": True}
+199 -80
View File
@@ -9,7 +9,8 @@ Endpoints:
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
from pydantic import BaseModel
from typing import Literal
from datetime import datetime, timedelta
from datetime import datetime, timedelta, date
from decimal import Decimal, InvalidOperation
import csv
import io
import json
@@ -19,6 +20,174 @@ from db import get_db, get_cursor
router = APIRouter(prefix="/api/sleep", tags=["sleep"])
def _strip_row_keys(row: dict) -> dict:
return {(k or "").strip(): (v.strip() if isinstance(v, str) else v) for k, v in row.items()}
def _safe_float(value) -> float | None:
if value is None or value == "":
return None
if isinstance(value, (int, float)):
return float(value)
if isinstance(value, Decimal):
return float(value)
try:
s = str(value).strip().replace(",", ".")
return float(s)
except (ValueError, InvalidOperation):
return None
def _parse_apple_sleep_datetime(value: str) -> datetime:
raw = (value or "").strip()
if not raw:
raise ValueError("empty datetime")
fmts = (
"%Y-%m-%d %H:%M:%S %z",
"%d.%m.%y %H:%M:%S",
"%d.%m.%Y %H:%M:%S",
"%Y-%m-%d %H:%M:%S",
)
last_err = None
for fmt in fmts:
try:
return datetime.strptime(raw, fmt)
except ValueError as e:
last_err = e
raise ValueError(f"Unbekanntes Datumsformat: {raw!r}") from last_err
def _hr_to_minutes(hours: float | None) -> int:
if hours is None:
return 0
return int(round(float(hours) * 60))
def _detect_apple_sleep_csv_format(fieldnames: list[str] | None) -> Literal["segments", "summary"]:
if not fieldnames:
raise HTTPException(
status_code=400,
detail="CSV enthält keine Spaltenüberschriften.",
)
fn = {(f or "").strip() for f in fieldnames}
if {"Start", "End", "Duration (hr)", "Value"}.issubset(fn):
return "segments"
if "Start" in fn and "End" in fn and "Total Sleep (hr)" in fn:
return "summary"
raise HTTPException(
status_code=400,
detail=(
"Unbekanntes Apple-Health-Schlaf-CSV. "
"Erwartet wird entweder der Segment-Export (Spalten Start, End, Duration (hr), Value) "
"oder die Schlafanalyse mit Nacht-Zusammenfassung (u. a. Total Sleep (hr), Core/Light, Deep, REM)."
),
)
def _build_nights_from_apple_summary(reader: csv.DictReader) -> dict[date, dict]:
nights_dict: dict[date, dict] = {}
for raw in reader:
row = _strip_row_keys(raw)
start_s = row.get("Start") or ""
end_s = row.get("End") or ""
if not start_s or not end_s:
continue
try:
start_dt = _parse_apple_sleep_datetime(start_s)
end_dt = _parse_apple_sleep_datetime(end_s)
except ValueError:
continue
dt_key = (row.get("Date/Time") or row.get("Datum/Uhrzeit") or "").strip()
if dt_key:
try:
wake_d = datetime.strptime(dt_key[:10], "%Y-%m-%d").date()
except ValueError:
wake_d = end_dt.date()
else:
wake_d = end_dt.date()
core_hr = _safe_float(row.get("Core (hr)"))
if core_hr is None:
core_hr = _safe_float(row.get("Light (hr)")) or 0.0
deep_min = _hr_to_minutes(_safe_float(row.get("Deep (hr)")))
rem_min = _hr_to_minutes(_safe_float(row.get("REM (hr)")))
light_min = _hr_to_minutes(core_hr)
awake_min = _hr_to_minutes(_safe_float(row.get("Awake (hr)")))
nights_dict[wake_d] = {
"bedtime": start_dt,
"wake_time": end_dt,
"segments": [],
"deep_minutes": deep_min,
"rem_minutes": rem_min,
"light_minutes": light_min,
"awake_minutes": awake_min,
}
return nights_dict
def _build_nights_from_apple_segments(reader: csv.DictReader, phase_map: dict) -> dict[date, dict]:
segments = []
for raw in reader:
row = _strip_row_keys(raw)
phase_key = (row.get("Value") or "").strip()
phase_en = phase_map.get(phase_key)
if phase_en is None:
continue
try:
start_dt = _parse_apple_sleep_datetime(row.get("Start") or "")
end_dt = _parse_apple_sleep_datetime(row.get("End") or "")
duration_hr = _safe_float(row.get("Duration (hr)"))
if duration_hr is None:
continue
except (ValueError, TypeError):
continue
duration_min = int(duration_hr * 60)
segments.append({
"start": start_dt,
"end": end_dt,
"duration_min": duration_min,
"phase": phase_en,
})
segments.sort(key=lambda s: s["start"])
nights = []
current_night = None
for seg in segments:
if current_night is None or (seg["start"] - current_night["wake_time"]).total_seconds() > 7200:
current_night = {
"bedtime": seg["start"],
"wake_time": seg["end"],
"segments": [],
"deep_minutes": 0,
"rem_minutes": 0,
"light_minutes": 0,
"awake_minutes": 0,
}
nights.append(current_night)
current_night["segments"].append(seg)
current_night["wake_time"] = max(current_night["wake_time"], seg["end"])
current_night["bedtime"] = min(current_night["bedtime"], seg["start"])
if seg["phase"] == "deep":
current_night["deep_minutes"] += seg["duration_min"]
elif seg["phase"] == "rem":
current_night["rem_minutes"] += seg["duration_min"]
elif seg["phase"] == "light":
current_night["light_minutes"] += seg["duration_min"]
elif seg["phase"] == "awake":
current_night["awake_minutes"] += seg["duration_min"]
nights_dict: dict[date, dict] = {}
for night in nights:
wake_date = night["wake_time"].date()
nights_dict[wake_date] = night
return nights_dict
# ── Models ────────────────────────────────────────────────────────────────────
class SleepCreate(BaseModel):
@@ -460,96 +629,46 @@ async def import_apple_health_sleep(
"""
Import sleep data from Apple Health CSV export.
Expected CSV format:
Start,End,Duration (hr),Value,Source
2026-03-14 22:44:23,2026-03-14 23:00:19,0.266,Kern,Apple Watch
Supports:
- Segment-Export: Start, End, Duration (hr), Value (Kern/Tief/REM/Wach oder Core/Deep/…)
- Schlafanalyse (Nacht-Zusammenfassung): Date/Time, Start, End, Total Sleep (hr),
Core/Light (hr), Deep (hr), REM (hr), Awake (hr), …
- Aggregates segments by night (wake date)
- Maps German phase names: Kern→light, REM→rem, Tief→deep, Wach→awake
- Stores raw segments in JSONB
- Does NOT overwrite manual entries (source='manual')
- Aggregates segments by night (wake date) where applicable
- Stores Roh-Segmente in JSONB (bei Zusammenfassung oft leer)
- Überschreibt keine manuellen Einträge (source='manual')
"""
pid = session['profile_id']
# Read CSV
content = await file.read()
csv_text = content.decode('utf-8-sig') # Handle BOM
csv_text = content.decode('utf-8-sig')
reader = csv.DictReader(io.StringIO(csv_text))
fmt = _detect_apple_sleep_csv_format(reader.fieldnames)
# Phase mapping (German → English)
phase_map = {
'Kern': 'light',
'REM': 'rem',
'Tief': 'deep',
'Wach': 'awake',
'Schlafend': None # Ignore initial sleep entry
"Kern": "light",
"Core": "light",
"Light": "light",
"REM": "rem",
"Tief": "deep",
"Deep": "deep",
"Wach": "awake",
"Awake": "awake",
"Schlafend": None,
"Asleep": None,
"In Bed": None,
}
# Parse segments
segments = []
for row in reader:
phase_de = row['Value'].strip()
phase_en = phase_map.get(phase_de)
if fmt == "summary":
nights_dict = _build_nights_from_apple_summary(reader)
else:
nights_dict = _build_nights_from_apple_segments(reader, phase_map)
if phase_en is None: # Skip "Schlafend"
continue
start_dt = datetime.strptime(row['Start'], '%Y-%m-%d %H:%M:%S')
end_dt = datetime.strptime(row['End'], '%Y-%m-%d %H:%M:%S')
duration_hr = float(row['Duration (hr)'])
duration_min = int(duration_hr * 60)
segments.append({
'start': start_dt,
'end': end_dt,
'duration_min': duration_min,
'phase': phase_en
})
# Sort segments chronologically
segments.sort(key=lambda s: s['start'])
# Group segments into nights (gap-based)
# If gap between segments > 2 hours → new night
nights = []
current_night = None
for seg in segments:
# Start new night if:
# 1. First segment
# 2. Gap > 2 hours since last segment
if current_night is None or (seg['start'] - current_night['wake_time']).total_seconds() > 7200:
current_night = {
'bedtime': seg['start'],
'wake_time': seg['end'],
'segments': [],
'deep_minutes': 0,
'rem_minutes': 0,
'light_minutes': 0,
'awake_minutes': 0
}
nights.append(current_night)
# Add segment to current night
current_night['segments'].append(seg)
current_night['wake_time'] = max(current_night['wake_time'], seg['end'])
current_night['bedtime'] = min(current_night['bedtime'], seg['start'])
# Sum phases
if seg['phase'] == 'deep':
current_night['deep_minutes'] += seg['duration_min']
elif seg['phase'] == 'rem':
current_night['rem_minutes'] += seg['duration_min']
elif seg['phase'] == 'light':
current_night['light_minutes'] += seg['duration_min']
elif seg['phase'] == 'awake':
current_night['awake_minutes'] += seg['duration_min']
# Convert nights list to dict with wake_date as key
nights_dict = {}
for night in nights:
wake_date = night['wake_time'].date() # Date when you woke up
nights_dict[wake_date] = night
if not nights_dict:
raise HTTPException(
status_code=400,
detail="Keine importierbaren Schlafzeilen gefunden (prüfe Start/Ende und Format).",
)
# Insert nights
imported = 0
@@ -0,0 +1,77 @@
"""
Persistenter System-Standard für die Produkt-Übersicht (Dashboard).
Key in system_config: dashboard_product_default — gültiges DashboardLayoutPayload (JSON).
"""
from __future__ import annotations
from typing import Any
from psycopg2.extras import Json
from dashboard_layout_schema import DashboardLayoutPayload, product_default_layout_dict
from db import get_cursor
SYSTEM_CONFIG_KEY_DASHBOARD_PRODUCT_DEFAULT = "dashboard_product_default"
def get_stored_product_default_validated(conn) -> dict[str, Any] | None:
"""Gültiges Layout aus DB oder None (fehlt/ungültig)."""
cur = get_cursor(conn)
cur.execute(
"SELECT value FROM system_config WHERE key = %s",
(SYSTEM_CONFIG_KEY_DASHBOARD_PRODUCT_DEFAULT,),
)
row = cur.fetchone()
if not row or row.get("value") is None:
return None
raw = row["value"]
if isinstance(raw, str):
import json
try:
raw = json.loads(raw)
except json.JSONDecodeError:
return None
if not isinstance(raw, dict):
return None
try:
payload = DashboardLayoutPayload.model_validate(
{"version": raw.get("version", 1), "widgets": raw.get("widgets", [])}
)
return payload.to_stored_dict()
except Exception:
return None
def get_product_default_base_dict(conn) -> dict[str, Any]:
"""Basis-Layout (ohne Entitlements): DB-Override oder Code-Standard."""
stored = get_stored_product_default_validated(conn)
if stored is not None:
return stored
return product_default_layout_dict()
def upsert_product_default_base(conn, layout: dict[str, Any]) -> dict[str, Any]:
payload = DashboardLayoutPayload.model_validate(layout)
stored = payload.to_stored_dict()
cur = get_cursor(conn)
cur.execute(
"""
INSERT INTO system_config (key, value, updated_at)
VALUES (%s, %s, CURRENT_TIMESTAMP)
ON CONFLICT (key) DO UPDATE SET
value = EXCLUDED.value,
updated_at = CURRENT_TIMESTAMP
""",
(SYSTEM_CONFIG_KEY_DASHBOARD_PRODUCT_DEFAULT, Json(stored)),
)
return stored
def delete_product_default_override(conn) -> None:
cur = get_cursor(conn)
cur.execute(
"DELETE FROM system_config WHERE key = %s",
(SYSTEM_CONFIG_KEY_DASHBOARD_PRODUCT_DEFAULT,),
)
@@ -0,0 +1,58 @@
import pytest
from dashboard_layout_schema import (
ALLOWED_WIDGET_IDS,
DashboardLayoutPayload,
coalesce_effective_layout,
default_layout_dict,
)
from widget_catalog import DEFAULT_PRODUCT_DASHBOARD_WIDGET_IDS
def test_default_has_all_allowed_ids():
d = default_layout_dict()
got = {w["id"] for w in d["widgets"]}
assert got == ALLOWED_WIDGET_IDS
assert {w["id"] for w in d["widgets"] if w["enabled"]} == DEFAULT_PRODUCT_DASHBOARD_WIDGET_IDS
def test_payload_rejects_duplicate_ids():
with pytest.raises(Exception):
DashboardLayoutPayload.model_validate(
{
"version": 1,
"widgets": [
{"id": "welcome", "enabled": True},
{"id": "welcome", "enabled": False},
],
}
)
def test_payload_requires_one_enabled():
with pytest.raises(Exception):
DashboardLayoutPayload.model_validate(
{
"version": 1,
"widgets": [{"id": "dashboard_greeting", "enabled": False}],
}
)
def test_coalesce_none():
custom, eff = coalesce_effective_layout(None)
assert custom is False
assert eff == default_layout_dict()
def test_coalesce_valid_raw():
raw = {
"version": 1,
"widgets": [
{"id": "welcome", "enabled": True},
{"id": "kpi_board", "enabled": True},
],
}
custom, eff = coalesce_effective_layout(raw)
assert custom is True
assert eff == raw
@@ -0,0 +1,133 @@
import pytest
from dashboard_layout_schema import DashboardLayoutPayload, coalesce_effective_layout, default_layout_dict
from dashboard_widget_config import validate_widget_entry_config
def test_body_chart_days_bounds():
assert validate_widget_entry_config("body_overview", {"chart_days": 7}) == {"chart_days": 7}
assert validate_widget_entry_config("body_overview", {"chart_days": 90}) == {"chart_days": 90}
assert validate_widget_entry_config("body_overview", {"chart_days": 42.0}) == {"chart_days": 42}
with pytest.raises(ValueError):
validate_widget_entry_config("body_overview", {"chart_days": 6})
with pytest.raises(ValueError):
validate_widget_entry_config("body_overview", {"chart_days": 91})
def test_welcome_config_rejected_unknown_key():
with pytest.raises(ValueError):
validate_widget_entry_config("welcome", {"x": 1})
def test_body_unknown_key():
with pytest.raises(ValueError):
validate_widget_entry_config("body_overview", {"chart_days": 30, "extra": 1})
def test_activity_chart_days():
assert validate_widget_entry_config("activity_overview", {"chart_days": 14}) == {"chart_days": 14}
with pytest.raises(ValueError):
validate_widget_entry_config("activity_overview", {"chart_days": 5})
def test_kpi_board_tiles():
assert validate_widget_entry_config("kpi_board", {}) == {}
assert validate_widget_entry_config("kpi_board", {"tiles": []}) == {"tiles": []}
assert validate_widget_entry_config(
"kpi_board",
{"tiles": [{"id": "body_fat"}, {"id": "avg_kcal"}, {"id": "ref:hr_max"}]},
) == {"tiles": [{"id": "body_fat"}, {"id": "avg_kcal"}, {"id": "ref:hr_max"}]}
with pytest.raises(ValueError):
validate_widget_entry_config("kpi_board", {"tiles": [{"id": "unknown"}]})
with pytest.raises(ValueError):
validate_widget_entry_config("kpi_board", {"tiles": [{"id": "body_fat"}, {"id": "body_fat"}]})
with pytest.raises(ValueError):
validate_widget_entry_config("kpi_board", {"extra": 1})
def test_quick_capture_visibility():
assert validate_widget_entry_config("quick_capture", {}) == {}
assert validate_widget_entry_config("quick_capture", {"show_weight": False}) == {"show_weight": False}
full = {
"show_weight": True,
"show_resting_hr": False,
"show_hrv": True,
"show_vo2_max": False,
}
assert validate_widget_entry_config("quick_capture", full) == full
with pytest.raises(ValueError):
validate_widget_entry_config("quick_capture", {"show_weight": "yes"})
with pytest.raises(ValueError):
validate_widget_entry_config(
"quick_capture",
{
"show_weight": False,
"show_resting_hr": False,
"show_hrv": False,
"show_vo2_max": False,
},
)
with pytest.raises(ValueError):
validate_widget_entry_config("quick_capture", {"extra": 1})
def test_nutrition_detail_charts_days():
assert validate_widget_entry_config("nutrition_detail_charts", {}) == {}
assert validate_widget_entry_config("nutrition_detail_charts", {"chart_days": 60}) == {"chart_days": 60}
with pytest.raises(ValueError):
validate_widget_entry_config("nutrition_detail_charts", {"chart_days": 3})
def test_recovery_charts_panel_days():
assert validate_widget_entry_config("recovery_charts_panel", {}) == {}
assert validate_widget_entry_config("recovery_charts_panel", {"chart_days": 28}) == {"chart_days": 28}
with pytest.raises(ValueError):
validate_widget_entry_config("recovery_charts_panel", {"chart_days": 99})
def test_trend_kcal_weight_chart_days():
assert validate_widget_entry_config("trend_kcal_weight", {}) == {}
assert validate_widget_entry_config("trend_kcal_weight", {"chart_days": 30}) == {"chart_days": 30}
with pytest.raises(ValueError):
validate_widget_entry_config("trend_kcal_weight", {"chart_days": 6})
def test_kpi_board_legacy_chart_days_dropped():
"""Nur chart_days (Alt-Layouts) → automatische Kachelwahl, kein Ø-Kal-Fenster mehr."""
assert validate_widget_entry_config("kpi_board", {"chart_days": 14}) == {}
assert validate_widget_entry_config("kpi_board", {"chart_days": 5}) == {}
def test_welcome_still_rejects_config():
with pytest.raises(ValueError):
validate_widget_entry_config("welcome", {"chart_days": 30})
def test_layout_payload_with_chart_days_roundtrip():
p = DashboardLayoutPayload.model_validate(
{
"version": 1,
"widgets": [
{"id": "welcome", "enabled": True},
{
"id": "body_overview",
"enabled": True,
"config": {"chart_days": 42},
},
],
}
)
d = p.to_stored_dict()
assert d["widgets"][1]["config"]["chart_days"] == 42
def test_coalesce_rejects_invalid_widget_config():
raw = {
"version": 1,
"widgets": [
{"id": "welcome", "enabled": True, "config": {"evil": True}},
],
}
custom, eff = coalesce_effective_layout(raw)
assert custom is False
assert eff == default_layout_dict()
@@ -0,0 +1,57 @@
from dashboard_layout_schema import DashboardLayoutPayload
from dashboard_widget_entitlements import apply_entitlements_to_layout_dict, widget_id_allowed
def test_apply_entitlements_disables_widget_without_access(monkeypatch):
monkeypatch.setattr(
"dashboard_widget_entitlements.widget_id_allowed",
lambda wid, pid, conn: wid != "nutrition_detail_charts",
)
raw = {
"version": 1,
"widgets": [
{"id": "welcome", "enabled": True},
{"id": "nutrition_detail_charts", "enabled": True},
],
}
out = apply_entitlements_to_layout_dict(raw, "p", None)
assert {w["id"]: w["enabled"] for w in out["widgets"]} == {
"welcome": True,
"nutrition_detail_charts": False,
}
def test_apply_entitlements_leaves_welcome_on_when_all_blocked(monkeypatch):
monkeypatch.setattr(
"dashboard_widget_entitlements.widget_id_allowed",
lambda wid, pid, conn: False,
)
raw = {
"version": 1,
"widgets": [
{"id": "welcome", "enabled": False},
{"id": "nutrition_detail_charts", "enabled": False},
],
}
out = apply_entitlements_to_layout_dict(raw, "p", None)
assert any(w["id"] == "welcome" and w["enabled"] for w in out["widgets"])
def test_widget_id_allowed_false_for_unknown_id():
assert widget_id_allowed("not-a-widget", "p", None) is False
def test_full_default_layout_still_validates_after_entitlements(monkeypatch):
monkeypatch.setattr(
"dashboard_widget_entitlements.widget_id_allowed",
lambda wid, pid, conn: wid != "ai_pipeline_insight",
)
from dashboard_layout_schema import default_layout_dict
d = default_layout_dict()
d["widgets"] = [{**x, "enabled": x["id"] == "ai_pipeline_insight"} for x in d["widgets"]]
adj = apply_entitlements_to_layout_dict(d, "p", None)
p2 = DashboardLayoutPayload.model_validate(adj)
ai = next(w for w in p2.widgets if w.id == "ai_pipeline_insight")
assert ai.enabled is False
assert any(w.enabled for w in p2.widgets)
@@ -0,0 +1,127 @@
"""
Tests: Focus Area Nutzungstypen (Migration 036, Router-Helfer).
Ohne MITAI_INTEGRATION_DB=1 werden nur SQL-Datei und reine Python-Helfer geprüft.
Mit gesetztem Flag optional Verifikation gegen eine PostgreSQL-Instanz (Migration 036 angewendet).
"""
from __future__ import annotations
import os
import sys
import uuid
from pathlib import Path
import pytest
BACKEND_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(BACKEND_ROOT))
def test_migration_036_defines_schema_and_seeds_keys():
p = BACKEND_ROOT / "migrations" / "036_focus_area_usage_types.sql"
assert p.is_file(), f"expected {p}"
text = p.read_text(encoding="utf-8")
assert "CREATE TABLE IF NOT EXISTS focus_area_usage_types" in text
assert "CREATE TABLE IF NOT EXISTS focus_area_definition_usage_types" in text
for key in (
"goal_priority",
"expected_training_effect",
"concrete_training_contribution",
):
assert key in text
assert "ON CONFLICT (key) DO NOTHING" in text
# Explizit: kein automatisches Befüllen der M:N-Tabelle
assert "INSERT INTO focus_area_definition_usage_types" not in text
def test_coerce_usage_type_keys_normalizes_values():
from focus_area_usage_helpers import coerce_usage_type_keys
assert coerce_usage_type_keys(None) == []
assert coerce_usage_type_keys([]) == []
assert coerce_usage_type_keys(["goal_priority", "expected_training_effect"]) == [
"goal_priority",
"expected_training_effect",
]
assert coerce_usage_type_keys('["concrete_training_contribution"]') == [
"concrete_training_contribution"
]
@pytest.mark.skipif(
os.getenv("MITAI_INTEGRATION_DB") != "1",
reason="Set MITAI_INTEGRATION_DB=1 plus DB_* env to run DB checks (nur Dev/CI!)",
)
def test_integration_focus_area_usage_types_seeded_and_junction_writable():
"""Nur gegen Dev-DB ausführen. Nutzt temporäre focus_area_definitions-Zeile, keine bestehenden Daten."""
from db import get_db, get_cursor
from focus_area_usage_helpers import coerce_usage_type_keys
tmp_id = str(uuid.uuid4())
tmp_key = f"tmp_usage_{tmp_id[:8]}"
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT key FROM focus_area_usage_types
ORDER BY sort_order, key
"""
)
keys = [row["key"] for row in cur.fetchall()]
assert keys == [
"goal_priority",
"expected_training_effect",
"concrete_training_contribution",
]
cur.execute(
"""
INSERT INTO focus_area_definitions
(id, key, name_de, category, is_active)
VALUES (%s, %s, 'tmp_test_usage', 'custom', false)
""",
(tmp_id, tmp_key),
)
cur.execute(
"""
SELECT COALESCE(
(
SELECT json_agg(faut.key ORDER BY faut.sort_order, faut.key)
FROM focus_area_definition_usage_types fadut
JOIN focus_area_usage_types faut ON faut.id = fadut.usage_type_id
WHERE fadut.focus_area_id = %s
),
'[]'::json
) AS allowed_usage_type_keys
""",
(tmp_id,),
)
assert coerce_usage_type_keys(cur.fetchone()["allowed_usage_type_keys"]) == []
cur.execute(
"""
INSERT INTO focus_area_definition_usage_types (focus_area_id, usage_type_id)
SELECT %s, u.id FROM focus_area_usage_types u WHERE u.key = %s
""",
(tmp_id, "goal_priority"),
)
cur.execute(
"""
INSERT INTO focus_area_definition_usage_types (focus_area_id, usage_type_id)
SELECT %s, u.id FROM focus_area_usage_types u WHERE u.key = %s
""",
(tmp_id, "expected_training_effect"),
)
cur.execute(
"""
SELECT COUNT(*) AS n
FROM focus_area_definition_usage_types
WHERE focus_area_id = %s
""",
(tmp_id,),
)
assert cur.fetchone()["n"] == 2
cur.execute("DELETE FROM focus_area_definitions WHERE id = %s", (tmp_id,))
@@ -0,0 +1,48 @@
"""Unit tests for data_layer.reference_values (summary assembly, no DB)."""
from data_layer.reference_values import build_summary_tiles_from_ranked_rows
def test_build_summary_tiles_single_type_two_rows():
raw = [
{
"type_key": "hr_max",
"type_label": "HF max",
"type_sort_order": 1,
"value_data_type": "decimal",
"rn": 1,
"id": 2,
"effective_date": "2026-04-01",
"value_numeric": 180.0,
"value_text": None,
"unit": "bpm",
},
{
"type_key": "hr_max",
"type_label": "HF max",
"type_sort_order": 1,
"value_data_type": "decimal",
"rn": 2,
"id": 1,
"effective_date": "2026-03-01",
"value_numeric": 175.0,
"value_text": None,
"unit": "bpm",
},
]
tiles = build_summary_tiles_from_ranked_rows(raw)
assert len(tiles) == 1
t = tiles[0]
assert t["type_key"] == "hr_max"
assert t["latest"]["value_numeric"] == 180.0
assert t["previous"]["value_numeric"] == 175.0
assert "sort_key" not in t
def test_build_summary_tiles_multi_type_order():
raw = [
{"type_key": "b", "type_label": "B", "type_sort_order": 2, "value_data_type": "decimal", "rn": 1, "id": 1},
{"type_key": "a", "type_label": "A", "type_sort_order": 1, "value_data_type": "decimal", "rn": 1, "id": 2},
]
tiles = build_summary_tiles_from_ranked_rows(raw)
assert [x["type_key"] for x in tiles] == ["a", "b"]
@@ -0,0 +1,45 @@
from dashboard_layout_schema import DashboardLayoutPayload, product_default_layout_dict
from dashboard_widget_entitlements import widgets_catalog_admin_payload
def test_widgets_catalog_admin_all_allowed():
p = widgets_catalog_admin_payload()
assert p["catalog_version"] == 1
assert len(p["widgets"]) >= 1
assert all(w["allowed"] is True for w in p["widgets"])
def test_get_product_default_base_uses_code_when_no_row(monkeypatch):
from system_dashboard_product_default import get_product_default_base_dict
class _Cur:
def execute(self, *a, **k):
pass
def fetchone(self):
return None
monkeypatch.setattr("system_dashboard_product_default.get_cursor", lambda _c: _Cur())
assert get_product_default_base_dict(object()) == product_default_layout_dict()
def test_get_product_default_base_uses_db_when_valid(monkeypatch):
from system_dashboard_product_default import get_product_default_base_dict
from widget_catalog import ALLOWED_WIDGET_IDS
small = {
"version": 1,
"widgets": [{"id": wid, "enabled": wid == "welcome"} for wid in sorted(ALLOWED_WIDGET_IDS)],
}
DashboardLayoutPayload.model_validate(small)
class _Cur:
def execute(self, *a, **k):
pass
def fetchone(self):
return {"value": small}
monkeypatch.setattr("system_dashboard_product_default.get_cursor", lambda _c: _Cur())
assert get_product_default_base_dict(object()) == small
@@ -0,0 +1,138 @@
"""
Unit tests: Layer 1 training profile resolver scaffold.
No database; pure template + algorithm + resolver behavior.
"""
import pytest
from data_layer.training_profile import (
CalculationTemplate,
DimensionSpec,
FocusAreaMapping,
TrainingEvaluationResult,
resolve_for_base_profile,
resolve_training_evaluation,
)
from data_layer.training_profile.algorithms.registry import (
get_algorithm,
list_algorithm_ids,
register_algorithm,
)
from data_layer.training_profile.models import AlgorithmRunResult
from data_layer.training_profile.profiles.registry import get_training_base_profile
from data_layer.training_profile.templates.registry import get_calculation_template
class TestAlgorithmRegistry:
def test_builtin_algorithms_registered(self):
ids = list_algorithm_ids()
assert "threshold_band" in ids
assert "linear_range" in ids
def test_get_algorithm_runs_threshold(self):
fn = get_algorithm("threshold_band")
r = fn(
inputs={"avg_hr": 130.0},
params={
"value_key": "avg_hr",
"bands": [
{"max": 120, "score": 0.2},
{"max": 150, "score": 0.8},
{"max": None, "score": 1.0},
],
},
)
assert r.normalized_score == 0.8
def test_duplicate_register_raises(self):
def dummy(*, inputs, params):
return AlgorithmRunResult(0.0, 0.0, [])
with pytest.raises(ValueError, match="already registered"):
register_algorithm("threshold_band", dummy)
class TestResolver:
def test_example_template_resolves(self):
tpl = get_calculation_template("scaffold_example_aerobic_v1")
result = resolve_training_evaluation(
activity_inputs={
"avg_hr": 135.0,
"duration_min": 45.0,
"distance_km": 10.0,
},
template=tpl,
)
assert isinstance(result, TrainingEvaluationResult)
assert result.template_id == "scaffold_example_aerobic_v1"
assert result.confidence == "high"
assert "aerobic_endurance" in result.focus_area_contributions
assert len(result.dimension_results) == 2
for dr in result.dimension_results:
assert dr.missing_inputs == []
def test_missing_required_input_skips_dimension(self):
tpl = get_calculation_template("scaffold_example_aerobic_v1")
result = resolve_training_evaluation(
activity_inputs={"avg_hr": 135.0},
template=tpl,
)
assert result.confidence in ("medium", "low", "insufficient")
skipped = [d for d in result.dimension_results if d.evidence.get("skipped")]
assert len(skipped) >= 1
def test_base_profile_filters_dimensions(self):
profile = get_training_base_profile("scaffold_strength_base")
tpl = get_calculation_template(profile.default_template_id)
result = resolve_training_evaluation(
activity_inputs={"duration_min": 50.0},
template=tpl,
base_profile=profile,
)
assert len(result.dimension_results) == 1
assert result.dimension_results[0].dimension_key == "effort"
def test_resolve_for_base_profile_convenience(self):
result = resolve_for_base_profile(
activity_inputs={"duration_min": 40.0},
base_profile_key="scaffold_strength_base",
include_trace=True,
)
assert result.base_profile_key == "scaffold_strength_base"
assert result.trace is not None
assert "effort" in result.trace
def test_to_serializable(self):
tpl = get_calculation_template("scaffold_example_strength_v1")
r = resolve_training_evaluation(
activity_inputs={"duration_min": 45.0},
template=tpl,
)
d = r.to_serializable()
assert d["template_id"] == tpl.id
assert "focus_area_contributions" in d
assert isinstance(d["dimension_results"], list)
class TestCustomTemplate:
def test_unknown_algorithm_raises(self):
bad = CalculationTemplate(
id="bad",
version="1",
label="bad",
dimensions=(
DimensionSpec(
key="x",
algorithm_id="does_not_exist",
inputs=("a",),
params={},
maps_to=(FocusAreaMapping("strength", 1.0),),
),
),
)
with pytest.raises(KeyError):
resolve_training_evaluation(
activity_inputs={"a": 1.0},
template=bad,
)
+59
View File
@@ -0,0 +1,59 @@
"""Widget-Katalog: Konsistenz (IDs, Default-Layout, Katalog-Response)."""
from dashboard_layout_schema import default_layout_dict
from dashboard_widget_entitlements import widgets_catalog_payload
from widget_catalog import (
ALLOWED_WIDGET_IDS,
DEFAULT_LAB_WIDGET_IDS,
DEFAULT_PRODUCT_DASHBOARD_WIDGET_IDS,
WIDGET_CATALOG,
)
def test_catalog_ids_unique_and_match_allowed():
ids = [e["id"] for e in WIDGET_CATALOG]
assert len(ids) == len(set(ids))
assert frozenset(ids) == ALLOWED_WIDGET_IDS
def test_default_layout_follows_catalog_order():
d = default_layout_dict()
assert d["version"] == 1
got = [w["id"] for w in d["widgets"]]
assert got == [e["id"] for e in WIDGET_CATALOG]
enabled_ids = {w["id"] for w in d["widgets"] if w["enabled"]}
assert enabled_ids == DEFAULT_PRODUCT_DASHBOARD_WIDGET_IDS
assert any(w["enabled"] for w in d["widgets"])
def test_lab_default_matches_lab_widget_ids():
from dashboard_layout_schema import lab_default_layout_dict
d = lab_default_layout_dict()
assert {w["id"] for w in d["widgets"] if w["enabled"]} == DEFAULT_LAB_WIDGET_IDS
def test_catalog_payload_shape(monkeypatch):
monkeypatch.setattr(
"dashboard_widget_entitlements._check_feature_access",
lambda *args, **kwargs: {"allowed": True},
)
r = widgets_catalog_payload("test-profile", None)
assert r["catalog_version"] == 1
assert len(r["widgets"]) == len(WIDGET_CATALOG)
assert {w["id"] for w in r["widgets"]} == ALLOWED_WIDGET_IDS
for w in r["widgets"]:
assert set(w.keys()) == {"id", "title", "description", "allowed"}
assert w["allowed"] is True
def test_catalog_marks_disallowed_when_feature_blocks(monkeypatch):
def _check(_pid, feature_id, conn=None):
return {"allowed": feature_id != "nutrition_entries"}
monkeypatch.setattr("dashboard_widget_entitlements._check_feature_access", _check)
r = widgets_catalog_payload("p", None)
by_id = {w["id"]: w for w in r["widgets"]}
assert by_id["welcome"]["allowed"] is True
assert by_id["nutrition_detail_charts"]["allowed"] is False
assert by_id["body_overview"]["allowed"] is True
+8 -4
View File
@@ -9,32 +9,36 @@ Semantic Versioning: MAJOR.MINOR.PATCH
APP_VERSION = "0.9n"
BUILD_DATE = "2026-04-05"
DB_SCHEMA_VERSION = "20260403" # Migration 034
DB_SCHEMA_VERSION = "20260406d" # Migration 040
MODULE_VERSIONS = {
"auth": "1.2.0",
"profiles": "1.1.0",
"reference_values": "1.3.0",
"admin_reference_value_types": "1.0.0",
"weight": "1.0.3",
"circumference": "1.0.1",
"caliper": "1.0.1",
"activity": "1.1.0",
"activity": "1.2.0", # GET /activity: optional days= window + limit
"nutrition": "1.0.2",
"photos": "1.0.0",
"insights": "1.3.0",
"prompts": "1.1.0",
"admin": "1.2.0",
"admin": "1.3.0", # Dashboard Produkt-Standard (system_config) + catalog-full
"stats": "1.0.1",
"exportdata": "1.1.0",
"importdata": "1.0.0",
"membership": "2.1.0",
"workflow": "0.6.0", # Phase 4: End Node Template Engine
"app_dashboard": "1.10.0", # Produkt-Standard aus system_config; Response-Form unverändert
}
CHANGELOG = [
{
"version": "0.9n",
"date": "2026-04-05",
"date": "2026-04-06",
"changes": [
"Admin: Produkt-Dashboard-Systemstandard (Migration 040 system_config, API, UI)",
"Phase 4: End Node Template Engine",
"workflow_models.py: EndNodeOutputMode enum (AUTO, TEMPLATE)",
"workflow_executor.py: execute_end_node() with Jinja2 template rendering",
+153
View File
@@ -0,0 +1,153 @@
"""
Öffentlicher Widget-Katalog (Dashboard-Lab / später Produkt-Dashboard).
Single Source für: erlaubte IDs, Standard-Reihenfolge, Anzeige-Metadaten für API/GUI.
Frontend-Komponenten registrieren dieselben IDs lokal (siehe widgetSystem/registerPilotLabWidgets).
"""
from __future__ import annotations
from typing import Any, NotRequired, TypedDict
class WidgetCatalogEntry(TypedDict):
"""requires_feature: optional features.id; fehlt oder leer → Widget immer sichtbar (nur Auth)."""
id: str
title: str
description: str
requires_feature: NotRequired[str]
# Reihenfolge = Default-Layout-Reihenfolge. Aktiv-Flags: DEFAULT_LAB_WIDGET_IDS (Rest zunächst aus).
WIDGET_CATALOG: list[WidgetCatalogEntry] = [
{
"id": "welcome",
"title": "Willkommen",
"description": "Begrüßung und Kurzkontext",
},
{
"id": "quick_capture",
"title": "Schnelleingabe",
"description": "Gewicht + Baseline-Vitals; optional show_weight / show_resting_hr / show_hrv / show_vo2_max (false = aus); Feature weight_entries",
"requires_feature": "weight_entries",
},
{
"id": "kpi_board",
"title": "KPI-Kacheln",
"description": "Referenzwerte, KF%, Ø-Kalorien — optional Kacheln & Reihenfolge (config.tiles, max. 9)",
},
{
"id": "body_overview",
"title": "Körper (Chart)",
"description": "Gewicht & Kennzahlen (optional: config chart_days 7–90); Feature weight_entries",
"requires_feature": "weight_entries",
},
{
"id": "activity_overview",
"title": "Aktivität",
"description": "Trainingstyp-Verteilung (Kuchen) + Konsistenz — Zeitraum über config chart_days 7–90; Feature activity_entries",
"requires_feature": "activity_entries",
},
{
"id": "dashboard_greeting",
"title": "Begrüßung (Produkt)",
"description": "Hallo, Datum & letztes Gewicht-Update",
},
{
"id": "quick_weight_today",
"title": "Gewicht heute",
"description": "Tagesgewicht erfassen (wie Produkt-Dashboard); Feature weight_entries",
"requires_feature": "weight_entries",
},
{
"id": "body_stat_strip",
"title": "Kennzahlen-Kacheln",
"description": "Gewicht, KF, Magermasse, Ø-kcal — Oberreihe; u. a. nutrition_entries (Ø-kcal)",
"requires_feature": "nutrition_entries",
},
{
"id": "status_pills",
"title": "Indikatoren (Pills)",
"description": "WHR, WHtR, Protein, KF; Feature nutrition_entries",
"requires_feature": "nutrition_entries",
},
{
"id": "profile_goals_progress",
"title": "Profil-Ziele",
"description": "Fortschritt Gewicht/Körperfett aus Profilfeldern",
},
{
"id": "trend_kcal_weight",
"title": "Trend Kalorien + Gewicht",
"description": "Linienchart (optional config chart_days 7–90, Default 30); Feature nutrition_entries",
"requires_feature": "nutrition_entries",
},
{
"id": "nutrition_activity_summary",
"title": "Ernährung & Aktivität Kurz",
"description": "Ø 7T Kacheln; Feature nutrition_entries",
"requires_feature": "nutrition_entries",
},
{
"id": "nutrition_detail_charts",
"title": "Ernährung — Detaillierte Charts",
"description": "Phase-0c NutritionCharts (optional chart_days 7–90, Default 30); Feature nutrition_entries",
"requires_feature": "nutrition_entries",
},
{
"id": "recovery_charts_panel",
"title": "Erholung — Charts R1–R5",
"description": "RecoveryCharts wie Verlauf (optional chart_days 7–90, Default 28)",
},
{
"id": "progress_photos",
"title": "Fortschrittsfotos",
"description": "Galerie der hochgeladenen Fotos; Feature photos",
"requires_feature": "photos",
},
{
"id": "recovery_sleep_rest",
"title": "Erholung",
"description": "Schlaf-Widget & Ruhetage",
},
{
"id": "goals_focus_teaser",
"title": "Ziele Teaser",
"description": "Kurzlink zur Ziele-Seite",
},
{
"id": "ai_pipeline_insight",
"title": "KI Pipeline & letzte Analyse",
"description": "Pipeline starten + Gesamt-Insight; Feature ai_pipeline",
"requires_feature": "ai_pipeline",
},
]
DEFAULT_LAB_WIDGET_IDS: frozenset[str] = frozenset(
{
"welcome",
"quick_capture",
"kpi_board",
"body_overview",
"activity_overview",
}
)
# Produkt-Übersicht (/): Default wenn Nutzer kein dashboard_layout in der DB hat (Physisch: nur Profil-JSON).
DEFAULT_PRODUCT_DASHBOARD_WIDGET_IDS: frozenset[str] = frozenset(
{
"dashboard_greeting",
"quick_weight_today",
"body_stat_strip",
"status_pills",
"trend_kcal_weight",
"nutrition_activity_summary",
"activity_overview",
"recovery_sleep_rest",
"goals_focus_teaser",
"profile_goals_progress",
"ai_pipeline_insight",
}
)
ALLOWED_WIDGET_IDS: frozenset[str] = frozenset(e["id"] for e in WIDGET_CATALOG)
@@ -0,0 +1,95 @@
# GUI, Informationsarchitektur, Admin & Navigation (Abnahme 2026-04-05)
> **Zweck:** Einheitliche Referenz für Menschen und Code-Agents (Cursor, Claude Code, …).
> **Gitea:** Teilaspekte zu [#30 Responsive UI](http://192.168.2.144:3000/Lars/mitai-jinkendo/issues/30); Admin-Layout kein separates Issue.
> **Branch-Realität:** Umsetzung auf `develop`, Deploy nach `main` wie üblich.
---
## Kurzüberblick
| Thema | Kern |
|-------|------|
| **Admin** | Eigener Bereich mit Shell wie KI-Analyse: Gruppen-Chips (mobil) / Sidebar (Desktop), Hub `/admin/g/:groupId`, Route-Guard `RequireAdmin` |
| **Ziele** | Eigener Hauptnav-Punkt `/goals`; nicht mehr primär unter Analyse; Dashboard + Einstellungen als Sekundär-Einstiege |
| **Einstellungen / Profil** | Nur **aktives** Profil inline; E-Mail-Self-Service; neue Profile nur **Admin → Benutzerverwaltung** |
| **KI-Analyse** | Neue Ergebnis-Karte im **rechten** Spalt der `analysis-split`, damit Kategorie-Nav nicht verdrängt wird |
| **PWA / iPhone** | Bottom-Nav: Safe Area auf **`.bottom-nav`**, kein Clipping durch `overflow-y` + `safe-area` auf Items |
| **Deploy Prod** | Workflow: `git fetch` + `git reset --hard origin/<branch>` statt `pull` bei schmutziger `package-lock` |
| **#14 Icon Picker** | Erledigt (`EmojiIconPicker`); Gitea geschlossen |
---
## Dateien (Single Source of Truth im Code)
| Bereich | Pfade |
|---------|--------|
| Hauptnavigation | `frontend/src/config/appNav.js` (`getMainNavItems`) |
| Active-State Bottom + Sidebar | `frontend/src/App.jsx` (`navItemActive`), `frontend/src/components/DesktopSidebar.jsx` |
| Admin Shell & Routing | `frontend/src/layouts/AdminShell.jsx`, `frontend/src/layouts/RequireAdmin.jsx`, `frontend/src/config/adminNav.js` (`ADMIN_GROUPS`, Hubs) |
| Admin-Seiten | `frontend/src/pages/AdminHomePage.jsx`, `AdminGroupHubPage.jsx`, `AdminUsersPage.jsx`, `AdminSystemPage.jsx`, … |
| Einstellungen Profil | `frontend/src/pages/SettingsPage.jsx`, `.settings-page__field` in `app.css` |
| KI-Analyse Layout | `frontend/src/pages/Analysis.jsx` + `.analysis-split*` in `app.css` |
| Admin-Zugriff verweigert | `frontend/src/pages/Dashboard.jsx` (`adminDenied` State aus `location.state`) |
| Bottom-Nav / Safe Area | `frontend/src/app.css` (`--nav-h`, `--nav-pad-top`, `.bottom-nav`, `.app-main` padding-bottom) |
| Deploy | `.gitea/workflows/deploy-prod.yml`, `deploy-dev.yml` |
| Backend Profil E-Mail | `backend/models.py` (`ProfileUpdate.email`), `backend/routers/profiles.py` (`update_profile` + Eindeutigkeit / Verifikation) |
| .gitignore Fix | `frontend/package-lock.json` eigene Zeile (war mit `settings.local` verklebt) |
---
## Navigation: Reihenfolge (Mobile & Desktop)
Übersicht → Erfassen → Verlauf → **Ziele** → Analyse → Einstellungen → **[Admin]**
- **Ziele:** `NavLink` mit `end: true` (exakt `/goals`).
- **Admin:** nur wenn `session.role === 'admin'`; Highlight bei `pathname.startsWith('/admin')`.
---
## Admin-Bereich (IA)
1. **Shell** nutzt dieselben UI-Klassen wie die Analyse: `.analysis-split`, `.analysis-split__nav-wrap`, `.analysis-split__main`.
2. **Nur Gruppen** in der Shell-Nav (inkl. Zähler pro Gruppe).
3. Konkrete Seiten: Karten auf **`/admin/g/:groupId`** (z. B. `features`, `prompts`, `system`).
4. **KI-Prompts** eigene Gruppe; **Basiseinstellungen** = SMTP + Placeholder-Export (`/admin/system`).
5. Kein Admin-Block mehr in den **Einstellungen** (nur Admin-Hinweis-Link zu Benutzerverwaltung).
---
## Backend-Hinweis Profil
`PUT /api/profile` akzeptiert `email`; Änderung setzt `email_verified` u. a. zurück (siehe `profiles.py`).
---
## Gitea / Issues (manuell oder `scripts/gitea/gitea_api.py`)
| Issue | Empfehlung |
|-------|------------|
| **#30** | Offen lassen oder TEILWEISE: Desktop-Sidebar existiert; ergänzt um Admin-Shell, scrollable Bottom-Nav, iOS Safe-Area. Kommentar mit Link **auf dieses Dokument**. |
| **#14** | Bereits geschlossen (Icon-Picker). |
| **Kein eigenes Admin-IA-Issue** | Optional: Sub-Issue „Admin Shell P7“ schließen oder mit #30 verknüpfen. |
Schließe **kein** großes #30 ohne Abnahme „volle Responsive-Spec“ – diese Session liefert nur einen **abgegrenzten** GUI-Stand.
---
## Checks für Folge-Agents
1. `frontend`: `npm run build`
2. Admin-Route als Nicht-Admin: Redirect `/`, Dashboard-Hinweis
3. iPhone PWA: Bottom-Nav nicht beschnitten; Content nicht hinter Home-Indicator
4. `develop` → nach Abnahme `main` + Deploy (siehe aktualisierte Workflows)
---
## Changelog-Kurz
- Admin: Shell, Hub-Routen, `RequireAdmin`, entfernt aus Settings.
- Ziele: `appNav`, Dashboard, Settings, Analyse nur noch Hinweis-Link.
- Settings: Mein Profil, E-Mail, keine Profilliste.
- Analyse: `newResult` in `analysis-split__main`.
- CSS: Bottom-Nav scroll + Safe Area + `--nav-pad-top`.
- Deploy: `reset --hard` auf Runner-Arbeitskopie.
- Review-Liste: #14 erledigt (siehe `REVIEW_OPEN_ISSUES_2026-04-04.md`).
+11 -9
View File
@@ -3,7 +3,7 @@
> **Gitea:** [#30 – Responsive UI](http://192.168.2.144:3000/Lars/mitai-jinkendo/issues/30)
> **Spec:** `.claude/docs/functional/RESPONSIVE_UI.md`
> **Breakpoint:** `<1024px` = Mobile (Bottom-Nav, bestehendes Verhalten), `≥1024px` = Desktop (Sidebar 220px)
> **Letzte Plan-Aktualisierung:** 2026-04-04
> **Letzte Plan-Aktualisierung:** 2026-04-05 (P7 Admin-Shell umgesetzt; Doku `GUI_IA_ADMIN_NAV_2026-04-05.md`; P8 ausstehend)
---
@@ -11,14 +11,14 @@
| Phase | Titel | Status | Datum / Notiz |
|-------|--------|--------|----------------|
| P0 | Vorbereitung & Baseline | ☐ pending | |
| P1 | App-Shell: Sidebar + Breakpoint + gemeinsame Navigation | ☐ pending | |
| P2 | Globales Layout & Content-Bereich (CSS) | ☐ pending | |
| P3 | Dashboard (Desktop-Grid) | ☐ pending | |
| P4 | Verlauf (Tabs links / Content rechts) | ☐ pending | |
| P5 | Analyse (Prompts links / Ergebnis rechts) | ☐ pending | |
| P6 | Erfassung / Capture & Formularseiten | ☐ pending | |
| P7 | Admin & restliche Vollbreiten-Seiten | ☐ pending | |
| P0 | Vorbereitung & Baseline | ☑ erledigt | Spec `RESPONSIVE_UI.md` bereinigt |
| P1 | App-Shell: Sidebar + Breakpoint + gemeinsame Navigation | ☑ erledigt | `DesktopSidebar`, `config/appNav.js`, Admin `/admin/*`-Highlight |
| P2 | Globales Layout & Content-Bereich (CSS) | ☑ erledigt | Desktop: Header aus, Content max 1200px; Mobile unverändert Bottom-Nav |
| P3 | Dashboard (Desktop-Grid) | ☑ erledigt | 4-spaltige Kennzahlen; Begrüßung; Ernährung/Aktivität 2-spaltig |
| P4 | Verlauf (Tabs links / Content rechts) | ☑ erledigt | `History.jsx` + `.history-*` in `app.css`; Tab-State bei `location.state.tab` |
| P5 | Analyse (Prompts links / Ergebnis rechts) | ☑ erledigt | `Analysis.jsx` + `.analysis-split*` in `app.css` |
| P6 | Erfassung / Capture & Formularseiten | ☑ erledigt | `.capture-page` + `--capture-content-max` (eine Desktop-Breite); CaptureShell-Navigation |
| P7 | Admin & restliche Vollbreiten-Seiten | ☑ erledigt (Kern) | **2026-04-05:** `AdminShell` + Hub-Routen + `adminNav`; Tabellen/„volle Breite“ weiter iterativ laut Spec §5.5 |
| P8 | Abschluss, Regression, Spec-Pflege | ☐ pending | |
**Status-Legende:** `☐ pending` · `◐ in Arbeit` · `☑ erledigt` · `⏸ blockiert`
@@ -202,6 +202,8 @@ Spec **§5.4**: Desktop Formulare **zentriert**, **max-width ~600px** im Content
## Phase P7 – Admin & übrige Seiten
**Stand 2026-04-05:** Admin nutzt **dedizierte Shell** mit Gruppen-Navigation und Hubs (`AdminShell`, `adminNav.js`, `RequireAdmin`) — IA- und Routing-Grundlage erledigt. Tabellen „mehr Breite“ / feinere Layout-Tuning gemäß §5.5 können weiterlaufen ohne Shell-Refactor. Doku: `GUI_IA_ADMIN_NAV_2026-04-05.md`.
### Ziel
Spec **§5.5**: Admin-Tabellen nutzen auf Desktop **mehr Breite**; Mobile weiterhin horizontales Scrollen wo nötig.
+8 -11
View File
@@ -17,14 +17,14 @@
| # | Titel (gekürzt) | Vorschlag | Notiz |
|---|-----------------|-----------|--------|
| 14 | Icon Picker Trainingstypen | OFFEN | Nur Freitext-Feld `icon` |
| 14 | Icon Picker Trainingstypen | **ERLEDIGT** | `EmojiIconPicker` in `AdminTrainingTypesPage.jsx`; Gitea #14 geschlossen (2026-04) |
| 15 | Quality-Filter KI & Charts | TEILWEISE | Registry/Charts Confidence, kein durchgängiges Produkt |
| 21 | Universeller CSV-Parser + Mapping | OFFEN | Modul-spezifische Parser |
| 25 | Ziele-System Goals | DONE? | GoalsPage, Router, Focus Areas |
| 26 | Charts erweitern | TEILWEISE | Phase-0c API + History/NutritionCharts |
| 27 | Korrelationen & Insights | TEILWEISE | C-Charts + offene Data-Layer-TODOs |
| 29 | Abilities-Matrix UI | TEILWEISE | Admin/ProfileBuilder, UX offen |
| 30 | Responsive UI Sidebar | OFFEN | Weiterhin Bottom-Nav-fokussiert |
| 30 | Responsive UI Sidebar | **TEILWEISE** | P1–P6 + **P7 Admin-Shell** + iOS Bottom-Nav Safe-Area; SSoT-Doku: **`GUI_IA_ADMIN_NAV_2026-04-05.md`**; #30 bleibt offen bis P8/Abnahme |
| 32 | Version-System (inkl. ehem. #33) | OFFEN | Gitea: Body/Titel 2026-04-04 aktualisiert; Runner/Build-Git bewusst später |
| 33 | — | GESCHLOSSEN | In #32 konsolidiert (superseded) |
| 34 | External Volumes Doku | PRÜFEN | Gegen Compose abgleichen |
@@ -48,14 +48,11 @@
## Details je Issue (älteste zuerst)
### #14 – [FEAT-001] Icon Picker für Trainingstypen
### #14 – [FEAT-001] Icon Picker für Trainingstypen — **ERLEDIGT**
**Code-Stand:** `AdminTrainingTypesPage.jsx` nutzt ein **Textfeld** `icon` (frei, z. B. Emoji). Kein dedizierter Icon-Picker (Palette, Vorschau, Kategorien).
**Code-Stand:** `AdminTrainingTypesPage.jsx` nutzt **`EmojiIconPicker`** (`frontend/src/components/EmojiIconPicker.jsx`) für Neu- und Bearbeiten-Dialoge; Wert bleibt String in `training_types.icon`.
**Vorschlag:** `OFFEN` – Issue beibehalten; optional präzisieren: „Emoji-Picker oder vordefinierte Icon-Liste statt Freitext“.
**Kommentar-Entwurf für Gitea:**
> Stand Backend/Frontend: `icon` wird als String in `training_types` gespeichert, Eingabe ist Freitext. Icon-Picker-UX steht noch aus.
**Gitea:** Issue **#14 geschlossen** (Kommentar + Close, Stand 2026-04).
---
@@ -115,11 +112,11 @@
### #30 – [FEAT] Responsive UI – Desktop Sidebar + 2-spaltig
**Code-Stand:** Weiterhin stark **Mobile-first** (z. B. `bottom-nav` in `App.jsx`); keine ausgebaute Desktop-Sidebar wie im klassischen Admin-Dashboard.
**Code-Stand (2026-04-05):** **Desktop-Sidebar** (`DesktopSidebar`, `config/appNav.js`) und **Mobile Bottom-Nav** mit horizontalem Scroll + **Safe Area** (`app.css`); **Admin** eigener Bereich **`AdminShell`** mit Gruppen-Hub wie Analyse (`adminNav.js`, `/admin/g/:groupId`, `RequireAdmin`). Siehe **`docs/issues/GUI_IA_ADMIN_NAV_2026-04-05.md`** (Dateipfade, IA, Deploy-Hinweis).
**Umsetzungsplan:** `docs/issues/PHASE_PLAN_RESPONSIVE_UI.md` (Phasen P0–P8, Abnahmekriterien & Tests, Fortschrittstabelle).
**Umsetzungsplan:** `docs/issues/PHASE_PLAN_RESPONSIVE_UI.md` (Phasen P0–P8). **P7** Kern umgesetzt; **P8** (Regression, finale Abnahme) stehen noch aus – Issue **nicht** schließen ohne P8-Checkliste.
**Vorschlag:** `OFFEN`.
**Vorschlag:** `TEILWEISE` – Gitea-Kommentar mit Link auf die GUI-Doku; Titel/Beschreibung optional um „Admin-Shell / Ziele-Nav / iOS PWA-Leiste“ ergänzen.
---
@@ -0,0 +1,202 @@
# Umsetzungsplan: Sportspezifisch auswertbare Trainingsprofile
**Status:** Konzept für fachliche Abstimmung / Konzeptagent
**Datum:** 2026-04-05
**Bezug:** Fachliches Teilkonzept „Sportspezifisch auswertbare Trainingsprofile“ (User-Entwurf)
**Hinweis:** Keine Implementierung ohne Freigabe der unter [Offene Fragen](#offene-fragen-für-den-fachlichen-konzeptagenten) gekläerten Punkte.
---
## 1. Kurzfazit: Machbarkeit
**Fachlich und technisch grundsätzlich machbar** als gestaffelte Erweiterung auf dem bestehenden System:
- `training_types.profile` (JSONB)
- `TrainingProfileEvaluator` (`backend/profile_evaluator.py`)
- Persistenz: `activity_log.evaluation`, `quality_label`, `overall_score`
**Engpass:** Viele im Teilkonzept genannten Kriterien (z. B. Muskelgruppen, Nähe zum muskulären Versagen, detaillierte Zonenzeiten) **lassen sich aus der aktuellen `activity_log`-Datenbasis nicht zuverlässig ableiten**. Dafür braucht es zusätzliche Erfassung, Importfelder oder explizite „niedrige Evidenz / unbekannt“-Markierung in Metriken und KI-Kontext (Placeholder-Registry, Erklärbarkeit).
---
## 2. Ist-Analyse (Abhängigkeiten)
### 2.1 Daten & Konfiguration
| Baustein | Rolle |
|---------|--------|
| `training_types` | `category`, `subcategory`, `name_*`, optional `abilities` (JSONB), `profile` (JSONB) |
| `activity_type_mappings` | Import/manuelles Mapping `activity_type` → `training_type_id` (unverändert lassen) |
| `training_parameters` | Registry messbarer Parameter für Regeln (`source_field` → `activity_log`) |
| `activity_log` | u. a. `training_type_id`, `evaluation`, `quality_label`, `overall_score` |
### 2.2 Bewertung heute
- Der Evaluator läuft über mehrere **rule_sets** (Minimumanforderungen, Zonen, Effekte, Periodisierung, KPI, Safety).
- **Ein** zusammengefasster `overall_score` und **ein** `quality_label` (`excellent` | `good` | `acceptable` | `poor`).
- **Relevanz, intrinsische Qualität, Zielbezug, Platzierung** sind im Ergebnis **nicht formal getrennt**; Periodisierung/Performance sind teils **MVP/vereinfacht**.
### 2.3 Downstream (nicht brechen)
- **Issue #31 / Quality Filter:** `profiles.quality_filter_level`, `quality_filter.py` (SQL-Fragmente nach `quality_label`)
- **Frontend:** Badges in Aktivitäts-UI, History-Hinweise
- **Data Layer / Charts:** u. a. `calculate_quality_sessions_pct`, `activity_score`, Korrelationen
- **Placeholder Registry:** u. a. `quality_sessions_pct` (bekannte Semantik-/Label-Diskrepanz, siehe unten)
### 2.4 Bekannte technische Inkonsistenz (Bestand)
`calculate_quality_sessions_pct` filtert u. a. auf `quality_label IN (..., 'very_good', ...)`, der `TrainingProfileEvaluator` setzt **`very_good` nicht**. Das sollte **vor oder zusammen mit** größeren Profil-Erweiterungen bereinigt werden, damit neue Dimensionen nicht auf wackeliger Basis validiert werden.
---
## 3. Umsetzungsprinzipien (Kompatibilität)
1. **Kein Big-Bang:** Consumer erwarten weiterhin sinnvolle `quality_label` / `overall_score`, es sei denn, es gibt eine **versionierte Cutover-Strategie**.
2. **Additive JSON-Struktur** in `evaluation` (z. B. mehrdimensionale Teilergebnisse), ohne bestehende Schlüssel willkürlich zu entfernen.
3. **Legacy-Vertrag festlegen:** z. B. `overall_score` = **primär intrinsische** Qualität (oder explizit „Legacy-Komposit“ mit `schema_version`).
4. **`training_types` bleibt Single Source** für Typ + Profil; Mapping-Import-Logik nicht „mitziehen“, außer es ist fachlich nötig.
5. **Neue Coach-Metriken:** über Placeholder Registry, mit Evidence-Tags; keine doppelte Wahrheit neben der Registry.
6. **KI:** `ai_context` / `interpretation_boundary` im Profil ausbaubar machen (was erlaubt/verboten ist, bei Datenlücken).
---
## 4. Phasenplan
### Phase 0 – Begriffe, Verträge, Bestandsaufnahme
- Glossar: Relevanz, intrinsische Qualität, Zielbeitrag, Platzierung, Belastung, sportspezifische Qualität → **Mapping auf bestehende `rule_sets`**.
- Vollständige Liste: wer liest `quality_label` / `evaluation` / `overall_score` (APIs, SQL, Frontend).
- Align: `very_good` vs. Evaluator-Labels; optional: Rolle von `acceptable` in „Qualitätssessions“ vs. globalem Filter **fachlich** klären.
### Phase 1 – Metamodell im Profil-JSON
- Erweiterung `training_types.profile`: z. B. `sport_logic`, `dimensions_config`, `goal_linkage`, `load_character`, `recovery_character`, `interference`, `ai_interpretation`.
- Evaluator liefert **Teilscores + Begründungen** pro Dimension; **Legacy-Felder** ableitbar und dokumentiert.
### Phase 2 – Zielbezug
- Input: aktive Ziele, `goal_mode`, Focus-Gewichte (`user_focus_area_weights`).
- Ausgabe: eigene Dimension **`goal_fit`**, ohne intrinsische Bewertung zu überschreiben.
### Phase 3 – Wochenkontext / Platzierung / Interferenz
- Kontext in `load_evaluation_context` erweitern (Reihenfolge, Vortag, Ruhetage, optional Vitals/Schlaf).
- Regeln schrittweise; False-Positive-Risiko beachten.
### Phase 4 – Sportspezifische Templates
- Profilvorlagen pro `sport_logic` (analog `profile_templates.py`), unterschiedliche Parameter und Schwellen.
- `confidence` / `data_sufficiency` pro Dimension.
### Phase 5 – Coach-Metriken & Placeholder
- Neue Platzhalter nur bei klarer Semantik; ggf. `quality_sessions_pct` **umschreiben** oder durch neuen Key ersetzen + Deprecation-Plan.
### Phase 6 – Frontend / Admin
- Dimensionen sichtbar machen; Badges können vorerst Legacy-Score anzeigen.
---
## 5. Risiken (Kurz)
| Risiko | Maßnahme |
|--------|----------|
| Bedeutung von `quality_label` wechselt still | `evaluation.schema_version`, dokumentierter Vertrag, ggf. separates `intrinsic_quality_label` nach Cutover |
| Charts/Scores springen | Shadow-Vergleich, gestuftes Rollout |
| KI übertreibt bei Datenlücken | `ai_interpretation` + Metadata-Evidence |
| Registry-Drift | Alle neuen Kennzahlen registrieren |
---
## Offene Fragen für den fachlichen Konzeptagenten
Die folgenden Blöcke sind bewusst als Markdown-Codeblöcke formatiert, damit sie **unverändert** in Prompts oder Tickets übernommen werden können.
### Block A – Priorität & Konflikte zwischen Dimensionen
```markdown
Wenn sich Dimensionen widersprechen (z. B. intrinsische Qualität „hoch“, Zielpassung „niedrig“, Platzierung „problematisch“):
1. Welche Dimension soll für die **primäre Nutzer-/Coach-Aussage** in der UI führend sein?
2. Gibt es eine **feste Prioritätsreihenfolge** (z. B. Sicherheit > Platzierung > Zielpassung > intrinsische Qualität) oder ist sie kontextabhängig?
3. Soll es eine **explizite „Gesamt-Coach-Empfehlung“** geben, die aus den Dimensionen kombiniert wird, oder nur parallele Teilurteile ohne Gesamtnote?
```
### Block B – Minimaldatensatz & Sportlogiken
```markdown
Pro Trainingsfamilie / „sport_logic“ (Kraft, Cardio, Schnellkraft, Kampfsport, Mobility, Erholung aktiv, Geist & Meditation):
1. Welche **messbaren Felder** sind minimal nötig, damit eine sportspezifische Bewertung **fachlich vertretbar** ist (nicht nur „nice to have“)?
2. Welche Aussagen dürfen **ohne** diese Felder **nicht** getroffen werden (nur „unbekannt“ / Confidence niedrig)?
3. Sollen fehlende Daten die **intrinsische** Bewertung hart begrenzen (Cap), oder nur **Zusatzdimensionen** betreffen?
```
### Block C – Einzeltraining vs. Wochenkontext
```markdown
Platzierung / Kontextqualität:
1. Darf schlechte Platzierung die **sichtbare Einheit-Qualität** numerisch senken, oder nur **Flags/Hinweise** erzeugen?
2. Welche zeitliche Auflösung ist Pflicht: nur **Datum** oder auch **start_time** / Reihenfolge am Tag?
3. Wie gehen wir mit **unvollständiger Historie** um (Importlücken, manuell gelöschte Einträge)?
```
### Block D – Ziele & Multi-Ziel
```markdown
Zielbezug (goal_fit):
1. Bewertung strikt gegen **ein Primärziel**, oder gewichtet gegen **alle aktiven Ziele**?
2. Wie werden **Focus Areas** vs. **konkrete Goals** priorisiert, wenn sie sich widersprechen?
3. Soll „behindert das Ziel“ (Teilkonzept) ein **eigener Score** oder nur eine **kategorische** Aussage sein?
```
### Block E – KI & Haftung / Grenzen
```markdown
KI-Interpretationsrahmen (pro Profil oder global):
1. Welche Formulierungen sind **verboten** (medizinische Diagnosen, absolute Leistungsversprechen, …)?
2. Muss jede KI-gestützte Aussage einen **Evidenz-Hinweis** tragen („basierend auf Dauer/HF“, „Muskelgruppen nicht erfasst“)?
3. Soll der Nutzer **opt-in** für interpretative Texte jenseits der Regeln haben?
```
### Block F – Legacy-Metriken & Filter
```markdown
Bestehende Kennzahlen:
1. Soll `quality_label` / `overall_score` dauerhaft **nur intrinsisch** bedeuten, oder ein **Komposit** aus mehreren Dimensionen?
2. Wie sollen `quality_sessions_pct` und der globale **Quality Filter** künftig mit mehrdimensionalen Urteilen umgehen (nur intrinsisch filtern vs. Kombination)?
3. Ist `acceptable` fachlich eine „Qualitätssession“ oder nur „formal ok“?
```
### Block G – Abnahme / Akzeptanz
```markdown
Abnahme:
1. Welche **messbaren** Abnahmekriterien gelten pro Phase (z. B. % konsistent bewerteter Sessions, keine Regression bei Filter-Charts)?
2. Wer **fachlich** sign-off: Rolle „Domain Owner“ vs. Entwicklung?
```
---
## Anhang: Referenz im Repository
| Thema | Pfad (orientierend) |
|-------|---------------------|
| Evaluator | `backend/profile_evaluator.py` |
| Regeln | `backend/rule_engine.py` |
| Auswertung + Kontext | `backend/evaluation_helper.py` |
| Profile JSON / Migration | `backend/migrations/014_training_profiles.sql`, Templates `backend/profile_templates.py` |
| Quality Filter | `backend/quality_filter.py` |
| Aktivitäts-API inkl. Eval | `backend/routers/activity.py` |
| Quality-Sessions-Metrik | `backend/data_layer/activity_metrics.py` (`calculate_quality_sessions_pct`) |
| Placeholder Registry | `backend/placeholder_registrations/activity_metrics.py` |
---
*Ende des Dokuments.*
+136 -72
View File
@@ -1,6 +1,6 @@
import { useEffect } from 'react'
import { BrowserRouter, Routes, Route, NavLink, useNavigate } from 'react-router-dom'
import { LayoutDashboard, PlusSquare, TrendingUp, BarChart2, Settings, LogOut } from 'lucide-react'
import { BrowserRouter, Routes, Route, NavLink, useLocation } from 'react-router-dom'
import { LogOut } from 'lucide-react'
import { ProfileProvider, useProfile } from './context/ProfileContext'
import { AuthProvider, useAuth } from './context/AuthContext'
import { setProfileId } from './utils/api'
@@ -11,6 +11,7 @@ import LoginScreen from './pages/LoginScreen'
import Register from './pages/Register'
import Verify from './pages/Verify'
import Dashboard from './pages/Dashboard'
import CaptureShell from './layouts/CaptureShell'
import CaptureHub from './pages/CaptureHub'
import WeightScreen from './pages/WeightScreen'
import CircumScreen from './pages/CircumScreen'
@@ -21,6 +22,11 @@ import NutritionPage from './pages/NutritionPage'
import ActivityPage from './pages/ActivityPage'
import Analysis from './pages/Analysis'
import SettingsPage from './pages/SettingsPage'
import SettingsShell from './layouts/SettingsShell'
import ProfileReferenceValuesPage from './pages/ProfileReferenceValuesPage'
import PilotVizPage from './pages/PilotVizPage'
import DashboardLabPage from './pages/DashboardLabPage'
import DashboardConfigurePage from './pages/DashboardConfigurePage'
import GuidePage from './pages/GuidePage'
import AdminTierLimitsPage from './pages/AdminTierLimitsPage'
import AdminFeaturesPage from './pages/AdminFeaturesPage'
@@ -33,6 +39,13 @@ import AdminTrainingProfiles from './pages/AdminTrainingProfiles'
import AdminPromptsPage from './pages/AdminPromptsPage'
import AdminGoalTypesPage from './pages/AdminGoalTypesPage'
import AdminFocusAreasPage from './pages/AdminFocusAreasPage'
import AdminReferenceValueTypesPage from './pages/AdminReferenceValueTypesPage'
import AdminHomePage from './pages/AdminHomePage'
import AdminUsersPage from './pages/AdminUsersPage'
import AdminSystemPage from './pages/AdminSystemPage'
import AdminGroupHubPage from './pages/AdminGroupHubPage'
import RequireAdmin from './layouts/RequireAdmin'
import AdminShell from './layouts/AdminShell'
import SubscriptionPage from './pages/SubscriptionPage'
import SleepPage from './pages/SleepPage'
import RestDaysPage from './pages/RestDaysPage'
@@ -40,21 +53,34 @@ import VitalsPage from './pages/VitalsPage'
import GoalsPage from './pages/GoalsPage'
import CustomGoalsPage from './pages/CustomGoalsPage'
import WorkflowEditorPage from './pages/WorkflowEditorPage'
import DesktopSidebar from './components/DesktopSidebar'
import { getMainNavItems } from './config/appNav'
import { isCaptureSectionPath } from './config/captureNav'
import './app.css'
function Nav() {
const links = [
{ to:'/', icon:<LayoutDashboard size={20}/>, label:'Übersicht' },
{ to:'/capture', icon:<PlusSquare size={20}/>, label:'Erfassen' },
{ to:'/history', icon:<TrendingUp size={20}/>, label:'Verlauf' },
{ to:'/analysis', icon:<BarChart2 size={20}/>, label:'Analyse' },
{ to:'/settings', icon:<Settings size={20}/>, label:'Einst.' },
]
function navItemActive(pathname, item, routerIsActive) {
if (item.to.startsWith('/admin')) return pathname.startsWith('/admin')
if (item.to === '/capture' && isCaptureSectionPath(pathname)) return true
return routerIsActive
}
function Nav({ isAdmin }) {
const items = getMainNavItems(isAdmin)
const loc = useLocation()
return (
<nav className="bottom-nav">
{links.map(l=>(
<NavLink key={l.to} to={l.to} end={l.to==='/'} className={({isActive})=>'nav-item'+(isActive?' active':'')}>
{l.icon}<span>{l.label}</span>
{items.map((item) => (
<NavLink
key={item.to}
to={item.to}
end={!!item.end}
className={({ isActive }) =>
'nav-item' +
(navItemActive(loc.pathname, item, isActive) ? ' active' : '')
}
>
<item.Icon size={20} strokeWidth={2} />
<span>{item.shortLabel || item.label}</span>
</NavLink>
))}
</nav>
@@ -62,9 +88,8 @@ function Nav() {
}
function AppShell() {
const { session, loading: authLoading, needsSetup, logout } = useAuth()
const { activeProfile, loading: profileLoading } = useProfile()
const nav = useNavigate()
const { session, loading: authLoading, needsSetup, logout, isAdmin } = useAuth()
const { activeProfile, loading: profileLoading } = useProfile()
const handleLogout = () => {
if (confirm('Wirklich abmelden?')) {
@@ -136,70 +161,109 @@ function AppShell() {
return (
<div className="app-shell">
<header className="app-header">
<span className="app-logo">Mitai Jinkendo</span>
<div style={{display:'flex', gap:12, alignItems:'center'}}>
<button
onClick={handleLogout}
title="Abmelden"
style={{
background:'none',
border:'none',
cursor:'pointer',
padding:6,
display:'flex',
alignItems:'center',
color:'var(--text2)',
transition:'color 0.15s'
}}
onMouseEnter={e => e.currentTarget.style.color = '#D85A30'}
onMouseLeave={e => e.currentTarget.style.color = 'var(--text2)'}
>
<LogOut size={18}/>
</button>
<NavLink to="/settings" style={{textDecoration:'none'}}>
{activeProfile
? <Avatar profile={activeProfile} size={30}/>
: <div style={{width:30,height:30,borderRadius:'50%',background:'var(--accent)'}}/>
}
</NavLink>
</div>
</header>
<main className="app-main">
<DesktopSidebar
isAdmin={isAdmin}
activeProfile={activeProfile}
sessionProfile={session?.profile}
onLogout={handleLogout}
/>
<div className="app-shell__column">
<header className="app-header app-header--mobile">
<span className="app-logo">Mitai Jinkendo</span>
<div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
<button
type="button"
onClick={handleLogout}
title="Abmelden"
style={{
background: 'none',
border: 'none',
cursor: 'pointer',
padding: 6,
display: 'flex',
alignItems: 'center',
color: 'var(--text2)',
transition: 'color 0.15s'
}}
onMouseEnter={(e) => {
e.currentTarget.style.color = '#D85A30'
}}
onMouseLeave={(e) => {
e.currentTarget.style.color = 'var(--text2)'
}}
>
<LogOut size={18} />
</button>
<NavLink to="/settings" style={{ textDecoration: 'none' }}>
{activeProfile ? (
<Avatar profile={activeProfile} size={30} />
) : (
<div
style={{
width: 30,
height: 30,
borderRadius: '50%',
background: 'var(--accent)'
}}
/>
)}
</NavLink>
</div>
</header>
<main className="app-main">
<Routes>
<Route path="/" element={<Dashboard/>}/>
<Route path="/capture" element={<CaptureHub/>}/>
<Route path="/wizard" element={<MeasureWizard/>}/>
<Route path="/weight" element={<WeightScreen/>}/>
<Route path="/circum" element={<CircumScreen/>}/>
<Route path="/caliper" element={<CaliperScreen/>}/>
<Route element={<CaptureShell />}>
<Route path="/capture" element={<CaptureHub />} />
<Route path="/wizard" element={<MeasureWizard />} />
<Route path="/weight" element={<WeightScreen />} />
<Route path="/circum" element={<CircumScreen />} />
<Route path="/caliper" element={<CaliperScreen />} />
<Route path="/sleep" element={<SleepPage />} />
<Route path="/rest-days" element={<RestDaysPage />} />
<Route path="/vitals" element={<VitalsPage />} />
<Route path="/custom-goals" element={<CustomGoalsPage />} />
<Route path="/nutrition" element={<NutritionPage />} />
<Route path="/activity" element={<ActivityPage />} />
<Route path="/guide" element={<GuidePage />} />
</Route>
<Route path="/history" element={<History/>}/>
<Route path="/sleep" element={<SleepPage/>}/>
<Route path="/rest-days" element={<RestDaysPage/>}/>
<Route path="/vitals" element={<VitalsPage/>}/>
<Route path="/goals" element={<GoalsPage/>}/>
<Route path="/custom-goals" element={<CustomGoalsPage/>}/>
<Route path="/nutrition" element={<NutritionPage/>}/>
<Route path="/activity" element={<ActivityPage/>}/>
<Route path="/analysis" element={<Analysis/>}/>
<Route path="/settings" element={<SettingsPage/>}/>
<Route path="/guide" element={<GuidePage/>}/>
<Route path="/admin/tier-limits" element={<AdminTierLimitsPage/>}/>
<Route path="/admin/features" element={<AdminFeaturesPage/>}/>
<Route path="/admin/tiers" element={<AdminTiersPage/>}/>
<Route path="/admin/coupons" element={<AdminCouponsPage/>}/>
<Route path="/admin/user-restrictions" element={<AdminUserRestrictionsPage/>}/>
<Route path="/admin/training-types" element={<AdminTrainingTypesPage/>}/>
<Route path="/admin/activity-mappings" element={<AdminActivityMappingsPage/>}/>
<Route path="/admin/training-profiles" element={<AdminTrainingProfiles/>}/>
<Route path="/admin/prompts" element={<AdminPromptsPage/>}/>
<Route path="/admin/goal-types" element={<AdminGoalTypesPage/>}/>
<Route path="/admin/focus-areas" element={<AdminFocusAreasPage/>}/>
<Route path="/settings" element={<SettingsShell />}>
<Route index element={<SettingsPage />} />
<Route path="reference-values" element={<ProfileReferenceValuesPage />} />
<Route path="dashboard-layout" element={<DashboardConfigurePage />} />
</Route>
<Route element={<RequireAdmin />}>
<Route path="admin" element={<AdminShell />}>
<Route index element={<AdminHomePage />} />
<Route path="g/:groupId" element={<AdminGroupHubPage />} />
<Route path="users" element={<AdminUsersPage />} />
<Route path="system" element={<AdminSystemPage />} />
<Route path="dashboard-product-default" element={<DashboardConfigurePage adminMode />} />
<Route path="tier-limits" element={<AdminTierLimitsPage/>}/>
<Route path="features" element={<AdminFeaturesPage/>}/>
<Route path="tiers" element={<AdminTiersPage/>}/>
<Route path="coupons" element={<AdminCouponsPage/>}/>
<Route path="user-restrictions" element={<AdminUserRestrictionsPage/>}/>
<Route path="training-types" element={<AdminTrainingTypesPage/>}/>
<Route path="activity-mappings" element={<AdminActivityMappingsPage/>}/>
<Route path="training-profiles" element={<AdminTrainingProfiles/>}/>
<Route path="prompts" element={<AdminPromptsPage/>}/>
<Route path="goal-types" element={<AdminGoalTypesPage/>}/>
<Route path="focus-areas" element={<AdminFocusAreasPage/>}/>
<Route path="reference-value-types" element={<AdminReferenceValueTypesPage/>}/>
</Route>
</Route>
<Route path="/workflow-editor/:id" element={<WorkflowEditorPage/>}/>
<Route path="/subscription" element={<SubscriptionPage/>}/>
<Route path="/pilot/viz" element={<PilotVizPage />} />
<Route path="/app/dashboard-lab" element={<DashboardLabPage />} />
</Routes>
</main>
<Nav/>
</main>
</div>
<Nav isAdmin={isAdmin} />
</div>
)
}
+840 -18
View File
@@ -12,9 +12,12 @@
--accent-dark: #0a5c43;
--danger: #D85A30;
--warn: #EF9F27;
--nav-h: 64px;
/* Höhe der eigentlichen Tab-Zeile (ohne Abstand/Home-Indicator) */
--nav-h: 56px;
--nav-pad-top: 8px;
--header-h: 52px;
--font: system-ui, -apple-system, 'Segoe UI', sans-serif;
--capture-content-max: 800px;
}
@media (prefers-color-scheme: dark) {
:root {
@@ -35,20 +38,61 @@ body { font-family: var(--font); background: var(--bg); color: var(--text1); -we
position: sticky; top: 0; z-index: 10;
}
.app-logo { font-size: 18px; font-weight: 700; color: var(--accent); letter-spacing: -0.02em; }
.app-main { flex: 1; overflow-y: auto; padding: 16px 16px calc(var(--nav-h) + 16px); }
/* unten: Tab-Leiste + Abstand nach oben zur Leiste + Home-Indicator (iPhone) */
.app-main {
flex: 1;
overflow-y: auto;
padding: 16px 16px calc(var(--nav-h) + var(--nav-pad-top) + env(safe-area-inset-bottom, 0px) + 20px);
}
.bottom-nav {
position: fixed; bottom: 0; left: 50%; transform: translateX(-50%);
width: 100%; max-width: 600px;
height: var(--nav-h); display: flex; align-items: stretch;
background: var(--surface); border-top: 1px solid var(--border);
position: fixed;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 100%;
max-width: 600px;
display: flex;
align-items: center;
background: var(--surface);
border-top: 1px solid var(--border);
z-index: 20;
overflow-x: auto;
overflow-y: visible;
-webkit-overflow-scrolling: touch;
scrollbar-width: none;
-ms-overflow-style: none;
justify-content: flex-start;
gap: 2px;
padding: var(--nav-pad-top) 6px env(safe-area-inset-bottom, 0px);
min-height: calc(var(--nav-h) + var(--nav-pad-top) + env(safe-area-inset-bottom, 0px));
height: auto;
box-sizing: border-box;
}
.bottom-nav::-webkit-scrollbar {
display: none;
}
.nav-item {
flex: 1; display: flex; flex-direction: column; align-items: center;
justify-content: center; gap: 3px; color: var(--text3);
text-decoration: none; font-size: 10px; font-weight: 500;
transition: color 0.15s; padding-bottom: env(safe-area-inset-bottom, 0);
flex: 0 0 auto;
min-width: 56px;
max-width: 96px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 3px;
color: var(--text3);
text-decoration: none;
font-weight: 500;
transition: color 0.15s;
padding: 2px 4px 4px;
box-sizing: border-box;
}
.nav-item span {
font-size: 10px;
line-height: 1.15;
text-align: center;
max-width: 100%;
}
.nav-item.active { color: var(--accent); }
.nav-item svg { flex-shrink: 0; }
@@ -86,6 +130,32 @@ body { font-family: var(--font); background: var(--bg); color: var(--text1); -we
}
.form-input:focus { outline: none; border-color: var(--accent); }
.form-unit { font-size: 12px; color: var(--text3); width: 24px; }
/* Einstellungen Profil: Label als Überschrift oben, volle Breite, linksbündig */
.settings-page__field {
display: flex;
flex-direction: column;
align-items: stretch;
gap: 8px;
padding: 12px 0;
border-bottom: 1px solid var(--border);
text-align: left;
}
.settings-page__field-label {
display: block;
font-size: 14px;
font-weight: 600;
color: var(--text1);
text-align: left;
line-height: 1.3;
}
.settings-page__field .form-input {
width: 100%;
max-width: 100%;
min-width: 0;
text-align: left;
box-sizing: border-box;
}
.form-select {
font-family: var(--font); font-size: 13px; color: var(--text1);
background: var(--surface2); border: 1.5px solid var(--border2);
@@ -125,6 +195,440 @@ body { font-family: var(--font); background: var(--bg); color: var(--text1); -we
/* Section */
.section-gap { margin-bottom: 16px; }
.page-title { font-size: 20px; font-weight: 700; margin-bottom: 16px; }
/* Verlauf: Mobile Tabs horizontale Leiste, Desktop vertikal links (P4 / RESPONSIVE_UI §5.2) */
.history-page__title {
margin-bottom: 12px;
}
.history-page__layout {
display: flex;
flex-direction: column;
gap: 16px;
}
.history-tabs {
margin-bottom: 0;
}
.history-tabs__scroller {
display: flex;
flex-direction: row;
gap: 6px;
overflow-x: auto;
padding-bottom: 6px;
-ms-overflow-style: none;
scrollbar-width: none;
}
.history-tabs__scroller::-webkit-scrollbar {
display: none;
}
.history-tab-btn {
white-space: nowrap;
flex-shrink: 0;
padding: 7px 14px;
border-radius: 20px;
border: 1.5px solid var(--border2);
background: var(--surface);
color: var(--text2);
font-family: var(--font);
font-size: 13px;
font-weight: 500;
cursor: pointer;
}
.history-tab-btn:hover {
border-color: var(--accent);
color: var(--text1);
}
.history-tab-btn.history-tab-btn--active {
border-color: var(--accent);
background: var(--accent);
color: white;
}
.history-tab-btn.history-tab-btn--active:hover {
color: white;
}
@media (min-width: 1024px) {
.history-page__layout {
flex-direction: row;
align-items: flex-start;
gap: 24px;
}
.history-tabs {
flex: 0 0 260px;
max-width: 280px;
position: sticky;
top: 16px;
align-self: flex-start;
}
.history-tabs__scroller {
flex-direction: column;
overflow-x: visible;
overflow-y: auto;
max-height: calc(100vh - 120px);
padding-bottom: 0;
gap: 8px;
}
.history-tab-btn {
display: flex;
align-items: center;
width: 100%;
text-align: left;
border-radius: 10px;
white-space: normal;
flex-shrink: 0;
padding: 10px 14px;
}
.history-content {
flex: 1;
min-width: 0;
}
}
/* KI-Analyse (P5): Mobile Prompt-Leiste oben / horizontal, Desktop links ~300px (RESPONSIVE_UI §5.3) */
.analysis-page__header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 16px;
gap: 12px;
flex-wrap: wrap;
}
.analysis-page__header > div:first-child {
flex: 1;
min-width: 0;
}
.analysis-split {
display: flex;
flex-direction: column;
gap: 16px;
}
.analysis-split__nav {
display: flex;
flex-direction: row;
gap: 6px;
overflow-x: auto;
padding-bottom: 6px;
-ms-overflow-style: none;
scrollbar-width: none;
}
.analysis-split__nav::-webkit-scrollbar {
display: none;
}
.analysis-split__nav-item {
flex-shrink: 0;
display: inline-flex;
align-items: center;
gap: 6px;
padding: 8px 14px;
border-radius: 20px;
border: 1.5px solid var(--border2);
background: var(--surface);
color: var(--text2);
font-family: var(--font);
font-size: 13px;
font-weight: 500;
cursor: pointer;
white-space: nowrap;
}
.analysis-split__nav-item:hover {
border-color: var(--accent);
color: var(--text1);
}
.analysis-split__nav-item--active {
border-color: var(--accent);
background: var(--accent);
color: white;
}
.analysis-split__nav-item--active:hover {
color: white;
}
.analysis-split__nav-item--active .muted {
color: rgba(255, 255, 255, 0.88) !important;
}
.analysis-split__nav-cat-count {
margin-left: 6px;
font-size: 11px;
font-weight: 500;
opacity: 0.92;
}
.analysis-split__nav-item--active .analysis-split__nav-cat-count {
color: rgba(255, 255, 255, 0.95);
opacity: 1;
}
a.analysis-split__nav-item {
text-decoration: none;
box-sizing: border-box;
}
.analysis-split__main {
min-width: 0;
}
@media (min-width: 1024px) {
.analysis-split {
flex-direction: row;
align-items: flex-start;
gap: 24px;
}
.analysis-split__nav-wrap {
flex: 0 0 300px;
max-width: 320px;
position: sticky;
top: 16px;
align-self: flex-start;
}
.analysis-split__nav {
flex-direction: column;
overflow-x: visible;
overflow-y: auto;
max-height: calc(100vh - 140px);
padding-bottom: 0;
gap: 8px;
}
.analysis-split__nav-item {
width: 100%;
justify-content: flex-start;
text-align: left;
border-radius: 10px;
white-space: normal;
}
.analysis-split__main {
flex: 1;
}
}
/* Erfassung: eine einheitliche Inhaltsbreite (Desktop), zentriert; mobil volle Breite */
.capture-page {
width: 100%;
max-width: 100%;
box-sizing: border-box;
}
@media (min-width: 1024px) {
.capture-page {
max-width: var(--capture-content-max);
margin-left: auto;
margin-right: auto;
}
}
/* Erfassung: Sub-Navigation (Mobil = Chips, Desktop = linke Spalte) */
.capture-shell {
width: 100%;
}
.capture-shell__layout {
display: flex;
flex-direction: column;
gap: 16px;
}
.capture-shell__nav {
display: flex;
flex-direction: row;
gap: 6px;
overflow-x: auto;
padding-bottom: 6px;
-ms-overflow-style: none;
scrollbar-width: none;
}
.capture-shell__nav::-webkit-scrollbar {
display: none;
}
.capture-shell__nav-item {
flex-shrink: 0;
display: inline-flex;
align-items: center;
gap: 6px;
padding: 7px 12px;
border-radius: 20px;
border: 1.5px solid var(--border2);
background: var(--surface);
color: var(--text2);
font-family: var(--font);
font-size: 13px;
font-weight: 500;
text-decoration: none;
white-space: nowrap;
cursor: pointer;
box-sizing: border-box;
}
.capture-shell__nav-item:hover {
border-color: var(--accent);
color: var(--text1);
}
.capture-shell__nav-item--active {
border-color: var(--accent);
background: var(--accent);
color: white;
}
.capture-shell__nav-item--active:hover {
color: white;
}
.capture-shell__nav-item--highlight:not(.capture-shell__nav-item--active) {
border-color: #7f77dd88;
background: #7f77dd14;
}
.capture-shell__nav-icon {
font-size: 15px;
line-height: 1;
}
.capture-shell__nav-label {
line-height: 1.2;
}
.capture-shell__main {
min-width: 0;
}
@media (min-width: 1024px) {
.capture-shell__layout {
flex-direction: row;
align-items: flex-start;
gap: 24px;
}
.capture-shell__nav-wrap {
flex: 0 0 260px;
max-width: 280px;
position: sticky;
top: 16px;
align-self: flex-start;
}
.capture-shell__nav {
flex-direction: column;
overflow-x: visible;
overflow-y: auto;
max-height: calc(100vh - 140px);
padding-bottom: 0;
gap: 8px;
}
.capture-shell__nav-item {
width: 100%;
justify-content: flex-start;
border-radius: 10px;
white-space: normal;
padding: 9px 12px;
}
.capture-shell__main {
flex: 1;
}
}
/* Einstellungen: gleiche Split-Struktur wie Analyse/Admin */
.settings-shell {
width: 100%;
}
/* Referenzwerte: Übersichtskacheln (responsive, bis 4 Spalten Desktop) */
.ref-value-tiles-grid {
display: grid;
gap: 12px;
grid-template-columns: 1fr;
}
@media (min-width: 520px) {
.ref-value-tiles-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (min-width: 900px) {
.ref-value-tiles-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@media (min-width: 1200px) {
.ref-value-tiles-grid {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
}
.ref-value-tile {
display: block;
width: 100%;
margin: 0;
padding: 14px 14px 12px;
text-align: left;
font-family: var(--font);
border-radius: 12px;
border: 1.5px solid var(--border2);
background: var(--surface);
color: var(--text1);
cursor: pointer;
box-sizing: border-box;
transition: border-color 0.15s, box-shadow 0.15s;
}
.ref-value-tile:hover {
border-color: var(--accent);
}
.ref-value-tile:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.ref-value-tile--active {
border-color: var(--accent);
background: var(--surface2);
}
/* Admin: Split-Layout wie .analysis-split (nur Gruppen in der Nav) */
.admin-shell {
width: 100%;
}
.admin-page {
width: 100%;
}
@media (min-width: 1024px) {
.admin-page {
max-width: var(--capture-content-max);
margin-left: auto;
margin-right: auto;
}
}
.muted { color: var(--text3); font-size: 13px; }
.empty-state { text-align: center; padding: 48px 16px; color: var(--text3); }
.empty-state h3 { font-size: 16px; color: var(--text2); margin-bottom: 6px; }
@@ -147,14 +651,332 @@ body { font-family: var(--font); background: var(--bg); color: var(--text1); -we
}
}
/* 6-item nav - smaller labels */
.nav-item span { font-size: 11px; }
/* 7-item nav scrollable */
.bottom-nav { overflow-x: auto; }
.nav-item span { font-size: 11px; }
.nav-item { min-width: 60px; }
/* Header with profile avatar */
.app-header { display:flex; align-items:center; justify-content:space-between; }
.app-header a { display:flex; }
/* ── Responsive shell: Desktop sidebar (≥1024px) — spec RESPONSIVE_UI.md ───── */
.app-shell__column {
display: flex;
flex-direction: column;
flex: 1;
min-width: 0;
min-height: 0;
}
.desktop-sidebar {
display: none;
flex-direction: column;
width: 220px;
height: 100vh;
position: fixed;
left: 0;
top: 0;
z-index: 30;
background: var(--surface);
border-right: 1px solid var(--border);
padding: 16px 0 16px;
}
.desktop-sidebar__brand {
display: flex;
align-items: center;
gap: 10px;
padding: 0 16px 20px;
border-bottom: 1px solid var(--border);
margin-bottom: 12px;
}
.desktop-sidebar__logo {
width: 40px;
height: 40px;
border-radius: 50%;
border: 3px solid var(--accent);
flex-shrink: 0;
opacity: 0.85;
}
.desktop-sidebar__title {
font-size: 15px;
font-weight: 700;
color: var(--accent);
letter-spacing: -0.02em;
line-height: 1.2;
}
.desktop-sidebar__nav {
display: flex;
flex-direction: column;
gap: 2px;
flex: 1;
overflow-y: auto;
padding: 0 0 12px;
}
.desktop-sidebar__link {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 16px 10px 13px;
text-decoration: none;
color: var(--text2);
font-size: 14px;
font-weight: 500;
border-left: 3px solid transparent;
border-radius: 0 8px 8px 0;
transition: background 0.15s, color 0.15s;
}
.desktop-sidebar__link:hover {
background: var(--surface2);
color: var(--text1);
}
.desktop-sidebar__link.desktop-sidebar__link--active {
background: var(--accent-light);
color: var(--accent);
border-left-color: var(--accent);
}
.desktop-sidebar__footer {
border-top: 1px solid var(--border);
padding: 16px 12px 0;
display: flex;
align-items: center;
gap: 8px;
}
.desktop-sidebar__user {
display: flex;
align-items: center;
gap: 10px;
flex: 1;
min-width: 0;
text-decoration: none;
color: inherit;
}
.desktop-sidebar__user-text {
display: flex;
flex-direction: column;
min-width: 0;
}
.desktop-sidebar__user-name {
font-size: 13px;
font-weight: 600;
color: var(--text1);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.desktop-sidebar__user-tier {
font-size: 11px;
color: var(--text3);
text-transform: lowercase;
}
.desktop-sidebar__logout {
flex-shrink: 0;
background: none;
border: none;
padding: 8px;
cursor: pointer;
color: var(--text3);
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
}
.desktop-sidebar__logout:hover {
color: var(--danger);
background: rgba(216, 90, 48, 0.08);
}
@media (max-width: 1023px) {
.app-shell {
display: flex;
flex-direction: column;
height: 100%;
max-width: 600px;
margin: 0 auto;
}
}
@media (min-width: 1024px) {
.app-shell {
display: block;
max-width: none;
margin: 0;
width: 100%;
min-height: 100%;
}
.desktop-sidebar {
display: flex;
}
.app-shell__column {
margin-left: 220px;
min-height: 100vh;
}
.app-header--mobile {
display: none !important;
}
.bottom-nav {
display: none !important;
}
.app-main {
padding: 24px 32px 32px;
padding-bottom: max(32px, env(safe-area-inset-bottom, 0px));
max-width: 1200px;
margin-left: auto;
margin-right: auto;
width: 100%;
box-sizing: border-box;
}
/* Dashboard (P3): Begrüßung + Kennzahlen-Zeile */
.dashboard-greeting {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
margin-bottom: 16px;
}
.dashboard-greeting__meta {
margin-top: 0 !important;
text-align: right;
}
}
/* ── Dashboard layout (Mobile baseline + Desktop im Block oben teilweise) ─ */
.dashboard-page {
width: 100%;
}
.dashboard-greeting {
margin-bottom: 16px;
}
/*
* Dashboard-Raster (KPI, Nebeneinander-Kacheln): 2 / 4 Spalten.
* StatCard, DashboardTile: span via --tile-sm / --tile-lg (JS clamp).
*/
.dashboard-stat-grid,
.dashboard-tile-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
}
.dashboard-stat-grid--mobile-4col,
.dashboard-tile-grid--mobile-4col {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
.dashboard-stat-card {
background: var(--surface);
border-radius: 12px;
padding: 12px 10px;
border: 1px solid var(--border);
transition: border-color 0.15s;
}
.dashboard-stat-card,
.dashboard-tile {
min-width: 0;
box-sizing: border-box;
grid-column: span var(--tile-sm, 1);
}
@media (min-width: 1024px) {
.dashboard-stat-card,
.dashboard-tile {
grid-column: span var(--tile-lg, 1);
}
}
/* ── Dashboard-Abschnitte (Überschrift + Trennlinie) ─ */
.dashboard-section {
margin-bottom: 22px;
}
.dashboard-section:last-child {
margin-bottom: 0;
}
.dashboard-section__header {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
padding-bottom: 10px;
margin-bottom: 12px;
border-bottom: 1px solid var(--border);
}
.dashboard-section__headline {
flex: 1;
min-width: 0;
}
.dashboard-section__title {
font-size: 13px;
font-weight: 700;
color: var(--text3);
text-transform: uppercase;
letter-spacing: 0.05em;
margin: 0;
}
.dashboard-section__description {
font-size: 12px;
color: var(--text3);
margin: 4px 0 0 0;
line-height: 1.35;
max-width: 640px;
}
.dashboard-section__body {
display: flex;
flex-direction: column;
gap: 12px;
}
.dashboard-section__actions {
flex-shrink: 0;
}
.dashboard-pill-row {
display: flex;
gap: 6px;
flex-wrap: wrap;
}
/* Ernährung/Aktivität: Raster wie KPI; Kacheln per DashboardTile steuerbar */
.dashboard-summary-row.dashboard-tile-grid {
margin-bottom: 0;
}
.dashboard-erholung-grid .dashboard-tile > .card,
.dashboard-summary-row .dashboard-tile > .card {
height: 100%;
}
@media (min-width: 1024px) {
.dashboard-stat-grid,
.dashboard-tile-grid {
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 10px;
}
}
@@ -0,0 +1,31 @@
/**
* Abschnitt mit optionalem Kopf (Titel, Beschreibung, Aktionen) und unterem Rand zur optischen Trennung.
*/
export default function DashboardSection({
title,
description,
headerRight,
children,
className = '',
bodyClassName = ''
}) {
const showHeader = title || description || headerRight
return (
<section className={`dashboard-section ${className}`.trim()}>
{showHeader && (
<header className="dashboard-section__header">
<div className="dashboard-section__headline">
{title ? <h2 className="dashboard-section__title">{title}</h2> : null}
{description ? (
<p className="dashboard-section__description">{description}</p>
) : null}
</div>
{headerRight ? (
<div className="dashboard-section__actions">{headerRight}</div>
) : null}
</header>
)}
<div className={`dashboard-section__body ${bodyClassName}`.trim()}>{children}</div>
</section>
)
}
@@ -0,0 +1,134 @@
import { useState } from 'react'
import {
clampTileSpan,
DASHBOARD_TILE_GRID_COLS,
} from '../utils/dashboardLayout'
export const PILL_TOOLTIPS = {
WHR: 'Waist-Hip-Ratio: Taille ÷ Hüfte. Maß für Bauchfettverteilung. Ziel: <0,90 (M) / <0,85 (F)',
WHtR: 'Waist-to-Height-Ratio: Taille ÷ Körpergröße. Gesündestest Maß: Ziel unter 0,50.',
KF: 'Körperfettanteil in Prozent (aus Caliper-Messung).',
'Protein Ø7T':
'Durchschnittliche tägliche Proteinaufnahme der letzten 7 Tage vs. Zielbereich (1,6–2,2g/kg KG).',
}
export function Pill({ label, value, status, sub }) {
const [tip, setTip] = useState(false)
const color = status === 'good' ? 'var(--accent)' : status === 'warn' ? 'var(--warn)' : '#D85A30'
const bg =
status === 'good'
? 'var(--accent-light)'
: status === 'warn'
? 'var(--warn-bg)'
: '#FCEBEB'
const tipText = PILL_TOOLTIPS[label]
return (
<div style={{ position: 'relative' }}>
<div
role={tipText ? 'button' : undefined}
onClick={() => tipText && setTip((s) => !s)}
onKeyDown={(e) => tipText && e.key === 'Enter' && setTip((s) => !s)}
tabIndex={tipText ? 0 : undefined}
style={{
display: 'flex',
alignItems: 'center',
gap: 5,
padding: '5px 10px',
borderRadius: 20,
background: bg,
border: `1px solid ${color}44`,
cursor: tipText ? 'help' : 'default',
}}
>
<div style={{ width: 7, height: 7, borderRadius: '50%', background: color, flexShrink: 0 }} />
<span style={{ fontSize: 12, fontWeight: 500, color: 'var(--text2)' }}>{label}</span>
<span style={{ fontSize: 12, fontWeight: 700, color }}>{value}</span>
{sub && <span style={{ fontSize: 10, color: 'var(--text3)' }}>{sub}</span>}
{tipText && (
<span style={{ fontSize: 10, color: 'var(--text3)', opacity: 0.7 }} aria-hidden>
ⓘ
</span>
)}
</div>
{tip && tipText && (
<div
role="tooltip"
onClick={() => setTip(false)}
style={{
position: 'absolute',
bottom: '110%',
left: 0,
zIndex: 50,
background: 'var(--surface)',
border: '1px solid var(--border)',
borderRadius: 8,
padding: '8px 10px',
fontSize: 11,
color: 'var(--text2)',
minWidth: 200,
maxWidth: 260,
lineHeight: 1.5,
boxShadow: '0 4px 16px rgba(0,0,0,0.15)',
}}
>
<strong>{label}</strong>
<br />
{tipText}
</div>
)}
</div>
)
}
/**
* KPI-Kachel (Dashboard-Raster).
*/
export function StatCard({
icon,
label,
value,
unit,
delta,
deltaGoodWhenNeg = false,
sub,
onClick,
color,
spanMobile = 1,
spanDesktop = 1,
}) {
const deltaColor =
delta == null
? null
: (deltaGoodWhenNeg ? delta < 0 : delta > 0)
? 'var(--accent)'
: 'var(--warn)'
const sm = clampTileSpan(spanMobile, DASHBOARD_TILE_GRID_COLS.mobile)
const lg = clampTileSpan(spanDesktop, DASHBOARD_TILE_GRID_COLS.desktop)
return (
<div
className="dashboard-stat-card"
onClick={onClick}
style={{
cursor: onClick ? 'pointer' : 'default',
'--tile-sm': String(sm),
'--tile-lg': String(lg),
}}
onMouseEnter={(e) => onClick && (e.currentTarget.style.borderColor = 'var(--accent)')}
onMouseLeave={(e) => onClick && (e.currentTarget.style.borderColor = 'var(--border)')}
>
<div style={{ fontSize: 18, marginBottom: 4 }}>{icon}</div>
<div style={{ fontSize: 11, color: 'var(--text3)', marginBottom: 2 }}>{label}</div>
<div style={{ fontSize: 19, fontWeight: 700, color: color || 'var(--text1)', lineHeight: 1.1 }}>
{value}
<span style={{ fontSize: 12, fontWeight: 400, color: 'var(--text3)', marginLeft: 2 }}>{unit}</span>
</div>
{delta != null && (
<div style={{ fontSize: 11, fontWeight: 600, color: deltaColor, marginTop: 2 }}>
{delta > 0 ? '+' : ''}
{delta} {unit}
</div>
)}
{sub && <div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 2 }}>{sub}</div>}
</div>
)
}
+29
View File
@@ -0,0 +1,29 @@
import {
clampTileSpan,
DASHBOARD_TILE_GRID_COLS
} from '../utils/dashboardLayout'
/**
* Kachel im Raster `.dashboard-tile-grid` / `.dashboard-stat-grid`.
* Standard: volle Zeile (Mobile 2/2, Desktop 4/4). Anpassbar via spanMobile / spanDesktop.
*/
export default function DashboardTile({
children,
spanMobile = DASHBOARD_TILE_GRID_COLS.mobile,
spanDesktop = DASHBOARD_TILE_GRID_COLS.desktop,
className = ''
}) {
const sm = clampTileSpan(spanMobile, DASHBOARD_TILE_GRID_COLS.mobile)
const lg = clampTileSpan(spanDesktop, DASHBOARD_TILE_GRID_COLS.desktop)
return (
<div
className={`dashboard-tile ${className}`.trim()}
style={{
'--tile-sm': String(sm),
'--tile-lg': String(lg)
}}
>
{children}
</div>
)
}
@@ -0,0 +1,86 @@
import { NavLink, useLocation } from 'react-router-dom'
import { LogOut } from 'lucide-react'
import { Avatar } from '../pages/ProfileSelect'
import { getMainNavItems } from '../config/appNav'
import { isCaptureSectionPath } from '../config/captureNav'
function sidebarLinkActive(pathname, item, routerIsActive) {
if (item.to.startsWith('/admin')) return pathname.startsWith('/admin')
if (item.to === '/capture' && isCaptureSectionPath(pathname)) return true
return routerIsActive
}
/**
* Desktop-Sidebar (≥1024px) — Sichtbarkeit via CSS (.desktop-sidebar).
*/
export default function DesktopSidebar({
isAdmin,
activeProfile,
sessionProfile,
onLogout
}) {
const loc = useLocation()
const items = getMainNavItems(isAdmin)
const tier = (activeProfile && activeProfile.tier) || sessionProfile?.tier || ''
return (
<aside className="desktop-sidebar" aria-label="Hauptnavigation">
<div className="desktop-sidebar__brand">
<div className="desktop-sidebar__logo" aria-hidden />
<div className="desktop-sidebar__title">Mitai Jinkendo</div>
</div>
<nav className="desktop-sidebar__nav">
{items.map((item) => (
<NavLink
key={item.to}
to={item.to}
end={!!item.end}
className={({ isActive }) =>
'desktop-sidebar__link' +
(sidebarLinkActive(loc.pathname, item, isActive)
? ' desktop-sidebar__link--active'
: '')
}
>
<item.Icon size={20} strokeWidth={2} />
<span>{item.label}</span>
</NavLink>
))}
</nav>
<div className="desktop-sidebar__footer">
<NavLink to="/settings" className="desktop-sidebar__user">
{activeProfile ? (
<Avatar profile={activeProfile} size={32} />
) : (
<div
style={{
width: 32,
height: 32,
borderRadius: '50%',
background: 'var(--accent)'
}}
/>
)}
<div className="desktop-sidebar__user-text">
<span className="desktop-sidebar__user-name">
{activeProfile?.name || 'Profil'}
</span>
{tier ? (
<span className="desktop-sidebar__user-tier">{tier}</span>
) : null}
</div>
</NavLink>
<button
type="button"
className="desktop-sidebar__logout"
onClick={onLogout}
title="Abmelden"
>
<LogOut size={18} />
</button>
</div>
</aside>
)
}
+78
View File
@@ -0,0 +1,78 @@
import { useState, useEffect } from 'react'
export default function EmailSettings() {
const [status, setStatus] = useState(null)
const [testTo, setTestTo] = useState('')
const [testing, setTesting] = useState(false)
const [testMsg, setTestMsg] = useState(null)
useEffect(()=>{
const token = localStorage.getItem('bodytrack_token')||''
fetch('/api/admin/email/status',{headers:{'X-Auth-Token':token}})
.then(r=>r.json()).then(setStatus)
},[])
const sendTest = async () => {
if (!testTo) return
setTesting(true); setTestMsg(null)
try {
const token = localStorage.getItem('bodytrack_token')||''
const r = await fetch('/api/admin/email/test',{
method:'POST',headers:{'Content-Type':'application/json','X-Auth-Token':token},
body:JSON.stringify({to:testTo})
})
if(!r.ok) throw new Error((await r.json()).detail)
setTestMsg('✓ Test-E-Mail gesendet!')
} catch(e){ setTestMsg('✗ Fehler: '+e.message) }
finally{ setTesting(false) }
}
return (
<div className="card section-gap" style={{marginTop:0}}>
<div style={{fontWeight:700,fontSize:14,marginBottom:10,display:'flex',alignItems:'center',gap:6}}>
📧 E-Mail Konfiguration (SMTP)
</div>
{!status ? <div className="spinner" style={{width:16,height:16}}/> : (
<>
<div style={{padding:'8px 12px',borderRadius:8,marginBottom:12,
background:status.configured?'var(--accent-light)':'var(--warn-bg)',
fontSize:12,color:status.configured?'var(--accent-dark)':'var(--warn-text)'}}>
{status.configured
? <>✓ Konfiguriert: <strong>{status.smtp_user}</strong> via {status.smtp_host}</>
: <>⚠️ Nicht konfiguriert. SMTP-Einstellungen in der <code>.env</code> Datei setzen.</>}
</div>
{status.configured && (
<>
<div style={{fontSize:11,color:'var(--text3)',marginBottom:10,lineHeight:1.5}}>
<strong>App-URL:</strong> {status.app_url}<br/>
<span style={{fontSize:10}}>Für korrekte Links in E-Mails (z.B. Recovery-Links). In .env als APP_URL setzen.</span>
</div>
<div style={{display:'flex',gap:8}}>
<input type="email" className="form-input" placeholder="test@beispiel.de"
value={testTo} onChange={e=>setTestTo(e.target.value)} style={{flex:1}}/>
<button className="btn btn-secondary" onClick={sendTest} disabled={testing}>
{testing?'…':'Test'}
</button>
</div>
{testMsg && <div style={{fontSize:12,marginTop:6,
color:testMsg.startsWith('✓')?'var(--accent)':'#D85A30'}}>{testMsg}</div>}
</>
)}
{!status.configured && (
<div style={{fontSize:11,color:'var(--text3)',lineHeight:1.6}}>
Füge folgende Zeilen zur <code>.env</code> Datei hinzu:<br/>
<code style={{background:'var(--surface2)',padding:'6px 8px',borderRadius:4,
display:'block',marginTop:6,fontSize:11}}>
SMTP_HOST=smtp.gmail.com<br/>
SMTP_PORT=587<br/>
SMTP_USER=deine@gmail.com<br/>
SMTP_PASS=dein_app_passwort<br/>
APP_URL=http://192.168.2.49:3002
</code>
</div>
)}
</>
)}
</div>
)
}
@@ -0,0 +1,113 @@
import { useState, useEffect } from 'react'
import { Check } from 'lucide-react'
import dayjs from 'dayjs'
import { api } from '../utils/api'
/**
* Tagesgewicht erfassen (wie Dashboard „Gewicht heute“).
*/
export default function QuickWeightEntry({ onSaved }) {
const [input, setInput] = useState('')
const [saving, setSaving] = useState(false)
const [saved, setSaved] = useState(false)
const [error, setError] = useState(null)
const [weightUsage, setWeightUsage] = useState(null)
const today = dayjs().format('YYYY-MM-DD')
const loadUsage = () => {
api
.getFeatureUsage()
.then((features) => {
const weightFeature = features.find((f) => f.feature_id === 'weight_entries')
setWeightUsage(weightFeature)
})
.catch((err) => console.error('Failed to load usage:', err))
}
useEffect(() => {
api.weightStats().then((s) => {
if (s?.latest?.date === today) setInput(String(s.latest.weight))
})
loadUsage()
}, [today])
const handleSave = async () => {
const w = parseFloat(input)
if (!w || w < 20 || w > 300) return
setSaving(true)
setError(null)
try {
await api.upsertWeight(today, w)
setSaved(true)
await loadUsage()
onSaved?.()
setTimeout(() => setSaved(false), 2000)
} catch (err) {
console.error('Save failed:', err)
setError(err.message || 'Fehler beim Speichern')
setTimeout(() => setError(null), 5000)
} finally {
setSaving(false)
}
}
const isDisabled = saving || !input || (weightUsage && !weightUsage.allowed)
const tooltipText =
weightUsage && !weightUsage.allowed
? `Limit erreicht (${weightUsage.used}/${weightUsage.limit}). Kontaktiere den Admin oder warte bis zum nächsten Reset.`
: ''
return (
<div>
{error && (
<div
style={{
padding: '8px 10px',
background: 'var(--danger-bg)',
border: '1px solid var(--danger)',
borderRadius: 8,
fontSize: 12,
color: 'var(--danger)',
marginBottom: 8,
}}
>
{error}
</div>
)}
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<input
type="number"
min={20}
max={300}
step={0.1}
className="form-input"
style={{ flex: 1, fontSize: 17, fontWeight: 600, textAlign: 'center' }}
placeholder="kg eingeben"
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && !isDisabled && handleSave()}
/>
<span style={{ fontSize: 13, color: 'var(--text3)' }}>kg</span>
<div title={tooltipText} style={{ display: 'inline-block' }}>
<button
type="button"
className="btn btn-primary"
style={{ padding: '8px 14px', cursor: isDisabled ? 'not-allowed' : 'pointer' }}
onClick={handleSave}
disabled={isDisabled}
>
{saved ? (
<Check size={15} />
) : saving ? (
<div className="spinner" style={{ width: 14, height: 14 }} />
) : weightUsage && !weightUsage.allowed ? (
'🔒 Limit'
) : (
'Speichern'
)}
</button>
</div>
</div>
</div>
)
}
@@ -15,8 +15,10 @@ export default function TrainingTypeDistribution({ days = 28 }) {
const [loading, setLoading] = useState(true)
useEffect(() => {
const safeDays = Math.max(1, Math.min(4000, Number(days) || 28))
const limit = Math.min(50_000, Math.max(250, safeDays * 25))
Promise.all([
api.listActivity(days),
api.listActivity(limit, safeDays),
api.getTrainingCategories()
]).then(([activities, cats]) => {
setCategories(cats)
@@ -43,7 +45,7 @@ export default function TrainingTypeDistribution({ days = 28 }) {
console.error('Failed to load training type distribution:', err)
setLoading(false)
})
}, [days, activeProfile?.quality_filter_level]) // Issue #31: Reload when quality filter changes
}, [days, activeProfile?.quality_filter_level, activeProfile?.id])
if (loading) {
return (
@@ -0,0 +1,183 @@
import {
LineChart,
Line,
XAxis,
YAxis,
Tooltip,
ResponsiveContainer,
CartesianGrid,
} from 'recharts'
import dayjs from 'dayjs'
import 'dayjs/locale/de'
dayjs.locale('de')
function rollingAvg(arr, key, w = 7) {
return arr.map((d, i) => {
const s = arr
.slice(Math.max(0, i - w + 1), i + 1)
.map((x) => x[key])
.filter((v) => v != null)
return s.length
? {
...d,
[`${key}_avg`]: Math.round((s.reduce((a, b) => a + b) / s.length) * 10) / 10,
}
: d
})
}
/**
* Kalorien + Gewicht im Zeitfenster (wie Dashboard-Trends).
* @param {{ weights: any[], nutrition: any[], windowDays?: number }} props
*/
export default function TrendKcalWeightChart({ weights, nutrition, windowDays = 30 }) {
const n = Math.max(7, Math.min(90, Number(windowDays) || 30))
const days = []
for (let i = n - 1; i >= 0; i--) days.push(dayjs().subtract(i, 'day').format('YYYY-MM-DD'))
const wMap = {}
;(weights || []).forEach((w) => {
wMap[w.date] = w.weight
})
const nMap = {}
;(nutrition || []).forEach((x) => {
nMap[x.date] = Math.round(x.kcal || 0)
})
let lastW = null
const combined = days
.map((date) => {
if (wMap[date]) lastW = wMap[date]
return {
date: dayjs(date).format('DD.MM'),
kcal: nMap[date] || null,
weight: wMap[date] || null,
weightLine: lastW,
}
})
.filter((d) => d.kcal || d.weightLine)
const withAvg = rollingAvg(combined, 'kcal')
const hasKcal = combined.some((d) => d.kcal)
const hasW = combined.some((d) => d.weightLine)
if (!hasKcal && !hasW) {
return (
<div style={{ padding: 20, textAlign: 'center', fontSize: 12, color: 'var(--text3)' }}>
Mehr Ernährungs- und Gewichtsdaten für den Chart nötig
</div>
)
}
return (
<ResponsiveContainer width="100%" height={160}>
<LineChart data={withAvg} margin={{ top: 4, right: 8, bottom: 0, left: -20 }}>
<CartesianGrid stroke="var(--border)" strokeDasharray="3 3" />
<XAxis
dataKey="date"
tick={{ fontSize: 9, fill: 'var(--text3)' }}
tickLine={false}
interval={Math.max(0, Math.floor(withAvg.length / 6) - 1)}
/>
{hasKcal && (
<YAxis
yAxisId="kcal"
tick={{ fontSize: 9, fill: 'var(--text3)' }}
tickLine={false}
domain={['auto', 'auto']}
/>
)}
{hasW && (
<YAxis
yAxisId="weight"
orientation="right"
tick={{ fontSize: 9, fill: 'var(--text3)' }}
tickLine={false}
domain={['auto', 'auto']}
/>
)}
<Tooltip
contentStyle={{
background: 'var(--surface)',
border: '1px solid var(--border)',
borderRadius: 8,
fontSize: 11,
}}
formatter={(v, name) => [
v == null ? '–' : `${Math.round(v)} ${name === 'weightLine' || name === 'weight' ? 'kg' : 'kcal'}`,
name === 'kcal_avg'
? 'Ø Kalorien (7T)'
: name === 'kcal'
? 'Kalorien'
: name === 'weightLine'
? 'Gewicht (interpoliert)'
: 'Gewicht Messung',
]}
/>
{hasKcal && (
<Line
yAxisId="kcal"
type="monotone"
dataKey="kcal"
stroke="#EF9F2744"
strokeWidth={1}
dot={false}
connectNulls={false}
/>
)}
{hasKcal && (
<Line
yAxisId="kcal"
type="monotone"
dataKey="kcal_avg"
stroke="#EF9F27"
strokeWidth={2}
dot={false}
connectNulls
name="kcal_avg"
/>
)}
{hasW && (
<Line
yAxisId="weight"
type="monotone"
dataKey="weightLine"
stroke="#378ADD88"
strokeWidth={1.5}
dot={false}
connectNulls
name="weightLine"
/>
)}
{hasW && (
<Line
yAxisId="weight"
type="monotone"
dataKey="weight"
stroke="#378ADD"
strokeWidth={0}
dot={(props) => {
const { cx, cy, value } = props
return value != null ? (
<circle
key={cx}
cx={cx}
cy={cy}
r={4}
fill="#378ADD"
stroke="white"
strokeWidth={1.5}
/>
) : (
<g key={cx} />
)
}}
connectNulls={false}
name="weight"
/>
)}
</LineChart>
</ResponsiveContainer>
)
}
@@ -0,0 +1,107 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Brain } from 'lucide-react'
import dayjs from 'dayjs'
import 'dayjs/locale/de'
import { api } from '../../utils/api'
import Markdown from '../../utils/Markdown'
dayjs.locale('de')
export default function AiPipelineInsightWidget({ refreshTick = 0 }) {
const nav = useNavigate()
const [insights, setInsights] = useState([])
const [showInsight, setShowInsight] = useState(false)
const [pipelineLoading, setPipelineLoading] = useState(false)
const [pipelineError, setPipelineError] = useState(null)
const load = () =>
api.latestInsights().then((ins) => setInsights(Array.isArray(ins) ? ins : [])).catch(() => setInsights([]))
useEffect(() => {
load()
}, [refreshTick])
const runPipeline = async () => {
setPipelineLoading(true)
setPipelineError(null)
try {
await api.insightPipeline()
await load()
} catch (e) {
setPipelineError(`Fehler: ${e.message}`)
} finally {
setPipelineLoading(false)
}
}
const latestInsight = insights.find((i) => i.scope === 'gesamt') || insights[0]
return (
<div className="card section-gap" style={{ marginBottom: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text1)' }}>KI-Auswertung</div>
<button type="button" className="btn btn-secondary" style={{ fontSize: 11, padding: '4px 10px' }} onClick={() => nav('/analysis')}>
<Brain size={11} /> Analysen →
</button>
</div>
<button type="button" className="btn btn-primary btn-full" style={{ marginBottom: 10 }} onClick={runPipeline} disabled={pipelineLoading}>
{pipelineLoading ? (
<>
<div className="spinner" style={{ width: 13, height: 13 }} /> Analyse läuft… (3 Stufen)
</>
) : (
<>
<Brain size={13} /> 🔬 Mehrstufige Analyse starten
</>
)}
</button>
{pipelineError && <div style={{ fontSize: 12, color: '#D85A30', marginBottom: 8 }}>{pipelineError}</div>}
{latestInsight ? (
<>
<div style={{ fontSize: 11, color: 'var(--text3)', marginBottom: 6 }}>
Letzte Analyse: {dayjs(latestInsight.created).format('DD. MMMM YYYY, HH:mm')}
</div>
<div style={{ maxHeight: showInsight ? 'none' : 120, overflow: 'hidden', position: 'relative' }}>
<Markdown text={latestInsight.content} />
{!showInsight && (
<div
style={{
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
height: 40,
background: 'linear-gradient(transparent,var(--surface))',
}}
/>
)}
</div>
<button
type="button"
style={{
background: 'none',
border: 'none',
cursor: 'pointer',
fontSize: 12,
color: 'var(--accent)',
marginTop: 6,
padding: 0,
}}
onClick={() => setShowInsight((s) => !s)}
>
{showInsight ? '▲ Weniger anzeigen' : '▼ Vollständig anzeigen'}
</button>
</>
) : (
<div style={{ fontSize: 13, color: 'var(--text3)', padding: '8px 0' }}>
Noch keine KI-Auswertung vorhanden.
<button type="button" className="btn btn-primary" style={{ marginTop: 8, display: 'block', fontSize: 12 }} onClick={() => nav('/analysis')}>
Erste Analyse erstellen
</button>
</div>
)}
</div>
)
}
@@ -0,0 +1,108 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import dayjs from 'dayjs'
import { api } from '../../utils/api'
import { useProfile } from '../../context/ProfileContext'
import { getBfCategory } from '../../utils/calc'
import { StatCard } from '../DashboardStatKit'
import { dashboardStatGridClassName, DASHBOARD_TILE_GRID_COLS } from '../../utils/dashboardLayout'
export default function BodyStatStripWidget({ refreshTick = 0 }) {
const nav = useNavigate()
const { activeProfile } = useProfile()
const sex = activeProfile?.sex || 'm'
const [weights, setWeights] = useState([])
const [calipers, setCalipers] = useState([])
const [nutrition, setNutrition] = useState([])
useEffect(() => {
Promise.all([api.listWeight(60), api.listCaliper(3), api.listNutrition(30)])
.then(([w, ca, n]) => {
setWeights(w)
setCalipers(ca)
setNutrition(n)
})
.catch(() => {
setWeights([])
setCalipers([])
setNutrition([])
})
}, [refreshTick])
const latestW = weights[0]
const prevW = weights[1]
const latestCal = calipers[0]
const wDelta = latestW && prevW ? Math.round((latestW.weight - prevW.weight) * 10) / 10 : null
const bfCat = latestCal?.body_fat_pct ? getBfCategory(latestCal.body_fat_pct, sex) : null
const bfPrev = calipers[1]?.body_fat_pct
const bfDelta =
latestCal?.body_fat_pct && bfPrev ? Math.round((latestCal.body_fat_pct - bfPrev) * 10) / 10 : null
const recentNutr = nutrition.filter((n) => n.date >= dayjs().subtract(7, 'day').format('YYYY-MM-DD'))
const avgKcal = recentNutr.length
? Math.round(recentNutr.reduce((s, n) => s + (n.kcal || 0), 0) / recentNutr.length)
: null
if (!latestW && !latestCal?.body_fat_pct && !avgKcal) {
return (
<div className="card section-gap" style={{ marginBottom: 16, fontSize: 13, color: 'var(--text3)' }}>
Noch keine Kennzahlen – erfasse Gewicht oder Körperdaten.
</div>
)
}
return (
<div className="card section-gap" style={{ marginBottom: 16 }}>
<div style={{ fontSize: 14, fontWeight: 700, marginBottom: 10, color: 'var(--text1)' }}>Kennzahlen</div>
<div className={dashboardStatGridClassName(DASHBOARD_TILE_GRID_COLS.mobile)}>
{latestW && (
<StatCard
icon="⚖️"
label="Gewicht"
value={latestW.weight}
unit="kg"
delta={wDelta}
deltaGoodWhenNeg
sub={dayjs(latestW.date).format('DD.MM.')}
onClick={() => nav('/history')}
color="#378ADD"
/>
)}
{latestCal?.body_fat_pct != null && (
<StatCard
icon="🫧"
label="Körperfett"
value={latestCal.body_fat_pct}
unit="%"
delta={bfDelta}
deltaGoodWhenNeg
sub={bfCat?.label}
onClick={() => nav('/history', { state: { tab: 'body' } })}
color={bfCat?.color}
/>
)}
{latestCal?.lean_mass != null && (
<StatCard
icon="💪"
label="Magermasse"
value={latestCal.lean_mass}
unit="kg"
sub={latestCal.date ? dayjs(latestCal.date).format('DD.MM.') : '–'}
onClick={() => nav('/history', { state: { tab: 'body' } })}
/>
)}
{avgKcal != null && (
<StatCard
icon="🍽️"
label="Ø Kalorien"
value={avgKcal}
unit="kcal"
sub="letzte 7 Tage"
onClick={() => nav('/history', { state: { tab: 'nutrition' } })}
color="#EF9F27"
/>
)}
</div>
</div>
)
}
@@ -0,0 +1,34 @@
import { useEffect, useState } from 'react'
import dayjs from 'dayjs'
import 'dayjs/locale/de'
import { useProfile } from '../../context/ProfileContext'
import { api } from '../../utils/api'
dayjs.locale('de')
/** Produkt-Dashboard: Begrüßung + Datum + letztes Gewicht-Datum */
export default function DashboardGreetingWidget({ refreshTick = 0 }) {
const { activeProfile } = useProfile()
const [latestWeightDate, setLatestWeightDate] = useState(null)
useEffect(() => {
api
.listWeight(1)
.then((rows) => {
setLatestWeightDate(rows?.[0]?.date || null)
})
.catch(() => setLatestWeightDate(null))
}, [refreshTick])
return (
<div className="card section-gap" style={{ marginBottom: 16 }}>
<h2 style={{ fontSize: 22, fontWeight: 800, margin: 0, color: 'var(--text1)' }}>
Hallo, {activeProfile?.name || 'Nutzer'} 👋
</h2>
<div style={{ fontSize: 12, color: 'var(--text3)', marginTop: 2 }}>
{dayjs().format('dddd, DD. MMMM YYYY')}
{latestWeightDate && ` · Letztes Update ${dayjs(latestWeightDate).format('DD.MM.')}`}
</div>
</div>
)
}
@@ -0,0 +1,47 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useProfile } from '../../context/ProfileContext'
import { api } from '../../utils/api'
export default function GoalsFocusTeaserWidget({ refreshTick = 0 }) {
const nav = useNavigate()
const { activeProfile } = useProfile()
const [goalsCount, setGoalsCount] = useState(null)
useEffect(() => {
if (!activeProfile?.id) return
api
.listGoals()
.then((list) => setGoalsCount(Array.isArray(list) ? list.length : 0))
.catch(() => setGoalsCount(null))
}, [activeProfile?.id, refreshTick])
return (
<div className="card section-gap" style={{ marginBottom: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text1)' }}>Ziele &amp; Fokus</div>
<button type="button" className="btn btn-secondary" style={{ fontSize: 12, padding: '6px 12px' }} onClick={() => nav('/goals')}>
Bearbeiten →
</button>
</div>
<div
style={{ cursor: 'pointer' }}
role="button"
tabIndex={0}
onKeyDown={(e) => e.key === 'Enter' && nav('/goals')}
onClick={() => nav('/goals')}
>
{goalsCount != null && (
<div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text1)', marginBottom: 8 }}>
{goalsCount === 0
? 'Noch keine Ziele angelegt.'
: `${goalsCount} ${goalsCount === 1 ? 'Ziel' : 'Ziele'} im System.`}
</div>
)}
<div style={{ fontSize: 12, color: 'var(--text2)' }}>
Focus Areas und Fortschritt – tippen zum Öffnen der Ziele-Seite.
</div>
</div>
</div>
)
}
@@ -0,0 +1,115 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import dayjs from 'dayjs'
import { api } from '../../utils/api'
import {
dashboardTileGridClassName,
DASHBOARD_TILE_GRID_COLS,
} from '../../utils/dashboardLayout'
import DashboardTile from '../DashboardTile'
export default function NutritionActivitySummaryWidget({ refreshTick = 0 }) {
const nav = useNavigate()
const [nutrition, setNutrition] = useState([])
const [activities, setActivities] = useState([])
const [latestWeight, setLatestWeight] = useState(null)
useEffect(() => {
Promise.all([api.listNutrition(30), api.listActivity(800, 30), api.listWeight(1)])
.then(([n, a, w]) => {
setNutrition(n)
setActivities(a)
setLatestWeight(w?.[0]?.weight ?? null)
})
.catch(() => {
setNutrition([])
setActivities([])
setLatestWeight(null)
})
}, [refreshTick])
const recentNutr = nutrition.filter((n) => n.date >= dayjs().subtract(7, 'day').format('YYYY-MM-DD'))
const avgKcal = recentNutr.length
? Math.round(recentNutr.reduce((s, n) => s + (n.kcal || 0), 0) / recentNutr.length)
: null
const avgProtein = recentNutr.length
? Math.round(recentNutr.reduce((s, n) => s + (n.protein_g || 0), 0) / recentNutr.length * 10) / 10
: null
const ptLow = Math.round((latestWeight || 80) * 1.6)
const proteinOk = avgProtein && avgProtein >= ptLow
const recentAct = activities.filter((a) => a.date >= dayjs().subtract(7, 'day').format('YYYY-MM-DD'))
const actKcal = recentAct.length ? Math.round(recentAct.reduce((s, a) => s + (a.kcal_active || 0), 0)) : null
const showNutr = !!(avgKcal || avgProtein)
const showAct = actKcal != null
if (!showNutr && !showAct) {
return (
<div className="card section-gap" style={{ marginBottom: 16, fontSize: 13, color: 'var(--text3)' }}>
Noch keine Ernährungs- oder Aktivitätsdaten (7 Tage).
</div>
)
}
const summaryBoth = showNutr && showAct
const summarySpanM = summaryBoth ? 1 : 2
const summarySpanD = summaryBoth ? 2 : 4
return (
<div className="card section-gap" style={{ marginBottom: 16 }}>
<div style={{ fontSize: 14, fontWeight: 700, marginBottom: 10, color: 'var(--text1)' }}>
Ernährung &amp; Aktivität
</div>
<div className={`dashboard-summary-row ${dashboardTileGridClassName(DASHBOARD_TILE_GRID_COLS.mobile)}`}>
{showNutr && (
<DashboardTile spanMobile={summarySpanM} spanDesktop={summarySpanD}>
<div
className="card"
style={{ cursor: 'pointer', height: '100%' }}
role="button"
tabIndex={0}
onKeyDown={(e) => e.key === 'Enter' && nav('/history', { state: { tab: 'nutrition' } })}
onClick={() => nav('/history', { state: { tab: 'nutrition' } })}
>
<div style={{ fontWeight: 600, fontSize: 12, marginBottom: 8, color: 'var(--text3)' }}>
🍽️ ERNÄHRUNG (Ø 7T)
</div>
{avgKcal != null && <div style={{ fontSize: 16, fontWeight: 700, color: '#EF9F27' }}>{avgKcal} kcal</div>}
{avgProtein != null && (
<div
style={{
fontSize: 13,
fontWeight: 600,
color: proteinOk ? 'var(--accent)' : 'var(--warn)',
}}
>
{avgProtein}g Protein {proteinOk ? '✓' : '⚠️'}
</div>
)}
<div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 4 }}>→ Verlauf Ernährung</div>
</div>
</DashboardTile>
)}
{showAct && (
<DashboardTile spanMobile={summarySpanM} spanDesktop={summarySpanD}>
<div
className="card"
style={{ cursor: 'pointer', height: '100%' }}
role="button"
tabIndex={0}
onKeyDown={(e) => e.key === 'Enter' && nav('/history', { state: { tab: 'activity' } })}
onClick={() => nav('/history', { state: { tab: 'activity' } })}
>
<div style={{ fontWeight: 600, fontSize: 12, marginBottom: 8, color: 'var(--text3)' }}>
🏋️ AKTIVITÄT (7T)
</div>
<div style={{ fontSize: 16, fontWeight: 700, color: '#EF9F27' }}>{actKcal} kcal</div>
<div style={{ fontSize: 13, color: 'var(--text2)' }}>{recentAct.length} Trainings</div>
<div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 4 }}>→ Verlauf Aktivität</div>
</div>
</DashboardTile>
)}
</div>
</div>
)
}
@@ -0,0 +1,32 @@
import { useNavigate } from 'react-router-dom'
import NutritionCharts from '../NutritionCharts'
import { normalizeBodyChartDays } from '../../widgetSystem/bodyChartDays'
/**
* Phase-0c-Ernährungscharts (wie „Detaillierte Charts“ im Verlauf).
* @param {{ refreshTick?: number, chartDays?: number }} props
*/
export default function NutritionDetailChartsWidget({ refreshTick = 0, chartDays }) {
const nav = useNavigate()
const days = chartDays != null ? normalizeBodyChartDays(chartDays) : 30
return (
<div className="card section-gap" style={{ marginBottom: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
<div>
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text1)' }}>Ernährung — Charts</div>
<div style={{ fontSize: 12, color: 'var(--text3)' }}>API-Charts · {days} Tage</div>
</div>
<button
type="button"
className="btn btn-secondary"
style={{ fontSize: 12, padding: '6px 12px' }}
onClick={() => nav('/history', { state: { tab: 'nutrition' } })}
>
Verlauf →
</button>
</div>
<NutritionCharts key={`${refreshTick}-${days}`} days={days} />
</div>
)
}
@@ -0,0 +1,109 @@
import { useEffect, useState } from 'react'
import { useProfile } from '../../context/ProfileContext'
import { getBfCategory } from '../../utils/calc'
import { api } from '../../utils/api'
/** Profil-Ziele Gewicht / Körperfett (Balken wie Dashboard) */
export default function ProfileGoalsProgressWidget({ refreshTick = 0 }) {
const { activeProfile } = useProfile()
const sex = activeProfile?.sex || 'm'
const [weights, setWeights] = useState([])
const [calipers, setCalipers] = useState([])
useEffect(() => {
Promise.all([api.listWeight(120), api.listCaliper(3)])
.then(([w, ca]) => {
setWeights(w)
setCalipers(ca)
})
.catch(() => {
setWeights([])
setCalipers([])
})
}, [refreshTick])
const latestW = weights[0]
const latestCal = calipers[0]
const bfCat = latestCal?.body_fat_pct ? getBfCategory(latestCal.body_fat_pct, sex) : null
const gw = activeProfile?.goal_weight
const gbf = activeProfile?.goal_bf_pct
if ((!gw || !latestW) && (!gbf || latestCal?.body_fat_pct == null)) return null
return (
<div className="card section-gap" style={{ marginBottom: 16 }}>
<div style={{ fontSize: 14, fontWeight: 700, marginBottom: 10, color: 'var(--text1)' }}>Profil-Ziele</div>
{gw && latestW && (
<div style={{ marginBottom: 10 }}>
{(() => {
const start = Math.max(...weights.map((w) => w.weight))
const curr = latestW.weight
const goal = gw
const total = start - goal
const done = start - curr
const pct = total > 0 ? Math.min(100, Math.round((done / total) * 100)) : 100
const remain = Math.round((curr - goal) * 10) / 10
return (
<>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 4 }}>
<span>
Gewicht: {curr} → {goal} kg
</span>
<span style={{ color: 'var(--accent)', fontWeight: 600 }}>
{remain > 0 ? `noch ${remain}kg` : 'Ziel erreicht! 🎉'}
</span>
</div>
<div style={{ height: 8, background: 'var(--border)', borderRadius: 4, overflow: 'hidden' }}>
<div
style={{
height: '100%',
width: `${pct}%`,
background: 'var(--accent)',
borderRadius: 4,
transition: 'width 0.5s',
}}
/>
</div>
<div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 2 }}>{pct}% des Weges</div>
</>
)
})()}
</div>
)}
{gbf && latestCal?.body_fat_pct != null && (
<div>
{(() => {
const curr = latestCal.body_fat_pct
const goal = gbf
const remain = Math.round((curr - goal) * 10) / 10
const pct =
curr <= goal ? 100 : Math.min(100, Math.round((1 - (curr - goal) / Math.max(curr - goal, 5)) * 100))
return (
<>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 4 }}>
<span>
Körperfett: {curr}% → {goal}%
</span>
<span style={{ color: 'var(--accent)', fontWeight: 600 }}>
{remain > 0 ? `noch ${remain}%` : 'Ziel erreicht! 🎉'}
</span>
</div>
<div style={{ height: 8, background: 'var(--border)', borderRadius: 4, overflow: 'hidden' }}>
<div
style={{
height: '100%',
width: `${pct}%`,
background: bfCat?.color || 'var(--accent)',
borderRadius: 4,
}}
/>
</div>
<div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 2 }}>Aktuell: {bfCat?.label}</div>
</>
)
})()}
</div>
)}
</div>
)
}
@@ -0,0 +1,86 @@
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { api } from '../../utils/api'
/**
* Fortschrittsfotos (Galerie wie Verlauf-Tab Fotos).
*/
export default function ProgressPhotosWidget({ refreshTick = 0 }) {
const nav = useNavigate()
const [photos, setPhotos] = useState([])
const [big, setBig] = useState(null)
useEffect(() => {
api.listPhotos().then(setPhotos).catch(() => setPhotos([]))
}, [refreshTick])
if (!photos.length) {
return (
<div className="card section-gap" style={{ marginBottom: 16, textAlign: 'center', padding: 24 }}>
<div style={{ fontSize: 13, color: 'var(--text3)', marginBottom: 12 }}>Noch keine Fotos.</div>
<button type="button" className="btn btn-primary" onClick={() => nav('/capture')}>
Zur Erfassung
</button>
</div>
)
}
return (
<div className="card section-gap" style={{ marginBottom: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text1)' }}>Fortschrittsfotos</div>
<button
type="button"
className="btn btn-secondary"
style={{ fontSize: 12, padding: '6px 12px' }}
onClick={() => nav('/history', { state: { tab: 'photos' } })}
>
Verlauf →
</button>
</div>
{big && (
<div
role="presentation"
style={{
position: 'fixed',
inset: 0,
background: 'rgba(0,0,0,0.9)',
zIndex: 100,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
onClick={() => setBig(null)}
>
<img src={api.photoUrl(big)} style={{ maxWidth: '100%', maxHeight: '100%', borderRadius: 8 }} alt="" />
</div>
)}
<div className="photo-grid">
{photos.map((p) => (
<div key={p.id} style={{ position: 'relative' }}>
<img
src={api.photoUrl(p.id)}
className="photo-thumb"
alt=""
onClick={() => setBig(p.id)}
/>
<div
style={{
position: 'absolute',
bottom: 4,
left: 4,
fontSize: 9,
background: 'rgba(0,0,0,0.6)',
color: 'white',
padding: '1px 4px',
borderRadius: 3,
}}
>
{p.date?.slice(0, 10) || p.created?.slice(0, 10)}
</div>
</div>
))}
</div>
</div>
)
}
@@ -0,0 +1,20 @@
import { useNavigate } from 'react-router-dom'
import QuickWeightEntry from '../QuickWeightEntry'
export default function QuickWeightTodayWidget({ onSaved }) {
const nav = useNavigate()
return (
<div className="card section-gap" style={{ marginBottom: 16 }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: 10 }}>
<div>
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text1)' }}>Gewicht heute</div>
<div style={{ fontSize: 12, color: 'var(--text3)' }}>Tageswert erfassen</div>
</div>
<button type="button" className="btn btn-secondary" style={{ fontSize: 12, padding: '6px 12px' }} onClick={() => nav('/weight')}>
Alle Einträge →
</button>
</div>
<QuickWeightEntry onSaved={onSaved} />
</div>
)
}
@@ -0,0 +1,32 @@
import { useNavigate } from 'react-router-dom'
import RecoveryCharts from '../RecoveryCharts'
import { normalizeBodyChartDays } from '../../widgetSystem/bodyChartDays'
/**
* Erholung R1–R5 (wie Verlauf Erholung).
* @param {{ refreshTick?: number, chartDays?: number }} props
*/
export default function RecoveryChartsPanelWidget({ refreshTick = 0, chartDays }) {
const nav = useNavigate()
const days = chartDays != null ? normalizeBodyChartDays(chartDays) : 28
return (
<div className="card section-gap" style={{ marginBottom: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
<div>
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text1)' }}>Erholung — Charts</div>
<div style={{ fontSize: 12, color: 'var(--text3)' }}>Schlaf, Recovery, Vitalwerte · {days} Tage</div>
</div>
<button
type="button"
className="btn btn-secondary"
style={{ fontSize: 12, padding: '6px 12px' }}
onClick={() => nav('/history', { state: { tab: 'recovery' } })}
>
Verlauf →
</button>
</div>
<RecoveryCharts key={`${refreshTick}-${days}`} days={days} />
</div>
)
}
@@ -0,0 +1,20 @@
import DashboardTile from '../DashboardTile'
import SleepWidget from '../SleepWidget'
import RestDaysWidget from '../RestDaysWidget'
import { dashboardTileGridClassName, DASHBOARD_TILE_GRID_COLS } from '../../utils/dashboardLayout'
export default function RecoverySleepRestWidget() {
return (
<div className="card section-gap" style={{ marginBottom: 16 }}>
<div style={{ fontSize: 14, fontWeight: 700, marginBottom: 10, color: 'var(--text1)' }}>Erholung</div>
<div className={`dashboard-erholung-grid ${dashboardTileGridClassName(DASHBOARD_TILE_GRID_COLS.mobile)}`}>
<DashboardTile spanMobile={1} spanDesktop={2}>
<SleepWidget />
</DashboardTile>
<DashboardTile spanMobile={1} spanDesktop={2}>
<RestDaysWidget />
</DashboardTile>
</div>
</div>
)
}
@@ -0,0 +1,89 @@
import { useEffect, useState } from 'react'
import dayjs from 'dayjs'
import { api } from '../../utils/api'
import { useProfile } from '../../context/ProfileContext'
import { getBfCategory } from '../../utils/calc'
import { Pill } from '../DashboardStatKit'
/** WHR, WHtR, Protein Ø7T, KF – wie Dashboard-Pill-Leiste */
export default function StatusPillsWidget({ refreshTick = 0 }) {
const { activeProfile } = useProfile()
const sex = activeProfile?.sex || 'm'
const height = activeProfile?.height || 178
const [weights, setWeights] = useState([])
const [calipers, setCalipers] = useState([])
const [circs, setCircs] = useState([])
const [nutrition, setNutrition] = useState([])
useEffect(() => {
Promise.all([api.listWeight(2), api.listCaliper(3), api.listCirc(2), api.listNutrition(30)])
.then(([w, ca, ci, n]) => {
setWeights(w)
setCalipers(ca)
setCircs(ci)
setNutrition(n)
})
.catch(() => {
setWeights([])
setCalipers([])
setCircs([])
setNutrition([])
})
}, [refreshTick])
const latestCal = calipers[0]
const latestCir = circs[0]
const latestW = weights[0]
const recentNutr = nutrition.filter((n) => n.date >= dayjs().subtract(7, 'day').format('YYYY-MM-DD'))
const avgProtein = recentNutr.length
? Math.round(recentNutr.reduce((s, n) => s + (n.protein_g || 0), 0) / recentNutr.length * 10) / 10
: null
const ptLow = Math.round((latestW?.weight || 80) * 1.6)
const proteinOk = avgProtein && avgProtein >= ptLow
const whr =
latestCir?.c_waist && latestCir?.c_hip
? Math.round((latestCir.c_waist / latestCir.c_hip) * 100) / 100
: null
const whtr =
latestCir?.c_waist && height ? Math.round((latestCir.c_waist / height) * 100) / 100 : null
const bfCat = latestCal?.body_fat_pct ? getBfCategory(latestCal.body_fat_pct, sex) : null
const pills = []
if (whr)
pills.push({
label: 'WHR',
value: whr,
status: whr < (sex === 'm' ? 0.9 : 0.85) ? 'good' : 'warn',
sub: `<${sex === 'm' ? '0,90' : '0,85'}`,
})
if (whtr) pills.push({ label: 'WHtR', value: whtr, status: whtr < 0.5 ? 'good' : 'warn', sub: '<0,50' })
if (avgProtein)
pills.push({
label: 'Protein Ø7T',
value: `${avgProtein}g`,
status: proteinOk ? 'good' : 'warn',
sub: `Ziel ${ptLow}g`,
})
if (bfCat && latestCal?.body_fat_pct != null)
pills.push({
label: 'KF',
value: `${latestCal.body_fat_pct}%`,
status: latestCal.body_fat_pct < (sex === 'm' ? 18 : 25) ? 'good' : 'warn',
sub: bfCat.label,
})
if (pills.length === 0) return null
return (
<div className="card section-gap" style={{ marginBottom: 16 }}>
<div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text3)', marginBottom: 8 }}>Indikatoren</div>
<div className="dashboard-pill-row">
{pills.map((p, i) => (
<Pill key={i} {...p} />
))}
</div>
</div>
)
}
@@ -0,0 +1,95 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { api } from '../../utils/api'
import TrendKcalWeightChart from '../TrendKcalWeightChart'
import { normalizeBodyChartDays } from '../../widgetSystem/bodyChartDays'
/**
* @param {{ refreshTick?: number, chartDays?: number }} props
*/
export default function TrendKcalWeightWidget({ refreshTick = 0, chartDays }) {
const nav = useNavigate()
const windowDays = chartDays != null ? normalizeBodyChartDays(chartDays) : 30
const fetchNutritionDays = Math.max(windowDays, 30)
const [weights, setWeights] = useState([])
const [nutrition, setNutrition] = useState([])
useEffect(() => {
Promise.all([api.listWeight(Math.max(60, windowDays + 30)), api.listNutrition(fetchNutritionDays)])
.then(([w, n]) => {
setWeights(w)
setNutrition(n)
})
.catch(() => {
setWeights([])
setNutrition([])
})
}, [refreshTick, windowDays, fetchNutritionDays])
if (weights.length <= 2 && nutrition.length <= 2) {
return (
<div className="card section-gap" style={{ marginBottom: 16, fontSize: 13, color: 'var(--text3)' }}>
Mehr Gewichts- und Ernährungsdaten für den Trend nötig.
</div>
)
}
return (
<div className="card section-gap" style={{ marginBottom: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
<div>
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text1)' }}>Trends</div>
<div style={{ fontSize: 12, color: 'var(--text3)' }}>
Kalorien und Gewicht ({windowDays} Tage)
</div>
</div>
<button
type="button"
className="btn btn-secondary"
style={{ fontSize: 12, padding: '6px 12px' }}
onClick={() => nav('/history', { state: { tab: 'body' } })}
>
Details →
</button>
</div>
<TrendKcalWeightChart weights={weights} nutrition={nutrition} windowDays={windowDays} />
<div
style={{
display: 'flex',
gap: 16,
justifyContent: 'center',
marginTop: 6,
fontSize: 10,
color: 'var(--text3)',
}}
>
<span>
<span
style={{
display: 'inline-block',
width: 12,
height: 2,
background: '#EF9F27',
verticalAlign: 'middle',
marginRight: 3,
}}
/>
Ø Kalorien
</span>
<span>
<span
style={{
display: 'inline-block',
width: 12,
height: 2,
background: '#378ADD',
verticalAlign: 'middle',
marginRight: 3,
}}
/>
Gewicht
</span>
</div>
</div>
)
}
@@ -0,0 +1,132 @@
import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import dayjs from 'dayjs'
import { api } from '../../utils/api'
import { useProfile } from '../../context/ProfileContext'
import TrainingTypeDistribution from '../TrainingTypeDistribution'
import {
BODY_CHART_DAYS_DEFAULT,
normalizeBodyChartDays,
} from '../../widgetSystem/bodyChartDays'
import PilotRuleCard from './PilotRuleCard'
export default function PilotActivitySection({ refreshTick = 0, chartDays = BODY_CHART_DAYS_DEFAULT }) {
const periodDays = normalizeBodyChartDays(chartDays)
const { activeProfile } = useProfile()
const globalQualityLevel = activeProfile?.quality_filter_level
const [activities, setActivities] = useState([])
const [loading, setLoading] = useState(true)
useEffect(() => {
let cancelled = false
;(async () => {
try {
const limit = Math.min(50_000, Math.max(200, periodDays * 25))
const a = await api.listActivity(limit, periodDays)
if (!cancelled) setActivities(Array.isArray(a) ? a : [])
} catch {
if (!cancelled) setActivities([])
} finally {
if (!cancelled) setLoading(false)
}
})()
return () => {
cancelled = true
}
}, [refreshTick, globalQualityLevel, periodDays])
const cutoff = dayjs().subtract(periodDays, 'day').format('YYYY-MM-DD')
const filtA = (activities || []).filter((d) => d.date >= cutoff)
const daysWithAct = new Set(filtA.map((a) => a.date)).size
const totalDays =
filtA.length > 0
? Math.min(periodDays, dayjs().diff(dayjs(filtA[filtA.length - 1]?.date), 'day') + 1)
: 0
const consistency = totalDays > 0 ? Math.round((daysWithAct / totalDays) * 100) : 0
const actRules = [
{
status: consistency >= 70 ? 'good' : consistency >= 40 ? 'warn' : 'bad',
icon: '📅',
category: 'Konsistenz',
title: `${consistency}% aktive Tage (${daysWithAct}/${Math.min(periodDays, totalDays || periodDays)} Tage)`,
detail:
consistency >= 70
? 'Ausgezeichnete Regelmäßigkeit.'
: consistency >= 40
? 'Ziel: 4–5 Einheiten/Woche.'
: 'Mehr Regelmäßigkeit empfohlen.',
value: `${consistency}%`,
},
]
if (loading) {
return (
<div className="card section-gap" style={{ textAlign: 'center', padding: 24 }}>
<div className="spinner" />
</div>
)
}
return (
<div className="section-gap" style={{ marginBottom: 24 }}>
<div
style={{
gridColumn: '1 / -1',
marginBottom: 12,
paddingBottom: 8,
borderBottom: '2px solid var(--border)',
}}
>
<h2 style={{ fontSize: 17, fontWeight: 700, margin: 0, color: 'var(--text1)' }}>Bereich Aktivität</h2>
<p style={{ fontSize: 12, color: 'var(--text2)', margin: '6px 0 0', lineHeight: 1.5 }}>
Trainingstyp-Verteilung {periodDays} Tage · Bewertung Konsistenz wie im Verlauf
</p>
</div>
{globalQualityLevel && globalQualityLevel !== 'all' && (
<div
style={{
marginBottom: 12,
padding: '8px 12px',
borderRadius: 8,
background: 'var(--surface2)',
border: '1px solid var(--border)',
fontSize: 12,
color: 'var(--text2)',
}}
>
Aktiver Qualitätsfilter im Profil – Aktivitätsdaten entsprechend gefiltert.
<Link to="/settings" style={{ marginLeft: 8, color: 'var(--accent)' }}>
Einstellungen
</Link>
</div>
)}
<div className="card section-gap">
<div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text3)', marginBottom: 8 }}>Trainingstyp-Verteilung</div>
<TrainingTypeDistribution days={periodDays} />
<div style={{ marginTop: 8, textAlign: 'right' }}>
<Link to="/history" state={{ tab: 'activity' }} style={{ fontSize: 12, color: 'var(--accent)' }}>
Vollständiger Verlauf Aktivität →
</Link>
</div>
</div>
<div className="card section-gap">
<div className="card-title">Bewertung · Aktivität</div>
{filtA.length === 0 ? (
<p style={{ fontSize: 13, color: 'var(--text2)', margin: 0 }}>
Noch keine Aktivitäten.{' '}
<Link to="/activity" style={{ color: 'var(--accent)' }}>
Training erfassen
</Link>
</p>
) : (
actRules.map((item, i) => <PilotRuleCard key={i} item={item} />)
)}
</div>
</div>
)
}
@@ -0,0 +1,230 @@
import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import {
LineChart,
Line,
XAxis,
YAxis,
Tooltip,
ResponsiveContainer,
CartesianGrid,
ReferenceLine,
} from 'recharts'
import { ChevronRight } from 'lucide-react'
import dayjs from 'dayjs'
import { api } from '../../utils/api'
import { useProfile } from '../../context/ProfileContext'
import { getInterpretation } from '../../utils/interpret'
import { rollingAvg, fmtDate } from '../../pilot/pilotChartUtils'
import {
BODY_CHART_DAYS_DEFAULT,
normalizeBodyChartDays,
} from '../../widgetSystem/bodyChartDays'
import PilotRuleCard from './PilotRuleCard'
export default function PilotBodySection({ refreshTick = 0, chartDays = BODY_CHART_DAYS_DEFAULT }) {
const windowDays = normalizeBodyChartDays(chartDays)
const { activeProfile } = useProfile()
const [weights, setWeights] = useState([])
const [calipers, setCalipers] = useState([])
const [circs, setCircs] = useState([])
const [loading, setLoading] = useState(true)
useEffect(() => {
let cancelled = false
;(async () => {
try {
const fetchDays = Math.max(120, windowDays + 60)
const [w, ca, ci] = await Promise.all([
api.listWeight(fetchDays),
api.listCaliper(Math.max(30, windowDays)),
api.listCirc(Math.max(30, windowDays)),
])
if (!cancelled) {
setWeights(Array.isArray(w) ? w : [])
setCalipers(Array.isArray(ca) ? ca : [])
setCircs(Array.isArray(ci) ? ci : [])
}
} catch {
if (!cancelled) {
setWeights([])
setCalipers([])
setCircs([])
}
} finally {
if (!cancelled) setLoading(false)
}
})()
return () => {
cancelled = true
}
}, [refreshTick, windowDays])
const cutoff = dayjs().subtract(windowDays, 'day').format('YYYY-MM-DD')
const filtW = [...(weights || [])]
.sort((a, b) => a.date.localeCompare(b.date))
.filter((d) => d.date >= cutoff)
const filtCal = (calipers || []).filter((d) => d.date >= cutoff)
const filtCir = (circs || []).filter((d) => d.date >= cutoff)
const hasWeight = filtW.length >= 2
const latestCal = filtCal[0]
const prevCal = filtCal[1]
const latestCir = filtCir[0]
const latestW2 = filtW[filtW.length - 1]
const withAvg = rollingAvg(filtW, 'weight', 7)
const withAvg14 = rollingAvg(filtW, 'weight', 14)
const wCd = withAvg.map((d, i) => ({
date: fmtDate(d.date),
weight: d.weight,
avg7: d.weight_avg,
avg14: withAvg14[i]?.weight_avg,
}))
const ws = filtW.map((w) => w.weight)
const avgAll = ws.length ? Math.round((ws.reduce((a, b) => a + b, 0) / ws.length) * 10) / 10 : null
const combined = {
...(latestCal || {}),
c_waist: latestCir?.c_waist,
c_hip: latestCir?.c_hip,
weight: latestW2?.weight,
}
const rules = getInterpretation(combined, activeProfile || {}, prevCal || null)
if (loading) {
return (
<div className="card section-gap" style={{ textAlign: 'center', padding: 24 }}>
<div className="spinner" />
</div>
)
}
return (
<div className="section-gap" style={{ marginBottom: 24 }}>
<div
style={{
gridColumn: '1 / -1',
marginBottom: 12,
paddingBottom: 8,
borderBottom: '2px solid var(--border)',
}}
>
<h2 style={{ fontSize: 17, fontWeight: 700, margin: 0, color: 'var(--text1)' }}>Bereich Körper</h2>
<p style={{ fontSize: 12, color: 'var(--text2)', margin: '6px 0 0', lineHeight: 1.5 }}>
Fokus letzte {windowDays} Tage · Gewicht mit Ø 7 / Ø 14 Tage wie im Verlauf
</p>
</div>
{!hasWeight && (
<div className="card" style={{ padding: 20, fontSize: 13, color: 'var(--text2)' }}>
Zu wenig Gewichtsdaten für den Graph.{' '}
<Link to="/weight" style={{ color: 'var(--accent)' }}>
Gewicht erfassen
</Link>
</div>
)}
{hasWeight && (
<div className="card section-gap">
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
<div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text3)' }}>
Gewicht · {filtW.length} Messungen ({windowDays}T)
</div>
<Link to="/history" state={{ tab: 'body' }} className="btn btn-secondary" style={{ fontSize: 10, padding: '2px 8px', textDecoration: 'none' }}>
Verlauf Körper <ChevronRight size={10} />
</Link>
</div>
<ResponsiveContainer width="100%" height={200}>
<LineChart data={wCd} margin={{ top: 4, right: 8, bottom: 0, left: -20 }}>
<CartesianGrid stroke="var(--border)" strokeDasharray="3 3" />
<XAxis
dataKey="date"
tick={{ fontSize: 9, fill: 'var(--text3)' }}
tickLine={false}
interval={Math.max(0, Math.floor(wCd.length / 6) - 1)}
/>
<YAxis tick={{ fontSize: 9, fill: 'var(--text3)' }} tickLine={false} domain={['auto', 'auto']} />
{avgAll && (
<ReferenceLine
y={avgAll}
stroke="var(--text3)"
strokeDasharray="4 4"
strokeWidth={1}
label={{ value: `Ø ${avgAll}`, fontSize: 9, fill: 'var(--text3)', position: 'right' }}
/>
)}
{activeProfile?.goal_weight && (
<ReferenceLine
y={activeProfile.goal_weight}
stroke="var(--accent)"
strokeDasharray="5 3"
strokeWidth={1.5}
label={{
value: `Ziel ${activeProfile.goal_weight}kg`,
fontSize: 9,
fill: 'var(--accent)',
position: 'right',
}}
/>
)}
<Tooltip
contentStyle={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 11 }}
formatter={(v, n) => [
`${v} kg`,
n === 'weight' ? 'Täglich' : n === 'avg7' ? 'Ø 7 Tage' : 'Ø 14 Tage',
]}
/>
<Line type="monotone" dataKey="weight" stroke="#378ADD88" strokeWidth={1.5} dot={{ r: 3, fill: '#378ADD' }} name="weight" />
<Line type="monotone" dataKey="avg7" stroke="#378ADD" strokeWidth={2.5} dot={false} name="avg7" />
<Line type="monotone" dataKey="avg14" stroke="#1D9E75" strokeWidth={2} dot={false} strokeDasharray="6 3" name="avg14" />
</LineChart>
</ResponsiveContainer>
<div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 6, fontSize: 10, color: 'var(--text3)', flexWrap: 'wrap' }}>
<span>
<span style={{ display: 'inline-block', width: 12, height: 2, background: '#378ADD88', verticalAlign: 'middle', marginRight: 3 }} />
Täglich
</span>
<span>
<span style={{ display: 'inline-block', width: 12, height: 2, background: '#378ADD', verticalAlign: 'middle', marginRight: 3 }} />
Ø 7T
</span>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}>
<svg width="14" height="4">
<line x1="0" y1="2" x2="14" y2="2" stroke="#1D9E75" strokeWidth="2" strokeDasharray="5 3" />
</svg>
Ø 14T
</span>
<span>
<span
style={{
display: 'inline-block',
width: 12,
height: 2,
background: 'var(--text3)',
verticalAlign: 'middle',
marginRight: 3,
borderTop: '2px dashed',
}}
/>
Ø Zeitraum
</span>
</div>
</div>
)}
{rules.length > 0 && (
<div className="card section-gap">
<div className="card-title">Bewertung · Körper</div>
<p style={{ fontSize: 12, color: 'var(--text2)', marginTop: 4, marginBottom: 10, lineHeight: 1.5 }}>
Körperfett, Magermasse (FFMI), BMI – gleiche Logik wie auf der Verlauf-Seite (Körper).
</p>
{rules.map((item, i) => (
<PilotRuleCard key={i} item={item} />
))}
</div>
)}
</div>
)
}
@@ -0,0 +1,222 @@
import { useState, useEffect, useMemo, useCallback } from 'react'
import { Link } from 'react-router-dom'
import dayjs from 'dayjs'
import { api } from '../../utils/api'
import { getBfCategory } from '../../utils/calc'
import { useProfile } from '../../context/ProfileContext'
import { KPI_KCAL_WINDOW_DEFAULT } from '../../widgetSystem/bodyChartDays'
import { kpiTileOrderFromConfig } from '../../widgetSystem/kpiBoardTiles'
const MAX_KPI = 9
function formatRefVal(row) {
if (row.value_numeric != null && row.value_numeric !== '') {
const n = Number(row.value_numeric)
return Number.isFinite(n) ? String(n) : String(row.value_numeric)
}
return row.value_text != null ? String(row.value_text) : '–'
}
function parseRefTypeKey(tileId) {
if (!tileId.startsWith('ref:')) return null
return tileId.slice(4) || null
}
function buildAutoTileIds(refTiles, hasBf, hasKcal) {
const ids = []
for (const t of refTiles) {
if (t?.type_key) ids.push(`ref:${t.type_key}`)
}
if (hasBf) ids.push('body_fat')
if (hasKcal) ids.push('avg_kcal')
return ids.slice(0, MAX_KPI)
}
/**
* KPIs: Referenzwerte, Körperfett, Ø Kalorien — max. 9 Kacheln.
* @param {{ refreshTick?: number, kpiConfig?: Record<string, unknown> }} props
* kpiConfig.tiles: geordnete Kachel-ids; fehlend = automatische Belegung (wie bisher).
*/
export default function PilotKpiBoard({ refreshTick = 0, kpiConfig }) {
const manualOrder = useMemo(() => kpiTileOrderFromConfig(kpiConfig), [kpiConfig])
const { activeProfile } = useProfile()
const sex = activeProfile?.sex || 'm'
const [refTiles, setRefTiles] = useState([])
const [refByKey, setRefByKey] = useState(() => new Map())
const [bf, setBf] = useState(null)
const [avgKcal, setAvgKcal] = useState(null)
const [loading, setLoading] = useState(true)
const [err, setErr] = useState(null)
useEffect(() => {
let cancelled = false
;(async () => {
try {
setLoading(true)
const kcalDays = KPI_KCAL_WINDOW_DEFAULT
const nutrLimit = Math.min(2000, Math.max(60, kcalDays * 5))
const [summary, calipers, nutrition] = await Promise.all([
api.listProfileReferenceValuesSummary().catch(() => ({ tiles: [] })),
api.listCaliper(3).catch(() => []),
api.listNutrition(nutrLimit).catch(() => []),
])
if (cancelled) return
const tiles = Array.isArray(summary?.tiles) ? summary.tiles.filter((t) => t?.latest) : []
const map = new Map(tiles.map((t) => [t.type_key, t]))
const latestCal = Array.isArray(calipers) && calipers[0]?.body_fat_pct != null ? calipers[0] : null
const recentNutr = (nutrition || []).filter(
(n) => n.date >= dayjs().subtract(kcalDays, 'day').format('YYYY-MM-DD'),
)
const kcal =
recentNutr.length > 0
? Math.round(recentNutr.reduce((s, n) => s + (n.kcal || 0), 0) / recentNutr.length)
: null
const wantBf = !!latestCal?.body_fat_pct
const wantKcal = kcal != null && kcal > 0
setRefTiles(tiles)
setRefByKey(map)
setBf(
wantBf
? {
pct: latestCal.body_fat_pct,
cat: getBfCategory(latestCal.body_fat_pct, sex),
date: latestCal.date,
}
: null,
)
setAvgKcal(wantKcal ? kcal : null)
setErr(null)
} catch (e) {
if (!cancelled) {
setErr(e.message || 'KPIs konnten nicht geladen werden')
setRefTiles([])
setRefByKey(new Map())
}
} finally {
if (!cancelled) setLoading(false)
}
})()
return () => {
cancelled = true
}
}, [refreshTick, sex])
const orderIds = useMemo(() => {
if (manualOrder !== undefined) {
return manualOrder
}
const hasBf = !!bf
const hasKcal = avgKcal != null && avgKcal > 0
return buildAutoTileIds(refTiles, hasBf, hasKcal)
}, [manualOrder, refTiles, bf, avgKcal])
const pushTileForId = useCallback(
(id, out) => {
if (id === 'body_fat') {
if (!bf) return
out.push(
<div key="kpi-bf" className="card" style={{ margin: 0, padding: 12, boxSizing: 'border-box' }}>
<div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text3)' }}>Körperfett</div>
<div style={{ fontSize: 17, fontWeight: 700, marginTop: 4, color: bf.cat?.color || 'var(--text1)' }}>
{bf.pct}%
</div>
<div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 4 }}>{bf.cat?.label || 'Caliper'}</div>
</div>,
)
return
}
if (id === 'avg_kcal') {
if (avgKcal == null) return
out.push(
<div key="kpi-kcal" className="card" style={{ margin: 0, padding: 12, boxSizing: 'border-box' }}>
<div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text3)' }}>
Ø Kalorien ({KPI_KCAL_WINDOW_DEFAULT}T)
</div>
<div style={{ fontSize: 17, fontWeight: 700, marginTop: 4, color: '#EF9F27' }}>{avgKcal} kcal</div>
<div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 4 }}>Ernährung</div>
</div>,
)
return
}
const tk = parseRefTypeKey(id)
if (!tk) return
const tile = refByKey.get(tk)
if (!tile?.latest) return
const l = tile.latest
out.push(
<div key={`ref-${tk}`} className="card" style={{ margin: 0, padding: 12, boxSizing: 'border-box' }}>
<div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text3)' }}>{tile.type_label}</div>
<div style={{ fontSize: 17, fontWeight: 700, marginTop: 4 }}>
{formatRefVal(l)}
{l.unit ? (
<span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text2)', marginLeft: 4 }}>{l.unit}</span>
) : null}
</div>
<div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 4 }}>Ref.wert</div>
</div>,
)
},
[bf, avgKcal, refByKey],
)
const visibleTiles = useMemo(() => {
const out = []
for (const id of orderIds) {
pushTileForId(id, out)
}
return out
}, [orderIds, pushTileForId])
if (loading) {
return (
<div className="card section-gap" style={{ textAlign: 'center', padding: 24 }}>
<div className="spinner" />
</div>
)
}
if (err) {
return (
<div className="card section-gap" style={{ color: 'var(--danger)', fontSize: 13 }}>
{err}
</div>
)
}
if (visibleTiles.length === 0) {
return (
<div className="card section-gap">
<div className="card-title">Kennzahlen</div>
<p style={{ fontSize: 13, color: 'var(--text2)', margin: 0 }}>
Noch keine Daten oder keine passenden Kacheln.{' '}
<Link to="/settings/reference-values" style={{ color: 'var(--accent)' }}>
Referenzwerte
</Link>
,{' '}
<Link to="/caliper" style={{ color: 'var(--accent)' }}>
Caliper
</Link>
,{' '}
<Link to="/nutrition" style={{ color: 'var(--accent)' }}>
Ernährung
</Link>
.
</p>
</div>
)
}
return (
<div className="card section-gap">
<div className="card-title">Kennzahlen</div>
<p style={{ fontSize: 12, color: 'var(--text2)', marginBottom: 12, lineHeight: 1.5 }}>
{manualOrder !== undefined
? 'Ausgewählte Kacheln in festgelegter Reihenfolge (ohne Daten werden Kacheln ausgelassen).'
: `Bis ${MAX_KPI} Kacheln: Referenzwerte, Körperfett, Ø Kalorien (${KPI_KCAL_WINDOW_DEFAULT}T).`}
</p>
<div className="ref-value-tiles-grid">{visibleTiles}</div>
</div>
)
}
@@ -0,0 +1,278 @@
import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Check } from 'lucide-react'
import dayjs from 'dayjs'
import { api } from '../../utils/api'
/**
* Schnelleingabe: Gewicht + Baseline Vitals (Ruhepuls, HRV, VO₂max) für heute.
* @param {{ onSaved?: () => void, captureConfig?: Record<string, unknown> }} props
* captureConfig: show_weight, show_resting_hr, show_hrv, show_vo2_max (false = ausblenden; fehlend = true)
*/
export default function PilotQuickCapture({ onSaved, captureConfig }) {
const cfgRaw = captureConfig && typeof captureConfig === 'object' ? captureConfig : {}
const showWeight = cfgRaw.show_weight !== false
const showRestingHr = cfgRaw.show_resting_hr !== false
const showHrv = cfgRaw.show_hrv !== false
const showVo2 = cfgRaw.show_vo2_max !== false
const showVitalsBlock = showRestingHr || showHrv || showVo2
const today = dayjs().format('YYYY-MM-DD')
const [weightInput, setWeightInput] = useState('')
const [weightSaving, setWeightSaving] = useState(false)
const [weightSaved, setWeightSaved] = useState(false)
const [weightErr, setWeightErr] = useState(null)
const [vForm, setVForm] = useState({
id: null,
resting_hr: '',
hrv: '',
vo2_max: '',
})
const [vSaving, setVSaving] = useState(false)
const [vErr, setVErr] = useState(null)
const [vOk, setVOk] = useState(false)
useEffect(() => {
api.weightStats().then((s) => {
if (s?.latest?.date === today) setWeightInput(String(s.latest.weight))
}).catch(() => {})
}, [today])
useEffect(() => {
let cancelled = false
;(async () => {
try {
const existing = await api.getBaselineByDate(today)
if (cancelled || !existing?.id) return
setVForm({
id: existing.id,
resting_hr: existing.resting_hr != null ? String(existing.resting_hr) : '',
hrv: existing.hrv != null ? String(existing.hrv) : '',
vo2_max: existing.vo2_max != null ? String(existing.vo2_max) : '',
})
} catch (err) {
const msg = String(err?.message || '')
if (msg.includes('404') || msg.toLowerCase().includes('nicht gefunden')) {
setVForm((f) => ({ ...f, id: null, resting_hr: '', hrv: '', vo2_max: '' }))
}
}
})()
return () => {
cancelled = true
}
}, [today])
const saveWeight = async () => {
const w = parseFloat(weightInput)
if (!w || w < 20 || w > 300) return
setWeightSaving(true)
setWeightErr(null)
try {
await api.upsertWeight(today, w)
setWeightSaved(true)
onSaved?.()
setTimeout(() => setWeightSaved(false), 2000)
} catch (e) {
setWeightErr(e.message || 'Fehler')
} finally {
setWeightSaving(false)
}
}
const saveVitals = async () => {
setVSaving(true)
setVErr(null)
setVOk(false)
try {
const payload = { date: today }
if (showRestingHr && vForm.resting_hr) payload.resting_hr = parseInt(vForm.resting_hr, 10)
if (showHrv && vForm.hrv) payload.hrv = parseInt(vForm.hrv, 10)
if (showVo2 && vForm.vo2_max) payload.vo2_max = parseFloat(vForm.vo2_max)
if (!payload.resting_hr && !payload.hrv && !payload.vo2_max) {
const hint = [showRestingHr && 'Ruhepuls', showHrv && 'HRV', showVo2 && 'VO₂max'].filter(Boolean).join(', ')
setVErr(
hint
? `Mindestens einen sichtbaren Wert angeben (${hint}).`
: 'Keine Vitalfelder sichtbar.'
)
setVSaving(false)
return
}
if (vForm.id) {
await api.updateBaseline(vForm.id, payload)
} else {
const created = await api.createBaseline(payload)
if (created?.id) setVForm((f) => ({ ...f, id: created.id }))
}
setVOk(true)
onSaved?.()
setTimeout(() => setVOk(false), 2000)
} catch (e) {
setVErr(e.message || 'Speichern fehlgeschlagen')
} finally {
setVSaving(false)
}
}
const cellStyle = {
flex: '1 1 140px',
minWidth: 0,
padding: 12,
borderRadius: 10,
border: '1px solid var(--border)',
background: 'var(--surface2)',
}
if (!showWeight && !showVitalsBlock) {
return (
<div className="card section-gap">
<div className="card-title">Schnelleingabe (heute)</div>
<p style={{ fontSize: 13, color: 'var(--text3)', margin: 0 }}>
Für dieses Widget sind keine Eingabebereiche aktiviert. Im Dashboard-Lab die Sichtbarkeit prüfen
oder <Link to="/vitals">Vitalwerte-Seite</Link> nutzen.
</p>
</div>
)
}
return (
<div className="card section-gap">
<div className="card-title">Schnelleingabe (heute)</div>
{(showWeight || showVitalsBlock) && (
<p style={{ fontSize: 12, color: 'var(--text2)', marginBottom: 12, lineHeight: 1.5 }}>
{showWeight && showVitalsBlock && 'Gewicht separat; Vitalwerte typischerweise gemeinsam. '}
{showWeight && !showVitalsBlock && 'Gewicht für heute. '}
{!showWeight && showVitalsBlock && 'Baseline-Vitalwerte für heute. '}
<Link to="/vitals" style={{ color: 'var(--accent)', fontSize: 12 }}>
Volle Vitalwerte-Seite →
</Link>
</p>
)}
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 12 }}>
{showWeight && (
<div style={cellStyle}>
<div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text3)', marginBottom: 6 }}>Gewicht</div>
{weightErr && (
<div style={{ fontSize: 11, color: 'var(--danger)', marginBottom: 6 }}>{weightErr}</div>
)}
<div style={{ display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }}>
<input
type="number"
className="form-input"
min={20}
max={300}
step={0.1}
style={{ flex: 1, minWidth: 72 }}
placeholder="kg"
value={weightInput}
onChange={(e) => setWeightInput(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && saveWeight()}
/>
<button
type="button"
className="btn btn-primary"
style={{ padding: '6px 12px' }}
disabled={weightSaving}
onClick={saveWeight}
>
{weightSaved ? <Check size={15} /> : weightSaving ? <div className="spinner" style={{ width: 14, height: 14 }} /> : 'OK'}
</button>
</div>
</div>
)}
{showVitalsBlock && (
<div style={{ ...cellStyle, flex: showWeight ? '2 1 280px' : '1 1 280px' }}>
<div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text3)', marginBottom: 6 }}>
Vitalwerte (Baseline)
</div>
{vErr && <div style={{ fontSize: 11, color: 'var(--danger)', marginBottom: 6 }}>{vErr}</div>}
<div
style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))',
gap: '12px 10px',
}}
>
{showRestingHr && (
<div>
<label
htmlFor="pqc-resting-hr"
className="form-label"
style={{ display: 'block', marginBottom: 4, fontSize: 11, fontWeight: 600, color: 'var(--text2)' }}
>
Ruhepuls
<span style={{ fontWeight: 400, color: 'var(--text3)' }}> (bpm)</span>
</label>
<input
id="pqc-resting-hr"
type="number"
className="form-input"
style={{ width: '100%' }}
inputMode="numeric"
value={vForm.resting_hr}
onChange={(e) => setVForm((f) => ({ ...f, resting_hr: e.target.value }))}
/>
</div>
)}
{showHrv && (
<div>
<label
htmlFor="pqc-hrv"
className="form-label"
style={{ display: 'block', marginBottom: 4, fontSize: 11, fontWeight: 600, color: 'var(--text2)' }}
>
HRV
<span style={{ fontWeight: 400, color: 'var(--text3)' }}> (ms)</span>
</label>
<input
id="pqc-hrv"
type="number"
className="form-input"
style={{ width: '100%' }}
inputMode="numeric"
value={vForm.hrv}
onChange={(e) => setVForm((f) => ({ ...f, hrv: e.target.value }))}
/>
</div>
)}
{showVo2 && (
<div>
<label
htmlFor="pqc-vo2"
className="form-label"
style={{ display: 'block', marginBottom: 4, fontSize: 11, fontWeight: 600, color: 'var(--text2)' }}
>
VO₂max
</label>
<input
id="pqc-vo2"
type="number"
className="form-input"
style={{ width: '100%' }}
step={0.1}
inputMode="decimal"
value={vForm.vo2_max}
onChange={(e) => setVForm((f) => ({ ...f, vo2_max: e.target.value }))}
/>
</div>
)}
</div>
<button
type="button"
className="btn btn-primary btn-full"
style={{ marginTop: 10 }}
disabled={vSaving}
onClick={saveVitals}
>
{vOk ? '✓ Gespeichert' : vSaving ? '…' : 'Vitalwerte speichern'}
</button>
</div>
)}
</div>
</div>
)
}
@@ -0,0 +1,59 @@
import { useState } from 'react'
import { ChevronDown, ChevronUp } from 'lucide-react'
import { getStatusColor, getStatusBg } from '../../utils/interpret'
export default function PilotRuleCard({ item }) {
const [open, setOpen] = useState(false)
const color = getStatusColor(item.status)
return (
<div style={{ border: `1px solid ${color}33`, borderRadius: 8, marginBottom: 6, overflow: 'hidden' }}>
<button
type="button"
onClick={() => setOpen((o) => !o)}
style={{
display: 'flex',
alignItems: 'center',
gap: 8,
padding: '8px 12px',
width: '100%',
textAlign: 'left',
background: `${getStatusBg(item.status)}88`,
border: 'none',
cursor: 'pointer',
fontFamily: 'var(--font)',
}}
>
<span style={{ fontSize: 15 }}>{item.icon}</span>
<div style={{ flex: 1 }}>
<div
style={{
fontSize: 11,
fontWeight: 600,
color,
textTransform: 'uppercase',
letterSpacing: '0.04em',
}}
>
{item.category}
</div>
<div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text1)' }}>{item.title}</div>
</div>
{item.value && <span style={{ fontSize: 14, fontWeight: 700, color }}>{item.value}</span>}
{open ? <ChevronUp size={14} color="var(--text3)" /> : <ChevronDown size={14} color="var(--text3)" />}
</button>
{open && (
<div
style={{
padding: '8px 12px',
fontSize: 12,
color: 'var(--text2)',
lineHeight: 1.6,
borderTop: `1px solid ${color}22`,
}}
>
{item.detail}
</div>
)}
</div>
)
}
@@ -0,0 +1,19 @@
import dayjs from 'dayjs'
import 'dayjs/locale/de'
import { useProfile } from '../../context/ProfileContext'
dayjs.locale('de')
export default function PilotWelcome() {
const { activeProfile } = useProfile()
return (
<div className="card section-gap" style={{ marginBottom: 16 }}>
<h2 style={{ fontSize: 20, fontWeight: 800, margin: 0, color: 'var(--text1)' }}>
Hallo, {activeProfile?.name || 'Nutzer'} 👋
</h2>
<p style={{ fontSize: 12, color: 'var(--text3)', margin: '6px 0 0' }}>
{dayjs().format('dddd, DD. MMMM YYYY')} · Pilot-Übersicht
</p>
</div>
)
}
+164
View File
@@ -0,0 +1,164 @@
/**
* Admin: Nur Gruppen in der Shell-Navigation; konkrete Seiten wählt man auf der Hub-Seite (/admin/g/:id).
* @typedef {{ to: string, label: string, description?: string }} AdminGroupItem
* @typedef {{ id: string, label: string, description: string, items: AdminGroupItem[] }} AdminGroup
*/
/** @type {AdminGroup[]} */
export const ADMIN_GROUPS = [
{
id: 'users',
label: 'Benutzerverwaltung',
description: 'Profile anlegen, Rollen setzen und Recovery-E-Mails pflegen.',
items: [
{
to: '/admin/users',
label: 'Profile & Rollen',
description: 'Neue Profile, Admin-Rolle, PIN und E-Mail pro Nutzer.',
},
],
},
{
id: 'features',
label: 'Features',
description: 'Feature-Registry, Kontingente und individuelle Overrides.',
items: [
{
to: '/admin/features',
label: 'Feature-Registry',
description: 'Features definieren und Kategorien zuordnen.',
},
{
to: '/admin/tier-limits',
label: 'Tier-Limits',
description: 'Limit-Matrix pro Tier bearbeiten.',
},
{
to: '/admin/user-restrictions',
label: 'User-Overrides',
description: 'Individuelle Feature-Limits setzen.',
},
],
},
{
id: 'subscription',
label: 'Subscription',
description: 'Tiers und Gutscheine für das Freemium-System.',
items: [
{ to: '/admin/tiers', label: 'Tiers', description: 'Abo-Stufen und Zuordnung.' },
{ to: '/admin/coupons', label: 'Coupons', description: 'Gutscheincodes verwalten.' },
],
},
{
id: 'training',
label: 'Trainingstypen',
description: 'Trainingstypen, Mappings und Trainings-Profile.',
items: [
{
to: '/admin/training-types',
label: 'Trainingstypen',
description: 'Kategorien und Typen verwalten.',
},
{
to: '/admin/activity-mappings',
label: 'Activity-Mappings',
description: 'Lernendes Zuordnungssystem (Sprache / Apple Health).',
},
{
to: '/admin/training-profiles',
label: 'Trainings-Profile',
description: 'Training-Type-Profile (#15).',
},
],
},
{
id: 'goals',
label: 'Ziele & Fokus',
description: 'Ziel-Typen und Focus Areas.',
items: [
{
to: '/admin/goal-types',
label: 'Ziel-Typen',
description: 'Custom Goal Types mit oder ohne Datenquelle.',
},
{
to: '/admin/focus-areas',
label: 'Focus Areas',
description: 'Dynamische Fokusbereiche und Kategorien.',
},
{
to: '/admin/reference-value-types',
label: 'Referenz-Kennwerte',
description: 'Typen für persönliche Referenzwerte (Schlüssel, Namen, Metadaten).',
},
],
},
{
id: 'prompts',
label: 'KI-Prompts',
description: 'Pipeline- und Basis-Prompts für die KI-Analyse.',
items: [
{
to: '/admin/prompts',
label: 'KI-Prompts verwalten',
description: 'Prompts bearbeiten, Stages, Test & Export.',
},
],
},
{
id: 'system',
label: 'Basiseinstellungen',
description: 'System-E-Mail und Platzhalter-Metadaten.',
items: [
{
to: '/admin/system',
label: 'SMTP & Metadaten-Export',
description: 'SMTP-Status, Test-Mail und Placeholder-Katalog (JSON/ZIP).',
},
{
to: '/admin/dashboard-product-default',
label: 'Produkt-Dashboard (Standard)',
description: 'Globales Standard-Layout der Startseite (DB oder Code-Fallback).',
},
],
},
]
export function adminGroupHubPath(groupId) {
return `/admin/g/${groupId}`
}
/**
* Shell-Navigation: Übersicht + eine Zeile/Spalte pro Gruppe (ohne Einzelseiten).
* @typedef {{ id: string, label: string, to: string, end?: boolean }} AdminShellNavEntry
* @returns {AdminShellNavEntry[]}
*/
export function getAdminShellNavEntries() {
return [
{ id: 'overview', label: 'Übersicht', to: '/admin', end: true },
...ADMIN_GROUPS.map((g) => ({
id: g.id,
label: g.label,
to: adminGroupHubPath(g.id),
end: false,
})),
]
}
/** Aktiver Shell-Eintrag inkl. Leaf-Routen der Gruppe (z. B. /admin/features → Gruppe „Features“). */
export function adminShellEntryIsActive(pathname, entry) {
if (entry.id === 'overview') {
return pathname === '/admin'
}
const group = ADMIN_GROUPS.find((x) => x.id === entry.id)
if (!group) return false
if (pathname === adminGroupHubPath(group.id)) return true
return group.items.some((it) => pathname === it.to)
}
/** Anzahl Unterseiten für Chip-Badge (wie KI-Analyse). */
export function adminShellEntryItemCount(entry) {
if (entry.id === 'overview') return 0
const g = ADMIN_GROUPS.find((x) => x.id === entry.id)
return g ? g.items.length : 0
}
+46
View File
@@ -0,0 +1,46 @@
import {
LayoutDashboard,
PlusSquare,
TrendingUp,
Target,
BarChart2,
Settings,
Shield
} from 'lucide-react'
/**
* Eine Quelle für Hauptnavigation (Bottom-Nav + Desktop-Sidebar).
* @typedef {{ to: string, label: string, shortLabel?: string, end?: boolean, Icon: import('react').ForwardRefExoticComponent }} AppNavItem
*/
/** @returns {Omit<AppNavItem, 'Icon'>[]} */
function baseItems() {
return [
{ to: '/', label: 'Übersicht', end: true },
{ to: '/capture', label: 'Erfassen' },
{ to: '/history', label: 'Verlauf' },
{ to: '/goals', label: 'Ziele', shortLabel: 'Ziele', end: true },
{ to: '/analysis', label: 'Analyse' },
{ to: '/settings', label: 'Einstellungen', shortLabel: 'Einst.' }
]
}
/** @param {boolean} isAdmin */
export function getMainNavItems(isAdmin) {
const icons = [
LayoutDashboard,
PlusSquare,
TrendingUp,
Target,
BarChart2,
Settings
]
const raw = baseItems().map((item, i) => ({
...item,
Icon: icons[i]
}))
if (isAdmin) {
raw.push({ to: '/admin', label: 'Admin', end: false, Icon: Shield })
}
return raw
}
+103
View File
@@ -0,0 +1,103 @@
/**
* Erfassungs-Routen: Kachel-Hub + Sub-Navigation (Chip / Seitenleiste).
* Pfade müssen mit den Routes in App.jsx unter CaptureShell übereinstimmen.
*/
export const CAPTURE_HUB_TILES = [
{
icon: '⚖️',
label: 'Gewicht',
sub: 'Tägliche Gewichtseingabe',
to: '/weight',
color: '#378ADD',
},
{
icon: '🪄',
label: 'Assistent',
sub: 'Schritt-für-Schritt Messung (Umfänge & Caliper)',
to: '/wizard',
color: '#7F77DD',
highlight: true,
},
{
icon: '📏',
label: 'Umfänge',
sub: 'Hals, Brust, Taille, Bauch, Hüfte, Oberschenkel, Wade, Arm',
to: '/circum',
color: '#1D9E75',
},
{
icon: '📐',
label: 'Caliper',
sub: 'Körperfett per Hautfaltenmessung',
to: '/caliper',
color: '#D85A30',
},
{
icon: '🍽️',
label: 'Ernährung',
sub: 'FDDB CSV importieren',
to: '/nutrition',
color: '#EF9F27',
},
{
icon: '🏋️',
label: 'Aktivität',
sub: 'Training manuell oder Apple Health importieren',
to: '/activity',
color: '#D4537E',
},
{
icon: '🌙',
label: 'Schlaf',
sub: 'Schlafdaten erfassen oder Apple Health importieren',
to: '/sleep',
color: '#7B68EE',
},
{
icon: '🛌',
label: 'Ruhetage',
sub: 'Kraft-, Cardio-, oder Entspannungs-Ruhetag erfassen',
to: '/rest-days',
color: '#9B59B6',
},
{
icon: '❤️',
label: 'Vitalwerte',
sub: 'Ruhepuls und HRV morgens erfassen',
to: '/vitals',
color: '#E74C3C',
},
{
icon: '🎯',
label: 'Eigene Ziele',
sub: 'Fortschritte für individuelle Ziele erfassen',
to: '/custom-goals',
color: '#1D9E75',
},
{
icon: '📖',
label: 'Messanleitung',
sub: 'Wie und wo genau messen?',
to: '/guide',
color: '#888780',
},
]
/** Erster Eintrag: zurück zur Kachel-Übersicht */
const OVERVIEW_ENTRY = {
icon: '📋',
label: 'Übersicht',
sub: 'Alle Erfassungsarten',
to: '/capture',
color: 'var(--accent)',
}
/** Reihenfolge für Chip- / Seitenleiste (inkl. Übersicht) */
export const CAPTURE_SHELL_NAV_ITEMS = [OVERVIEW_ENTRY, ...CAPTURE_HUB_TILES]
export const CAPTURE_SECTION_PATHS = CAPTURE_SHELL_NAV_ITEMS.map((e) => e.to)
export function isCaptureSectionPath(pathname) {
return CAPTURE_SECTION_PATHS.includes(pathname)
}
+10
View File
@@ -0,0 +1,10 @@
/**
* Einstellungen: Sub-Navigation (Mobil = Chip-Leiste, Desktop = linke Spalte).
* Pfade müssen mit den Routes unter SettingsShell in App.jsx übereinstimmen.
*/
export const SETTINGS_SHELL_NAV_ITEMS = [
{ id: 'general', label: 'Allgemein', to: '/settings', end: true },
{ id: 'dashboard-layout', label: 'Übersicht', to: '/settings/dashboard-layout' },
{ id: 'reference-values', label: 'Referenzwerte', to: '/settings/reference-values' },
]
+51
View File
@@ -0,0 +1,51 @@
import { Outlet, NavLink, useLocation } from 'react-router-dom'
import {
getAdminShellNavEntries,
adminShellEntryIsActive,
adminShellEntryItemCount,
} from '../config/adminNav'
/**
* Wie KI-Analyse: nur Gruppen-Chips (mobil) bzw. Seitenleiste (desktop);
* konkrete Admin-Seiten über Hub unter /admin/g/:groupId.
*/
export default function AdminShell() {
const loc = useLocation()
const entries = getAdminShellNavEntries()
return (
<div className="admin-shell">
<div className="analysis-split">
<div className="analysis-split__nav-wrap">
<nav className="analysis-split__nav" aria-label="Adminbereich">
{entries.map((entry) => {
const active = adminShellEntryIsActive(loc.pathname, entry)
const count = adminShellEntryItemCount(entry)
return (
<NavLink
key={entry.id}
to={entry.to}
end={!!entry.end}
className={() =>
'analysis-split__nav-item' +
(active ? ' analysis-split__nav-item--active' : '')
}
>
{entry.label}
{count > 0 && (
<span className="analysis-split__nav-cat-count">({count})</span>
)}
</NavLink>
)
})}
</nav>
</div>
<div className="analysis-split__main">
<div className="admin-page">
<Outlet />
</div>
</div>
</div>
</div>
)
}
+36
View File
@@ -0,0 +1,36 @@
import { Outlet, NavLink } from 'react-router-dom'
import { CAPTURE_SHELL_NAV_ITEMS } from '../config/captureNav'
/**
* Erfassung: Mobil Chip-Leiste, Desktop linke Spalte – Wechsel zwischen Masken ohne Hub.
*/
export default function CaptureShell() {
return (
<div className="capture-shell">
<div className="capture-shell__layout">
<nav className="capture-shell__nav-wrap" aria-label="Erfassungsbereiche">
<div className="capture-shell__nav">
{CAPTURE_SHELL_NAV_ITEMS.map((e) => (
<NavLink
key={e.to}
to={e.to}
end={e.to === '/capture'}
className={({ isActive }) =>
'capture-shell__nav-item' +
(isActive ? ' capture-shell__nav-item--active' : '') +
(e.highlight ? ' capture-shell__nav-item--highlight' : '')
}
>
<span className="capture-shell__nav-icon" aria-hidden>{e.icon}</span>
<span className="capture-shell__nav-label">{e.label}</span>
</NavLink>
))}
</div>
</nav>
<div className="capture-shell__main">
<Outlet />
</div>
</div>
</div>
)
}
+11
View File
@@ -0,0 +1,11 @@
import { Navigate, Outlet, useLocation } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
export default function RequireAdmin() {
const { isAdmin } = useAuth()
const loc = useLocation()
if (!isAdmin) {
return <Navigate to="/" replace state={{ from: loc.pathname, adminDenied: true }} />
}
return <Outlet />
}
+33
View File
@@ -0,0 +1,33 @@
import { Outlet, NavLink } from 'react-router-dom'
import { SETTINGS_SHELL_NAV_ITEMS } from '../config/settingsNav'
/**
* Wie Admin / KI-Analyse: Chips horizontal (mobil) bzw. Seitenleiste (Desktop).
*/
export default function SettingsShell() {
return (
<div className="settings-shell">
<div className="analysis-split">
<div className="analysis-split__nav-wrap">
<nav className="analysis-split__nav" aria-label="Einstellungen">
{SETTINGS_SHELL_NAV_ITEMS.map((item) => (
<NavLink
key={item.id}
to={item.to}
end={!!item.end}
className={({ isActive }) =>
'analysis-split__nav-item' + (isActive ? ' analysis-split__nav-item--active' : '')
}
>
{item.label}
</NavLink>
))}
</nav>
</div>
<div className="analysis-split__main">
<Outlet />
</div>
</div>
</div>
)
}
+1 -1
View File
@@ -254,7 +254,7 @@ export default function ActivityPage() {
}
return (
<div>
<div className="capture-page">
<h1 className="page-title">Aktivität</h1>
<div className="tabs" style={{overflowX:'auto',flexWrap:'nowrap'}}>
+137 -13
View File
@@ -14,8 +14,19 @@ const CATEGORIES = [
{ value: 'custom', label: 'Eigene' }
]
function groupAreasByCategory(areas) {
const grouped = {}
for (const area of areas) {
const cat = area.category || 'other'
if (!grouped[cat]) grouped[cat] = []
grouped[cat].push(area)
}
return grouped
}
export default function AdminFocusAreasPage() {
const [data, setData] = useState({ areas: [], grouped: {}, total: 0 })
const [usageTypesCatalog, setUsageTypesCatalog] = useState([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [showInactive, setShowInactive] = useState(false)
@@ -34,11 +45,35 @@ export default function AdminFocusAreasPage() {
loadData()
}, [showInactive])
useEffect(() => {
let cancelled = false
;(async () => {
try {
const r = await api.listFocusAreaUsageTypes()
if (!cancelled) setUsageTypesCatalog(r.usage_types || [])
} catch (e) {
console.error('usage-types catalog:', e)
if (!cancelled) setUsageTypesCatalog([])
}
})()
return () => { cancelled = true }
}, [])
const loadData = async () => {
try {
setLoading(true)
const result = await api.listFocusAreaDefinitions(showInactive)
setData(result)
const areas = (result.areas || []).map(a => ({
...a,
allowed_usage_type_keys: Array.isArray(a.allowed_usage_type_keys)
? a.allowed_usage_type_keys
: []
}))
setData({
areas,
grouped: groupAreasByCategory(areas),
total: result.total ?? areas.length
})
setError(null)
} catch (err) {
console.error('Failed to load focus areas:', err)
@@ -74,14 +109,20 @@ export default function AdminFocusAreasPage() {
const handleUpdate = async (id) => {
try {
const area = data.areas.find(a => a.id === id)
await api.updateFocusAreaDefinition(id, {
name_de: area.name_de,
name_en: area.name_en,
icon: area.icon,
description: area.description,
category: area.category,
is_active: area.is_active
})
const usageKeys = Array.isArray(area.allowed_usage_type_keys)
? area.allowed_usage_type_keys
: []
await Promise.all([
api.updateFocusAreaDefinition(id, {
name_de: area.name_de,
name_en: area.name_en,
icon: area.icon,
description: area.description,
category: area.category,
is_active: area.is_active
}),
api.setFocusAreaUsageTypes(id, usageKeys)
])
setEditingId(null)
await loadData()
} catch (err) {
@@ -113,12 +154,25 @@ export default function AdminFocusAreasPage() {
}
const updateField = (id, field, value) => {
setData(prev => ({
...prev,
areas: prev.areas.map(a =>
setData(prev => {
const areas = prev.areas.map(a =>
a.id === id ? { ...a, [field]: value } : a
)
}))
return { ...prev, areas, grouped: groupAreasByCategory(areas), total: areas.length }
})
}
const toggleUsageTypeKey = (areaId, key, checked) => {
setData(prev => {
const areas = prev.areas.map(a => {
if (a.id !== areaId) return a
const cur = new Set(Array.isArray(a.allowed_usage_type_keys) ? a.allowed_usage_type_keys : [])
if (checked) cur.add(key)
else cur.delete(key)
return { ...a, allowed_usage_type_keys: [...cur] }
})
return { ...prev, areas, grouped: groupAreasByCategory(areas), total: areas.length }
})
}
if (loading) {
@@ -364,6 +418,45 @@ export default function AdminFocusAreasPage() {
/>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 6 }}>
Erlaubte Nutzungstypen
</label>
{usageTypesCatalog.length === 0 ? (
<span style={{ fontSize: 12, color: 'var(--text3)' }}>
Kein Katalog geladen (Backend / Migration prüfen).
</span>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{usageTypesCatalog.map(ut => (
<label
key={ut.id}
style={{
fontSize: 13,
display: 'flex',
alignItems: 'flex-start',
gap: 8,
cursor: 'pointer'
}}
>
<input
type="checkbox"
style={{ marginTop: 3 }}
checked={(area.allowed_usage_type_keys || []).includes(ut.key)}
onChange={(e) =>
toggleUsageTypeKey(area.id, ut.key, e.target.checked)
}
/>
<span>
<span style={{ display: 'block' }}>{ut.label_de}</span>
<code style={{ fontSize: 11, color: 'var(--text3)' }}>{ut.key}</code>
</span>
</label>
))}
</div>
)}
</div>
<div style={{ display: 'flex', gap: 8 }}>
<button
className="btn-primary"
@@ -430,6 +523,37 @@ export default function AdminFocusAreasPage() {
{area.description}
</div>
)}
{(area.allowed_usage_type_keys || []).length > 0 && (
<div
style={{
fontSize: 12,
marginTop: 8,
display: 'flex',
flexWrap: 'wrap',
gap: 6
}}
>
{(area.allowed_usage_type_keys || []).map(k => {
const ut = usageTypesCatalog.find(x => x.key === k)
return (
<span
key={k}
style={{
padding: '2px 8px',
borderRadius: 6,
background: 'var(--surface2)',
border: '1px solid var(--border)',
color: 'var(--text2)'
}}
title={k}
>
{ut?.label_de || k}
</span>
)
})}
</div>
)}
</div>
<div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
+57
View File
@@ -0,0 +1,57 @@
import { useParams, Navigate, Link } from 'react-router-dom'
import { ADMIN_GROUPS } from '../config/adminNav'
export default function AdminGroupHubPage() {
const { groupId } = useParams()
const group = ADMIN_GROUPS.find((g) => g.id === groupId)
if (!group) {
return <Navigate to="/admin" replace />
}
return (
<div>
<h2 className="page-title" style={{ margin: '0 0 8px', fontSize: 18 }}>
{group.label}
</h2>
<p style={{ fontSize: 13, color: 'var(--text2)', marginBottom: 18, lineHeight: 1.6 }}>
{group.description}
</p>
<p style={{ fontSize: 12, fontWeight: 600, color: 'var(--text3)', marginBottom: 12 }}>
Bereich wählen · {group.items.length}{' '}
{group.items.length === 1 ? 'Seite' : 'Seiten'}
</p>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{group.items.map((item) => (
<Link
key={item.to}
to={item.to}
className="card section-gap"
style={{
margin: 0,
textDecoration: 'none',
color: 'inherit',
borderColor: 'var(--accent)',
borderWidth: 2,
display: 'block',
}}
>
<div style={{ fontWeight: 700, fontSize: 15, color: 'var(--accent)', marginBottom: 4 }}>
{item.label}
</div>
{item.description && (
<div style={{ fontSize: 12, color: 'var(--text2)', lineHeight: 1.5 }}>
{item.description}
</div>
)}
</Link>
))}
</div>
<div style={{ marginTop: 20 }}>
<Link to="/admin" className="btn btn-secondary" style={{ fontSize: 13 }}>
← Zur Übersicht
</Link>
</div>
</div>
)
}
+41
View File
@@ -0,0 +1,41 @@
import { Link } from 'react-router-dom'
import { Shield } from 'lucide-react'
import { ADMIN_GROUPS, adminGroupHubPath } from '../config/adminNav'
export default function AdminHomePage() {
return (
<div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
<Shield size={20} color="var(--accent)" />
<h1 className="page-title" style={{ margin: 0 }}>Adminbereich</h1>
</div>
<p style={{ fontSize: 13, color: 'var(--text2)', marginBottom: 18, lineHeight: 1.6 }}>
Wähle links oder oben eine <strong>Gruppe</strong>. Die einzelnen Verwaltungsseiten erreichst du auf der
folgenden Gruppenseite – wie bei der KI-Analyse (Kategorie → Detail).
</p>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{ADMIN_GROUPS.map((group) => (
<Link
key={group.id}
to={adminGroupHubPath(group.id)}
className="card section-gap"
style={{
margin: 0,
textDecoration: 'none',
color: 'inherit',
display: 'block',
}}
>
<div style={{ fontWeight: 700, fontSize: 15, marginBottom: 6 }}>{group.label}</div>
<div style={{ fontSize: 12, color: 'var(--text2)', lineHeight: 1.5 }}>
{group.description}
</div>
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 8 }}>
{group.items.length} {group.items.length === 1 ? 'Bereich' : 'Bereiche'}
</div>
</Link>
))}
</div>
</div>
)
}
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff. Show more