86 Commits
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 / build-frontend (push) Successful in 16s
Build Test / lint-backend (push) Successful in 0s
- 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 / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 0s
- 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 / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
- 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 / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 0s
- 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 / build-frontend (push) Successful in 23s
Build Test / lint-backend (push) Successful in 0s
- 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 / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
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 / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 0s
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 / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 0s
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 / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
2026-04-05 07:58:38 +02:00
Lars 922c846b03 chore: Remove generated test results file
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 07:47:00 +02:00
LarsandClaude Opus 4.6 7deca6c64d test: Add unit tests for End Node Template Engine
Build Test / build-frontend (push) Waiting to run
Deploy Development / deploy (push) Has been cancelled
Build Test / lint-backend (push) Waiting to run
- test_end_node_template.py: Tests for execute_end_node()
- Tests AUTO mode (backward compatible concatenation)
- Tests TEMPLATE mode (Jinja2 rendering, conditionals)
- Tests error handling (missing template, syntax errors)

Note: Tests require Jinja2, run in Docker or CI/CD environment.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 07:46:49 +02:00
LarsandClaude Opus 4.6 fac76c28da fix: Handle None workflow_id in success path
Deploy Development / deploy (push) Successful in 52s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
Also use 'N/A' placeholder in ExecutionResult when workflow_id is None
(when using graph_data directly instead of workflow_definitions).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 07:28:30 +02:00
LarsandClaude Opus 4.6 6016eec250 fix: Add ON CONFLICT to workflow_executions insert
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Prevents duplicate key violation when save_execution_state is called
multiple times with the same execution_id (e.g., during error handling).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 07:26:10 +02:00
LarsandClaude Opus 4.6 c95b4e185d fix: Edge format normalization and nullable workflow_id
Deploy Development / deploy (push) Successful in 55s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
Fixes:
1. Edge Format Mismatch:
   - graph_data uses React Flow format (source/target)
   - WorkflowEdge expects backend format (from/to)
   - Added normalization in parse_workflow_graph()

2. UUID Validation Error:
   - workflow_id can be None when using graph_data (Phase 5)
   - save_execution_state now accepts Optional[str]
   - ExecutionResult uses "N/A" placeholder when None

Changes:
- workflow_engine.py: normalize edges before Pydantic validation
- workflow_executor.py: Optional[str] for workflow_id parameter

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 07:22:32 +02:00
LarsandClaude Opus 4.6 fe28cce921 fix: Workflow executor graph parsing and error handling
Deploy Development / deploy (push) Successful in 52s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 1s
Fixes:
- graph_data was incorrectly json.dumps() encoded (should stay as dict)
- workflow_id=None in error handler caused ValidationError
- parse_workflow_graph expects Dict, not str

Changes:
- Use graph_dict directly instead of json.dumps(graph_data)
- Set workflow_id="" when None in error handler

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 07:18:43 +02:00
LarsandClaude Opus 4.6 b888f5d3c8 feat: Phase 4 - End Node Template Engine (v0.9n)
Deploy Development / deploy (push) Successful in 52s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
Backend:
- workflow_models.py: EndNodeOutputMode enum (AUTO, TEMPLATE)
- workflow_executor.py: execute_end_node() with Jinja2 rendering
- Template Context: {{node_id.analysis_core}}, {{node_id.decision_signals.key}}
- Conditional Rendering: {% if node_id %} for optional paths
- AUTO Mode: Backward compatible (concatenates all analyses)
- TEMPLATE Mode: Custom Jinja2 templates with placeholders

Features:
- Access node results: {{node_id.analysis_core}}
- Access signals: {{node_id.decision_signals.relevanz}}
- Optional paths: {% if node_id %}...{% endif %}
- Default values: {{node_id|default("N/A")}}

Version: 0.9n
Module: workflow 0.6.0
Konzept: konzept_workflow_engine_konsolidated.md (Section 11)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 07:07:49 +02:00
Lars cab5758b0d fix: Save prompt_name in graph_data for readable node display
Deploy Development / deploy (push) Successful in 53s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
Bug:
- Analysis nodes showed "Prompt #7edc6d6b-6cd5..." in canvas
- After re-selecting prompt, showed readable name "Pipeline: Ernährungs-Analyse"
- After loading workflow, showed UUID again

Root Cause:
- Serializer saved only prompt_id, not prompt_name
- Deserializer expected prompt_name but got null
- AnalysisNode fallback logic: data.prompt_name || `Prompt #{prompt_id}`
- Result: Showed UUID as fallback

Fix:
- workflowSerializer.js line 25: Added prompt_name to serialization
- Now saves both prompt_id AND prompt_name in graph_data
- On load: prompt_name is restored → AnalysisNode shows readable name

Testing:
- Create workflow with analysis node + prompt selection
- Save → Canvas should show "Pipeline: Körper-Analyse" (not UUID)
- Reload → Canvas should still show readable name (not UUID)
2026-04-04 22:50:40 +02:00
Lars d9bcaaaac6 fix: Add missing GET /api/prompts/{id} endpoint
Deploy Development / deploy (push) Successful in 51s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Critical Backend Bug:
- Frontend calls api.getPrompt(id) → GET /api/prompts/{uuid}
- Backend had NO endpoint for single prompt retrieval by ID
- Result: 405 Method Not Allowed

Backend Endpoints Before:
✓ GET /api/prompts - List all
✓ POST /api/prompts - Create
✓ PUT /api/prompts/{id} - Update
✗ GET /api/prompts/{id} - MISSING!

Backend Endpoints After:
✓ GET /api/prompts - List all
✓ GET /api/prompts/{id} - Get single (NEW)
✓ POST /api/prompts - Create
✓ PUT /api/prompts/{id} - Update

Implementation:
- Added get_prompt(prompt_id: str) function
- Returns single prompt by UUID
- 404 if not found
- Requires auth (admin or user)

This fixes:
- Workflow loading after save (loadWorkflow calls getPrompt)
- Workflow editing from admin list (Edit button calls getPrompt)
- All 405 Method Not Allowed errors

Root Cause: Backend was incomplete, missing basic CRUD read-by-id endpoint
2026-04-04 22:43:07 +02:00
Lars 84c1fa3c1d fix: UUID handling - remove parseInt() for prompt IDs
Deploy Development / deploy (push) Successful in 47s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 1s
Critical Bug Fixes:
1. Prompt IDs are UUIDs (strings), NOT numbers
2. parseInt(UUID) produces wrong results:
   - parseInt("3b4d7d64-...") = 3 (truncates at first non-digit)
   - parseInt("aa291dde-...") = NaN
3. This caused:
   - Prompt selection: saved as NaN instead of UUID
   - Load workflow: GET /api/prompts/3 instead of /api/prompts/3b4d7d64-...
   - 405 Method Not Allowed errors

Changes:
- useEffect: loadWorkflow(id) instead of loadWorkflow(parseInt(id))
- Prompt onChange: prompt_id: promptId (string) instead of parseInt(promptId)
- Removed NaN check (unnecessary for UUID strings)

Root Cause: Backend uses UUID primary keys, frontend assumed integer IDs

Testing: Console logs still active for verification
2026-04-04 22:39:08 +02:00
Lars 2b8bebd381 debug: Add comprehensive console logging for workflow editor debugging
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Debug Logs Added:
- useEffect: Log ID validation and loadWorkflow calls
- loadWorkflow: Log API response, graph_data, deserialization results
- handleNodeUpdate: Log updates and resulting node state
- handleSave: Log serialization, API calls, navigation

Bug Fixes:
- useEffect: Add !isNaN(parseInt(id)) check to prevent /api/prompts/NaN calls
- Prompt selection: String conversion for value prop (Number vs String mismatch)
  - <select value={String(selectedNode.data.prompt_id)}>
  - <option value={String(prompt.id)}>
  - onChange: find with String(p.id) === promptId

Issues to Debug:
- Why does useEffect run with id=undefined after navigate?
- Why does loadWorkflow not populate nodes/edges?
- Why does prompt selection not persist?

Next Step: User tests with Browser Console open, reports logs
2026-04-04 22:30:43 +02:00
Lars 2f70a39052 fix: Phase 5 - Workflow Editor UX Fixes (Round 3)
Deploy Development / deploy (push) Successful in 53s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Frontend Fixes:
- AdminPromptsPage: Edit button navigates to workflow-editor for workflow type prompts
- WorkflowEditorPage: Fixed save navigation (alert before navigate)
- WorkflowEditorPage: selectedNode derived from selectedNodeId (eliminates stale state)
- FallbackConfig: Show node labels instead of IDs in fallback edge dropdown
- WorkflowCanvas: Enable edge deletion with deletable: true
- WorkflowEditorPage: Hide sidebar when config panel is open

Bugs Fixed:
- C1: Save error "Method Not Allowed" after success
- C2: Edit button in admin doesn't open workflow editor
- H1: Prompt selection not displayed when re-editing node
- H2: Fallback edge dropdown shows node_1/node_2 instead of names
- H3: Cannot delete edges
- M1: Sidebar takes space when config panel open

Technical Changes:
- Replaced useState(selectedNode) with useState(selectedNodeId) + derived selectedNode
- Removed sync useEffect (no longer needed with derived state)
- Added nodes prop to FallbackConfig for label lookup
- Swapped alert/navigate order to prevent navigation errors

Testing: Manual testing required (see manual test cases)
2026-04-04 21:16:15 +02:00
LarsandClaude Opus 4.6 7d22b052dd fix: Phase 5 - Workflow save + node persistence bugs
Deploy Development / deploy (push) Successful in 47s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
KRITISCHE FIXES:

1. Backend: Workflow-Type Support
   - models.py: graph_data Feld hinzugefügt
   - models.py: slug Optional (auto-generiert)
   - prompts.py: 'workflow' in erlaubten Typen
   - prompts.py: graph_data in INSERT/UPDATE
   - prompts.py: Auto-Slug-Generierung aus Name
   - FIX: "Field required: slug" Error behoben

2. Frontend: Node-Updates Persistence
   - selectedNode sync mit nodes array (useEffect)
   - FIX: Änderungen gingen verloren (stale state)
   - FIX: Prompt-Auswahl nicht sichtbar nach Edit
   - FIX: Fallback-Strategy nicht gespeichert
   - FIX: Node-Name Änderungen nicht übernommen

BEHOBEN:
- ❌ Save fehlgeschlagen → ✅ Workflows speicherbar
- ❌ Node-Name ignoriert → ✅ Live-Update
- ❌ Prompt verschwindet → ✅ Bleibt sichtbar
- ❌ Fallback nicht saved → ✅ Persistiert

Tested: Backend API akzeptiert jetzt type='workflow'

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-04 19:17:41 +02:00
LarsandClaude Opus 4.6 e3ef18674a fix: Phase 5 - Critical UX bugs in Workflow Editor
Deploy Development / deploy (push) Successful in 55s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
Behebt 5 kritische Bugs die Editor unbenutzbar machten:

BUG-01: Config Panel - Close Button hinzugefügt (×)
- User war im Config Panel "gefangen"
- Jetzt: Click × zum Deselektieren

BUG-02: Save UX - Validierungs-Feedback verbessert
- Speichern-Button zeigt Lock-Icon (🔒) bei Fehlern
- Tooltip erklärt warum Speichern blockiert ist
- Error-Message mit Hinweis auf Validierung

BUG-03: Analysis Node - Prompt-Auswahl implementiert
- Dropdown zum Auswählen von Basis-Prompts
- Lädt verfügbare Prompts via API
- Zeigt gewählten Prompt-Namen an

BUG-04: Label-Input - UX verbessert
- Header zeigt "Node-Konfiguration" (nicht Label)
- Input hat Placeholder und Hilfetext
- "Änderungen automatisch übernommen" Hinweis

BUG-05: Admin Page - "Neuer Workflow" Button
- Button neben "+ Neuer Prompt"
- Navigiert zu /workflow-editor/new
- Workflow-Filter im Type-Filter hinzugefügt

Tested: Manuell durch User (alle Bugs bestätigt gefixt)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-04 18:59:47 +02:00
LarsandClaude Opus 4.6 dc59596f01 feat: Phase 5 - Visual Workflow Editor (Option B)
Deploy Development / deploy (push) Failing after 1s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 1s
Backend (Mini-Backend 1-2h):
- Migration 016: ai_prompts.graph_data JSONB column
- workflow_executor: graph_data parameter support (backward-compatible)
- prompt_executor: execute_workflow_prompt uses graph_data

Frontend (Main effort 25-35h):
- WorkflowCanvas: React Flow wrapper component
- 5 Custom Nodes: Start, End, Analysis, Logic, Join
- 4 Config Panels: QuestionAugmentation, LogicExpression, Fallback, Join
- workflowValidation: Structural + logical validation
- workflowSerializer: Canvas ↔ JSONB conversion
- WorkflowEditorPage: Main orchestration (420 LOC)
- Route: /workflow-editor/:id
- CSS: workflowEditor.css (300 LOC)

Architecture:
- Option B: ai_prompts.type='workflow' (not separate table)
- panels/ subdirectory for clean separation
- WorkflowCanvas reusable component
- User GUI identical (Workflows = Prompts)
- Backward-compatible (type='pipeline' unchanged)

Version: v0.9m → v0.9n (Phase 5 complete)
Module: workflow 0.5.0 → 0.6.0

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-04 17:56:00 +02:00
Lars a7058c30be feat: Enhance EmojiIconPicker with search functionality and keyword support
Deploy Development / deploy (push) Successful in 49s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
2026-04-04 14:22:44 +02:00
Lars 2101080719 feat: Expand EmojiIconPicker with additional curated emoji groups and enhance functionality for custom groups
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
2026-04-04 14:17:35 +02:00
Lars 5aae999a65 feat: Add EmojiIconPicker component and integrate it into Admin pages for icon selection
Deploy Development / deploy (push) Successful in 45s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 13s
2026-04-04 14:07:54 +02:00
Lars dc87e7f3b8 cursor_Setup
Deploy Development / deploy (push) Successful in 44s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
2026-04-04 14:05:50 +02:00
LarsandClaude Opus 4.6 c607cd1833 fix: Convert joined signals Dict to List for NodeExecutionState
Deploy Development / deploy (push) Successful in 50s
Build Test / build-frontend (push) Successful in 22s
Build Test / lint-backend (push) Successful in 0s
NodeExecutionState expects normalized_signals as List[NormalizedSignal],
but join_evaluator returns Dict[str, NormalizedSignal].

Fix: Convert dict to list before returning NodeExecutionState.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-04 12:33:58 +02:00
LarsandClaude Opus 4.6 e2a132353d feat: Phase 4 - Join Nodes and Path Consolidation
Deploy Development / deploy (push) Successful in 45s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Backend Implementation (v0.9m, workflow 0.5.0):
- join_evaluator.py (394 lines): Join-Strategie-Evaluator
  - evaluate_join_node(): Hauptlogik für Join-Node Execution
  - Join-Strategien: wait_all, wait_any, best_effort
  - Skip-Handling: ignore_skipped, use_placeholder, require_minimum
  - Result Consolidation: merge analysis_cores, combine signals
  - Partial Execution: korrekte Behandlung von SKIPPED/FAILED Pfaden

- workflow_executor.py: execute_join_node() Integration
  - BFS-Traversierung erweitert für Join-Nodes
  - NodeExecutionState List → Dict Konvertierung für Signale
  - Signal-Name-Kollisionen via node_id Präfix gelöst

Testing (49 Tests passing):
- test_phase4_join_nodes.py: 18 neue Unit Tests
  - Join-Strategien (wait_all, wait_any, best_effort)
  - Skip-Handling (ignore, placeholder)
  - Result Consolidation (merge, combine)
  - Partial Execution (mixed status paths)
  - Helper Functions (collect, check, merge, combine)

- Backward Compatibility: 31 Phase 2/3 Tests (alle passing)
  - test_phase2_workflow_executor.py: 1 Test aktualisiert
  - test_phase3_logic_evaluator.py: 20 Tests unverändert

Konzept: konzept_workflow_engine_konsolidated.md (Sektion 8.8)
Anforderungsanalyse: phase4_anforderungsanalyse.md

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-04 12:27:31 +02:00
LarsandClaude Opus 4.6 2ce0874dcb feat: Phase 3 - Logic Nodes + Conditional Branching
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Backend:
- logic_evaluator.py (NEU, 307 Zeilen): Deterministischer Logic Evaluator
  - Vergleichsoperatoren: EQ, NEQ, IN, NOT_IN, GT, LT, GTE, LTE, CONTAINS
  - Logische Operatoren: AND, OR, NOT mit Verschachtelung
  - Resolve signal references (node_id.question_type)
  - Error handling für UNCLEAR/INVALID/NOT_DECIDABLE Signale

- workflow_executor.py (ERWEITERT):
  - execute_logic_node(): Bedingungen evaluieren, Pfade aktivieren/deaktivieren
  - execute_workflow(): BFS-Traversierung mit Edge-Activation statt Sequential
  - _apply_fallback(): 4 Fallback-Strategien (CONSERVATIVE_SKIP, DEFAULT_PATH, UNCERTAINTY_PATH, DOCUMENT_ONLY)
  - _has_active_incoming_edge(): Prüft ob Node erreichbar ist
  - _get_edges_by_label(): Findet then/else/uncertainty Pfade

- workflow_models.py (ERWEITERT):
  - LogicOperator.CONTAINS hinzugefügt

- version.py: 0.9k → 0.9l, workflow 0.3.0 → 0.4.0

Tests:
- test_phase3_logic_evaluator.py (NEU): 20 Unit Tests (alle passing)
  - Comparison operators (EQ, NEQ, IN, GT, LT, CONTAINS)
  - Logical operators (AND, OR, NOT)
  - Nested expressions
  - Error handling (missing refs, UNCLEAR/INVALID signals)

- test_phase2_workflow_executor.py (AKTUALISIERT): 11 Tests (alle passing)
  - execute_node() graph parameter hinzugefügt (Phase 3 requirement)
  - test_execute_node_unknown_type: logic → join (logic jetzt implementiert)

- test_phase3_workflow_branching.py (NEU): Integration Tests vorbereitet
  - Erfordert vollständige DB-Mock-Strategie (wird in E2E-Test nachgeholt)

Phase 2 Backward Compatibility: ✅ Alle Phase 2 Tests bestehen weiterhin

Konzept: .claude/task/Workflow_engine_prompting_engine/konzept_workflow_engine_konsolidated.md
Anforderungsanalyse: .claude/task/Workflow_engine_prompting_engine/phase3_anforderungsanalyse.md

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-04 08:02:22 +02:00
Lars 16dc08cd7d test: Add regression test for hybrid model - node spectrum overrides catalog
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
2026-04-03 21:55:19 +02:00
Lars c588372f3a fix: Hybrid model - node-specific question spectrums override catalog (Phase 1 requirement)
Deploy Development / deploy (push) Successful in 44s
Build Test / build-frontend (push) Successful in 21s
Build Test / lint-backend (push) Successful in 0s
2026-04-03 21:49:13 +02:00
Lars 585f189b13 fix: Remove extra_vars parameter from resolve_placeholders call - function doesn't support it yet
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
2026-04-03 21:44:39 +02:00
Lars acd4830795 fix: Access topological_order directly from engine, not from non-existent validator attribute
Deploy Development / deploy (push) Successful in 50s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 1s
2026-04-03 21:38:45 +02:00
Lars ac2e7cf5bb fix: Use dict keys for all RealDictCursor row access in Phase 2 code
Deploy Development / deploy (push) Successful in 50s
Build Test / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 1s
2026-04-03 21:36:44 +02:00
Lars 0725461056 fix: Use dict keys instead of numeric indices for RealDictCursor rows
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
2026-04-03 21:34:47 +02:00
Lars ce4666a535 fix: Import call_openrouter from routers.prompts instead of non-existent openrouter module
Deploy Development / deploy (push) Successful in 47s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
2026-04-03 21:33:09 +02:00
Lars 1f8791f4dd feat: Phase 2 - Normalisierung + Workflow Executor
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Backend:
- normalization_engine.py (200 Zeilen): Synonym-Mapping, 5 Statuswerte
  * normalize_decision_signal(): Kaskade (exact → case → synonym → invalid)
  * apply_synonym_mapping(): DB-basierte Synonyme (case-insensitive)
  * normalize_all_signals(): Batch-Processing gegen Katalog
  * load_question_catalog(): Lädt normalization_rules aus DB
- workflow_executor.py (440 Zeilen): Sequenzielle Workflow-Ausführung
  * execute_workflow(): Traversiert DAG in topologischer Reihenfolge
  * execute_node(): Führt analysis nodes aus (start/end = no-op)
  * aggregate_results(): Kombiniert analysis_core + normalized_signals
  * save_execution_state(): Persistiert in workflow_executions
- workflow_models.py: Erweitert um Phase 2 Models
  * SignalStatus Enum (valid, normalized, unclear, invalid, not_decidable)
  * NormalizedSignal (question_type, raw_value, normalized_value, status)
  * NodeExecutionState (node_id, status, analysis_core, normalized_signals)
  * ExecutionResult (execution_id, workflow_id, status, node_states, aggregated_result)
- workflow_engine.py: Neue Funktion get_execution_order()
  * Flattened topological sort für sequenzielle Execution
  * Phase 7: Wird zu levels (parallele Execution)
- prompt_executor.py: execute_workflow_prompt() Implementierung
  * Ruft workflow_executor.execute_workflow() auf
  * Konvertiert ExecutionResult zu API-Response
- routers/workflows.py (230 Zeilen): Workflow Execution API
  * POST /api/workflows/{id}/execute (mit enable_debug)
  * GET /api/workflows/executions/{id} (lädt gespeicherten State)
  * GET /api/workflows (listet alle aktiven Workflows)
  * GET /api/workflows/{id} (lädt einzelnen Workflow mit Graph)
- main.py: Router-Registrierung (workflows.router)

Tests:
- test_phase2_normalization.py (17 Tests): Alle Normalisierungs-Szenarien
  * Exact match, case-insensitive, synonym mapping, invalid, whitespace
  * Batch-Normalisierung, not_in_catalog, mixed validity
- test_phase2_workflow_executor.py (10 Tests): Executor + Aggregation
  * aggregate_results mit verschiedenen Konstellationen
  * execute_node für start/end/analysis/unknown
  * Integration mit question_augmenter + result_container_parser

Alle 27 Unit-Tests bestanden.

version: 0.9k (backend)
module:  workflow 0.3.0

Konzept: .claude/task/Workflow_engine_prompting_engine/anforderungsanalyse_umsetzungsplan.md (Phase 2)
2026-04-03 21:20:23 +02:00
Lars ca562b7130 feat: Phase 1 - Fragenergänzung + Strukturierter Container
Deploy Development / deploy (push) Successful in 49s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
Backend:
- question_augmenter.py (290 Zeilen): Hybrid-Modell für Fragenergänzungen
  * merge_question_augmentations(): Knotengebundene Fragen überschreiben Prompt-Defaults
  * augment_prompt_with_questions(): Markdown-formatierte Fragenergänzung
  * parse_question_augmentations_from_jsonb(): JSONB → QuestionAugmentation[]
- result_container_parser.py (250 Zeilen): Markdown-Sektionen-Parsing
  * parse_result_container(): Extrahiert Analysekern, Entscheidungsanteil, Begründungsanker
  * validate_decision_signal(): Normalisierung gegen answer_spectrum
  * Fallback-Parsing bei unstrukturierten Antworten
- routers/workflow_questions.py (236 Zeilen): CRUD für workflow_question_catalog
  * GET /api/workflow/questions (mit active_only Filter)
  * POST/PUT/DELETE (Admin only, Soft Delete)
- prompt_executor.py: Integration in execute_base_prompt()
  * Fragenergänzung vor LLM-Call (wenn node_questions oder catalog vorhanden)
  * Result-Container-Parsing nach LLM-Response
- main.py: Router-Registrierung (workflow_questions)

Tests:
- test_phase1_question_augmenter.py (8 Tests): Hybrid-Modell, Formatierung, JSONB-Parsing
- test_phase1_result_container_parser.py (17 Tests): Sektion-Extraktion, Decision-Parsing, Validierung

Alle 25 Unit-Tests bestanden.

version: 0.9j (backend)
module:  workflow 0.2.0

Konzept: .claude/task/Workflow_engine_prompting_engine/konzept_workflow_engine_konsolidated.md (Phase 1)
2026-04-03 18:02:25 +02:00
LarsandClaude Opus 4.6 b5be6e21a5 feat: Phase 0 - Workflow Engine Foundation
Deploy Development / deploy (push) Successful in 50s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Backend:
- DB-Migration 034: workflow_definitions, workflow_question_catalog, workflow_executions
- ai_prompts.question_augmentations JSONB-Spalte (Hybridmodell: Prompt-Defaults)
- 6 Grundtypen Fragenergänzungen mit Normalisierungsregeln (Seed-Daten)
- Pydantic-Modelle (16 Models, 11 Enums) in workflow_models.py
- Workflow-Engine: Graph-Parsing, Topologische Sortierung, DAG-Validierung
- Dispatcher-Erweiterung type='workflow' (Stub für Phase 1-3)
- Adjacency Lists, Erreichbarkeits-Prüfungen, Zyklen-Erkennung

Testing:
- 22 Unit-Tests (alle bestanden): Graph-Parsing, Validierung, Topologische Sortierung
- Fixtures: simple_valid_graph, parallel_graph, branching_graph

Version:
- APP_VERSION 0.9i
- DB_SCHEMA_VERSION 20260403
- Module: workflow 0.1.0

Anforderungsanalyse: .claude/task/Workflow_engine_prompting_engine/anforderungsanalyse_umsetzungsplan.md
Konzept-Basis: .claude/task/Workflow_engine_prompting_engine/konzept_workflow_engine_konsolidated.md

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 16:55:51 +02:00
191 changed files with 25303 additions and 1493 deletions

No files matched your search

+6
View File
@@ -27,3 +27,9 @@ ALLOWED_ORIGINS=https://mitai.jinkendo.de
# ── Pfade ───────────────────────────────────────────────────────
PHOTOS_DIR=/app/photos
ENVIRONMENT=production
# ── Gitea API (lokal, für scripts/gitea/gitea_api.py – niemals committen) ──
GITEA_BASE_URL=http://192.168.2.144:3000
GITEA_OWNER=Lars
GITEA_REPO=mitai-jinkendo
GITEA_TOKEN=
+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
+5 -1
View File
@@ -61,4 +61,8 @@ tmp/
#.claude Konfiguration
.claude/
.claude/settings.local.jsonfrontend/package-lock.json
# Cursor MCP mit Secrets (Example: .cursor/mcp.json.example)
.cursor/mcp.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 []
+396
View File
@@ -0,0 +1,396 @@
"""
Join Evaluator (Phase 4)
Evaluiert Join-Knoten: Sammelt incoming paths, prüft Strategien, konsolidiert Ergebnisse.
Join-Strategien:
- wait_all: Alle eingehenden Pfade müssen ausgeführt sein (strikt)
- wait_any: Mindestens ein Pfad muss ausgeführt sein
- best_effort: Verwendet verfügbare Pfade (fehlertoleranz)
Skip-Handling:
- ignore_skipped: Übersprungene Pfade nicht in Ergebnis
- use_placeholder: Platzhalter für übersprungene Pfade
- require_minimum: Mindestanzahl erforderlich
Konzept-Basis: konzept_workflow_engine_konsolidated.md (Sektion 8.8)
Anforderungsanalyse: phase4_anforderungsanalyse.md
"""
from typing import Dict, Any, Optional, List, NamedTuple
from pydantic import BaseModel, Field
import logging
from workflow_models import (
WorkflowNode,
WorkflowGraph,
JoinStrategy,
SkipHandling,
NodeStatus,
NormalizedSignal
)
logger = logging.getLogger(__name__)
# ── Data Structures ───────────────────────────────────────────────────────────
class PathStatus(NamedTuple):
"""
Status eines eingehenden Pfads am Join-Node.
Attributes:
node_id: ID des Source-Nodes (Node vor dem Join)
status: Ausführungsstatus (EXECUTED, SKIPPED, FAILED)
analysis_core: Analyseinhalt (wenn vorhanden)
signals: Normalisierte Signale des Nodes (question_type → Signal)
"""
node_id: str
status: NodeStatus
analysis_core: Optional[str]
signals: Dict[str, NormalizedSignal] # Converted from List to Dict by _collect_incoming_paths
class JoinResult(BaseModel):
"""
Ergebnis der Join-Evaluation.
Enthält konsolidierte Daten aller eingehenden Pfade.
"""
ready: bool = Field(..., description="Sind erforderliche Pfade verfügbar?")
consolidated_analysis_core: Dict[str, str] = Field(
default_factory=dict,
description="Konsolidierte Analysekerne: node_id → analysis_core"
)
consolidated_signals: Dict[str, NormalizedSignal] = Field(
default_factory=dict,
description="Konsolidierte Signale: node_id.question_id → signal"
)
metadata: Dict[str, Any] = Field(
default_factory=dict,
description="Pfad-Status, Statistiken, Hinweise"
)
error: Optional[str] = Field(None, description="Fehler bei nicht erfüllter Strategie")
# ── Helper Functions ──────────────────────────────────────────────────────────
def _collect_incoming_paths(
node: WorkflowNode,
graph: WorkflowGraph,
context: Dict[str, Any]
) -> List[PathStatus]:
"""
Sammelt alle eingehenden Pfade eines Join-Nodes.
Args:
node: Join-Node
graph: Workflow-Graph
context: Execution context mit node_results
Returns:
List[PathStatus] - Status aller eingehenden Pfade
Details:
- Findet alle Edges mit to_node == join_node.id
- Extrahiert NodeExecutionState aus context["node_results"]
- Erstellt PathStatus für jeden incoming node
"""
incoming_edges = [e for e in graph.edges if e.to_node == node.id]
paths: List[PathStatus] = []
logger.debug(f"Join node {node.id}: Found {len(incoming_edges)} incoming edges")
for edge in incoming_edges:
source_node_id = edge.from_node
# Hole NodeExecutionState aus context
node_state = context["node_results"].get(source_node_id)
if node_state:
# Node wurde ausgeführt
# Convert List[NormalizedSignal] to Dict[question_type → Signal]
signals_dict = {}
if node_state.normalized_signals:
for signal in node_state.normalized_signals:
signals_dict[signal.question_type] = signal
path = PathStatus(
node_id=source_node_id,
status=node_state.status,
analysis_core=node_state.analysis_core,
signals=signals_dict
)
paths.append(path)
logger.debug(f" Path {source_node_id}: {node_state.status.value}")
else:
# Node nicht in node_results → wurde nicht besucht (unreachable)
path = PathStatus(
node_id=source_node_id,
status=NodeStatus.SKIPPED,
analysis_core=None,
signals={}
)
paths.append(path)
logger.debug(f" Path {source_node_id}: not visited (unreachable)")
return paths
def _check_join_strategy(
paths: List[PathStatus],
strategy: JoinStrategy
) -> tuple[bool, Optional[str]]:
"""
Prüft ob Join-Strategie erfüllt ist.
Args:
paths: Liste aller eingehenden Pfade
strategy: Join-Strategie (wait_all, wait_any, best_effort)
Returns:
(ready: bool, error: Optional[str])
- ready: True wenn Strategie erfüllt
- error: Fehlermeldung wenn nicht erfüllt
Strategien:
- wait_all: Alle Pfade EXECUTED (strikt)
- wait_any: Mindestens ein Pfad EXECUTED
- best_effort: Immer ready (fehlertoleranz)
"""
executed_paths = [p for p in paths if p.status == NodeStatus.EXECUTED]
failed_paths = [p for p in paths if p.status == NodeStatus.FAILED]
skipped_paths = [p for p in paths if p.status == NodeStatus.SKIPPED]
logger.debug(f"Join strategy check: {strategy.value}")
logger.debug(f" Executed: {len(executed_paths)}/{len(paths)}")
logger.debug(f" Failed: {len(failed_paths)}")
logger.debug(f" Skipped: {len(skipped_paths)}")
if strategy == JoinStrategy.WAIT_ALL:
# Alle Pfade müssen EXECUTED sein
if len(executed_paths) < len(paths):
missing = [p.node_id for p in paths if p.status != NodeStatus.EXECUTED]
error = f"wait_all strategy failed: {len(executed_paths)}/{len(paths)} paths executed. Missing: {missing}"
logger.warning(error)
return False, error
return True, None
elif strategy == JoinStrategy.WAIT_ANY:
# Mindestens ein Pfad EXECUTED
if len(executed_paths) == 0:
error = f"wait_any strategy failed: no paths executed ({len(failed_paths)} failed, {len(skipped_paths)} skipped)"
logger.warning(error)
return False, error
return True, None
elif strategy == JoinStrategy.BEST_EFFORT:
# Immer bereit (fehlertoleranz)
if len(executed_paths) == 0:
logger.info(f"best_effort: No paths executed, but continuing (fehlertoleranz)")
return True, None
else:
# Unbekannte Strategie
error = f"Unknown join strategy: {strategy}"
logger.error(error)
return False, error
def _merge_analysis_cores(
paths: List[PathStatus],
skip_handling: Optional[SkipHandling]
) -> Dict[str, str]:
"""
Merged Analysekerne aller eingehenden Pfade.
Args:
paths: Liste aller Pfade
skip_handling: Umgang mit übersprungenen Pfaden
Returns:
Dict[node_id → analysis_core]
Details:
- EXECUTED Pfade: analysis_core übernehmen
- SKIPPED Pfade: abhängig von skip_handling
- IGNORE_SKIPPED: nicht in Ergebnis
- USE_PLACEHOLDER: Platzhalter "[Skipped: {node_id}]"
- FAILED Pfade: Platzhalter "[Failed: {node_id}]"
"""
merged: Dict[str, str] = {}
for path in paths:
if path.status == NodeStatus.EXECUTED and path.analysis_core:
# Normale Übernahme
merged[path.node_id] = path.analysis_core
elif path.status == NodeStatus.SKIPPED:
# Skip-Handling
if skip_handling == SkipHandling.USE_PLACEHOLDER:
merged[path.node_id] = f"[Path skipped: {path.node_id}]"
elif skip_handling == SkipHandling.IGNORE_SKIPPED:
# Nicht in Ergebnis
pass
# REQUIRE_MINIMUM wird in _check_join_strategy behandelt
elif path.status == NodeStatus.FAILED:
# Failed Pfade dokumentieren
merged[path.node_id] = f"[Path failed: {path.node_id}]"
logger.debug(f"Merged analysis cores: {len(merged)} entries")
return merged
def _combine_signals(
paths: List[PathStatus]
) -> Dict[str, NormalizedSignal]:
"""
Kombiniert Signale aller eingehenden Pfade.
Args:
paths: Liste aller Pfade
Returns:
Dict[node_id.question_id → NormalizedSignal]
Details:
- Signal-Namen werden mit node_id geprefixed (verhindert Kollision)
- Format: "node_id.question_id" → Signal
- Nur EXECUTED Pfade werden berücksichtigt
Beispiel:
path_a.relevanz → Signal(value="hoch", ...)
path_b.relevanz → Signal(value="mittel", ...)
"""
combined: Dict[str, NormalizedSignal] = {}
for path in paths:
if path.status != NodeStatus.EXECUTED:
# Nur ausgeführte Pfade haben valide Signale
continue
for signal_key, signal in path.signals.items():
# Präfix mit node_id (verhindert Kollision)
prefixed_key = f"{path.node_id}.{signal_key}"
combined[prefixed_key] = signal
logger.debug(f"Combined signals: {len(combined)} entries")
return combined
# ── Main Function ─────────────────────────────────────────────────────────────
def evaluate_join_node(
node: WorkflowNode,
graph: WorkflowGraph,
context: Dict[str, Any]
) -> JoinResult:
"""
Evaluiert Join-Node: Sammelt Pfade, prüft Strategie, konsolidiert Ergebnisse.
Args:
node: Join-Node aus Workflow-Graph
graph: Gesamter Workflow-Graph
context: Execution context mit node_results
Returns:
JoinResult mit konsolidierten Daten
Workflow:
1. Sammle incoming paths (_collect_incoming_paths)
2. Prüfe Join-Strategie (_check_join_strategy)
3. Merge analysis_cores (_merge_analysis_cores)
4. Combine signals (_combine_signals)
5. Baue metadata (Pfad-Status, Statistiken)
Beispiel:
>>> result = evaluate_join_node(join_node, graph, context)
>>> result.ready
True
>>> result.consolidated_analysis_core
{"path_a": "Analysis A...", "path_b": "Analysis B..."}
"""
logger.info(f"Evaluating join node: {node.id}")
# 1. Sammle incoming paths
paths = _collect_incoming_paths(node, graph, context)
if not paths:
# Kein eingehender Pfad (Fehlkonfiguration)
logger.warning(f"Join node {node.id}: No incoming edges found")
return JoinResult(
ready=False,
error="No incoming edges for join node",
metadata={"note": "Configuration error: join node must have incoming edges"}
)
# 2. Prüfe Join-Strategie
strategy = node.join_strategy or JoinStrategy.WAIT_ALL # Default
skip_handling = node.skip_handling or SkipHandling.IGNORE_SKIPPED # Default
ready, strategy_error = _check_join_strategy(paths, strategy)
if not ready:
# Strategie nicht erfüllt
executed_list = [p.node_id for p in paths if p.status == NodeStatus.EXECUTED]
skipped_list = [p.node_id for p in paths if p.status == NodeStatus.SKIPPED]
failed_list = [p.node_id for p in paths if p.status == NodeStatus.FAILED]
return JoinResult(
ready=False,
error=strategy_error,
metadata={
"join_strategy": strategy.value,
"total_paths": len(paths),
"executed_paths": len(executed_list),
"skipped_paths": len(skipped_list),
"failed_paths": len(failed_list),
"path_details": {
"executed": executed_list,
"skipped": skipped_list,
"failed": failed_list
}
}
)
# 3. Merge analysis_cores
merged_cores = _merge_analysis_cores(paths, skip_handling)
# 4. Combine signals
combined_signals = _combine_signals(paths)
# 5. Baue metadata
executed_count = sum(1 for p in paths if p.status == NodeStatus.EXECUTED)
skipped_count = sum(1 for p in paths if p.status == NodeStatus.SKIPPED)
failed_count = sum(1 for p in paths if p.status == NodeStatus.FAILED)
metadata = {
"join_strategy": strategy.value,
"skip_handling": skip_handling.value,
"total_paths": len(paths),
"executed_paths": executed_count,
"skipped_paths": skipped_count,
"failed_paths": failed_count,
"path_details": {
"executed": [p.node_id for p in paths if p.status == NodeStatus.EXECUTED],
"skipped": [p.node_id for p in paths if p.status == NodeStatus.SKIPPED],
"failed": [p.node_id for p in paths if p.status == NodeStatus.FAILED]
}
}
# Spezielle Hinweise
if executed_count == 0 and strategy == JoinStrategy.BEST_EFFORT:
metadata["note"] = "No paths executed, but best_effort allows empty consolidation"
logger.info(f"Join node {node.id}: Consolidated {executed_count}/{len(paths)} paths")
return JoinResult(
ready=True,
consolidated_analysis_core=merged_cores,
consolidated_signals=combined_signals,
metadata=metadata
)
+268
View File
@@ -0,0 +1,268 @@
"""
Logic Evaluator (Phase 3)
Rein deterministischer boolescher Evaluator für Workflow-Bedingungen.
Keine KI, keine Interpretation - nur strikte Logik-Auswertung.
Unterstützt:
- Vergleichsoperatoren: EQ, NEQ, IN, NOT_IN, GT, LT, GTE, LTE, CONTAINS
- Logische Operatoren: AND, OR, NOT
- Verschachtelung via operands
"""
from typing import Dict, Any, Optional, Tuple, List
import logging
from workflow_models import (
LogicExpression,
LogicOperator,
NormalizedSignal,
SignalStatus
)
logger = logging.getLogger(__name__)
def evaluate_logic_expression(
expression: LogicExpression,
context: Dict[str, Any]
) -> Tuple[bool, Optional[str]]:
"""
Evaluiert LogicExpression gegen context.
Args:
expression: Die auszuwertende Bedingung
context: Execution context mit node_results
Returns:
(result: bool, error: Optional[str])
- result: True/False basierend auf Auswertung
- error: Fehlermeldung wenn Evaluation fehlschlägt
Beispiel:
expression = LogicExpression(
operator=LogicOperator.EQ,
ref="body.relevanz",
value="decrease"
)
result, error = evaluate_logic_expression(expression, context)
"""
try:
operator = expression.operator
# Logische Operatoren (verschachtelt)
if operator == LogicOperator.AND:
return _evaluate_and(expression, context)
elif operator == LogicOperator.OR:
return _evaluate_or(expression, context)
elif operator == LogicOperator.NOT:
return _evaluate_not(expression, context)
# Vergleichsoperatoren (benötigen ref)
elif operator in [
LogicOperator.EQ, LogicOperator.NEQ,
LogicOperator.IN, LogicOperator.NOT_IN,
LogicOperator.GT, LogicOperator.LT,
LogicOperator.GTE, LogicOperator.LTE,
LogicOperator.CONTAINS
]:
return _evaluate_comparison(expression, context)
else:
return False, f"Unknown operator: {operator}"
except Exception as e:
logger.error(f"Logic evaluation failed: {e}", exc_info=True)
return False, str(e)
def _evaluate_and(
expression: LogicExpression,
context: Dict[str, Any]
) -> Tuple[bool, Optional[str]]:
"""Evaluiert AND - alle operands müssen True sein."""
if not expression.operands:
return False, "AND requires operands"
for operand in expression.operands:
result, error = evaluate_logic_expression(operand, context)
if error:
return False, f"AND operand failed: {error}"
if not result:
return False, None # Short-circuit: einer False → gesamt False
return True, None
def _evaluate_or(
expression: LogicExpression,
context: Dict[str, Any]
) -> Tuple[bool, Optional[str]]:
"""Evaluiert OR - mindestens ein operand muss True sein."""
if not expression.operands:
return False, "OR requires operands"
errors = []
for operand in expression.operands:
result, error = evaluate_logic_expression(operand, context)
if error:
errors.append(error)
continue
if result:
return True, None # Short-circuit: einer True → gesamt True
# Alle False oder Fehler
if errors:
return False, f"All OR operands failed: {', '.join(errors)}"
return False, None
def _evaluate_not(
expression: LogicExpression,
context: Dict[str, Any]
) -> Tuple[bool, Optional[str]]:
"""Evaluiert NOT - negiert operand."""
if not expression.operands or len(expression.operands) != 1:
return False, "NOT requires exactly one operand"
result, error = evaluate_logic_expression(expression.operands[0], context)
if error:
return False, f"NOT operand failed: {error}"
return not result, None
def _evaluate_comparison(
expression: LogicExpression,
context: Dict[str, Any]
) -> Tuple[bool, Optional[str]]:
"""Evaluiert Vergleichsoperator."""
if not expression.ref:
return False, f"{expression.operator} requires ref"
# Signal auflösen
signal, error = resolve_signal_reference(expression.ref, context)
if error:
return False, error
if signal is None:
return False, f"Signal not found: {expression.ref}"
# Prüfe Signal-Status
if signal.status in [SignalStatus.UNCLEAR, SignalStatus.INVALID, SignalStatus.NOT_DECIDABLE]:
return False, f"Signal '{expression.ref}' has status {signal.status} - cannot evaluate"
# Vergleich durchführen
left_value = signal.normalized_value or signal.raw_value
right_value = expression.value
return compare_values(expression.operator, left_value, right_value)
def resolve_signal_reference(
ref: str,
context: Dict[str, Any]
) -> Tuple[Optional[NormalizedSignal], Optional[str]]:
"""
Löst Referenz wie "node_1.relevanz" auf.
Args:
ref: Signal-Referenz im Format "node_id.question_type"
context: Execution context mit node_results
Returns:
(signal, error_message)
Error wenn:
- Node existiert nicht in context
- Signal-Typ existiert nicht für diesen Node
"""
# Parse reference
parts = ref.split(".")
if len(parts) != 2:
return None, f"Invalid reference format: '{ref}' (expected 'node_id.question_type')"
node_id, question_type = parts
# Hole Node-Results aus context
node_results = context.get("node_results", {})
if node_id not in node_results:
return None, f"Node '{node_id}' not found in context"
node_state = node_results[node_id]
# Suche Signal
for signal in node_state.normalized_signals:
if signal.question_type == question_type:
return signal, None
return None, f"Signal '{question_type}' not found in node '{node_id}'"
def compare_values(
operator: LogicOperator,
left: Any,
right: Any
) -> Tuple[bool, Optional[str]]:
"""
Führt Vergleichsoperation durch.
Args:
operator: Vergleichsoperator
left: Linker Wert (aus Signal)
right: Rechter Wert (aus Expression)
Returns:
(result: bool, error: Optional[str])
"""
try:
if operator == LogicOperator.EQ:
return left == right, None
elif operator == LogicOperator.NEQ:
return left != right, None
elif operator == LogicOperator.IN:
if not isinstance(right, (list, tuple, set)):
return False, f"IN operator requires list, got {type(right)}"
return left in right, None
elif operator == LogicOperator.NOT_IN:
if not isinstance(right, (list, tuple, set)):
return False, f"NOT_IN operator requires list, got {type(right)}"
return left not in right, None
elif operator == LogicOperator.CONTAINS:
# left enthält right (z.B. String-Suche)
if isinstance(left, str) and isinstance(right, str):
return right in left, None
elif isinstance(left, (list, tuple, set)):
return right in left, None
else:
return False, f"CONTAINS not supported for types {type(left)}/{type(right)}"
elif operator == LogicOperator.GT:
return _numeric_compare(left, right, lambda a, b: a > b)
elif operator == LogicOperator.LT:
return _numeric_compare(left, right, lambda a, b: a < b)
elif operator == LogicOperator.GTE:
return _numeric_compare(left, right, lambda a, b: a >= b)
elif operator == LogicOperator.LTE:
return _numeric_compare(left, right, lambda a, b: a <= b)
else:
return False, f"Unknown comparison operator: {operator}"
except Exception as e:
return False, f"Comparison failed: {e}"
def _numeric_compare(left: Any, right: Any, compare_fn) -> Tuple[bool, Optional[str]]:
"""Hilfsfunktion für numerische Vergleiche."""
try:
left_num = float(left) if not isinstance(left, (int, float)) else left
right_num = float(right) if not isinstance(right, (int, float)) else right
return compare_fn(left_num, right_num), None
except (ValueError, TypeError) as e:
return False, f"Cannot compare as numbers: {left} vs {right} ({e})"
+12
View File
@@ -26,6 +26,11 @@ from routers import evaluation # v9d/v9e Training Type Profiles (#15)
from routers import goals, focus_areas # v9e/v9g Goal System v2.0 (Dynamic Focus Areas)
from routers import goal_types, goal_progress, training_phases, fitness_tests # v9h Goal System (Split routers)
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"))
@@ -110,6 +115,13 @@ app.include_router(focus_areas.router) # /api/focus-areas/* (v9g Focus
# Phase 0c Multi-Layer Architecture
app.include_router(charts.router) # /api/charts/* (Phase 0c Charts API)
# 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("/")
def root():
@@ -0,0 +1,35 @@
-- Migration 016: Workflow Support in ai_prompts (Phase 5)
-- Erweitert ai_prompts für type='workflow' (Option B - Backward-kompatibel)
-- Neue Spalte für Workflow-Graphen
ALTER TABLE ai_prompts ADD COLUMN graph_data JSONB;
-- Index für Workflow-Queries
CREATE INDEX IF NOT EXISTS idx_ai_prompts_type ON ai_prompts(type);
CREATE INDEX IF NOT EXISTS idx_ai_prompts_graph_data ON ai_prompts USING GIN (graph_data);
-- Kommentar
COMMENT ON COLUMN ai_prompts.graph_data IS 'Workflow-Graph (nur für type=workflow): {nodes: [...], edges: [...], metadata: {...}}';
-- Beispiel-Struktur (Dokumentation):
-- {
-- "nodes": [
-- {"id": "start", "type": "start", "label": "Start", "position": {"x": 100, "y": 100}},
-- {"id": "analysis_1", "type": "analysis", "prompt_id": 5, "questions": [...], ...},
-- {"id": "logic_1", "type": "logic", "condition": {...}, ...},
-- {"id": "join_1", "type": "join", "join_strategy": "wait_all", ...},
-- {"id": "end", "type": "end", "label": "Ende", "position": {"x": 500, "y": 300}}
-- ],
-- "edges": [
-- {"id": "e1", "source": "start", "target": "analysis_1"},
-- {"id": "e2", "source": "analysis_1", "target": "logic_1"},
-- {"id": "e3", "source": "logic_1", "target": "join_1"},
-- {"id": "e4", "source": "join_1", "target": "end"}
-- ],
-- "metadata": {
-- "created_at": "2026-04-04T12:00:00Z",
-- "version": "1.0"
-- }
-- }
-- Migration erfolgreich
@@ -0,0 +1,132 @@
-- Migration 034: Workflow Foundation
-- Phase 0: Datenmodell für Workflow-Erweiterung der Prompt Engine
-- Erstellt: 2026-04-03
-- ============================================================
-- Tabelle: workflow_definitions
-- Speichert Workflow-Graphen (Knoten + Kanten)
-- ============================================================
CREATE TABLE IF NOT EXISTS workflow_definitions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255) NOT NULL,
slug VARCHAR(100) UNIQUE NOT NULL,
description TEXT,
graph JSONB NOT NULL, -- Der Workflow-Graph (Knoten + Kanten)
version INTEGER DEFAULT 1,
active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_workflow_definitions_slug ON workflow_definitions(slug);
CREATE INDEX IF NOT EXISTS idx_workflow_definitions_active ON workflow_definitions(active);
-- ============================================================
-- Tabelle: workflow_question_catalog
-- Katalog der Fragenergänzungen (6 Grundtypen)
-- ============================================================
CREATE TABLE IF NOT EXISTS workflow_question_catalog (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
question_type VARCHAR(50) NOT NULL, -- relevanz, prioritaet, selektion, ausschluss, eskalation, unsicherheit
label VARCHAR(255) NOT NULL,
question_template TEXT NOT NULL, -- Template für die Frage
answer_spectrum JSONB NOT NULL, -- z.B. ["ja", "nein", "unklar"]
normalization_rules JSONB, -- Regeln für Normalisierung (Synonyme, etc.)
active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_workflow_question_catalog_type ON workflow_question_catalog(question_type);
CREATE INDEX IF NOT EXISTS idx_workflow_question_catalog_active ON workflow_question_catalog(active);
-- Seed: 6 Grundtypen der Fragenergänzungen
INSERT INTO workflow_question_catalog (question_type, label, question_template, answer_spectrum, normalization_rules, active) VALUES
(
'relevanz',
'Relevanz-Frage',
'Ist eine vertiefte Analyse in diesem Bereich relevant?',
'["ja", "nein", "unklar"]'::JSONB,
'{"synonyms": {"ja": ["yes", "Ja", "JA", "relevant", "sinnvoll"], "nein": ["no", "Nein", "NEIN", "nicht relevant", "unwichtig"], "unklar": ["unclear", "unsure", "vielleicht", "möglicherweise"]}}'::JSONB,
true
),
(
'prioritaet',
'Prioritäts-Frage',
'Wie hoch ist die Priorität für eine Analyse in diesem Bereich?',
'["hoch", "mittel", "niedrig", "unklar"]'::JSONB,
'{"synonyms": {"hoch": ["high", "Hoch", "HOCH", "urgent", "dringend"], "mittel": ["medium", "Mittel", "MITTEL", "moderat"], "niedrig": ["low", "Niedrig", "NIEDRIG", "gering"], "unklar": ["unclear", "unsure", "kann nicht einschätzen"]}}'::JSONB,
true
),
(
'selektion',
'Selektions-Frage',
'Soll dieser Pfad ausgewählt werden?',
'["ja", "nein", "unklar"]'::JSONB,
'{"synonyms": {"ja": ["yes", "Ja", "JA", "auswählen", "select"], "nein": ["no", "Nein", "NEIN", "nicht auswählen", "skip"], "unklar": ["unclear", "unsure", "vielleicht"]}}'::JSONB,
true
),
(
'ausschluss',
'Ausschluss-Frage',
'Soll dieser Pfad ausgeschlossen werden?',
'["ja", "nein", "unklar"]'::JSONB,
'{"synonyms": {"ja": ["yes", "Ja", "JA", "ausschließen", "exclude"], "nein": ["no", "Nein", "NEIN", "nicht ausschließen", "include"], "unklar": ["unclear", "unsure", "vielleicht"]}}'::JSONB,
true
),
(
'eskalation',
'Eskalations-Frage',
'Ist eine Eskalation oder besondere Aufmerksamkeit erforderlich?',
'["ja", "nein", "unklar"]'::JSONB,
'{"synonyms": {"ja": ["yes", "Ja", "JA", "eskalieren", "alert"], "nein": ["no", "Nein", "NEIN", "normal", "routine"], "unklar": ["unclear", "unsure", "vielleicht"]}}'::JSONB,
true
),
(
'unsicherheit',
'Unsicherheits-Frage',
'Besteht Unsicherheit in der Bewertung?',
'["ja", "nein", "unklar"]'::JSONB,
'{"synonyms": {"ja": ["yes", "Ja", "JA", "unsicher", "uncertain"], "nein": ["no", "Nein", "NEIN", "sicher", "certain"], "unklar": ["unclear", "unsure", "vielleicht"]}}'::JSONB,
true
);
-- ============================================================
-- Tabelle: workflow_executions
-- Ausführungs-Log für Workflow-Runs
-- ============================================================
CREATE TABLE IF NOT EXISTS workflow_executions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
workflow_id UUID REFERENCES workflow_definitions(id) ON DELETE CASCADE,
profile_id UUID REFERENCES profiles(id) ON DELETE CASCADE,
status VARCHAR(20) NOT NULL DEFAULT 'running', -- running, completed, failed, partial
node_states JSONB, -- Status jedes Knotens (executed, skipped, unclear, failed)
execution_log JSONB, -- Detaillierter Ablauf
started_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
completed_at TIMESTAMP WITH TIME ZONE
);
CREATE INDEX IF NOT EXISTS idx_workflow_executions_workflow_id ON workflow_executions(workflow_id);
CREATE INDEX IF NOT EXISTS idx_workflow_executions_profile_id ON workflow_executions(profile_id);
CREATE INDEX IF NOT EXISTS idx_workflow_executions_status ON workflow_executions(status);
CREATE INDEX IF NOT EXISTS idx_workflow_executions_started_at ON workflow_executions(started_at DESC);
-- ============================================================
-- Erweiterung bestehende Tabelle: ai_prompts
-- Optionale Prompt-gebundene Standard-Fragenergänzungen
-- (Sekundär: Knotenspezifische Fragen haben Vorrang)
-- ============================================================
ALTER TABLE ai_prompts
ADD COLUMN IF NOT EXISTS question_augmentations JSONB;
COMMENT ON COLUMN ai_prompts.question_augmentations IS 'Optionale Standard-Fragenergänzungen für diesen Prompt. Knotenspezifische Fragen im Workflow-Graph haben Vorrang (Hybridmodell mit Vorrangregel).';
-- ============================================================
-- Kommentare für Dokumentation
-- ============================================================
COMMENT ON TABLE workflow_definitions IS 'Workflow-Graphen (Knoten + Kanten) als JSONB. Erweitert die Prompt Engine um verzweigbare, bedingte Analysen.';
COMMENT ON TABLE workflow_question_catalog IS 'Katalog der 6 Grundtypen von Fragenergänzungen mit Antwortspektren und Normalisierungsregeln.';
COMMENT ON TABLE workflow_executions IS 'Ausführungs-Log für Workflow-Runs mit Knoten-Status und detailliertem Ablauf.';
COMMENT ON COLUMN workflow_definitions.graph IS 'JSONB: {nodes: [{id, type, prompt_slug, question_augmentations, position}, ...], edges: [{id, from, to}, ...]}';
COMMENT ON COLUMN workflow_executions.node_states IS 'JSONB: {node_id: {status: "executed|skipped|unclear|failed", ...}, ...}';
COMMENT ON COLUMN workflow_executions.execution_log IS 'JSONB: Chronologischer Ablauf mit Timestamps, Entscheidungen, normalisierten Signalen.';
@@ -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);
+8 -3
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 ───────────────────────────────────────────────────────────
@@ -177,12 +178,12 @@ class StageCreate(BaseModel):
class UnifiedPromptCreate(BaseModel):
"""Create a new unified prompt (base or pipeline type)"""
"""Create a new unified prompt (base, pipeline, or workflow type)"""
name: str
slug: str
slug: Optional[str] = None # Auto-generated from name if not provided
display_name: Optional[str] = None
description: Optional[str] = None
type: str # 'base' or 'pipeline'
type: str # 'base' | 'pipeline' | 'workflow'
category: str = 'ganzheitlich'
active: bool = True
sort_order: int = 0
@@ -195,6 +196,9 @@ class UnifiedPromptCreate(BaseModel):
# For pipeline prompts (multi-stage workflow)
stages: Optional[list[StageCreate]] = None # Required if type='pipeline'
# For workflow prompts (visual graph editor)
graph_data: Optional[dict] = None # Required if type='workflow'
class UnifiedPromptUpdate(BaseModel):
"""Update an existing unified prompt"""
@@ -209,6 +213,7 @@ class UnifiedPromptUpdate(BaseModel):
output_format: Optional[str] = None
output_schema: Optional[dict] = None
stages: Optional[list[StageCreate]] = None
graph_data: Optional[dict] = None # For workflow type
# ── Pipeline Config Models (Issue #28) ─────────────────────────────────────
+237
View File
@@ -0,0 +1,237 @@
"""
Normalization Engine (Phase 2)
Normalisiert decision_signals gegen answer_spectrum mit Synonymen.
Konzept-Basis: konzept_workflow_engine_konsolidated.md (Sektion 8.5)
Anforderungsanalyse: anforderungsanalyse_umsetzungsplan.md (Phase 2)
"""
from typing import Dict, List, Optional
from workflow_models import NormalizedSignal, SignalStatus
import logging
logger = logging.getLogger(__name__)
def normalize_decision_signal(
question_type: str,
raw_value: str,
answer_spectrum: List[str],
normalization_rules: Optional[Dict] = None
) -> NormalizedSignal:
"""
Normalisiert ein einzelnes Entscheidungssignal.
Normalisierungs-Kaskade:
1. Exakte Übereinstimmung → valid
2. Case-insensitive Übereinstimmung → normalized
3. Synonym-Mapping (aus normalization_rules) → normalized
4. Keine Übereinstimmung → invalid
Args:
question_type: Typ der Frage (z.B. "relevanz")
raw_value: Rohe LLM-Antwort (z.B. "JA", "yes", "ja")
answer_spectrum: Erlaubte Werte (z.B. ["ja", "nein", "unklar"])
normalization_rules: Optional: {"synonyms": {"ja": ["yes", "Ja", "JA"], ...}}
Returns:
NormalizedSignal mit status + normalized_value
Beispiele:
>>> normalize_decision_signal("relevanz", "ja", ["ja", "nein"])
NormalizedSignal(status=VALID, normalized_value="ja")
>>> normalize_decision_signal("relevanz", "JA", ["ja", "nein"])
NormalizedSignal(status=NORMALIZED, normalized_value="ja")
>>> normalize_decision_signal("relevanz", "yes", ["ja", "nein"],
... {"synonyms": {"ja": ["yes", "Yes"]}})
NormalizedSignal(status=NORMALIZED, normalized_value="ja")
>>> normalize_decision_signal("relevanz", "vielleicht", ["ja", "nein"])
NormalizedSignal(status=INVALID, normalized_value=None)
"""
# 1. Exakte Übereinstimmung
if raw_value in answer_spectrum:
logger.debug(f"{question_type}: '{raw_value}' → valid (exact match)")
return NormalizedSignal(
question_type=question_type,
raw_value=raw_value,
normalized_value=raw_value,
status=SignalStatus.VALID
)
# 2. Case-insensitive Matching
raw_lower = raw_value.strip().lower()
for allowed in answer_spectrum:
if raw_lower == allowed.lower():
logger.debug(f"{question_type}: '{raw_value}' → normalized (case-insensitive)")
return NormalizedSignal(
question_type=question_type,
raw_value=raw_value,
normalized_value=allowed,
status=SignalStatus.NORMALIZED,
metadata={"method": "case_insensitive"}
)
# 3. Synonym Mapping
if normalization_rules and "synonyms" in normalization_rules:
normalized = apply_synonym_mapping(
raw_value=raw_value,
synonyms=normalization_rules["synonyms"]
)
if normalized:
logger.debug(f"{question_type}: '{raw_value}' → normalized (synonym → '{normalized}')")
return NormalizedSignal(
question_type=question_type,
raw_value=raw_value,
normalized_value=normalized,
status=SignalStatus.NORMALIZED,
metadata={"method": "synonym"}
)
# 4. Keine Übereinstimmung
logger.warning(f"{question_type}: '{raw_value}' → invalid (no match in spectrum {answer_spectrum})")
return NormalizedSignal(
question_type=question_type,
raw_value=raw_value,
normalized_value=None,
status=SignalStatus.INVALID
)
def apply_synonym_mapping(
raw_value: str,
synonyms: Dict[str, List[str]]
) -> Optional[str]:
"""
Mappt raw_value auf Synonym-Gruppe (case-insensitive).
Args:
raw_value: "yes" oder "YES" oder "Yes"
synonyms: {"ja": ["yes", "Ja", "JA"], "nein": ["no", "No"]}
Returns:
"ja" (Schlüssel der Gruppe) oder None
Beispiele:
>>> apply_synonym_mapping("yes", {"ja": ["yes", "Yes"], "nein": ["no"]})
"ja"
>>> apply_synonym_mapping("YES", {"ja": ["yes"], "nein": ["no"]})
"ja"
>>> apply_synonym_mapping("vielleicht", {"ja": ["yes"], "nein": ["no"]})
None
"""
raw_lower = raw_value.strip().lower()
for canonical_value, synonym_list in synonyms.items():
# Check case-insensitive gegen alle Synonyme
for syn in synonym_list:
if raw_lower == syn.lower():
return canonical_value
return None
def normalize_all_signals(
decision_signals: Dict[str, str],
catalog_dict: Dict[str, Dict]
) -> List[NormalizedSignal]:
"""
Normalisiert alle decision_signals gegen Katalog.
Args:
decision_signals: {"relevanz": "ja", "prioritaet": "HOCH"}
catalog_dict: {
"relevanz": {
"answer_spectrum": ["ja", "nein", "unklar"],
"normalization_rules": {"synonyms": {...}}
},
...
}
Returns:
Liste von NormalizedSignal (ein Signal pro question_type)
Beispiele:
>>> signals = {"relevanz": "ja", "prioritaet": "HOCH"}
>>> catalog = {
... "relevanz": {"answer_spectrum": ["ja", "nein"], "normalization_rules": None},
... "prioritaet": {"answer_spectrum": ["hoch", "mittel", "niedrig"], "normalization_rules": None}
... }
>>> normalized = normalize_all_signals(signals, catalog)
>>> len(normalized)
2
>>> normalized[0].status
<SignalStatus.VALID: 'valid'>
>>> normalized[1].status
<SignalStatus.NORMALIZED: 'normalized'>
"""
normalized = []
for question_type, raw_value in decision_signals.items():
if question_type not in catalog_dict:
logger.warning(f"Question type '{question_type}' not in catalog → not_decidable")
normalized.append(NormalizedSignal(
question_type=question_type,
raw_value=raw_value,
normalized_value=None,
status=SignalStatus.NOT_DECIDABLE,
metadata={"error": "not_in_catalog"}
))
continue
catalog_entry = catalog_dict[question_type]
signal = normalize_decision_signal(
question_type=question_type,
raw_value=raw_value,
answer_spectrum=catalog_entry["answer_spectrum"],
normalization_rules=catalog_entry.get("normalization_rules")
)
normalized.append(signal)
return normalized
def load_question_catalog(db_connection) -> Dict[str, Dict]:
"""
Lädt workflow_question_catalog aus DB.
Returns:
{
"relevanz": {
"answer_spectrum": ["ja", "nein", "unklar"],
"normalization_rules": {"synonyms": {"ja": ["yes", "Yes"], ...}}
},
"prioritaet": {...},
...
}
Beispiel:
>>> from db import get_db
>>> with get_db() as conn:
... catalog = load_question_catalog(conn)
... assert "relevanz" in catalog
... assert "answer_spectrum" in catalog["relevanz"]
"""
from db import get_cursor
cur = get_cursor(db_connection)
cur.execute("""
SELECT question_type, answer_spectrum, normalization_rules
FROM workflow_question_catalog
WHERE active = true
""")
rows = cur.fetchall()
catalog = {}
for row in rows:
catalog[row['question_type']] = {
"answer_spectrum": row['answer_spectrum'], # JSONB already parsed by psycopg2
"normalization_rules": row['normalization_rules'] # JSONB or None
}
logger.info(f"Loaded question catalog: {len(catalog)} types")
return catalog
+123 -7
View File
@@ -192,6 +192,10 @@ async def execute_prompt(
# Pipeline prompt: multi-stage execution
return await execute_pipeline_prompt(prompt, variables, openrouter_call_func, enable_debug, catalog)
elif prompt_type == 'workflow':
# Workflow prompt: graph-based execution (Phase 0: Foundation)
return await execute_workflow_prompt(prompt, variables, openrouter_call_func, enable_debug, catalog)
else:
raise HTTPException(400, f"Unknown prompt type: {prompt_type}")
@@ -201,18 +205,54 @@ async def execute_base_prompt(
variables: Dict[str, Any],
openrouter_call_func,
enable_debug: bool = False,
catalog: Optional[Dict] = None
catalog: Optional[Dict] = None,
node_questions: Optional[list] = None # Phase 1: Knotengebundene Fragen
) -> Dict[str, Any]:
"""Execute a base-type prompt (single template)."""
"""
Execute a base-type prompt (single template).
Phase 1: Unterstützt Fragenergänzungen (Hybridmodell)
- node_questions: Knotengebundene Fragen (Priorität 1)
- prompt.question_augmentations: Prompt-Defaults (Priorität 2)
"""
from question_augmenter import (
parse_question_augmentations_from_jsonb,
merge_question_augmentations,
augment_prompt_with_questions
)
from result_container_parser import parse_result_container_robust
template = prompt.get('template')
if not template:
raise HTTPException(400, f"Base prompt missing template: {prompt['slug']}")
debug_info = {} if enable_debug else None
# Phase 1: Load question augmentations (Hybridmodell)
prompt_default_questions = None
if prompt.get('question_augmentations'):
try:
from workflow_models import QuestionAugmentation
prompt_default_questions = parse_question_augmentations_from_jsonb(
prompt['question_augmentations']
)
except Exception as e:
if enable_debug:
debug_info['question_augmentations_error'] = str(e)
# Merge question augmentations (Vorrangregel: Knoten > Prompt)
questions = merge_question_augmentations(node_questions, prompt_default_questions)
# Resolve placeholders (with optional catalog for |d modifier)
prompt_text = resolve_placeholders(template, variables, debug_info, catalog)
# Phase 1: Augment prompt with questions (if any)
if questions:
prompt_text = augment_prompt_with_questions(prompt_text, questions)
if enable_debug:
debug_info['question_augmentations_count'] = len(questions)
debug_info['question_types'] = [q.type for q in questions]
if enable_debug:
debug_info['template'] = template
debug_info['final_prompt'] = prompt_text[:500] + ('...' if len(prompt_text) > 500 else '')
@@ -225,12 +265,24 @@ async def execute_base_prompt(
debug_info['ai_response_length'] = len(response)
debug_info['ai_response_preview'] = response[:200] + ('...' if len(response) > 200 else '')
# Validate JSON if required
output_format = prompt.get('output_format', 'text')
if output_format == 'json':
output = validate_json_output(response, prompt.get('output_schema'), debug_info if enable_debug else None)
# Phase 1: Parse structured result if questions were used
if questions:
expected_question_types = [q.type for q in questions]
container = parse_result_container_robust(response, expected_question_types)
if enable_debug:
debug_info['parsing_status'] = container['parsing_status']
debug_info['parsing_warnings'] = container.get('warnings', [])
output = container
output_format = 'structured_container' # New format type
else:
output = response
# Legacy behavior: Validate JSON if required
output_format = prompt.get('output_format', 'text')
if output_format == 'json':
output = validate_json_output(response, prompt.get('output_schema'), debug_info if enable_debug else None)
else:
output = response
result = {
"type": "base",
@@ -524,3 +576,67 @@ async def execute_prompt_with_data(
# Execute prompt
return await execute_prompt(prompt_slug, variables, openrouter_call_func, enable_debug)
async def execute_workflow_prompt(
prompt: Dict,
variables: Dict[str, Any],
openrouter_call_func,
enable_debug: bool = False,
catalog: Optional[Dict] = None
) -> Dict[str, Any]:
"""
Execute a workflow-type prompt (graph-based execution).
Phase 2-4: Sequenzielle Workflow-Execution, conditional branching, path consolidation
Phase 5: Graph aus ai_prompts.graph_data (nicht workflow_definitions)
Args:
prompt: Prompt dict from database (must have 'graph_data' field)
variables: Dict of variables for placeholder replacement
openrouter_call_func: Async function(prompt_text, model) -> response_text
enable_debug: If True, include debug information in response
catalog: Optional placeholder catalog
Returns:
Dict with execution results:
{
"type": "workflow",
"execution_id": "...",
"status": "completed" | "failed",
"aggregated_result": {...},
"node_states": [...], # Only if enable_debug=True
"error": "..." # Only if status=failed
}
"""
from workflow_executor import execute_workflow
# Phase 5: Graph aus ai_prompts.graph_data
graph_data = prompt.get('graph_data')
if not graph_data:
raise HTTPException(400, "Workflow-Prompt fehlt 'graph_data' Feld")
# Execute workflow (mit graph_data statt workflow_id)
result = await execute_workflow(
graph_data=graph_data, # NEU: Direkt graph_data übergeben
profile_id=variables.get('profile_id', 'unknown'), # From context
variables=variables,
openrouter_call_func=openrouter_call_func,
enable_debug=enable_debug
)
# Convert ExecutionResult to dict for API response
response = {
"type": "workflow",
"execution_id": result.execution_id,
"status": result.status,
"aggregated_result": result.aggregated_result
}
if enable_debug:
response["node_states"] = [s.model_dump() for s in result.node_states]
if result.error:
response["error"] = result.error
return response
+289
View File
@@ -0,0 +1,289 @@
"""
Question Augmenter (Phase 1)
Generiert Fragenergänzungs-Suffix für Analyseprompts.
Konzept-Basis: konzept_workflow_engine_konsolidated.md (Sektion 6.4, 8.3)
Anforderungsanalyse: anforderungsanalyse_umsetzungsplan.md (Sektion 4.2, 6)
Hybridmodell (Sektion 6):
- Primär: Knotengebundene Fragenergänzungen (am Workflow-Knoten definiert)
- Sekundär: Prompt-gebundene Standardfragen (optional in ai_prompts.question_augmentations)
- Vorrangregel: Knotenspezifische überschreiben Prompt-Defaults
Output-Format (User-Entscheidung 2):
- Markdown-Sektionen mit klaren Delimitern (statt verpflichtendem JSON-Mode)
"""
from typing import List, Dict, Optional, Any
from workflow_models import QuestionAugmentation
from db import get_db, get_cursor, r2d
def generate_question_suffix(questions: List[QuestionAugmentation]) -> str:
"""
Generiert Fragenergänzungs-Suffix für einen Analyseprompt.
Format (Markdown-Sektionen):
```
## Analyse
[Hauptinhalt deines Prompts hier]
## Entscheidungsfragen
Beantworte folgende Fragen präzise:
- Relevanz: [ja/nein/unklar]
- Priorität: [hoch/mittel/niedrig/unklar]
## Begründung
[Optional: Kurze Plausibilisierung deiner Antworten (1-2 Sätze)]
```
Args:
questions: Liste von QuestionAugmentation-Objekten
Returns:
Fragenergänzungs-Suffix als Markdown-String
Raises:
ValueError: Bei leerer Fragenliste
"""
if not questions:
raise ValueError("Fragenliste darf nicht leer sein")
# Build question list
question_lines = []
for q in questions:
# Format: "- Fragentyp: [erlaubte Werte]"
spectrum_str = "/".join(q.answer_spectrum)
question_lines.append(f"- {q.type.capitalize()}: [{spectrum_str}]")
question_block = "\n".join(question_lines)
suffix = f"""
---
**WICHTIG: Strukturiere deine Antwort wie folgt:**
## Analyse
[Deine Hauptanalyse hier - beantworte die ursprüngliche Frage ausführlich]
## Entscheidungsfragen
Beantworte folgende Fragen **präzise** mit den vorgegebenen Werten:
{question_block}
## Begründung
[Optional: Kurze Plausibilisierung deiner Entscheidungsfragen-Antworten (1-2 Sätze)]
**Hinweise:**
- Antworte bei Entscheidungsfragen NUR mit den vorgegebenen Werten
- Bei Unsicherheit wähle "unklar"
- Die Begründung ist optional, aber hilfreich für die Nachvollziehbarkeit
"""
return suffix
def load_question_augmentations_from_db(
question_types: Optional[List[str]] = None
) -> List[QuestionAugmentation]:
"""
Lädt Fragenergänzungen aus der Datenbank (workflow_question_catalog).
Args:
question_types: Optionale Liste von Fragetypen zum Filtern
(z.B. ["relevanz", "prioritaet"])
Wenn None: Alle aktiven Fragen werden geladen
Returns:
Liste von QuestionAugmentation-Objekten
Raises:
HTTPException: Bei Datenbankfehlern
"""
with get_db() as conn:
cur = get_cursor(conn)
if question_types:
placeholders = ", ".join(["%s"] * len(question_types))
cur.execute(
f"""SELECT id, question_type, label, question_template, answer_spectrum
FROM workflow_question_catalog
WHERE active = true AND question_type IN ({placeholders})
ORDER BY question_type""",
tuple(question_types)
)
else:
cur.execute(
"""SELECT id, question_type, label, question_template, answer_spectrum
FROM workflow_question_catalog
WHERE active = true
ORDER BY question_type"""
)
rows = cur.fetchall()
questions = []
for row in rows:
db_row = r2d(row)
questions.append(
QuestionAugmentation(
id=db_row['question_type'], # Verwende Typ als ID (z.B. "relevanz")
type=db_row['question_type'],
question=db_row['question_template'],
answer_spectrum=db_row['answer_spectrum']
)
)
return questions
def merge_question_augmentations(
node_questions: Optional[List[QuestionAugmentation]],
prompt_default_questions: Optional[List[QuestionAugmentation]]
) -> List[QuestionAugmentation]:
"""
Merged Fragenergänzungen nach Hybridmodell-Vorrangregel.
Vorrangregel (Sektion 6.2 der Anforderungsanalyse):
1. Knotenspezifische Fragenergänzungen überschreiben Prompt-Defaults
2. Wenn Knoten keine Fragen definiert: Prompt-Defaults werden verwendet (falls vorhanden)
3. Wenn weder Knoten noch Prompt Fragen definieren: Leere Liste
Args:
node_questions: Fragenergänzungen am Workflow-Knoten (primär)
prompt_default_questions: Fragenergänzungen am Prompt (sekundär)
Returns:
Gemergete Liste von QuestionAugmentation-Objekten
"""
# Vorrangregel 1: Knotenspezifische Fragen haben absolute Priorität
if node_questions:
return node_questions
# Vorrangregel 2: Wenn Knoten keine Fragen hat, verwende Prompt-Defaults
if prompt_default_questions:
return prompt_default_questions
# Vorrangregel 3: Wenn weder Knoten noch Prompt Fragen haben: Leere Liste
return []
def parse_question_augmentations_from_jsonb(
jsonb_data: Optional[Dict[str, Any]]
) -> List[QuestionAugmentation]:
"""
Parsed QuestionAugmentation-Objekte aus JSONB-Daten (z.B. ai_prompts.question_augmentations).
Format:
[
{
"id": "q1",
"type": "relevanz",
"question": "Ist eine vertiefte Analyse relevant?",
"answer_spectrum": ["ja", "nein", "unklar"]
},
...
]
Args:
jsonb_data: JSONB-Array als Python-Dict/List
Returns:
Liste von QuestionAugmentation-Objekten
Raises:
ValueError: Bei ungültigem Format
"""
if not jsonb_data:
return []
if not isinstance(jsonb_data, list):
raise ValueError("question_augmentations muss ein Array sein")
questions = []
for item in jsonb_data:
try:
questions.append(QuestionAugmentation(**item))
except Exception as e:
raise ValueError(f"Ungültiges QuestionAugmentation-Format: {e}")
return questions
def get_question_augmentation_instruction() -> str:
"""
Gibt generische Instruktion für strukturierte Antwort zurück.
Diese Instruktion wird IMMER zum Prompt hinzugefügt, wenn Fragenergänzungen aktiv sind.
Returns:
Instruktions-String als Markdown
"""
return """
---
**WICHTIG: Strukturiere deine Antwort in folgenden Markdown-Sektionen:**
1. **## Analyse** - Deine Hauptanalyse (beantworte die ursprüngliche Frage)
2. **## Entscheidungsfragen** - Beantworte die unten stehenden Fragen PRÄZISE mit den vorgegebenen Werten
3. **## Begründung** - Optional: Kurze Plausibilisierung deiner Entscheidungsfragen (1-2 Sätze)
"""
def format_question_list(questions: List[QuestionAugmentation]) -> str:
"""
Formatiert Fragenliste als Markdown-Liste.
Format:
```
- Relevanz: [ja/nein/unklar]
- Priorität: [hoch/mittel/niedrig/unklar]
```
Args:
questions: Liste von QuestionAugmentation-Objekten
Returns:
Formatierte Markdown-Liste
"""
lines = []
for q in questions:
spectrum_str = "/".join(q.answer_spectrum)
lines.append(f"- **{q.type.capitalize()}**: [{spectrum_str}]")
return "\n".join(lines)
def augment_prompt_with_questions(
base_prompt: str,
questions: List[QuestionAugmentation]
) -> str:
"""
Fügt Fragenergänzungen zu einem Basis-Prompt hinzu.
Args:
base_prompt: Original-Prompt-Text
questions: Liste von Fragenergänzungen
Returns:
Erweiterter Prompt mit Fragenergänzungen
Raises:
ValueError: Bei leerer Fragenliste
"""
if not questions:
raise ValueError("Keine Fragenergänzungen vorhanden")
instruction = get_question_augmentation_instruction()
question_list = format_question_list(questions)
augmented_prompt = f"""{base_prompt}
{instruction}
**Entscheidungsfragen:**
{question_list}
"""
return augmented_prompt
+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
+271
View File
@@ -0,0 +1,271 @@
"""
Result Container Parser (Phase 1)
Parsed strukturierte LLM-Antworten (Markdown-Sektionen).
Konzept-Basis: konzept_workflow_engine_konsolidated.md (Sektion 8.2)
Anforderungsanalyse: anforderungsanalyse_umsetzungsplan.md (Sektion 4.1)
Erwartet Format (Markdown-Sektionen):
```
## Analyse
[Hauptinhalt]
## Entscheidungsfragen
- Relevanz: ja
- Priorität: hoch
## Begründung
[Optional: Plausibilisierung]
```
Output:
```python
{
"analysis_core": str,
"decision_signals": Dict[str, str], # {"relevanz": "ja", "prioritaet": "hoch"}
"reasoning_anchors": Optional[str]
}
```
"""
import re
from typing import Dict, Optional, List, Tuple
def parse_result_container(llm_output: str) -> Dict:
"""
Parsed strukturierte LLM-Antwort in Ergebniscontainer.
Extrahiert drei Bereiche:
1. **Analysekern** (## Analyse)
2. **Entscheidungsanteil** (## Entscheidungsfragen)
3. **Begründungsanker** (## Begründung, optional)
Args:
llm_output: Vollständiger LLM-Output als String
Returns:
Dict mit drei Bereichen:
{
"analysis_core": str,
"decision_signals": Dict[str, str],
"reasoning_anchors": Optional[str],
"parsing_status": str # "complete", "partial", "failed"
}
Raises:
ValueError: Bei komplett fehlgeschlagenem Parsing
"""
# Extrahiere Sektionen
analysis_core = extract_section(llm_output, "Analyse")
decision_section = extract_section(llm_output, "Entscheidungsfragen")
reasoning_anchors = extract_section(llm_output, "Begründung")
# Parse Entscheidungsfragen
decision_signals = {}
if decision_section:
decision_signals = parse_decision_questions(decision_section)
# Determine parsing status
if analysis_core and decision_signals:
parsing_status = "complete"
elif analysis_core or decision_signals:
parsing_status = "partial"
else:
parsing_status = "failed"
# Fallback: Wenn keine Strukturierung erkannt, verwende gesamten Output als Analysekern
if parsing_status == "failed":
analysis_core = llm_output
parsing_status = "fallback"
return {
"analysis_core": analysis_core or "",
"decision_signals": decision_signals,
"reasoning_anchors": reasoning_anchors,
"parsing_status": parsing_status
}
def extract_section(text: str, section_name: str) -> Optional[str]:
"""
Extrahiert eine Markdown-Sektion aus dem Text.
Sucht nach:
- `## Section_Name` (Überschrift)
- Alles bis zur nächsten `##` Überschrift
Args:
text: Volltext
section_name: Name der Sektion (z.B. "Analyse", "Entscheidungsfragen")
Returns:
Sektionsinhalt (ohne Überschrift) oder None wenn nicht gefunden
"""
# Pattern: ## Section_Name (mit optionalem Whitespace)
# Captured content bis zur nächsten ## oder Ende
pattern = rf'##\s*{re.escape(section_name)}\s*\n(.*?)(?=\n##|\Z)'
match = re.search(pattern, text, re.DOTALL | re.IGNORECASE)
if match:
content = match.group(1).strip()
return content if content else None
return None
def parse_decision_questions(section_text: str) -> Dict[str, str]:
"""
Parsed Entscheidungsfragen aus Sektion.
Erwartet Format:
```
- Relevanz: ja
- Priorität: hoch
- Selektion: nein
```
Alternativen:
```
Relevanz: ja
Priorität: hoch
```
oder:
```
- **Relevanz**: ja
- **Priorität**: hoch
```
Args:
section_text: Text der Entscheidungsfragen-Sektion
Returns:
Dict mit {frage_typ: antwort}
Beispiel: {"relevanz": "ja", "prioritaet": "hoch"}
"""
signals = {}
# Pattern: Matcht verschiedene Formatvariationen
# Gruppe 1: Fragetyp (z.B. "Relevanz", "**Priorität**")
# Gruppe 2: Antwort (z.B. "ja", "hoch")
patterns = [
r'-\s*\*?\*?(\w+)\*?\*?\s*:\s*\[?([^\]\n]+)\]?', # "- **Relevanz**: [ja]"
r'^\s*\*?\*?(\w+)\*?\*?\s*:\s*\[?([^\]\n]+)\]?', # "Relevanz: ja" (ohne -)
]
for pattern in patterns:
matches = re.finditer(pattern, section_text, re.MULTILINE | re.IGNORECASE)
for match in matches:
question_type = match.group(1).strip().lower()
answer = match.group(2).strip()
# Entferne Klammern und Whitespace
answer = answer.strip('[]()').strip()
signals[question_type] = answer
return signals
def validate_decision_signal(
signal_value: str,
answer_spectrum: List[str]
) -> Tuple[str, str]:
"""
Validiert ein Entscheidungssignal gegen Antwortspektrum.
Gibt zurück:
- (normalized_value, status)
Status:
- "valid": Antwort exakt im Spektrum
- "normalized": Antwort wurde normalisiert (z.B. "Ja" → "ja")
- "invalid": Antwort außerhalb des Spektrums
Args:
signal_value: Rohe Antwort vom LLM
answer_spectrum: Erlaubte Werte (z.B. ["ja", "nein", "unklar"])
Returns:
Tuple (normalisierter_wert, status)
"""
# Exakte Übereinstimmung (case-sensitive)
if signal_value in answer_spectrum:
return signal_value, "valid"
# Case-insensitive Matching
signal_lower = signal_value.lower()
for allowed in answer_spectrum:
if signal_lower == allowed.lower():
return allowed, "normalized"
# Keine Übereinstimmung
return signal_value, "invalid"
def extract_analysis_core_fallback(llm_output: str) -> str:
"""
Fallback-Methode: Extrahiert Analysekern wenn keine Strukturierung erkannt.
Versucht intelligent zu identifizieren was der Hauptinhalt ist:
1. Wenn Text vor "## Entscheidungsfragen" existiert: Verwende das
2. Sonst: Verwende gesamten Text
Args:
llm_output: Vollständiger LLM-Output
Returns:
Best-Guess für Analysekern
"""
# Suche nach "## Entscheidungsfragen" Marker
pattern = r'##\s*Entscheidungsfragen'
match = re.search(pattern, llm_output, re.IGNORECASE)
if match:
# Text vor dem Marker ist wahrscheinlich die Analyse
return llm_output[:match.start()].strip()
# Fallback: Gesamter Text
return llm_output.strip()
def parse_result_container_robust(
llm_output: str,
expected_questions: Optional[List[str]] = None
) -> Dict:
"""
Robuste Variante des Parsings mit zusätzlicher Validierung.
Args:
llm_output: Vollständiger LLM-Output
expected_questions: Optionale Liste erwarteter Fragetypen (z.B. ["relevanz", "prioritaet"])
Returns:
Ergebniscontainer mit zusätzlichem "warnings"-Feld
"""
result = parse_result_container(llm_output)
warnings = []
# Prüfe ob erwartete Fragen vorhanden
if expected_questions:
found_questions = set(result['decision_signals'].keys())
expected_set = set(expected_questions)
missing = expected_set - found_questions
if missing:
warnings.append(f"Fehlende Entscheidungsfragen: {', '.join(missing)}")
unexpected = found_questions - expected_set
if unexpected:
warnings.append(f"Unerwartete Entscheidungsfragen: {', '.join(unexpected)}")
# Prüfe Parsing-Status
if result['parsing_status'] == "partial":
warnings.append("Parsing unvollständig: Einige Sektionen fehlen")
elif result['parsing_status'] == "fallback":
warnings.append("Keine Strukturierung erkannt, Fallback-Parsing verwendet")
result['warnings'] = warnings
return result
+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)
+41 -8
View File
@@ -53,6 +53,20 @@ def list_prompts(session: dict=Depends(require_auth)):
return [r2d(r) for r in cur.fetchall()]
@router.get("/{prompt_id}")
def get_prompt(prompt_id: str, session: dict=Depends(require_auth)):
"""Get single AI prompt by ID (UUID)."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM ai_prompts WHERE id=%s", (prompt_id,))
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Prompt not found")
return r2d(row)
@router.post("")
def create_prompt(p: PromptCreate, session: dict=Depends(require_admin)):
"""Create new AI prompt (admin only)."""
@@ -1380,20 +1394,26 @@ async def execute_unified_prompt(
@router.post("/unified")
def create_unified_prompt(p: UnifiedPromptCreate, session: dict = Depends(require_admin)):
"""
Create a new unified prompt (base or pipeline type).
Create a new unified prompt (base, pipeline, or workflow type).
Admin only.
"""
with get_db() as conn:
cur = get_cursor(conn)
# Auto-generate slug if not provided (for workflows)
if not p.slug:
import re
base_slug = re.sub(r'[^a-z0-9_]+', '_', p.name.lower()).strip('_')
p.slug = f"{base_slug}_{uuid.uuid4().hex[:6]}"
# Check for duplicate slug
cur.execute("SELECT id FROM ai_prompts WHERE slug=%s", (p.slug,))
if cur.fetchone():
raise HTTPException(status_code=400, detail="Slug already exists")
# Validate type
if p.type not in ['base', 'pipeline']:
raise HTTPException(status_code=400, detail="Type must be 'base' or 'pipeline'")
if p.type not in ['base', 'pipeline', 'workflow']:
raise HTTPException(status_code=400, detail="Type must be 'base', 'pipeline', or 'workflow'")
# Validate base type has template
if p.type == 'base' and not p.template:
@@ -1403,6 +1423,10 @@ def create_unified_prompt(p: UnifiedPromptCreate, session: dict = Depends(requir
if p.type == 'pipeline' and not p.stages:
raise HTTPException(status_code=400, detail="Pipeline prompts require stages")
# Validate workflow type has graph_data
if p.type == 'workflow' and not p.graph_data:
raise HTTPException(status_code=400, detail="Workflow prompts require graph_data")
# Convert stages to JSONB
stages_json = None
if p.stages:
@@ -1426,16 +1450,22 @@ def create_unified_prompt(p: UnifiedPromptCreate, session: dict = Depends(requir
prompt_id = str(uuid.uuid4())
# Convert graph_data to JSONB
graph_data_json = None
if p.graph_data:
graph_data_json = json.dumps(p.graph_data)
cur.execute(
"""INSERT INTO ai_prompts
(id, slug, name, display_name, description, template, category, active, sort_order,
type, stages, output_format, output_schema)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""",
type, stages, output_format, output_schema, graph_data)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""",
(
prompt_id, p.slug, p.name, p.display_name, p.description,
p.template, p.category, p.active, p.sort_order,
p.type, stages_json, p.output_format,
json.dumps(p.output_schema) if p.output_schema else None
json.dumps(p.output_schema) if p.output_schema else None,
graph_data_json
)
)
@@ -1470,8 +1500,8 @@ def update_unified_prompt(prompt_id: str, p: UnifiedPromptUpdate, session: dict
updates.append('description=%s')
values.append(p.description)
if p.type is not None:
if p.type not in ['base', 'pipeline']:
raise HTTPException(status_code=400, detail="Type must be 'base' or 'pipeline'")
if p.type not in ['base', 'pipeline', 'workflow']:
raise HTTPException(status_code=400, detail="Type must be 'base', 'pipeline', or 'workflow'")
updates.append('type=%s')
values.append(p.type)
if p.category is not None:
@@ -1512,6 +1542,9 @@ def update_unified_prompt(prompt_id: str, p: UnifiedPromptUpdate, session: dict
])
updates.append('stages=%s')
values.append(stages_json)
if p.graph_data is not None:
updates.append('graph_data=%s')
values.append(json.dumps(p.graph_data))
if not updates:
return {"ok": True}
+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
+235
View File
@@ -0,0 +1,235 @@
"""
Workflow Questions Router (Phase 1)
CRUD für workflow_question_catalog Tabelle.
Endpunkte:
- GET /api/workflow/questions - Liste aller Fragen
- GET /api/workflow/questions/{id} - Einzelne Frage
- POST /api/workflow/questions - Neue Frage (Admin only)
- PUT /api/workflow/questions/{id} - Frage aktualisieren (Admin only)
- DELETE /api/workflow/questions/{id} - Frage löschen (Admin only)
"""
from fastapi import APIRouter, Depends, HTTPException
from typing import List, Optional
from auth import require_auth, require_admin
from db import get_db, get_cursor, r2d
from workflow_models import QuestionCatalogEntry
from pydantic import BaseModel
router = APIRouter()
class QuestionCatalogCreate(BaseModel):
"""Request-Modell für neue Frage"""
question_type: str
label: str
question_template: str
answer_spectrum: List[str]
normalization_rules: Optional[dict] = None
class QuestionCatalogUpdate(BaseModel):
"""Request-Modell für Frage-Update"""
label: Optional[str] = None
question_template: Optional[str] = None
answer_spectrum: Optional[List[str]] = None
normalization_rules: Optional[dict] = None
active: Optional[bool] = None
@router.get("/api/workflow/questions")
def list_questions(
active_only: bool = True,
session: dict = Depends(require_auth)
):
"""
Liste alle Fragen aus dem Katalog.
Query-Parameter:
- active_only: Nur aktive Fragen (default: true)
"""
with get_db() as conn:
cur = get_cursor(conn)
if active_only:
cur.execute(
"""SELECT id, question_type, label, question_template, answer_spectrum,
normalization_rules, active, created_at::text as created_at
FROM workflow_question_catalog
WHERE active = true
ORDER BY question_type"""
)
else:
cur.execute(
"""SELECT id, question_type, label, question_template, answer_spectrum,
normalization_rules, active, created_at::text as created_at
FROM workflow_question_catalog
ORDER BY question_type"""
)
rows = cur.fetchall()
return [r2d(row) for row in rows]
@router.get("/api/workflow/questions/{question_id}")
def get_question(
question_id: str,
session: dict = Depends(require_auth)
):
"""Einzelne Frage abrufen"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""SELECT id, question_type, label, question_template, answer_spectrum,
normalization_rules, active, created_at::text as created_at
FROM workflow_question_catalog
WHERE id = %s""",
(question_id,)
)
row = cur.fetchone()
if not row:
raise HTTPException(404, f"Frage nicht gefunden: {question_id}")
return r2d(row)
@router.post("/api/workflow/questions")
def create_question(
data: QuestionCatalogCreate,
session: dict = Depends(require_admin)
):
"""
Neue Frage erstellen (Admin only).
Validierungen:
- question_type muss eindeutig sein
- answer_spectrum muss mindestens 2 Werte enthalten
"""
# Validierung
if len(data.answer_spectrum) < 2:
raise HTTPException(400, "answer_spectrum muss mindestens 2 Werte enthalten")
with get_db() as conn:
cur = get_cursor(conn)
# Prüfe ob question_type bereits existiert
cur.execute(
"SELECT id FROM workflow_question_catalog WHERE question_type = %s",
(data.question_type,)
)
if cur.fetchone():
raise HTTPException(400, f"question_type '{data.question_type}' existiert bereits")
# Erstelle Frage
cur.execute(
"""INSERT INTO workflow_question_catalog
(question_type, label, question_template, answer_spectrum, normalization_rules, active)
VALUES (%s, %s, %s, %s, %s, true)
RETURNING id, created_at::text as created_at""",
(
data.question_type,
data.label,
data.question_template,
json.dumps(data.answer_spectrum),
json.dumps(data.normalization_rules) if data.normalization_rules else None
)
)
result = cur.fetchone()
conn.commit()
return {
"id": result[0],
"question_type": data.question_type,
"label": data.label,
"question_template": data.question_template,
"answer_spectrum": data.answer_spectrum,
"normalization_rules": data.normalization_rules,
"active": True,
"created_at": result[1]
}
@router.put("/api/workflow/questions/{question_id}")
def update_question(
question_id: str,
data: QuestionCatalogUpdate,
session: dict = Depends(require_admin)
):
"""Frage aktualisieren (Admin only)"""
import json
# Prüfe ob Frage existiert
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT id FROM workflow_question_catalog WHERE id = %s", (question_id,))
if not cur.fetchone():
raise HTTPException(404, f"Frage nicht gefunden: {question_id}")
# Build UPDATE statement dynamically
updates = []
params = []
if data.label is not None:
updates.append("label = %s")
params.append(data.label)
if data.question_template is not None:
updates.append("question_template = %s")
params.append(data.question_template)
if data.answer_spectrum is not None:
if len(data.answer_spectrum) < 2:
raise HTTPException(400, "answer_spectrum muss mindestens 2 Werte enthalten")
updates.append("answer_spectrum = %s")
params.append(json.dumps(data.answer_spectrum))
if data.normalization_rules is not None:
updates.append("normalization_rules = %s")
params.append(json.dumps(data.normalization_rules))
if data.active is not None:
updates.append("active = %s")
params.append(data.active)
if not updates:
raise HTTPException(400, "Keine Aktualisierungen angegeben")
params.append(question_id)
update_sql = f"UPDATE workflow_question_catalog SET {', '.join(updates)} WHERE id = %s"
cur.execute(update_sql, tuple(params))
conn.commit()
# Return updated question
return get_question(question_id, session)
@router.delete("/api/workflow/questions/{question_id}")
def delete_question(
question_id: str,
session: dict = Depends(require_admin)
):
"""
Frage löschen (Admin only).
Setzt active=false statt physischem Löschen (Soft Delete).
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"UPDATE workflow_question_catalog SET active = false WHERE id = %s RETURNING id",
(question_id,)
)
result = cur.fetchone()
if not result:
raise HTTPException(404, f"Frage nicht gefunden: {question_id}")
conn.commit()
return {"status": "deleted", "id": question_id}
+222
View File
@@ -0,0 +1,222 @@
"""
Workflow Execution Router (Phase 2)
Endpunkte für Workflow-Execution und Ergebnis-Abruf.
Phase 2: Sequenzielle Execution
Phase 3: Conditional branching
"""
from fastapi import APIRouter, Depends, HTTPException
from auth import require_auth
from db import get_db, get_cursor, r2d
from pydantic import BaseModel
from typing import Dict, Any, Optional
import logging
logger = logging.getLogger(__name__)
router = APIRouter()
class WorkflowExecuteRequest(BaseModel):
"""Request-Body für Workflow-Execution"""
variables: Dict[str, Any] = {}
enable_debug: bool = False
@router.post("/api/workflows/{workflow_id}/execute")
async def execute_workflow_endpoint(
workflow_id: str,
request: WorkflowExecuteRequest,
session: dict = Depends(require_auth)
):
"""
Führt einen Workflow aus.
Args:
workflow_id: UUID des Workflows (aus workflow_definitions)
request.variables: Platzhalter-Werte (optional, z.B. {"name": "Lars"})
request.enable_debug: Debug-Modus (zeigt node_states im Response)
Returns:
{
"execution_id": "...",
"status": "completed" | "failed",
"aggregated_result": {
"combined_analysis": "...",
"all_signals": [...],
"total_nodes": 3,
"executed_nodes": 3,
"failed_nodes": 0
},
"node_states": [...], # Nur wenn enable_debug=true
"error": "..." # Nur wenn failed
}
Beispiel:
POST /api/workflows/abc123/execute
{
"variables": {"name": "Lars"},
"enable_debug": true
}
"""
from prompt_executor import execute_workflow_prompt
from routers.prompts import call_openrouter
profile_id = session["profile_id"]
# Add profile_id to variables (für placeholder_resolver)
variables = {**request.variables, "profile_id": profile_id}
# Load workflow as "prompt" (für execute_workflow_prompt)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT id, name, slug FROM workflow_definitions WHERE id = %s AND active = true",
(workflow_id,)
)
row = cur.fetchone()
if not row:
raise HTTPException(404, f"Workflow nicht gefunden: {workflow_id}")
workflow_prompt = {
"id": row['id'],
"name": row['name'],
"slug": row['slug'],
"type": "workflow"
}
try:
result = await execute_workflow_prompt(
prompt=workflow_prompt,
variables=variables,
openrouter_call_func=call_openrouter,
enable_debug=request.enable_debug
)
return result
except Exception as e:
logger.error(f"Workflow execution failed: {e}", exc_info=True)
raise HTTPException(500, f"Workflow-Ausführung fehlgeschlagen: {str(e)}")
@router.get("/api/workflows/executions/{execution_id}")
def get_execution_result(
execution_id: str,
session: dict = Depends(require_auth)
):
"""
Lädt gespeicherten Execution State aus DB.
Args:
execution_id: UUID der Execution (aus workflow_executions)
Returns:
{
"id": "...",
"workflow_id": "...",
"profile_id": "...",
"status": "completed" | "failed",
"node_states": [...], # JSONB
"execution_log": {...},
"started_at": "2026-04-03T12:00:00",
"completed_at": "2026-04-03T12:00:10"
}
Beispiel:
GET /api/workflows/executions/abc123
"""
profile_id = session["profile_id"]
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT id, workflow_id, profile_id, status, node_states, execution_log,
started_at::text, completed_at::text
FROM workflow_executions
WHERE id = %s AND profile_id = %s
""", (execution_id, profile_id))
row = cur.fetchone()
if not row:
raise HTTPException(404, "Execution nicht gefunden")
return r2d(row)
@router.get("/api/workflows")
def list_workflows(
session: dict = Depends(require_auth)
):
"""
Listet alle aktiven Workflows auf.
Returns:
[
{
"id": "...",
"name": "...",
"slug": "...",
"description": "...",
"version": 1,
"created_at": "...",
"updated_at": "..."
},
...
]
Beispiel:
GET /api/workflows
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT id, name, slug, description, version,
created_at::text, updated_at::text
FROM workflow_definitions
WHERE active = true
ORDER BY name
""")
rows = cur.fetchall()
return [r2d(row) for row in rows]
@router.get("/api/workflows/{workflow_id}")
def get_workflow(
workflow_id: str,
session: dict = Depends(require_auth)
):
"""
Lädt einen einzelnen Workflow mit Graph.
Args:
workflow_id: UUID des Workflows
Returns:
{
"id": "...",
"name": "...",
"slug": "...",
"description": "...",
"graph": {...}, # JSONB
"version": 1,
"active": true,
"created_at": "...",
"updated_at": "..."
}
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT id, name, slug, description, graph, version, active,
created_at::text, updated_at::text
FROM workflow_definitions
WHERE id = %s AND active = true
""", (workflow_id,))
row = cur.fetchone()
if not row:
raise HTTPException(404, "Workflow nicht gefunden")
return r2d(row)
@@ -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)
+244
View File
@@ -0,0 +1,244 @@
"""
Unit Tests: End Node Template Engine (Phase 4)
Tests execute_end_node() mit AUTO und TEMPLATE modes.
"""
import pytest
from datetime import datetime
from workflow_executor import execute_end_node
from workflow_models import (
WorkflowNode, EndNodeOutputMode, NodeStatus, NodeExecutionState
)
class TestEndNodeTemplateEngine:
"""Tests für End Node Template Rendering"""
def test_auto_mode_concatenates_all_analyses(self):
"""AUTO mode: Concatenates all analysis_core values"""
# Setup: Node mit AUTO mode
end_node = WorkflowNode(
id="end",
type="end",
output_mode=EndNodeOutputMode.AUTO
)
# Setup: Context mit 2 executed nodes
context = {
"node_results": {
"analysis1": NodeExecutionState(
node_id="analysis1",
status=NodeStatus.EXECUTED,
analysis_core="Body analysis result",
decision_signals={"relevanz": "hoch"}
),
"analysis2": NodeExecutionState(
node_id="analysis2",
status=NodeStatus.EXECUTED,
analysis_core="Training recommendation",
decision_signals={"prioritaet": "mittel"}
)
}
}
# Execute
result = execute_end_node(end_node, context)
# Assert
assert result.status == NodeStatus.EXECUTED
assert "## analysis1" in result.analysis_core
assert "Body analysis result" in result.analysis_core
assert "## analysis2" in result.analysis_core
assert "Training recommendation" in result.analysis_core
print("✓ AUTO mode concatenation works")
def test_auto_mode_skips_skipped_nodes(self):
"""AUTO mode: Skips nodes with status SKIPPED"""
end_node = WorkflowNode(
id="end",
type="end",
output_mode=EndNodeOutputMode.AUTO
)
context = {
"node_results": {
"analysis1": NodeExecutionState(
node_id="analysis1",
status=NodeStatus.EXECUTED,
analysis_core="Executed analysis"
),
"analysis2": NodeExecutionState(
node_id="analysis2",
status=NodeStatus.SKIPPED,
analysis_core="This should not appear"
)
}
}
result = execute_end_node(end_node, context)
assert "Executed analysis" in result.analysis_core
assert "This should not appear" not in result.analysis_core
print("✓ AUTO mode skips SKIPPED nodes")
def test_template_mode_basic_rendering(self):
"""TEMPLATE mode: Renders Jinja2 template with node placeholders"""
end_node = WorkflowNode(
id="end",
type="end",
output_mode=EndNodeOutputMode.TEMPLATE,
template=(
"# Final Result\n\n"
"## Analysis\n"
"{{analysis1.analysis_core}}\n\n"
"## Signals\n"
"Relevanz: {{analysis1.relevanz}}"
)
)
context = {
"node_results": {
"analysis1": NodeExecutionState(
node_id="analysis1",
status=NodeStatus.EXECUTED,
analysis_core="Test analysis content",
decision_signals={"relevanz": "hoch"}
)
}
}
result = execute_end_node(end_node, context)
assert result.status == NodeStatus.EXECUTED
assert "# Final Result" in result.analysis_core
assert "Test analysis content" in result.analysis_core
assert "Relevanz: hoch" in result.analysis_core
print("✓ TEMPLATE mode basic rendering works")
def test_template_conditional_rendering(self):
"""TEMPLATE mode: Conditional rendering with {% if node_id %}"""
end_node = WorkflowNode(
id="end",
type="end",
output_mode=EndNodeOutputMode.TEMPLATE,
template=(
"# Result\n\n"
"{% if analysis1 %}"
"Analysis 1 executed\n"
"{% endif %}"
"{% if analysis2 %}"
"Analysis 2 executed\n"
"{% endif %}"
)
)
context = {
"node_results": {
"analysis1": NodeExecutionState(
node_id="analysis1",
status=NodeStatus.EXECUTED,
analysis_core="Content 1"
)
# analysis2 not in results (optional path not taken)
}
}
result = execute_end_node(end_node, context)
assert "Analysis 1 executed" in result.analysis_core
assert "Analysis 2 executed" not in result.analysis_core
print("✓ TEMPLATE mode conditional rendering works")
def test_template_default_values(self):
"""TEMPLATE mode: Default values for missing nodes"""
end_node = WorkflowNode(
id="end",
type="end",
output_mode=EndNodeOutputMode.TEMPLATE,
template=(
"Result: {{missing_node.analysis_core|default('Nicht verfügbar')}}"
)
)
context = {"node_results": {}}
result = execute_end_node(end_node, context)
assert "Nicht verfügbar" in result.analysis_core
print("✓ TEMPLATE mode default values work")
def test_template_missing_template_fails(self):
"""TEMPLATE mode without template raises error"""
end_node = WorkflowNode(
id="end",
type="end",
output_mode=EndNodeOutputMode.TEMPLATE,
template=None # Missing template
)
context = {"node_results": {}}
result = execute_end_node(end_node, context)
assert result.status == NodeStatus.FAILED
assert "no template defined" in result.error.lower()
print("✓ TEMPLATE mode fails without template")
def test_template_syntax_error_fails(self):
"""TEMPLATE mode with invalid syntax fails gracefully"""
end_node = WorkflowNode(
id="end",
type="end",
output_mode=EndNodeOutputMode.TEMPLATE,
template="{% invalid syntax %}"
)
context = {"node_results": {}}
result = execute_end_node(end_node, context)
assert result.status == NodeStatus.FAILED
assert "template rendering failed" in result.error.lower()
print("✓ TEMPLATE mode handles syntax errors")
def test_auto_mode_empty_results(self):
"""AUTO mode with no executed nodes returns placeholder"""
end_node = WorkflowNode(
id="end",
type="end",
output_mode=EndNodeOutputMode.AUTO
)
context = {"node_results": {}}
result = execute_end_node(end_node, context)
assert result.status == NodeStatus.EXECUTED
assert "[No analysis generated]" in result.analysis_core
print("✓ AUTO mode handles empty results")
if __name__ == "__main__":
# Run tests
test = TestEndNodeTemplateEngine()
print("\n=== Testing End Node Template Engine ===\n")
test.test_auto_mode_concatenates_all_analyses()
test.test_auto_mode_skips_skipped_nodes()
test.test_template_mode_basic_rendering()
test.test_template_conditional_rendering()
test.test_template_default_values()
test.test_template_missing_template_fails()
test.test_template_syntax_error_fails()
test.test_auto_mode_empty_results()
print("\n✅ All tests passed!\n")
@@ -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
+128
View File
@@ -0,0 +1,128 @@
"""
Application Version Information
Semantic Versioning: MAJOR.MINOR.PATCH
- MAJOR: Breaking Change, DB-Migration inkompatibel
- MINOR: Neues Feature, neues Modul
- PATCH: Bugfix, kleine Änderung, Refactor
"""
APP_VERSION = "0.9n"
BUILD_DATE = "2026-04-05"
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.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.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-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",
"Template Context: {{node_id.analysis_core}}, {{node_id.decision_signals.key}}",
"Conditional Rendering: {% if node_id %} for optional paths",
"AUTO Mode: Backward compatible concatenation of all analyses",
"TEMPLATE Mode: Custom Jinja2 templates with placeholder support",
]
},
{
"version": "0.9m",
"date": "2026-04-04",
"changes": [
"Phase 4: Join Nodes and Path Consolidation",
"join_evaluator.py: Join-Strategie-Evaluator (wait_all, wait_any, best_effort)",
"Path Status Collection: Sammelt incoming paths, prüft Ausführungsstatus",
"Result Consolidation: Merged analysis_cores + combined signals (mit node_id Präfix)",
"Skip-Handling: IGNORE_SKIPPED, USE_PLACEHOLDER, REQUIRE_MINIMUM",
"Partial Execution: Korrekte Behandlung von SKIPPED/FAILED Pfaden",
"workflow_executor.py: execute_join_node() Implementation",
"NodeExecutionState: List[NormalizedSignal] korrekt konvertiert zu Dict",
"Unit-Tests Phase 4: 18 Tests für Join Nodes (alle passing)",
"Phase 2/3 Backward Compatibility: 31 Tests (alle passing)",
]
},
{
"version": "0.9l",
"date": "2026-04-04",
"changes": [
"Phase 3: Logic Nodes + Conditional Branching",
"logic_evaluator.py: Deterministischer Logic Evaluator (EQ, NEQ, IN, GT, LT, CONTAINS, AND, OR, NOT)",
"workflow_executor.py: Conditional Branching via BFS-Traversierung mit Edge-Activation",
"execute_logic_node(): Bedingungen evaluieren, then/else Pfade aktivieren",
"Fallback-Strategien: CONSERVATIVE_SKIP, DEFAULT_PATH, UNCERTAINTY_PATH, DOCUMENT_ONLY",
"workflow_models.py: CONTAINS Operator hinzugefügt",
"Unit-Tests Phase 3: 20 Tests für Logic Evaluator (alle passing)",
"Phase 2 Backward Compatibility: 11 Tests aktualisiert (alle passing)",
]
},
{
"version": "0.9k",
"date": "2026-04-03",
"changes": [
"Phase 2: Normalisierung + Workflow Executor",
"normalization_engine.py: Synonym-Mapping, 5 Statuswerte (valid, normalized, unclear, invalid, not_decidable)",
"workflow_executor.py: Sequenzielle Workflow-Ausführung, Node-State-Tracking, Ergebnis-Aggregation",
"Integration in prompt_executor.py: Dispatcher für type='workflow'",
"API-Router workflows.py: POST /workflows/{id}/execute, GET /workflows/executions/{id}",
"Unit-Tests Phase 2: 27 Tests (normalization_engine + workflow_executor)",
"Erweitert: workflow_models.py (NormalizedSignal, NodeExecutionState, ExecutionResult)",
]
},
{
"version": "0.9j",
"date": "2026-04-03",
"changes": [
"Phase 1: Fragenergänzung + Strukturierter Container",
"question_augmenter.py: Hybrid-Modell (Knotengebundene Fragen überschreiben Prompt-Defaults)",
"result_container_parser.py: Markdown-Sektionen (Analysekern, Entscheidungsanteil, Begründungsanker)",
"Integration in execute_base_prompt(): Fragenergänzung vor LLM-Call, Parsing nach LLM-Response",
"API-Router workflow_questions.py: CRUD für workflow_question_catalog",
"Unit-Tests Phase 1: 25 Tests (question_augmenter + result_container_parser)",
]
},
{
"version": "0.9i",
"date": "2026-04-03",
"changes": [
"Phase 0: Workflow Engine Foundation",
"DB-Migration 034: workflow_definitions, workflow_question_catalog, workflow_executions",
"Pydantic-Modelle für Workflow-Graph (WorkflowGraph, Node, Edge, Condition)",
"Graph-Parsing, Topologische Sortierung, DAG-Validierung",
"Dispatcher-Erweiterung: type='workflow' (Stub-Implementierung)",
"Unit-Tests für Phase 0 (Graph-Parsing, Zyklen-Erkennung, Erreichbarkeit)",
]
},
{
"version": "0.9h+",
"date": "2026-03-28",
"changes": [
"Phase 0c: Multi-Layer Data Architecture Complete",
"Data Layer Migration (97 Funktionen in 6 Modulen)",
"20 neue Chart Endpoints (E1-E5, A1-A8, R1-R5, C1-C4)",
"Single Source of Truth für Datenberechnungen",
]
},
]
+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)
+443
View File
@@ -0,0 +1,443 @@
"""
Workflow Engine (Phase 0: Foundation)
Graph-Parsing, topologische Sortierung, DAG-Validierung.
Konzept-Basis: konzept_workflow_engine_konsolidated.md
Anforderungsanalyse: anforderungsanalyse_umsetzungsplan.md
Phase 0: Foundation (Graph-Parsing, Validation)
Phase 1-3: Vollständige Execution-Logic
"""
from typing import Dict, List, Set, Optional, Tuple, Any
from workflow_models import (
WorkflowGraph,
WorkflowNode,
WorkflowEdge,
NodeType,
NodeStatus
)
from fastapi import HTTPException
class WorkflowEngine:
"""
Workflow-Execution-Engine für graph-basierte Prompt-Workflows.
Phase 0: Graph-Parsing und Validierung
Phase 1-3: Execution-Logic
"""
def __init__(self, graph: WorkflowGraph):
"""
Initialisiere Engine mit Workflow-Graph.
Args:
graph: Workflow-Graph (Knoten + Kanten)
Raises:
HTTPException: Bei ungültigem Graph (Zyklen, fehlende Knoten, etc.)
"""
self.graph = graph
self.nodes_by_id: Dict[str, WorkflowNode] = {node.id: node for node in graph.nodes}
self.edges_by_id: Dict[str, WorkflowEdge] = {edge.id: edge for edge in graph.edges}
# Adjacency lists für Traversierung
self.outgoing_edges: Dict[str, List[WorkflowEdge]] = {}
self.incoming_edges: Dict[str, List[WorkflowEdge]] = {}
# Build adjacency lists
for edge in graph.edges:
# Outgoing edges (from node)
if edge.from_node not in self.outgoing_edges:
self.outgoing_edges[edge.from_node] = []
self.outgoing_edges[edge.from_node].append(edge)
# Incoming edges (to node)
if edge.to_node not in self.incoming_edges:
self.incoming_edges[edge.to_node] = []
self.incoming_edges[edge.to_node].append(edge)
# Validiere Graph
self._validate_graph()
# Topologische Sortierung
self.topological_order = self._topological_sort()
def _validate_graph(self):
"""
Validiere Workflow-Graph.
Prüfungen:
1. Alle referenzierten Knoten existieren
2. Genau ein START-Knoten
3. Mindestens ein END-Knoten
4. Keine Zyklen (DAG)
5. Alle Knoten erreichbar vom START
6. Alle Knoten können END erreichen
Raises:
HTTPException: Bei Validierungsfehlern
"""
errors = []
# 1. Prüfe ob alle referenzierten Knoten existieren
for edge in self.graph.edges:
if edge.from_node not in self.nodes_by_id:
errors.append(f"Edge {edge.id}: from_node '{edge.from_node}' existiert nicht")
if edge.to_node not in self.nodes_by_id:
errors.append(f"Edge {edge.id}: to_node '{edge.to_node}' existiert nicht")
if errors:
raise HTTPException(400, {"error": "Ungültiger Graph", "details": errors})
# 2. Genau ein START-Knoten
start_nodes = [n for n in self.graph.nodes if n.type == NodeType.START]
if len(start_nodes) == 0:
errors.append("Kein START-Knoten gefunden")
elif len(start_nodes) > 1:
errors.append(f"Mehrere START-Knoten gefunden: {[n.id for n in start_nodes]}")
# 3. Mindestens ein END-Knoten
end_nodes = [n for n in self.graph.nodes if n.type == NodeType.END]
if len(end_nodes) == 0:
errors.append("Kein END-Knoten gefunden")
if errors:
raise HTTPException(400, {"error": "Ungültiger Graph", "details": errors})
# 4. Keine Zyklen (DAG-Prüfung)
cycle = self._detect_cycle()
if cycle:
errors.append(f"Zyklus erkannt: {' → '.join(cycle)}")
if errors:
raise HTTPException(400, {"error": "Ungültiger Graph (Zyklus)", "details": errors})
# 5. Alle Knoten erreichbar vom START
start_node = start_nodes[0]
reachable = self._get_reachable_nodes(start_node.id)
unreachable = [n.id for n in self.graph.nodes if n.id not in reachable]
if unreachable:
errors.append(f"Knoten nicht erreichbar vom START: {unreachable}")
# 6. Alle Knoten können END erreichen (Rückwärts-Prüfung)
end_nodes_ids = [n.id for n in end_nodes]
can_reach_end = self._get_nodes_reaching_end(end_nodes_ids)
cannot_reach_end = [n.id for n in self.graph.nodes if n.id not in can_reach_end]
if cannot_reach_end:
errors.append(f"Knoten können END nicht erreichen: {cannot_reach_end}")
if errors:
raise HTTPException(400, {"error": "Ungültiger Graph (Erreichbarkeit)", "details": errors})
def _detect_cycle(self) -> Optional[List[str]]:
"""
Erkenne Zyklen im Graph mittels DFS.
Returns:
Liste der Knoten im Zyklus, oder None wenn kein Zyklus
"""
visited: Set[str] = set()
rec_stack: Set[str] = set() # Recursion stack für DFS
parent: Dict[str, Optional[str]] = {}
def dfs(node_id: str) -> Optional[List[str]]:
visited.add(node_id)
rec_stack.add(node_id)
# Besuche alle Nachbarn
for edge in self.outgoing_edges.get(node_id, []):
neighbor = edge.to_node
if neighbor not in visited:
parent[neighbor] = node_id
cycle = dfs(neighbor)
if cycle:
return cycle
elif neighbor in rec_stack:
# Zyklus gefunden! Rekonstruiere Pfad
cycle_path = [neighbor]
current = node_id
while current != neighbor:
cycle_path.append(current)
current = parent.get(current)
cycle_path.append(neighbor) # Schließe Zyklus
return list(reversed(cycle_path))
rec_stack.remove(node_id)
return None
# Starte DFS von allen Knoten (für disconnected components)
for node in self.graph.nodes:
if node.id not in visited:
parent[node.id] = None
cycle = dfs(node.id)
if cycle:
return cycle
return None
def _get_reachable_nodes(self, start_node_id: str) -> Set[str]:
"""
Finde alle vom Startknoten aus erreichbaren Knoten (Vorwärts-Traversierung).
Args:
start_node_id: ID des Startknotens
Returns:
Set aller erreichbaren Knoten-IDs
"""
reachable: Set[str] = set()
stack = [start_node_id]
while stack:
current = stack.pop()
if current in reachable:
continue
reachable.add(current)
# Füge alle Nachbarn hinzu
for edge in self.outgoing_edges.get(current, []):
stack.append(edge.to_node)
return reachable
def _get_nodes_reaching_end(self, end_node_ids: List[str]) -> Set[str]:
"""
Finde alle Knoten die mindestens einen END-Knoten erreichen können.
Rückwärts-Traversierung von END-Knoten.
Args:
end_node_ids: Liste der END-Knoten-IDs
Returns:
Set aller Knoten-IDs die END erreichen können
"""
can_reach_end: Set[str] = set()
stack = list(end_node_ids)
while stack:
current = stack.pop()
if current in can_reach_end:
continue
can_reach_end.add(current)
# Füge alle Vorgänger hinzu (rückwärts)
for edge in self.incoming_edges.get(current, []):
stack.append(edge.from_node)
return can_reach_end
def _topological_sort(self) -> List[str]:
"""
Berechne topologische Sortierung des Graphen (Kahn's Algorithm).
Die topologische Sortierung gibt eine Reihenfolge vor, in der Knoten
ausgeführt werden können, ohne dass Abhängigkeiten verletzt werden.
Returns:
Liste der Knoten-IDs in topologischer Reihenfolge
Raises:
HTTPException: Bei Zyklen (sollte durch _validate_graph verhindert sein)
"""
# Berechne In-Degree für jeden Knoten
in_degree: Dict[str, int] = {node.id: 0 for node in self.graph.nodes}
for edge in self.graph.edges:
in_degree[edge.to_node] += 1
# Queue mit Knoten ohne Vorgänger (In-Degree = 0)
queue = [node_id for node_id, degree in in_degree.items() if degree == 0]
sorted_order = []
while queue:
# Entferne Knoten mit In-Degree 0
current = queue.pop(0)
sorted_order.append(current)
# Reduziere In-Degree aller Nachbarn
for edge in self.outgoing_edges.get(current, []):
neighbor = edge.to_node
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
# Wenn nicht alle Knoten sortiert wurden: Zyklus (sollte nicht passieren)
if len(sorted_order) != len(self.graph.nodes):
raise HTTPException(
500,
"Topologische Sortierung fehlgeschlagen (Zyklus?). "
"Dies sollte durch _validate_graph verhindert worden sein."
)
return sorted_order
def get_execution_order(self) -> List[List[str]]:
"""
Berechne Ausführungs-Reihenfolge als Ebenen (für parallele Execution).
Knoten auf derselben Ebene können parallel ausgeführt werden.
Returns:
Liste von Ebenen, jede Ebene ist eine Liste von Knoten-IDs:
[
["node_start"],
["node_1", "node_2"], # können parallel laufen
["node_3"],
["node_end"]
]
"""
# Berechne Level für jeden Knoten (längster Pfad vom START)
levels: Dict[str, int] = {}
for node_id in self.topological_order:
# Finde maximales Level aller Vorgänger
incoming = self.incoming_edges.get(node_id, [])
if not incoming:
# Knoten ohne Vorgänger (START)
levels[node_id] = 0
else:
max_parent_level = max(levels[edge.from_node] for edge in incoming)
levels[node_id] = max_parent_level + 1
# Gruppiere Knoten nach Level
max_level = max(levels.values()) if levels else 0
execution_order = [[] for _ in range(max_level + 1)]
for node_id, level in levels.items():
execution_order[level].append(node_id)
return execution_order
async def execute(
self,
variables: Dict[str, Any],
openrouter_call_func,
profile_id: str,
enable_debug: bool = False
) -> Dict[str, Any]:
"""
Führe Workflow aus.
Phase 0: Stub-Implementierung
Phase 1-3: Vollständige Implementierung mit:
- Fragenergänzung
- Normalisierung
- Logik-Auswertung
- Pfad-Routing
- Join-Konsolidierung
Args:
variables: Dict of variables for placeholder replacement
openrouter_call_func: Async function(prompt_text) -> response_text
profile_id: User profile ID
enable_debug: If True, include debug information
Returns:
Dict with execution results
Raises:
HTTPException: 501 Not Implemented (Phase 0)
"""
raise HTTPException(
status_code=501,
detail="Workflow-Execution noch nicht implementiert (Phase 0: Foundation). "
"Vollständige Implementierung erfolgt in Phase 1-3."
)
def parse_workflow_graph(graph_jsonb: Dict) -> WorkflowGraph:
"""
Parse JSONB-Graph aus Datenbank zu Pydantic WorkflowGraph-Modell.
Args:
graph_jsonb: JSONB dict aus workflow_definitions.graph
Unterstützt beide Edge-Formate:
- Backend: {"from": "...", "to": "..."}
- Frontend: {"source": "...", "target": "..."}
Returns:
Validiertes WorkflowGraph-Objekt
Raises:
ValidationError: Bei ungültigem Graph-Format
"""
# Normalize edges: convert React Flow format (source/target) to backend format (from/to)
if "edges" in graph_jsonb:
normalized_edges = []
for edge in graph_jsonb["edges"]:
normalized_edge = edge.copy()
# Convert source → from, target → to (if present)
if "source" in normalized_edge and "from" not in normalized_edge:
normalized_edge["from"] = normalized_edge.pop("source")
if "target" in normalized_edge and "to" not in normalized_edge:
normalized_edge["to"] = normalized_edge.pop("target")
normalized_edges.append(normalized_edge)
graph_jsonb = {**graph_jsonb, "edges": normalized_edges}
return WorkflowGraph(**graph_jsonb)
def validate_workflow_graph(graph: WorkflowGraph) -> Tuple[bool, List[str]]:
"""
Validiere Workflow-Graph (ohne Engine zu initialisieren).
Kann für UI-Validierung verwendet werden (vor dem Speichern).
Args:
graph: Workflow-Graph
Returns:
Tuple (is_valid, errors)
- is_valid: True wenn Graph gültig
- errors: Liste von Fehler-Strings (leer wenn valid)
"""
try:
engine = WorkflowEngine(graph)
return True, []
except HTTPException as e:
# Extrahiere Fehler aus HTTPException detail
detail = e.detail
if isinstance(detail, dict):
errors = detail.get('details', [detail.get('error', str(e))])
else:
errors = [str(detail)]
return False, errors
except Exception as e:
return False, [f"Unerwarteter Fehler: {str(e)}"]
def get_execution_order(graph: WorkflowGraph) -> List[str]:
"""
Berechne sequenzielle Ausführungs-Reihenfolge (Phase 2).
Phase 2: Sequenziell (flattened topological sort).
Phase 7: Parallele Execution (levels statt flat list).
Args:
graph: Workflow-Graph
Returns:
Liste von Knoten-IDs in Ausführungsreihenfolge
Beispiel: ["start", "node_1", "node_2", "end"]
Raises:
HTTPException: Bei ungültigem Graph
Beispiel:
>>> from workflow_models import WorkflowGraph, WorkflowNode, WorkflowEdge
>>> graph = WorkflowGraph(
... nodes=[
... WorkflowNode(id="start", type="start"),
... WorkflowNode(id="end", type="end")
... ],
... edges=[WorkflowEdge(id="e1", from_node="start", to_node="end")]
... )
>>> get_execution_order(graph)
['start', 'end']
"""
engine = WorkflowEngine(graph)
# Nutze topological_order (flattened)
return engine.topological_order
+900
View File
@@ -0,0 +1,900 @@
"""
Workflow Executor (Phase 4)
Führt Workflows mit conditional branching und path consolidation aus.
Phase 2: Sequential execution
Phase 3: Conditional branching, Logic Nodes, Fallback strategies
Phase 4: Join Nodes, Path consolidation
Konzept-Basis: konzept_workflow_engine_konsolidated.md
Anforderungsanalyse: anforderungsanalyse_umsetzungsplan.md (Phase 2-4)
"""
from typing import Dict, Any, List, Optional, Set
from datetime import datetime
import uuid
import logging
import json
from jinja2 import Template, TemplateError
from workflow_models import (
WorkflowGraph, NodeExecutionState, ExecutionResult,
NodeStatus, NormalizedSignal, FallbackStrategy, SignalStatus,
EndNodeOutputMode
)
from workflow_engine import parse_workflow_graph, get_execution_order
from question_augmenter import (
augment_prompt_with_questions,
parse_question_augmentations_from_jsonb
)
from result_container_parser import parse_result_container
from normalization_engine import normalize_all_signals, load_question_catalog
from logic_evaluator import evaluate_logic_expression, resolve_signal_reference
from join_evaluator import evaluate_join_node as evaluate_join_node_core
from db import get_db, get_cursor
logger = logging.getLogger(__name__)
async def execute_workflow(
workflow_id: Optional[str] = None,
graph_data: Optional[Dict] = None, # Phase 5: Direkt von ai_prompts.graph_data
profile_id: str = None,
variables: Dict[str, Any] = None,
openrouter_call_func = None, # Callback für LLM-Calls: async (prompt, model) -> str
enable_debug: bool = False
) -> ExecutionResult:
"""
Führt einen Workflow aus (mit conditional branching und path consolidation).
Phase 2: Linear execution in topological order.
Phase 3: Conditional branching basierend auf logic nodes.
Phase 4: Join nodes und path consolidation.
Phase 5: Unterstützt graph_data direkt (aus ai_prompts, nicht workflow_definitions)
Args:
workflow_id: UUID des Workflows (legacy, für workflow_definitions Tabelle)
graph_data: Workflow-Graph als Dict (NEU, für ai_prompts.graph_data)
profile_id: UUID des Profils
variables: Platzhalter-Werte (z.B. {"name": "Lars", ...})
openrouter_call_func: async (prompt, model) -> str
enable_debug: Debug-Modus
Returns:
ExecutionResult mit allen node_states
Beispiel (Phase 5):
>>> result = await execute_workflow(
... graph_data={"nodes": [...], "edges": [...]},
... profile_id="test-profile",
... variables={"name": "Lars"},
... openrouter_call_func=my_llm_func
... )
"""
execution_id = str(uuid.uuid4())
started_at = datetime.utcnow().isoformat()
logger.info(f"Starting workflow execution: {execution_id}")
try:
# 1. Lade Workflow-Definition
if graph_data:
# Phase 5: Graph direkt aus ai_prompts.graph_data (already a dict)
graph_dict = graph_data
logger.debug(f"Using provided graph_data")
elif workflow_id:
# Phase 0-4: Graph aus workflow_definitions Tabelle (legacy)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT graph FROM workflow_definitions WHERE id = %s AND active = true",
(workflow_id,)
)
row = cur.fetchone()
if not row:
raise ValueError(f"Workflow not found: {workflow_id}")
graph_dict = row['graph'] # PostgreSQL JSONB returns dict
logger.debug(f"Loaded graph from workflow_definitions: {workflow_id}")
else:
raise ValueError("Entweder workflow_id oder graph_data muss übergeben werden")
# 2. Parse Graph
graph = parse_workflow_graph(graph_dict)
logger.debug(f"Parsed graph: {len(graph.nodes)} nodes, {len(graph.edges)} edges")
# 4. Lade Question Catalog
with get_db() as conn:
catalog = load_question_catalog(conn)
logger.debug(f"Loaded catalog: {len(catalog)} question types")
# 5. Execute Nodes mit conditional branching (Phase 3)
node_states: List[NodeExecutionState] = []
context = {
"variables": variables,
"profile_id": profile_id,
"node_results": {}, # Phase 3: Store full NodeExecutionState
"active_edges": {} # Phase 3: Track edge activation
}
# Phase 3: BFS traversal mit edge activation
start_node = next((n for n in graph.nodes if n.type == "start"), None)
if not start_node:
raise ValueError("No start node found in workflow")
visited: Set[str] = set()
queue = [start_node.id]
while queue:
node_id = queue.pop(0)
if node_id in visited:
continue
visited.add(node_id)
node = next(n for n in graph.nodes if n.id == node_id)
# Prüfe ob Node aktiv ist (mindestens eine incoming edge aktiv)
if not _has_active_incoming_edge(node, graph, context):
logger.info(f"Skipping node {node_id}: no active incoming edges")
node_states.append(NodeExecutionState(
node_id=node_id,
status=NodeStatus.SKIPPED,
error="no_active_incoming_edges",
started_at=datetime.utcnow().isoformat(),
completed_at=datetime.utcnow().isoformat()
))
continue
logger.info(f"Executing node: {node_id} (type: {node.type})")
node_state = await execute_node(
node=node,
context=context,
catalog=catalog,
graph=graph, # Phase 3: Needed for logic nodes
openrouter_call_func=openrouter_call_func,
enable_debug=enable_debug
)
node_states.append(node_state)
context["node_results"][node_id] = node_state
# Füge Nachfolger zur Queue hinzu
outgoing_edges = [e for e in graph.edges if e.from_node == node_id]
for edge in outgoing_edges:
# Prüfe ob Edge aktiv ist (default: True, Logic Nodes setzen auf False)
if context["active_edges"].get(edge.id, True):
queue.append(edge.to_node)
# 6. Aggregiere Ergebnisse
aggregated = aggregate_results(node_states)
# 7. Speichere Execution State
completed_at = datetime.utcnow().isoformat()
save_execution_state(
execution_id=execution_id,
workflow_id=workflow_id,
profile_id=profile_id,
node_states=node_states,
status="completed",
started_at=started_at,
completed_at=completed_at
)
logger.info(f"Workflow execution completed: {execution_id}")
return ExecutionResult(
execution_id=execution_id,
workflow_id=workflow_id or "N/A", # Placeholder when graph_data is used directly
status="completed",
node_states=node_states,
aggregated_result=aggregated,
started_at=started_at,
completed_at=completed_at
)
except Exception as e:
logger.error(f"Workflow execution failed: {e}", exc_info=True)
# Speichere Failed State
completed_at = datetime.utcnow().isoformat()
save_execution_state(
execution_id=execution_id,
workflow_id=workflow_id, # Can be None when graph_data is used
profile_id=profile_id,
node_states=node_states if 'node_states' in locals() else [],
status="failed",
started_at=started_at,
completed_at=completed_at,
error=str(e)
)
return ExecutionResult(
execution_id=execution_id,
workflow_id=workflow_id or "N/A", # ExecutionResult requires string, use placeholder
status="failed",
node_states=node_states if 'node_states' in locals() else [],
aggregated_result={},
started_at=started_at,
completed_at=completed_at,
error=str(e)
)
async def execute_node(
node,
context: Dict[str, Any],
catalog: Dict[str, Dict],
graph: WorkflowGraph, # Phase 3: Needed for logic nodes
openrouter_call_func,
enable_debug: bool = False
) -> NodeExecutionState:
"""
Führt einen einzelnen Knoten aus.
Args:
node: WorkflowNode (aus graph.nodes)
context: Execution context (variables, profile_id, node_results, active_edges)
catalog: Question catalog
graph: WorkflowGraph (für Logic Nodes)
openrouter_call_func: LLM callback: async (prompt, model) -> str
enable_debug: Debug mode
Returns:
NodeExecutionState
Node Types:
- start/end: No-op
- analysis: Load prompt → augment → LLM → parse → normalize
- logic: Evaluate condition → activate/deactivate edges (Phase 3)
- join: Consolidate paths → merge results (Phase 4)
"""
started_at = datetime.utcnow().isoformat()
try:
# Start Node: No-Op
if node.type == "start":
logger.debug(f"Node {node.id}: No-op (start)")
return NodeExecutionState(
node_id=node.id,
status=NodeStatus.EXECUTED,
started_at=started_at,
completed_at=datetime.utcnow().isoformat()
)
# End Node: Output Generation (Phase 4)
if node.type == "end":
return execute_end_node(node, context)
# Logic Nodes (Phase 3)
if node.type == "logic":
return execute_logic_node(node, context, graph)
# Join Nodes (Phase 4)
if node.type == "join":
return execute_join_node(node, context, graph)
# Analysis Nodes
if node.type == "analysis":
# 1. Lade Prompt
prompt_template = await load_prompt_template(node.prompt_slug, context)
logger.debug(f"Node {node.id}: Loaded prompt '{node.prompt_slug}'")
# 2. Parse question_augmentations
questions = []
if node.question_augmentations:
# Convert list of dicts to JSONB-like format for parser
questions_jsonb = [q.model_dump() if hasattr(q, 'model_dump') else q for q in node.question_augmentations]
questions = parse_question_augmentations_from_jsonb(questions_jsonb)
logger.debug(f"Node {node.id}: {len(questions)} question augmentations")
# 3. Augment Prompt
if questions:
augmented_prompt = augment_prompt_with_questions(
base_prompt=prompt_template,
questions=questions
)
else:
augmented_prompt = prompt_template
# 4. LLM Call
logger.debug(f"Node {node.id}: Calling LLM")
llm_response = await openrouter_call_func(
augmented_prompt,
"anthropic/claude-sonnet-4" # Default model
)
# 5. Parse Result Container
parsed = parse_result_container(llm_response)
logger.debug(f"Node {node.id}: Parsed response (status: {parsed['parsing_status']})")
# 6. Normalize Signals
normalized_signals = []
if parsed["decision_signals"]:
# Hybrid Model: Node-spezifische Questions überschreiben Catalog
node_catalog = catalog.copy()
if node.question_augmentations:
for q in node.question_augmentations:
q_dict = q.model_dump() if hasattr(q, 'model_dump') else q
node_catalog[q_dict['type']] = {
"answer_spectrum": q_dict['answer_spectrum'],
"normalization_rules": None # Node-Questions haben keine Synonyme
}
logger.debug(f"Node {node.id}: Override catalog for '{q_dict['type']}' with node-specific spectrum")
normalized_signals = normalize_all_signals(
decision_signals=parsed["decision_signals"],
catalog_dict=node_catalog
)
logger.info(f"Node {node.id}: Normalized {len(normalized_signals)} signals")
return NodeExecutionState(
node_id=node.id,
status=NodeStatus.EXECUTED,
analysis_core=parsed["analysis_core"],
decision_signals=parsed["decision_signals"],
normalized_signals=normalized_signals,
reasoning_anchors=parsed.get("reasoning_anchors"),
started_at=started_at,
completed_at=datetime.utcnow().isoformat()
)
# Unbekannter Node-Typ (Phase 4: join)
raise ValueError(f"Node type '{node.type}' not implemented yet (Phase 4+)")
except Exception as e:
logger.error(f"Node execution failed ({node.id}): {e}", exc_info=True)
return NodeExecutionState(
node_id=node.id,
status=NodeStatus.FAILED,
error=str(e),
started_at=started_at,
completed_at=datetime.utcnow().isoformat()
)
def execute_logic_node(
node,
context: Dict[str, Any],
graph: WorkflowGraph
) -> NodeExecutionState:
"""
Führt Logic Node aus (Phase 3).
Args:
node: WorkflowNode vom Typ "logic"
context: Execution context mit node_results
graph: WorkflowGraph
Returns:
NodeExecutionState mit evaluation_result in metadata
Logic:
1. Evaluiere node.condition.expression
2. Wähle then_path oder else_path basierend auf Ergebnis
3. Bei Fehler/Unsicherheit: Wende fallback an
4. Markiere gewählte Edge(s) als aktiv, andere als inaktiv
5. Return NodeExecutionState mit evaluation_result
"""
started_at = datetime.utcnow().isoformat()
try:
if not node.condition:
raise ValueError(f"Logic node {node.id} has no condition")
# 1. Evaluiere Bedingung
result, error = evaluate_logic_expression(node.condition.expression, context)
if error:
# Fehler bei Evaluation → Fallback anwenden
logger.warning(f"Logic node {node.id}: evaluation error: {error}")
activated_edges = _apply_fallback(node, graph, context, error)
else:
# Erfolgreiche Evaluation
logger.info(f"Logic node {node.id}: evaluated to {result}")
# 2. Wähle Pfad basierend auf Ergebnis
if result:
# Condition TRUE → then_path aktivieren
activated_edges = _get_edges_by_label(node.id, "then", graph)
else:
# Condition FALSE → else_path aktivieren
activated_edges = _get_edges_by_label(node.id, "else", graph)
# 3. Markiere Edges als aktiv/inaktiv
outgoing_edges = [e for e in graph.edges if e.from_node == node.id]
for edge in outgoing_edges:
context["active_edges"][edge.id] = edge.id in activated_edges
logger.debug(f"Logic node {node.id}: activated edges: {activated_edges}")
return NodeExecutionState(
node_id=node.id,
status=NodeStatus.EXECUTED,
started_at=started_at,
completed_at=datetime.utcnow().isoformat(),
analysis_core=json.dumps({
"evaluation_result": result if not error else None,
"error": error,
"activated_edges": activated_edges
})
)
except Exception as e:
logger.error(f"Logic node execution failed ({node.id}): {e}", exc_info=True)
return NodeExecutionState(
node_id=node.id,
status=NodeStatus.FAILED,
error=str(e),
started_at=started_at,
completed_at=datetime.utcnow().isoformat()
)
def execute_join_node(
node,
context: Dict[str, Any],
graph: WorkflowGraph
) -> NodeExecutionState:
"""
Führt Join Node aus (Phase 4).
Args:
node: WorkflowNode vom Typ "join"
context: Execution context mit node_results
graph: WorkflowGraph
Returns:
NodeExecutionState mit konsolidierten Daten
Logic:
1. Evaluiere Join-Strategie (via join_evaluator)
2. Prüfe ob ready (alle erforderlichen Pfade verfügbar?)
3. Konsolidiere Ergebnisse (merge analysis_core, combine signals)
4. Return NodeExecutionState mit konsolidierten Daten
Error Handling:
- wait_all + fehlende Pfade → FAILED
- wait_any + keine Pfade → FAILED
- best_effort + keine Pfade → EXECUTED (mit metadata)
"""
started_at = datetime.utcnow().isoformat()
try:
logger.info(f"Executing join node: {node.id}")
# 1. Evaluiere Join-Node
join_result = evaluate_join_node_core(node, graph, context)
# 2. Prüfe ob ready
if not join_result.ready:
# Strategie nicht erfüllt → FAILED
logger.warning(f"Join node {node.id}: Not ready - {join_result.error}")
return NodeExecutionState(
node_id=node.id,
status=NodeStatus.FAILED,
error=join_result.error,
started_at=started_at,
completed_at=datetime.utcnow().isoformat(),
metadata=join_result.metadata
)
# 3. Baue konsolidierten analysis_core
# Format: JSON mit node_id → analysis_core mapping
consolidated_core_json = json.dumps(
join_result.consolidated_analysis_core,
ensure_ascii=False,
indent=2
)
# 4. Log Konsolidierung
executed_count = join_result.metadata.get("executed_paths", 0)
total_count = join_result.metadata.get("total_paths", 0)
logger.info(
f"Join node {node.id}: Consolidated {executed_count}/{total_count} paths"
)
# 5. Convert consolidated_signals Dict → List[NormalizedSignal]
# (NodeExecutionState expects List, but join_evaluator returns Dict)
consolidated_signals_list = list(join_result.consolidated_signals.values())
# 6. Return NodeExecutionState
return NodeExecutionState(
node_id=node.id,
status=NodeStatus.EXECUTED,
analysis_core=consolidated_core_json,
normalized_signals=consolidated_signals_list,
metadata=join_result.metadata,
started_at=started_at,
completed_at=datetime.utcnow().isoformat()
)
except Exception as e:
logger.error(f"Join node execution failed ({node.id}): {e}", exc_info=True)
return NodeExecutionState(
node_id=node.id,
status=NodeStatus.FAILED,
error=str(e),
started_at=started_at,
completed_at=datetime.utcnow().isoformat()
)
def execute_end_node(
node,
context: Dict[str, Any]
) -> NodeExecutionState:
"""
Führt End Node aus (Phase 4 - Template Engine).
Args:
node: WorkflowNode vom Typ "end"
context: Execution context mit node_results
Returns:
NodeExecutionState mit finaler Ausgabe in analysis_core
Output Modes:
- AUTO: Concatenates all analysis_core values (backward compatible)
- TEMPLATE: Renders Jinja2 template with {{node_id.property}} placeholders
Template Context:
- {{node_id.analysis_core}}: Analysis text from node
- {{node_id.decision_signals}}: Dict of raw decision signals
- {{node_id.decision_signals.key}}: Specific signal value
- {{node_id.status}}: Node execution status
- Conditional rendering: {% if node_id %}...{% endif %}
- Default values: {{node_id|default("fallback")}}
Example Template:
```
# Final Analysis
## Body Composition
{{body_analysis.analysis_core}}
{% if training_analysis %}
## Training Recommendation
{{training_analysis.analysis_core}}
{% endif %}
## Decision Factors
- Relevance: {{body_analysis.decision_signals.relevanz}}
- Priority: {{body_analysis.decision_signals.prioritaet}}
```
"""
started_at = datetime.utcnow().isoformat()
try:
logger.info(f"Executing end node: {node.id}")
# Determine output mode (default: AUTO for backward compatibility)
output_mode = node.output_mode or EndNodeOutputMode.AUTO
if output_mode == EndNodeOutputMode.AUTO:
# AUTO mode: Concatenate all analysis_core values
logger.debug(f"End node {node.id}: Using AUTO output mode")
combined_analysis = []
for node_id, node_state in context.get("node_results", {}).items():
if node_state.status == NodeStatus.EXECUTED and node_state.analysis_core:
combined_analysis.append(f"## {node_id}\n{node_state.analysis_core}")
final_output = "\n\n".join(combined_analysis) if combined_analysis else "[No analysis generated]"
elif output_mode == EndNodeOutputMode.TEMPLATE:
# TEMPLATE mode: Render Jinja2 template
logger.debug(f"End node {node.id}: Using TEMPLATE output mode")
if not node.template:
raise ValueError(f"End node {node.id} has output_mode=TEMPLATE but no template defined")
# Build template context: {{node_id}} → {analysis_core, decision_signals, status}
template_context = {}
for node_id, node_state in context.get("node_results", {}).items():
template_context[node_id] = {
"analysis_core": node_state.analysis_core or "",
"decision_signals": node_state.decision_signals or {},
"reasoning_anchors": node_state.reasoning_anchors or "",
"status": node_state.status.value if node_state.status else "unknown",
# Add individual signal access: {{node_id.signal_name}}
**node_state.decision_signals # Flatten signals into node context
}
logger.debug(f"End node {node.id}: Built template context for {len(template_context)} nodes")
# Render template
try:
jinja_template = Template(node.template)
final_output = jinja_template.render(template_context)
logger.info(f"End node {node.id}: Template rendered successfully ({len(final_output)} chars)")
except TemplateError as te:
error_msg = f"Template rendering failed: {str(te)}"
logger.error(f"End node {node.id}: {error_msg}")
return NodeExecutionState(
node_id=node.id,
status=NodeStatus.FAILED,
error=error_msg,
started_at=started_at,
completed_at=datetime.utcnow().isoformat()
)
else:
raise ValueError(f"Unknown output_mode: {output_mode}")
# Return NodeExecutionState with final output
return NodeExecutionState(
node_id=node.id,
status=NodeStatus.EXECUTED,
analysis_core=final_output,
started_at=started_at,
completed_at=datetime.utcnow().isoformat()
)
except Exception as e:
logger.error(f"End node execution failed ({node.id}): {e}", exc_info=True)
return NodeExecutionState(
node_id=node.id,
status=NodeStatus.FAILED,
error=str(e),
started_at=started_at,
completed_at=datetime.utcnow().isoformat()
)
def _apply_fallback(
node,
graph: WorkflowGraph,
context: Dict[str, Any],
error: str
) -> List[str]:
"""
Wendet Fallback-Strategie an.
Args:
node: WorkflowNode
graph: WorkflowGraph
context: Execution context
error: Fehler bei Evaluation
Returns:
Liste von Edge-IDs die aktiviert werden sollen
"""
if not node.fallback:
# Default: Konservativ (else-Pfad nehmen)
logger.warning(f"Node {node.id}: No fallback configured, using DEFAULT_PATH")
return _get_edges_by_label(node.id, "else", graph)
strategy = node.fallback.strategy
if strategy == FallbackStrategy.CONSERVATIVE_SKIP:
# Skip alle outgoing edges
logger.info(f"Node {node.id}: CONSERVATIVE_SKIP - deactivating all paths")
return []
elif strategy == FallbackStrategy.DEFAULT_PATH:
# Nimm else-Pfad
logger.info(f"Node {node.id}: DEFAULT_PATH - taking else path")
return _get_edges_by_label(node.id, "else", graph)
elif strategy == FallbackStrategy.UNCERTAINTY_PATH:
# Expliziter Unsicherheits-Pfad (falls vorhanden)
logger.info(f"Node {node.id}: UNCERTAINTY_PATH")
uncertainty_edges = _get_edges_by_label(node.id, "uncertainty", graph)
if uncertainty_edges:
return uncertainty_edges
else:
# Fallback to else
logger.warning(f"Node {node.id}: No uncertainty path found, using else")
return _get_edges_by_label(node.id, "else", graph)
elif strategy == FallbackStrategy.DOCUMENT_ONLY:
# Alle Pfade aktiv lassen (wie ohne Bedingung)
logger.info(f"Node {node.id}: DOCUMENT_ONLY - all paths remain active")
outgoing_edges = [e for e in graph.edges if e.from_node == node.id]
return [e.id for e in outgoing_edges]
else:
logger.warning(f"Node {node.id}: Unknown fallback strategy {strategy}, using DEFAULT_PATH")
return _get_edges_by_label(node.id, "else", graph)
def _get_edges_by_label(node_id: str, label: str, graph: WorkflowGraph) -> List[str]:
"""
Findet alle ausgehenden Edges mit bestimmtem Label.
Args:
node_id: Node-ID
label: Edge-Label (z.B. "then", "else", "uncertainty")
graph: WorkflowGraph
Returns:
Liste von Edge-IDs
"""
matching_edges = [
e.id for e in graph.edges
if e.from_node == node_id and e.label == label
]
return matching_edges
def _has_active_incoming_edge(node, graph: WorkflowGraph, context: Dict[str, Any]) -> bool:
"""
Prüft ob Node mindestens eine aktive incoming edge hat.
Args:
node: WorkflowNode
graph: WorkflowGraph
context: Execution context mit active_edges
Returns:
True wenn mindestens eine incoming edge aktiv ist
"""
# Start-Node hat keine incoming edges → immer aktiv
if node.type == "start":
return True
incoming_edges = [e for e in graph.edges if e.to_node == node.id]
# Keine incoming edges → nicht erreichbar
if not incoming_edges:
return False
# Prüfe ob mindestens eine aktiv ist
active_edges = context.get("active_edges", {})
for edge in incoming_edges:
if active_edges.get(edge.id, True): # Default: True (Phase 2 Kompatibilität)
return True
return False
async def load_prompt_template(prompt_slug: str, context: Dict[str, Any]) -> str:
"""
Lädt Prompt-Template aus DB und resolved Platzhalter.
Args:
prompt_slug: Slug des Prompts (z.B. "pipeline_body")
context: {"variables": {"name": "Lars", ...}, "profile_id": "..."}
Returns:
Resolved prompt template
Beispiel:
>>> template = await load_prompt_template("pipeline_body", {"profile_id": "123"})
>>> "{{name}}" not in template
True
"""
from placeholder_resolver import resolve_placeholders
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT template FROM ai_prompts WHERE slug = %s AND active = true",
(prompt_slug,)
)
row = cur.fetchone()
if not row:
raise ValueError(f"Prompt not found: {prompt_slug}")
template = row['template']
# Resolve Placeholders
profile_id = context.get("profile_id")
resolved = resolve_placeholders(
template=template,
profile_id=profile_id
)
# TODO Phase 3: Support custom variables from workflow context
return resolved
def aggregate_results(node_states: List[NodeExecutionState]) -> Dict[str, Any]:
"""
Aggregiert Ergebnisse aller Knoten.
Args:
node_states: Liste aller NodeExecutionState
Returns:
{
"combined_analysis": "## node_1\n...\n\n## node_2\n...",
"all_signals": [{question_type, normalized_value, status}, ...],
"total_nodes": 3,
"executed_nodes": 3,
"failed_nodes": 0
}
Beispiel:
>>> states = [
... NodeExecutionState(node_id="n1", status=NodeStatus.EXECUTED, analysis_core="Test 1"),
... NodeExecutionState(node_id="n2", status=NodeStatus.EXECUTED, analysis_core="Test 2")
... ]
>>> result = aggregate_results(states)
>>> "## n1" in result["combined_analysis"]
True
>>> result["executed_nodes"]
2
"""
combined_analysis = []
all_signals = []
for state in node_states:
if state.status == NodeStatus.EXECUTED and state.analysis_core:
combined_analysis.append(f"## {state.node_id}\n{state.analysis_core}")
if state.normalized_signals:
all_signals.extend([s.model_dump() for s in state.normalized_signals])
return {
"combined_analysis": "\n\n".join(combined_analysis),
"all_signals": all_signals,
"total_nodes": len(node_states),
"executed_nodes": sum(1 for s in node_states if s.status == NodeStatus.EXECUTED),
"failed_nodes": sum(1 for s in node_states if s.status == NodeStatus.FAILED),
"skipped_nodes": sum(1 for s in node_states if s.status == NodeStatus.SKIPPED) # Phase 3
}
def save_execution_state(
execution_id: str,
workflow_id: Optional[str], # None when using graph_data directly (Phase 5)
profile_id: str,
node_states: List[NodeExecutionState],
status: str,
started_at: str,
completed_at: Optional[str] = None,
error: Optional[str] = None
):
"""
Speichert Execution State in workflow_executions.
Args:
execution_id: UUID der Execution
workflow_id: UUID des Workflows (None wenn graph_data direkt verwendet wird)
profile_id: UUID des Profils
node_states: Liste aller NodeExecutionState
status: 'completed' | 'failed' | 'partial'
started_at: ISO timestamp
completed_at: ISO timestamp (optional)
error: Fehlermeldung (optional)
Beispiel:
>>> save_execution_state(
... execution_id="exec-123",
... workflow_id="wf-456",
... profile_id="prof-789",
... node_states=[],
... status="completed",
... started_at="2026-04-03T12:00:00"
... )
"""
# Serialize node_states to JSON
node_states_json = [s.model_dump() for s in node_states]
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
INSERT INTO workflow_executions
(id, workflow_id, profile_id, status, node_states, execution_log, started_at, completed_at)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (id) DO UPDATE SET
status = EXCLUDED.status,
node_states = EXCLUDED.node_states,
execution_log = EXCLUDED.execution_log,
completed_at = EXCLUDED.completed_at
""", (
execution_id,
workflow_id,
profile_id,
status,
json.dumps(node_states_json),
json.dumps({"error": error} if error else {}),
started_at,
completed_at
))
conn.commit()
logger.info(f"Saved execution state: {execution_id} (status: {status})")
+358
View File
@@ -0,0 +1,358 @@
"""
Pydantic Models for Workflow Engine (Phase 0)
Data validation schemas for Workflow-Graph, Knoten, Kanten, Bedingungen.
Konzept-Basis: konzept_workflow_engine_konsolidated.md
Anforderungsanalyse: anforderungsanalyse_umsetzungsplan.md
"""
from typing import Optional, List, Dict, Any
from pydantic import BaseModel, Field
from enum import Enum
# ── Enums ─────────────────────────────────────────────────────────────────────
class NodeType(str, Enum):
"""Workflow-Knotentypen"""
START = "start"
ANALYSIS = "analysis"
LOGIC = "logic"
JOIN = "join"
END = "end"
class JoinStrategy(str, Enum):
"""Join-Strategien für Pfad-Konsolidierung"""
WAIT_ALL = "wait_all" # Warte auf alle eingehenden Pfade
WAIT_ANY = "wait_any" # Warte auf mindestens einen Pfad
BEST_EFFORT = "best_effort" # Verwende verfügbare Pfade
class SkipHandling(str, Enum):
"""Umgang mit übersprungenen Pfaden am Join"""
IGNORE_SKIPPED = "ignore_skipped" # Übersprungene Pfade ignorieren
USE_PLACEHOLDER = "use_placeholder" # Platzhalter für übersprungene Pfade
REQUIRE_MINIMUM = "require_minimum" # Mindestanzahl erforderlich
class FallbackStrategy(str, Enum):
"""Fallback-Strategien bei unklaren/ungültigen Signalen"""
CONSERVATIVE_SKIP = "conservative_skip" # Konservativ: Pfad überspringen
DEFAULT_PATH = "default_path" # Standard-Pfad ausführen
UNCERTAINTY_PATH = "uncertainty_path" # Expliziter Unsicherheits-Pfad
DOCUMENT_ONLY = "document_only" # Nur dokumentieren, kein Routing
class NodeStatus(str, Enum):
"""Ausführungsstatus eines Knotens"""
PENDING = "pending"
EXECUTING = "executing" # Phase 2: Gerade in Ausführung
EXECUTED = "executed"
SKIPPED = "skipped"
UNCLEAR = "unclear"
FAILED = "failed"
class SignalStatus(str, Enum):
"""Status nach Normalisierung (Phase 2)"""
VALID = "valid" # Exakte Übereinstimmung mit Spektrum
NORMALIZED = "normalized" # Gemappt (Synonym/Case-insensitive)
UNCLEAR = "unclear" # Mehrdeutig oder widersprüchlich
INVALID = "invalid" # Außerhalb des Spektrums
NOT_DECIDABLE = "not_decidable" # Kein Signal vorhanden
class LogicOperator(str, Enum):
"""Logische Operatoren für Bedingungen"""
EQ = "eq" # ==
NEQ = "neq" # !=
IN = "in" # in
NOT_IN = "not_in" # not in
GT = "gt" # >
LT = "lt" # <
GTE = "gte" # >=
LTE = "lte" # <=
CONTAINS = "contains" # String/List contains (Phase 3)
AND = "and"
OR = "or"
NOT = "not"
class EndNodeOutputMode(str, Enum):
"""Output-Modi für End Node (Phase 4)"""
AUTO = "auto" # Automatisch: Concatenate all analyses
TEMPLATE = "template" # Custom Jinja2 template
# ── Hilfsmodelle ──────────────────────────────────────────────────────────────
class Position(BaseModel):
"""Position eines Knotens im visuellen Editor"""
x: float
y: float
class QuestionAugmentation(BaseModel):
"""
Fragenergänzung zu einem Analyseprompt.
Hybridmodell (Sektion 6 der Anforderungsanalyse):
- Primär: Knotengebunden (am Workflow-Knoten definiert)
- Sekundär: Prompt-gebundene Standardfragen (optional)
- Vorrangregel: Knotenspezifische überschreiben Prompt-Defaults
"""
id: str = Field(..., description="Eindeutige ID der Frage (für Referenzierung in Logik-Knoten)")
type: str = Field(..., description="Fragetyp: relevanz, prioritaet, selektion, ausschluss, eskalation, unsicherheit")
question: str = Field(..., description="Fragetext (kann Template-Variablen enthalten)")
answer_spectrum: List[str] = Field(..., description="Erlaubte Antworten, z.B. ['ja', 'nein', 'unklar']")
# ── Bedingungsmodelle ─────────────────────────────────────────────────────────
class LogicOperand(BaseModel):
"""
Operand einer Logik-Bedingung.
Referenziert normalisierte Signale aus vorangegangenen Knoten.
Format: "node_id.question_id" (z.B. "node_1.q1")
"""
ref: str = Field(..., description="Referenz zum Signal: node_id.question_id")
operator: LogicOperator = Field(..., description="Vergleichsoperator")
value: Any = Field(..., description="Vergleichswert")
class LogicExpression(BaseModel):
"""
Logik-Ausdruck (verschachtelbar).
Beispiel:
{
"operator": "and",
"operands": [
{"ref": "node_1.q1", "operator": "eq", "value": "ja"},
{"ref": "node_1.q2", "operator": "in", "value": ["hoch", "mittel"]}
]
}
oder verschachtelt:
{
"operator": "or",
"operands": [
{
"operator": "and",
"operands": [...]
},
{"ref": "node_2.q1", "operator": "eq", "value": "ja"}
]
}
"""
operator: LogicOperator = Field(..., description="Logischer Operator (and, or, not) oder Vergleichsoperator")
operands: Optional[List[Any]] = Field(None, description="Liste von Operanden (LogicOperand oder verschachtelte LogicExpression)")
# Bei einfachem Vergleich:
ref: Optional[str] = Field(None, description="Signal-Referenz (nur bei Vergleichsoperatoren)")
value: Optional[Any] = Field(None, description="Vergleichswert (nur bei Vergleichsoperatoren)")
class Condition(BaseModel):
"""
Bedingung für einen Logik-Knoten.
Unterstützt if/else-if/else-Logik.
"""
type: str = Field(default="if", description="Bedingungstyp: if, else-if, else")
expression: Optional[LogicExpression] = Field(None, description="Logischer Ausdruck (null bei 'else')")
then_path: Optional[str] = Field(None, description="Edge-ID für 'then'-Pfad")
else_path: Optional[str] = Field(None, description="Edge-ID für 'else'-Pfad")
class FallbackConfig(BaseModel):
"""Fallback-Konfiguration für Logik-Knoten"""
strategy: FallbackStrategy = Field(..., description="Fallback-Strategie")
on_unclear: Optional[str] = Field(None, description="Edge-ID für Unsicherheits-Pfad")
on_invalid: Optional[str] = Field(None, description="Edge-ID bei ungültigen Signalen")
# ── Workflow-Graph-Modelle ────────────────────────────────────────────────────
class WorkflowNode(BaseModel):
"""
Workflow-Knoten (Teil des Graph-JSONB).
Verschiedene Typen haben unterschiedliche Felder:
- START/END: nur id, type, position
- ANALYSIS: prompt_slug, question_augmentations
- LOGIC: condition, fallback
- JOIN: join_strategy, skip_handling
"""
id: str = Field(..., description="Eindeutige Knoten-ID")
type: NodeType = Field(..., description="Knotentyp")
position: Optional[Position] = Field(None, description="Position im visuellen Editor")
# ANALYSIS-Knoten
prompt_slug: Optional[str] = Field(None, description="Slug des auszuführenden Prompts")
question_augmentations: Optional[List[QuestionAugmentation]] = Field(None, description="Fragenergänzungen (knotengebunden, überschreiben Prompt-Defaults)")
# LOGIC-Knoten
condition: Optional[Condition] = Field(None, description="Bedingung für Pfad-Routing")
fallback: Optional[FallbackConfig] = Field(None, description="Fallback-Konfiguration")
# JOIN-Knoten (Phase 4)
join_strategy: Optional[JoinStrategy] = Field(None, description="Join-Strategie")
skip_handling: Optional[SkipHandling] = Field(None, description="Umgang mit übersprungenen Pfaden")
min_paths: Optional[int] = Field(None, description="Mindestanzahl erforderlicher Pfade (für REQUIRE_MINIMUM)")
timeout_seconds: Optional[int] = Field(None, description="Timeout für BEST_EFFORT-Strategie")
# END-Knoten (Phase 4)
output_mode: Optional[EndNodeOutputMode] = Field(None, description="Output-Modus: auto oder template")
template: Optional[str] = Field(None, description="Jinja2 template für finales Ergebnis (wenn output_mode=template)")
class WorkflowEdge(BaseModel):
"""
Workflow-Kante (Verbindung zwischen Knoten).
"""
model_config = {"populate_by_name": True} # Erlaubt sowohl 'from_node' als auch 'from' (Alias)
id: str = Field(..., description="Eindeutige Edge-ID")
from_node: str = Field(..., alias="from", description="Quell-Knoten-ID")
to_node: str = Field(..., alias="to", description="Ziel-Knoten-ID")
label: Optional[str] = Field(None, description="Label für visuelle Darstellung (z.B. 'then', 'else')")
class WorkflowGraph(BaseModel):
"""
Workflow-Graph (gespeichert als JSONB in workflow_definitions.graph).
Repräsentiert einen DAG (Directed Acyclic Graph).
"""
nodes: List[WorkflowNode] = Field(..., description="Liste aller Knoten")
edges: List[WorkflowEdge] = Field(..., description="Liste aller Kanten")
# ── Workflow-Definition (DB-Modell) ───────────────────────────────────────────
class WorkflowDefinitionCreate(BaseModel):
"""Request-Modell für Workflow-Erstellung"""
name: str
slug: str
description: Optional[str] = None
graph: WorkflowGraph
class WorkflowDefinitionUpdate(BaseModel):
"""Request-Modell für Workflow-Update"""
name: Optional[str] = None
description: Optional[str] = None
graph: Optional[WorkflowGraph] = None
active: Optional[bool] = None
class WorkflowDefinition(BaseModel):
"""Response-Modell für Workflow-Definition"""
id: str
name: str
slug: str
description: Optional[str] = None
graph: WorkflowGraph
version: int
active: bool
created_at: str
updated_at: str
# ── Workflow-Execution (DB-Modell) ────────────────────────────────────────────
class NodeState(BaseModel):
"""Ausführungsstatus eines Knotens"""
status: NodeStatus
result: Optional[Dict[str, Any]] = Field(None, description="Ergebnis der Knoten-Ausführung (Prompt-Output, normalisierte Signale, etc.)")
timestamp: Optional[str] = Field(None, description="Zeitpunkt der Ausführung")
error: Optional[str] = Field(None, description="Fehlermeldung bei Status=failed")
class WorkflowExecutionCreate(BaseModel):
"""Request-Modell für Workflow-Ausführung (Start)"""
workflow_id: str
# profile_id kommt aus Session
class WorkflowExecution(BaseModel):
"""Response-Modell für Workflow-Execution"""
id: str
workflow_id: str
profile_id: str
status: str
node_states: Optional[Dict[str, NodeState]] = None
execution_log: Optional[List[Dict[str, Any]]] = None
started_at: str
completed_at: Optional[str] = None
# ── Question Catalog (DB-Modell) ──────────────────────────────────────────────
class QuestionCatalogEntry(BaseModel):
"""Eintrag im Fragenkatalog"""
id: str
question_type: str
label: str
question_template: str
answer_spectrum: List[str]
normalization_rules: Optional[Dict[str, Any]] = None
active: bool
created_at: str
# ── Phase 2: Normalisierung & Execution ───────────────────────────────────────
class NormalizedSignal(BaseModel):
"""
Normalisiertes Entscheidungssignal (Phase 2).
Resultat der Normalisierung einer Rohantwort gegen das Antwortspektrum.
"""
question_type: str = Field(..., description="Typ der Frage (z.B. 'relevanz')")
raw_value: str = Field(..., description="Original LLM-Antwort")
normalized_value: Optional[str] = Field(None, description="Gemappter Wert (null bei invalid/not_decidable)")
status: SignalStatus = Field(..., description="Normalisierungsstatus")
confidence: float = Field(default=1.0, description="Konfidenz (für späteren Einsatz)")
metadata: Dict[str, Any] = Field(default_factory=dict, description="Zusatzinfo (z.B. method: 'synonym')")
class NodeExecutionState(BaseModel):
"""
Detaillierter Ausführungsstatus eines Knotens (Phase 2).
Erweitert NodeState um Phase-1-Komponenten (analysis_core, decision_signals, etc.)
"""
node_id: str = Field(..., description="Knoten-ID")
status: NodeStatus = Field(..., description="Ausführungsstatus")
# Phase 1 Result Container
analysis_core: Optional[str] = Field(None, description="Hauptanalyse aus ## Analyse Sektion")
decision_signals: Dict[str, str] = Field(default_factory=dict, description="Rohe Signale (pre-normalization)")
normalized_signals: List[NormalizedSignal] = Field(default_factory=list, description="Normalisierte Signale (Phase 2)")
reasoning_anchors: Optional[str] = Field(None, description="Begründungsanker aus ## Begründung")
# Error & Timing
error: Optional[str] = Field(None, description="Fehlermeldung bei failed")
started_at: Optional[str] = Field(None, description="Start-Timestamp (ISO)")
completed_at: Optional[str] = Field(None, description="End-Timestamp (ISO)")
class ExecutionResult(BaseModel):
"""
Ergebnis einer Workflow-Ausführung (Phase 2).
Wird von workflow_executor.execute_workflow() zurückgegeben.
"""
execution_id: str = Field(..., description="UUID der Execution")
workflow_id: str = Field(..., description="UUID des Workflows")
status: str = Field(..., description="Gesamt-Status: 'completed', 'failed', 'partial'")
node_states: List[NodeExecutionState] = Field(..., description="States aller ausgeführten Knoten")
aggregated_result: Dict[str, Any] = Field(default_factory=dict, description="Aggregierte Ergebnisse (combined_analysis, all_signals, etc.)")
started_at: str = Field(..., description="Start-Timestamp (ISO)")
completed_at: Optional[str] = Field(None, description="End-Timestamp (ISO)")
error: Optional[str] = Field(None, description="Fehlermeldung bei failed")
@@ -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`).
+266
View File
@@ -0,0 +1,266 @@
# Phasenplan: Responsive UI (Desktop Sidebar + Mobile/PWA)
> **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-05 (P7 Admin-Shell umgesetzt; Doku `GUI_IA_ADMIN_NAV_2026-04-05.md`; P8 ausstehend)
---
## Fortschritt (kurz)
| Phase | Titel | Status | Datum / Notiz |
|-------|--------|--------|----------------|
| 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`
---
## Testumgebung (für alle Phasen)
| ID | Umgebung | Verwendung |
|----|-----------|------------|
| T-H1 | Chromium Desktop, Fenster **≥1280px** | Desktop-Layout, Sidebar |
| T-H2 | Chromium, DevTools **375×812** (o. ä.) | Mobile-Layout, Bottom-Nav |
| T-H3 | Chromium, Breite **1023px** vs **1024px** | Breakpoint-Grenze |
| T-H4 | **iPhone** (Safari), installierte **PWA** | Regression Mobile/PWA |
| T-H5 | optional: iPad quer (**≥1024px**) | Desktop-Sidebar auf Tablet quer |
**Allgemein:** Kein Pflicht-E2E-Framework im Repo; Abnahme primär **manuell** nach Checklisten unten. Optional später: Playwright-Smoke (`viewport`-Wechsel).
---
## Phase P0 – Vorbereitung & Baseline
### Ziel
Risikoarm starten: Ist-Stand dokumentieren, Spec bereinigen, keine funktionale UI-Änderung.
### Aufgaben
- [ ] Bekannte Artefakte am Ende von `.claude/docs/functional/RESPONSIVE_UI.md` entfernen (Zeilen `EOF` / `echo …`), falls noch vorhanden.
- [ ] Kurz notieren: aktuelle `app-shell`/`max-width:600px` in `app.css` ist die Mobile-Baseline (siehe Code-Review).
### Abnahmekriterien
- Spec-Datei endet mit den „Offenen Fragen“; keine Shell-Zeilenduplikate aus Fremdkopien.
- Plan-Datei (dieses Dokument) ist im Repo und verlinkt (optional in Gitea #30 kommentieren).
### Tests (P0)
| Test | Schritt | Erwartung |
|------|---------|-----------|
| P0-T1 | `RESPONSIVE_UI.md` öffnen | Letzte sinnvolle Zeile ist Frage 4 oder Abschnittsende; kein `echo`/`EOF` |
| P0-T2 | `npm run build` im `frontend/` | Exit 0 |
---
## Phase P1 – App-Shell: Sidebar + Breakpoint + gemeinsame Navigation
### Ziel
Desktop: feste **Sidebar 220px** links gemäß Spec; Mobile: **unverändert** Bottom-Nav. **Eine** Navigationsdefinition (Routes/Labels/Icons) für beide Darstellungen. Öffentliche Auth-Routen (`/register`, `/verify`, …) **nicht** in Sidebar/Bottom-Nav einbinden (wie heute).
### Aufgaben (technisch orientierend)
- [ ] Nav-Items aus `App.jsx` (`Nav`-Komponente) in **eine** exportierbare Struktur (z. B. `navItems` Array + `admin`-Eintrag nur bei `role === 'admin'`), von **Desktop-Sidebar** und **Mobile `Nav`** gemeinsam genutzt.
- [ ] Neue Komponente z. B. `DesktopSidebar.jsx` (oder `AppSidebar.jsx`): Logo/Branding, gleiche Links wie Bottom-Nav, unten Nutzerbereich (Avatar, Name/Tier laut Spec – Daten aus `useProfile`/`useAuth` wo möglich).
- [ ] `AppShell`: bei `≥1024px` Sidebar sichtbar, **Bottom-Nav ausgeblendet**; bei `<1024px` **umgekehrt**.
- [ ] Aktiver Route-State: `NavLink`/`active` in Sidebar **gleiche Semantik** wie Bottom-Nav (`end` bei `/` beachten).
- [ ] **Kein** `resize`-Listener pflichtig; primär **CSS** (`@media (min-width: 1024px)`) für Sichtbarkeit; falls nötig nur für Edge-Cases.
### Abnahmekriterien
- Unter **1024px**: UI wirkt **wie vor P1** (Bottom-Nav sichtbar, Sidebar unsichtbar); PWA-Start auf iPhone unverändert nutzbar.
- Ab **1024px**: Sidebar sichtbar, fixed links, ~220px; Bottom-Nav **nicht** sichtbar.
- Admin-Link nur für Admins in **beiden** Navs.
- Abmelden erreichbar (Spec: im Sidebar-Footer; falls Mobile weiter nur im Header: ** dokumentieren als Abweichung** oder gleich ziehen).
### Tests (P1)
| Test | Schritt | Erwartung |
|------|---------|-----------|
| P1-T1 | T-H2: einloggen, alle 5 Haupt-Routen antippen | Bottom-Nav aktiv, kein Layout-Bruch |
| P1-T2 | T-H1: gleiche Routen | Nur Sidebar-Navigation sichtbar, korrekte Aktiv-Markierung |
| P1-T3 | T-H3: Breite 1023→1024 wechseln | Sidebar erscheint / Bottom verschwindet ohne Reload; kein „Flackern“-Loop |
| P1-T4 | T-H4: PWA | Login, Hauptflows kurz (Dashboard, Erfassung) – Bottom-Nav ok |
| P1-T5 | Admin-User T-H1 | Admin-Eintrag in Sidebar; Nicht-Admin ohne Admin |
---
## Phase P2 – Globales Layout & Content-Bereich
### Ziel
Desktop-**Content** rechts von der Sidebar: Spec **margin-left 220px**, Padding **24px 32px**, **max-width 1200px** zentriert im verbleibenden Raum. Mobile: beibehaltene Abstände (**16px**, **80px** bottom für Nav).
### Aufgaben
- [ ] `app.css`: `.app-shell` **nicht** mehr global `max-width: 600px` für Desktop; Mobile beibehalten oder per Media Query trennen.
- [ ] `.app-main` Padding/Bottom: Mobile `calc(nav + 16px)`; Desktop **ohne** Bottom-Nav-Padding (oder nur safe-area falls nötig).
- [ ] Optional Desktop: **Top-Header** (`app-header`) redundant mit Sidebar-Branding – **vereinheitlichen** (z. B. Header auf Desktop ausblenden oder auf kompakte Toolbar reduzieren), damit keine doppelte Logo-Zeile.
### Abnahmekriterien
- Desktop: Content nutzt **sichtbar mehr** horizontalen Raum als heute (max 1200px Inhalt, zentriert).
- Mobile: **kein** zusätzliches horizontales Scrollen der Gesamtseite durch P1/P2.
- Keine Überlappung Sidebar/Content.
### Tests (P2)
| Test | Schritt | Erwartung |
|------|---------|-----------|
| P2-T1 | T-H1: lange Seite scrollen | Nur Main-Area scrollt; Sidebar bleibt sichtbar (fixed) |
| P2-T2 | T-H2 | Weiterhin nutzbarer unterer Rand für Bottom-Nav |
| P2-T3 | T-H1: sehr breiter Monitor | Content max ~1200px, optisch zentriert rechts von Sidebar |
---
## Phase P3 – Dashboard (Desktop-Grid)
### Ziel
Spec **§5.1**: Desktop mehrspaltige Karten (z. B. 4 Spalten für Kennzahlen-Zeile); Mobile Karten untereinander.
### Aufgaben
- [ ] `Dashboard.jsx`: Layout in **CSS Grid** o. ä. mit `@media (min-width: 1024px)` für 4-Spalten-Zeile(n) laut Wireframe; Mobile unveränderte Reihenfolge.
- [ ] Charts/„volle Breite“-Blöcke unter den Karten laut Spec.
### Abnahmekriterien
- Mobile Dashboard **visuell vergleichbar** zum Stand vor P3 (keine funktionalen Regressionen).
- Desktop: klar erkennbares **Grid**; keine übermäßigen Lücken bei typischer Viewport-Höhe.
### Tests (P3)
| Test | Schritt | Erwartung |
|------|---------|-----------|
| P3-T1 | T-H2 Dashboard | Karten untereinander, lesbar |
| P3-T2 | T-H1 Dashboard | Mehrspaltigkeit wie Spec; kein horizontaler Overflow |
| P3-T3 | Daten mit/ohne Werte | Keine Layout-Crashes (leere Zustände) |
---
## Phase P4 – Verlauf (`History.jsx`)
### Ziel
Spec **§5.2**: Desktop **Tabs vertikal links**, Chart/Tabelle **rechts** (volle restliche Breite); Mobile Tabs oben wie heute.
### Aufgaben
- [ ] Tab-Steuerung refaktorieren oder per CSS **ohne** doppelte State-Logik.
- [ ] Desktop: flex/grid `240–280px` Tab-Spalte + flex 1 Chart-Bereich (feinjustierbar).
### Abnahmekriterien
- Alle bisherigen Verlauf-**Tabs** funktionieren (Gewicht, KF, Umfänge, … – wie im aktuellen Code).
- Mobile UX **unverändert** vom Nutzergefühl her (Tabs oben).
- Desktop: klar **zwei Spalten**; Chart nutzt rechte Fläche.
### Tests (P4)
| Test | Schritt | Erwartung |
|------|---------|-----------|
| P4-T1 | T-H2: Tab wechseln | Wie bisher |
| P4-T2 | T-H1: jeder Tab | Linke Liste + rechter Chart-Bereich sichtbar |
| P4-T3 | Langes Tab-Label / viele Tabs | Kein Layout-Bruch (Scroll in Tab-Spalte falls nötig) |
---
## Phase P5 – Analyse (`Analysis.jsx`)
### Ziel
Spec **§5.3**: Desktop **Prompt-Liste links (~300px)**, Ergebnis **rechts**; Mobile untereinander.
### Aufgaben
- [ ] Layout splitten; Pipeline/Prompt-Bereiche so umbauen, dass Lesbarkeit und Scroll-Verhalten stimmen.
### Abnahmekriterien
- KI-Ausführung, Platzhalter-Tabelle, Experten-Modus: weiter bedienbar.
- Desktop: Ergebnisbereich hat **deutlich mehr** Breite als Mobile.
### Tests (P5)
| Test | Schritt | Erwartung |
|------|---------|-----------|
| P5-T1 | T-H2: Analyse ausführen | Flow wie bisher |
| P5-T2 | T-H1: langes Ergebnis | Rechte Spalte scrollbar, linke Prompt-Liste fix oder eigen-scroll |
| P5-T3 | Kleines Fenster knapp unter 1024px | Kein „mittendrin“ kaputtes Layout |
---
## Phase P6 – Erfassung / Capture & Formularseiten
### Ziel
Spec **§5.4**: Desktop Formulare **zentriert**, **max-width ~600px** im Content-Bereich; Mobile volle Breite wie heute.
### Aufgaben
- [ ] `CaptureHub` und relevante Seiten (`WeightScreen`, …) unter Desktop-Wrapper; wo sinnvoll **gemeinsame** Klasse `.capture-form-desktop` in `app.css`.
### Abnahmekriterien
- Mobile: keine Verschlechterung der Eingabe.
- Desktop: Formulare nicht „volle 1200px“, sondern **lesbar begrenzt**.
### Tests (P6)
| Test | Schritt | Erwartung |
|------|---------|-----------|
| P6-T1 | T-H2: Gewicht erfassen | Vollbreite ok |
| P6-T2 | T-H1: gleiche Seite | Schmale, zentrierte Spalte |
| P6-T3 | Capture-Hub Kacheln | Umbruch auf Desktop ordentlich |
---
## 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.
### Aufgaben
- [ ] `Admin*Page.jsx` und ähnliche Tabellen-Seiten: unnötige `max-width`-Erbe von Mobile entfernen; **nicht** jede Admin-Seite einzeln zerstören – priorisiert häufig genutzte.
### Abnahmekriterien
- Keine regressiven Auth-Schutz-Änderungen.
- Desktop: **mehr sichtbare Spalten** bei typischen Admin-Tabellen.
### Tests (P7)
| Test | Schritt | Erwartung |
|------|---------|-----------|
| P7-T1 | T-H1: z. B. Admin Training Types | Tabelle nutzt Breite; horizontales Scrollen nur bei Bedarf |
| P7-T2 | T-H2: gleiche Seite | Weiter bedienbar mit Scroll |
---
## Phase P8 – Abschluss, Regression, Dokumentation
### Ziel
Release-tauglich machen; Spec und Issue aktualisieren.
### Aufgaben
- [ ] Alle Phasen P1–P7 in Fortschrittstabelle auf ☑ setzen.
- [ ] Vollständiger **Regression-Pass** (Routenliste aus `App.jsx`).
- [ ] Gitea #30: Abschlusskommentar mit **Screenshots** (optional) + Hinweis auf diesen Plan.
- [ ] `REVIEW_OPEN_ISSUES_2026-04-04.md` oder Nachfolger: #30 auf DONE setzen, wenn aus eurer Sicht erledigt.
### Abnahmekriterien (Gesamt gem. #30 / Spec)
- [ ] Desktop **≥1024px**: Sidebar links, Bottom-Nav aus.
- [ ] Mobile **<1024px**: Bottom-Nav unten, Sidebar aus.
- [ ] Aktive Route in beiden Navs korrekt.
- [ ] Dashboard / Verlauf / Analyse / Erfassung / Admin gemäß Spec umgesetzt.
- [ ] Resize ohne JavaScript-Zwang stabil (CSS-first).
- [ ] **PWA iPhone** weiterhin funktionsfähig (Kernflows).
### Tests (P8 – Smoke-Checkliste)
| Route | T-H2 | T-H1 |
|-------|------|------|
| `/` | ☐ | ☐ |
| `/capture` | ☐ | ☐ |
| `/history` | ☐ | ☐ |
| `/analysis` | ☐ | ☐ |
| `/settings` | ☐ | ☐ |
| 1× Admin (falls verfügbar) | ☐ | ☐ |
| T-H4 PWA kurz | ☐ | n/a |
---
## Parallelität (Canvas / Workflow)
- Während **P1–P2** möglichst **keine** parallelenden Änderungen an `App.jsx` / globalem `app.css` ohne Absprache.
- Neue **Workflow-/Canvas-Routen**: nur innerhalb von `<main>`; Sidebar- und Breakpoint-**Kontrakt** einhalten (`margin-left`, keine zweite globale Spalte).
---
## Planpflege
Änderungen an Phasen, Kriterien oder Status: **dieses File** anpassen und kurz „Letzte Plan-Aktualisierung“ oben datieren. Bei größeren Scope-Änderungen Gitea #30 kommentieren.
@@ -0,0 +1,262 @@
# Gitea offene Issues – Review-Entwurf (Stand Code 2026-04-04)
> **Zweck:** Du kannst diese Datei **lesen, anpassen, abstreichen**. Nach Freigabe: Kommentare / Schließungen / Konsolidierungen in Gitea umsetzen (manuell oder per `scripts/gitea/gitea_api.py`).
>
> **Sortierung:** Nach **`created_at` aufsteigend** (älteste Issues zuerst). Duplikat-Issues mit gleichem Inhalt sind am Ende des Abschnitts „Duplikate“ gebündelt.
>
> **Legende `Vorschlag`:**
> - `OFFEN` – noch sinnvoll, weiterverfolgen
> - `TEILWEISE` – Teil umgesetzt, Beschreibung/AC anpassen
> - `PRÜFEN` – kurzer manueller Test nötig
> - `DUPLIKAT` – mit anderem Issue zusammenführen
> - `DONE?` – wirkt im Repo erledigt, ggf. schließen nach deiner Bestätigung
---
## Kurz-Übersicht (28 eindeutige Issue-Nummern, zeitlich älteste zuerst)
| # | Titel (gekürzt) | Vorschlag | Notiz |
|---|-----------------|-----------|--------|
| 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 | **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 |
| 35 | `subscriptions` Tabelle | PRÜFEN | Schema prüfen |
| 36 | BUG Trainingstyp ISE | PRÜFEN | Logs nötig |
| 37 | Feature Enforcement Activity CSV | OFFEN | Import ohne vorgeschalteten Check |
| 38 | Feature Enforcement Nutrition CSV UI | DONE? / TEILWEISE | Backend-Check da |
| 39 | Usage-Badges Dashboard/Assistent | TEILWEISE | v. a. Gewicht im Dashboard |
| 40 | Logout Header | DONE? | `App.jsx` LogOut-Button |
| 42 | Enhanced Debug UI | DUPLIKAT | Mit #43 zusammenführen |
| 43 | Enhanced Debug UI | DUPLIKAT | Mit #42 zusammenführen |
| 45 | Prompt-Optimierer | OFFEN | Backlog |
| 46 | Prompt-Ersteller | OFFEN | Backlog |
| 47 | Wertetabelle Optimierung | OFFEN | UX-Feinschliff |
| 49 | Prompt-Zuordnung Verlauf | OFFEN | Kein klarer Treffer |
| 54 | Placeholder Registry … | DUPLIKAT | Wie #55 |
| 55 | Placeholder Registry … | OFFEN / TEILWEISE | `validate_all` existiert |
| 56–58 | Body Cluster Restarbeiten | DUPLIKAT | Dreimal gleicher Inhalt → ein Issue |
---
## Details je Issue (älteste zuerst)
### #14 – [FEAT-001] Icon Picker für Trainingstypen — **ERLEDIGT**
**Code-Stand:** `AdminTrainingTypesPage.jsx` nutzt **`EmojiIconPicker`** (`frontend/src/components/EmojiIconPicker.jsx`) für Neu- und Bearbeiten-Dialoge; Wert bleibt String in `training_types.icon`.
**Gitea:** Issue **#14 geschlossen** (Kommentar + Close, Stand 2026-04).
---
### #15 – [FEAT-002] Quality-Filter für KI-Auswertungen & Charts
**Code-Stand:** Charts/Data-Layer nutzen **Confidence** u. a.; Placeholder-Registry hat viele `quality_filter_policy` / Evidence-Felder (teilweise `UNRESOLVED`/`TO_VERIFY`). Ein **einheitlicher** „Quality-Filter“-Mechanismus über alle KI-Auswertungen ist nicht eindeutig als fertiges Feature erkennbar.
**Vorschlag:** `TEILWEISE` – Issue-Text auf konkrete Lücken schärfen (welche Prompts/Charts, welche Schwellen, SSoT Registry?).
**Kommentar-Entwurf:**
> Teilaspekte existieren (z. B. Confidence in Chart-Endpoints, Registry-Felder). Offen: durchgängige KI-/Chart-Quality-Pipeline und Abgleich mit Issue-Zielbild.
---
### #21 – [FEATURE] Universeller CSV-Parser mit lernbarem Feldmapping
**Code-Stand:** Modulspezifische CSV-Imports (Activity, Nutrition, Vitals, Sleep, …) mit jeweils eigenem Parser; **lernbares Mapping** stark bei **Activity** über `activity_type_mappings`. Kein **ein** generischer CSV-Engine wie im Issue beschrieben.
**Vorschlag:** `OFFEN` – oder Scope reduzieren („pro Modul konsolidieren“).
---
### #25 – [FEAT] Ziele-System (Goals) v9e Kernfeature
**Code-Stand:** `goals`-Router, `GoalsPage`, Focus Areas, Migrationen – laut Projektstand **weitgehend implementiert**.
**Vorschlag:** `DONE?` nach deiner Abnahme – Issue-Body auf verbleibende Teilziele kürzen oder schließen.
**Kommentar-Entwurf:**
> Backend/Frontend Goals + Focus Areas sind im Repo vorhanden. Bitte verbleibende Wünsche als neue Sub-Issues oder AC hier abhaken und schließen.
---
### #26 – [FEAT] Charts & Visualisierungen erweitern
**Code-Stand:** `backend/routers/charts.py` (Phase 0c), viele `api.get…Chart` in `api.js`; `History.jsx` + `NutritionCharts` / `RecoveryCharts` nutzen Chart-Daten.
**Vorschlag:** `TEILWEISE` – Issue auf konkrete fehlende Chart-Typen/UI-Verdrahtung schärfen (falls noch offen).
---
### #27 – [FEAT] Korrelationen & Insights erweitern
**Code-Stand:** Chart-Endpunkte C1–C4 u. a.; Data-Layer `correlations.py` mit TODO-Stellen in Teilen.
**Vorschlag:** `TEILWEISE` – Liste fehlender Korrelationen/Insights vs. Code ergänzen.
---
### #29 – [FEAT] Abilities-Matrix UI (v9f)
**Code-Stand:** Training Types mit `abilities` JSONB, `AdminTrainingProfiles`, `ProfileBuilder` – vollständige „5D Matrix“-UX unklar ohne Produktvorgabe.
**Vorschlag:** `TEILWEISE` – AC mit aktuellen Screenshots/Flows abgleichen.
---
### #30 – [FEAT] Responsive UI – Desktop Sidebar + 2-spaltig
**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). **P7** Kern umgesetzt; **P8** (Regression, finale Abnahme) stehen noch aus – Issue **nicht** schließen ohne P8-Checkliste.
**Vorschlag:** `TEILWEISE` – Gitea-Kommentar mit Link auf die GUI-Doku; Titel/Beschreibung optional um „Admin-Shell / Ziele-Nav / iOS PWA-Leiste“ ergänzen.
---
### #32 – Version-System (inkl. ehem. #33)
**Gitea (2026-04-04):** #33 geschlossen; Inhalt in **#32** zusammengeführt (ein Epic: `/api/version`, `version.js`, Settings, `main.py`-Konsistenz). Automatische Git-/Build-Identität über den Runner: **zurückgestellt**, geplant als **separates Issue** nach der Basis.
**Code-Stand:** `backend/version.py` vorhanden; **`GET /api/version`** fehlt; `main.py`: Root `v9c-dev`, `FastAPI(..., version="3.0.0")`.
**Vorschlag:** `OFFEN` – Umsetzung laut aktualisiertem Gitea-Issue #32.
---
### #34 – External Volumes dokumentieren (Legacy bodytrack_*)
**Vorschlag:** `PRÜFEN` – gegen aktuelle `docker-compose`/Deploy-Doku im Repo halten; dann schließen oder Aktualisierung kommentieren.
---
### #35 – Deprecated Tabelle `subscriptions` entfernen
**Code-Stand:** Im Migrations-Ordner **kein** aktueller Treffer auf `subscriptions` (Stichprobe); Membership-System nutzt andere Tabellen.
**Vorschlag:** `PRÜFEN` – einmal `schema.sql` / DB prüfen, ob Tabelle noch existiert. Wenn weg: Issue schließen mit Verweis auf Migration.
---
### #36 – BUG-009: Trainingstyp-Erstellung → Internal Server Error
**Code-Stand:** `TrainingTypeCreate` enthält `abilities` / `profile` (JSONB). ISE oft durch DB-Constraint, NULL/JSON oder fehlende Spalte – **ohne Laufzeit-Log nicht verifiziert**.
**Vorschlag:** `PRÜFEN` – in Gitea Notiz: aktueller Request-Body + Stacktrace aus `docker logs`; wenn behoben: schließen.
---
### #37 – Feature-Enforcement Activity CSV-Import
**Code-Stand:** `create_activity` nutzt `check_feature_access` für `activity_entries`. **`import_activity_csv`** startet **ohne** vorgeschalteten Limit-Check (im gelesenen Abschnitt nur `get_pid` + Parse) – von Issue #37 noch **nicht** erfüllt.
**Vorschlag:** `OFFEN` – hoch priorisieren; analog Nutrition: ein Check vor Bulk-Import + Zählung.
---
### #38 – Feature-Enforcement Nutrition CSV-Import UI
**Code-Stand:** `import_nutrition_csv` ruft **`check_feature_access`** für `nutrition_entries` auf (inkl. Logging).
**Vorschlag:** `TEILWEISE` / `DONE?` – falls UI-Feedback gewünscht, im Issue auf konkrete UI-Lücken eingehen (Banner, Disable Button).
---
### #39 – Usage-Badges im Dashboard-Assistenten
**Code-Stand:** `Dashboard.jsx` nutzt `getFeatureUsage()` für **Gewichts-Widget** (Limit/Lock). Unklar ob „Assistent“-Modus = gesamtes Dashboard oder separater Guide.
**Vorschlag:** `TEILWEISE` – Issue präzisieren, welche Kacheln/Bereiche Badges brauchen.
---
### #40 – Logout-Button im App-Header (neben Avatar)
**Code-Stand:** `App.jsx` – Header mit **`LogOut` neben Avatar** (Umsetzung vorhanden).
**Vorschlag:** `DONE?` – nach kurzem Klicktest **schließen**.
**Kommentar-Entwurf:**
> In `App.jsx` ist ein Logout-Button im Header umgesetzt. Bitte in target Umgebung verifizieren und schließen.
---
### #42 / #43 – Enhanced Debug / Prompt Analysis UI (Issue #28 Phase C)
**Code-Stand:** `Analysis.jsx` mit Expert-Modus, Platzhalter-Gruppierung – kann Teile von Phase C abdecken.
**Vorschlag:** `DUPLIKAT` – **ein** Issue behalten; anderes schließen mit Verweis. Inhalte zusammenführen.
---
### #45 – KI Prompt-Optimierer
**Vorschlag:** `OFFEN` – Backlog, nicht im aktuellen Code sichtbar.
---
### #46 – KI Prompt-Ersteller
**Vorschlag:** `OFFEN` – wie #45.
---
### #47 – Wertetabelle Optimierung
**Code-Stand:** Wertetabelle in `Analysis.jsx` / Metadata – viele Punkte eher UX/Performance.
**Vorschlag:** `OFFEN` – konkrete UI-Schmerzpunkte in Sub-Tasks splitten.
---
### #49 – Prompt-Zuordnung zu Verlaufsseiten
**Code-Stand:** Kein eindeutiger Treffer zu „History page prompt assignment“ in kurzer Suche.
**Vorschlag:** `OFFEN` – kurz präzisieren (Welche Seite, welches Datenmodell).
---
### #54 / #55 – Placeholder Registry UNRESOLVED & TO_VERIFY
**Code-Stand:** `placeholder_registry_export.py` liefert **`validation_report` über `registry.validate_all()`** (nicht mehr leer aus dem frühen Issue-Text für Body-Cluster „{}“-Teil). Evidence `TO_VERIFY`/`UNRESOLVED` existieren weiter in Registrations.
**Vorschlag:** `#54` und `#55` **zusammenlegen** (gleiches Thema, Titel nur Encoding-Unterschied). Ein Issue offen lassen, Metadaten-Audit fortsetzen.
---
### #56 / #57 / #58 – Body Cluster Restarbeiten & Metadaten-Verifizierung
**Inhalt:** identische bzw. nahezu identische Langbeschreibung (Metadaten, Layer 2b, Nutrition confidence_logic, Validation Report).
**Vorschlag:** `DUPLIKAT` – **eines** behalten (z. B. niedrigste Nummer oder neueste #58 mit aktualisiertem Stand), andere **schließen** mit Verweis „Duplicate of #X“. Validation-Teil: Code hat bereits `validate_all` – Issue-Text Abschnitt „leeres validation_report“ **aktualisieren**.
**Kommentar-Entwurf:**
> Dreimal dasselbe Issue. Vorschlag: #56/#57 schließen, Tracking nur in #XX. `validation_report` wird aus `registry.validate_all()` befüllt; verbleibende Arbeit: TO_VERIFY-Felder Layer 2b + Nutrition confidence_logic laut Checkliste.
---
## Nachbearbeitung in Gitea (Checkliste für dich)
- [ ] Duplikate schließen und verlinken (#42/#43, #54/#55, #56–#58).
- [ ] „DONE?“-Issues manuell testen (`#25`, `#38`, `#40`).
- [ ] `#37` umsetzen oder Kommentar „noch offen“ bestätigen.
- [x] `#32`–`#33` in Gitea zusammengeführt (#33 geschlossen); Umsetzung weiter über #32.
- [ ] Kommentare aus diesem Dokument kopieren/anpassen.
- [ ] Optional: Labels in Gitea setzen (`duplicate`, `blocked`, `needs-retest`).
---
## Technischer Hinweis (Audit / Security)
Aus dem Code-Audit 2026-04-04: kritische Punkte (`get_pid` / `X-Profile-Id`, `/api/profiles` ohne Admin) sind **nicht** 1:1 als Gitea-Issues in dieser offenen Liste sichtbar – ggf. **separate** Security-Issues aus `.claude/docs/audit/20260404_code_audit/gitea/` anlegen, falls noch nicht vorhanden.
---
*Erzeugt aus Gitea API (28 offene Issues, sortiert nach `created_at`) und statischer Code-Analyse im Workspace. Kein Laufzeit-Test auf dem Pi.*
@@ -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.*
+427
View File
@@ -15,6 +15,7 @@
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.23.1",
"reactflow": "^11.11.4",
"recharts": "^2.12.7"
},
"devDependencies": {
@@ -2059,6 +2060,108 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@reactflow/background": {
"version": "11.3.14",
"resolved": "https://registry.npmjs.org/@reactflow/background/-/background-11.3.14.tgz",
"integrity": "sha512-Gewd7blEVT5Lh6jqrvOgd4G6Qk17eGKQfsDXgyRSqM+CTwDqRldG2LsWN4sNeno6sbqVIC2fZ+rAUBFA9ZEUDA==",
"license": "MIT",
"dependencies": {
"@reactflow/core": "11.11.4",
"classcat": "^5.0.3",
"zustand": "^4.4.1"
},
"peerDependencies": {
"react": ">=17",
"react-dom": ">=17"
}
},
"node_modules/@reactflow/controls": {
"version": "11.2.14",
"resolved": "https://registry.npmjs.org/@reactflow/controls/-/controls-11.2.14.tgz",
"integrity": "sha512-MiJp5VldFD7FrqaBNIrQ85dxChrG6ivuZ+dcFhPQUwOK3HfYgX2RHdBua+gx+40p5Vw5It3dVNp/my4Z3jF0dw==",
"license": "MIT",
"dependencies": {
"@reactflow/core": "11.11.4",
"classcat": "^5.0.3",
"zustand": "^4.4.1"
},
"peerDependencies": {
"react": ">=17",
"react-dom": ">=17"
}
},
"node_modules/@reactflow/core": {
"version": "11.11.4",
"resolved": "https://registry.npmjs.org/@reactflow/core/-/core-11.11.4.tgz",
"integrity": "sha512-H4vODklsjAq3AMq6Np4LE12i1I4Ta9PrDHuBR9GmL8uzTt2l2jh4CiQbEMpvMDcp7xi4be0hgXj+Ysodde/i7Q==",
"license": "MIT",
"dependencies": {
"@types/d3": "^7.4.0",
"@types/d3-drag": "^3.0.1",
"@types/d3-selection": "^3.0.3",
"@types/d3-zoom": "^3.0.1",
"classcat": "^5.0.3",
"d3-drag": "^3.0.0",
"d3-selection": "^3.0.0",
"d3-zoom": "^3.0.0",
"zustand": "^4.4.1"
},
"peerDependencies": {
"react": ">=17",
"react-dom": ">=17"
}
},
"node_modules/@reactflow/minimap": {
"version": "11.7.14",
"resolved": "https://registry.npmjs.org/@reactflow/minimap/-/minimap-11.7.14.tgz",
"integrity": "sha512-mpwLKKrEAofgFJdkhwR5UQ1JYWlcAAL/ZU/bctBkuNTT1yqV+y0buoNVImsRehVYhJwffSWeSHaBR5/GJjlCSQ==",
"license": "MIT",
"dependencies": {
"@reactflow/core": "11.11.4",
"@types/d3-selection": "^3.0.3",
"@types/d3-zoom": "^3.0.1",
"classcat": "^5.0.3",
"d3-selection": "^3.0.0",
"d3-zoom": "^3.0.0",
"zustand": "^4.4.1"
},
"peerDependencies": {
"react": ">=17",
"react-dom": ">=17"
}
},
"node_modules/@reactflow/node-resizer": {
"version": "2.2.14",
"resolved": "https://registry.npmjs.org/@reactflow/node-resizer/-/node-resizer-2.2.14.tgz",
"integrity": "sha512-fwqnks83jUlYr6OHcdFEedumWKChTHRGw/kbCxj0oqBd+ekfs+SIp4ddyNU0pdx96JIm5iNFS0oNrmEiJbbSaA==",
"license": "MIT",
"dependencies": {
"@reactflow/core": "11.11.4",
"classcat": "^5.0.4",
"d3-drag": "^3.0.0",
"d3-selection": "^3.0.0",
"zustand": "^4.4.1"
},
"peerDependencies": {
"react": ">=17",
"react-dom": ">=17"
}
},
"node_modules/@reactflow/node-toolbar": {
"version": "1.3.14",
"resolved": "https://registry.npmjs.org/@reactflow/node-toolbar/-/node-toolbar-1.3.14.tgz",
"integrity": "sha512-rbynXQnH/xFNu4P9H+hVqlEUafDCkEoCy0Dg9mG22Sg+rY/0ck6KkrAQrYrTgXusd+cEJOMK0uOOFCK2/5rSGQ==",
"license": "MIT",
"dependencies": {
"@reactflow/core": "11.11.4",
"classcat": "^5.0.3",
"zustand": "^4.4.1"
},
"peerDependencies": {
"react": ">=17",
"react-dom": ">=17"
}
},
"node_modules/@remix-run/router": {
"version": "1.23.2",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz",
@@ -2554,24 +2657,159 @@
"@babel/types": "^7.28.2"
}
},
"node_modules/@types/d3": {
"version": "7.4.3",
"resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz",
"integrity": "sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==",
"license": "MIT",
"dependencies": {
"@types/d3-array": "*",
"@types/d3-axis": "*",
"@types/d3-brush": "*",
"@types/d3-chord": "*",
"@types/d3-color": "*",
"@types/d3-contour": "*",
"@types/d3-delaunay": "*",
"@types/d3-dispatch": "*",
"@types/d3-drag": "*",
"@types/d3-dsv": "*",
"@types/d3-ease": "*",
"@types/d3-fetch": "*",
"@types/d3-force": "*",
"@types/d3-format": "*",
"@types/d3-geo": "*",
"@types/d3-hierarchy": "*",
"@types/d3-interpolate": "*",
"@types/d3-path": "*",
"@types/d3-polygon": "*",
"@types/d3-quadtree": "*",
"@types/d3-random": "*",
"@types/d3-scale": "*",
"@types/d3-scale-chromatic": "*",
"@types/d3-selection": "*",
"@types/d3-shape": "*",
"@types/d3-time": "*",
"@types/d3-time-format": "*",
"@types/d3-timer": "*",
"@types/d3-transition": "*",
"@types/d3-zoom": "*"
}
},
"node_modules/@types/d3-array": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
"integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",
"license": "MIT"
},
"node_modules/@types/d3-axis": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/@types/d3-axis/-/d3-axis-3.0.6.tgz",
"integrity": "sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==",
"license": "MIT",
"dependencies": {
"@types/d3-selection": "*"
}
},
"node_modules/@types/d3-brush": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/@types/d3-brush/-/d3-brush-3.0.6.tgz",
"integrity": "sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==",
"license": "MIT",
"dependencies": {
"@types/d3-selection": "*"
}
},
"node_modules/@types/d3-chord": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/@types/d3-chord/-/d3-chord-3.0.6.tgz",
"integrity": "sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==",
"license": "MIT"
},
"node_modules/@types/d3-color": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
"integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
"license": "MIT"
},
"node_modules/@types/d3-contour": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/@types/d3-contour/-/d3-contour-3.0.6.tgz",
"integrity": "sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==",
"license": "MIT",
"dependencies": {
"@types/d3-array": "*",
"@types/geojson": "*"
}
},
"node_modules/@types/d3-delaunay": {
"version": "6.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.4.tgz",
"integrity": "sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==",
"license": "MIT"
},
"node_modules/@types/d3-dispatch": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/@types/d3-dispatch/-/d3-dispatch-3.0.7.tgz",
"integrity": "sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA==",
"license": "MIT"
},
"node_modules/@types/d3-drag": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",
"integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",
"license": "MIT",
"dependencies": {
"@types/d3-selection": "*"
}
},
"node_modules/@types/d3-dsv": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/@types/d3-dsv/-/d3-dsv-3.0.7.tgz",
"integrity": "sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==",
"license": "MIT"
},
"node_modules/@types/d3-ease": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
"integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",
"license": "MIT"
},
"node_modules/@types/d3-fetch": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/@types/d3-fetch/-/d3-fetch-3.0.7.tgz",
"integrity": "sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==",
"license": "MIT",
"dependencies": {
"@types/d3-dsv": "*"
}
},
"node_modules/@types/d3-force": {
"version": "3.0.10",
"resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz",
"integrity": "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==",
"license": "MIT"
},
"node_modules/@types/d3-format": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.4.tgz",
"integrity": "sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==",
"license": "MIT"
},
"node_modules/@types/d3-geo": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.0.tgz",
"integrity": "sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==",
"license": "MIT",
"dependencies": {
"@types/geojson": "*"
}
},
"node_modules/@types/d3-hierarchy": {
"version": "3.1.7",
"resolved": "https://registry.npmjs.org/@types/d3-hierarchy/-/d3-hierarchy-3.1.7.tgz",
"integrity": "sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==",
"license": "MIT"
},
"node_modules/@types/d3-interpolate": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
@@ -2587,6 +2825,24 @@
"integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
"license": "MIT"
},
"node_modules/@types/d3-polygon": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-polygon/-/d3-polygon-3.0.2.tgz",
"integrity": "sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==",
"license": "MIT"
},
"node_modules/@types/d3-quadtree": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/@types/d3-quadtree/-/d3-quadtree-3.0.6.tgz",
"integrity": "sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==",
"license": "MIT"
},
"node_modules/@types/d3-random": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/d3-random/-/d3-random-3.0.3.tgz",
"integrity": "sha512-Imagg1vJ3y76Y2ea0871wpabqp613+8/r0mCLEBfdtqC7xMSfj9idOnmBYyMoULfHePJyxMAw3nWhJxzc+LFwQ==",
"license": "MIT"
},
"node_modules/@types/d3-scale": {
"version": "4.0.9",
"resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
@@ -2596,6 +2852,18 @@
"@types/d3-time": "*"
}
},
"node_modules/@types/d3-scale-chromatic": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@types/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",
"integrity": "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==",
"license": "MIT"
},
"node_modules/@types/d3-selection": {
"version": "3.0.11",
"resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.11.tgz",
"integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==",
"license": "MIT"
},
"node_modules/@types/d3-shape": {
"version": "3.1.8",
"resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz",
@@ -2611,12 +2879,37 @@
"integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
"license": "MIT"
},
"node_modules/@types/d3-time-format": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-4.0.3.tgz",
"integrity": "sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==",
"license": "MIT"
},
"node_modules/@types/d3-timer": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",
"integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
"license": "MIT"
},
"node_modules/@types/d3-transition": {
"version": "3.0.9",
"resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz",
"integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==",
"license": "MIT",
"dependencies": {
"@types/d3-selection": "*"
}
},
"node_modules/@types/d3-zoom": {
"version": "3.0.8",
"resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.8.tgz",
"integrity": "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==",
"license": "MIT",
"dependencies": {
"@types/d3-interpolate": "*",
"@types/d3-selection": "*"
}
},
"node_modules/@types/estree": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
@@ -2624,6 +2917,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/geojson": {
"version": "7946.0.16",
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
"integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
"license": "MIT"
},
"node_modules/@types/raf": {
"version": "3.4.3",
"resolved": "https://registry.npmjs.org/@types/raf/-/raf-3.4.3.tgz",
@@ -3024,6 +3323,12 @@
"node": ">=10.0.0"
}
},
"node_modules/classcat": {
"version": "5.0.5",
"resolved": "https://registry.npmjs.org/classcat/-/classcat-5.0.5.tgz",
"integrity": "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==",
"license": "MIT"
},
"node_modules/clsx": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
@@ -3145,6 +3450,28 @@
"node": ">=12"
}
},
"node_modules/d3-dispatch": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",
"integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-drag": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",
"integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",
"license": "ISC",
"dependencies": {
"d3-dispatch": "1 - 3",
"d3-selection": "3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-ease": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
@@ -3200,6 +3527,16 @@
"node": ">=12"
}
},
"node_modules/d3-selection": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",
"integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",
"license": "ISC",
"peer": true,
"engines": {
"node": ">=12"
}
},
"node_modules/d3-shape": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
@@ -3245,6 +3582,41 @@
"node": ">=12"
}
},
"node_modules/d3-transition": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz",
"integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",
"license": "ISC",
"dependencies": {
"d3-color": "1 - 3",
"d3-dispatch": "1 - 3",
"d3-ease": "1 - 3",
"d3-interpolate": "1 - 3",
"d3-timer": "1 - 3"
},
"engines": {
"node": ">=12"
},
"peerDependencies": {
"d3-selection": "2 - 3"
}
},
"node_modules/d3-zoom": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",
"integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",
"license": "ISC",
"dependencies": {
"d3-dispatch": "1 - 3",
"d3-drag": "2 - 3",
"d3-interpolate": "1 - 3",
"d3-selection": "2 - 3",
"d3-transition": "2 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/data-view-buffer": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz",
@@ -5161,6 +5533,24 @@
"react-dom": ">=16.6.0"
}
},
"node_modules/reactflow": {
"version": "11.11.4",
"resolved": "https://registry.npmjs.org/reactflow/-/reactflow-11.11.4.tgz",
"integrity": "sha512-70FOtJkUWH3BAOsN+LU9lCrKoKbtOPnz2uq0CV2PLdNSwxTXOhCbsZr50GmZ+Rtw3jx8Uv7/vBFtCGixLfd4Og==",
"license": "MIT",
"dependencies": {
"@reactflow/background": "11.3.14",
"@reactflow/controls": "11.2.14",
"@reactflow/core": "11.11.4",
"@reactflow/minimap": "11.7.14",
"@reactflow/node-resizer": "2.2.14",
"@reactflow/node-toolbar": "1.3.14"
},
"peerDependencies": {
"react": ">=17",
"react-dom": ">=17"
}
},
"node_modules/recharts": {
"version": "2.15.4",
"resolved": "https://registry.npmjs.org/recharts/-/recharts-2.15.4.tgz",
@@ -6187,6 +6577,15 @@
"browserslist": ">= 4.21.0"
}
},
"node_modules/use-sync-external-store": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
"integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",
"license": "MIT",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/utrie": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/utrie/-/utrie-1.0.2.tgz",
@@ -6761,6 +7160,34 @@
"integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
"dev": true,
"license": "ISC"
},
"node_modules/zustand": {
"version": "4.5.7",
"resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",
"integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",
"license": "MIT",
"dependencies": {
"use-sync-external-store": "^1.2.2"
},
"engines": {
"node": ">=12.7.0"
},
"peerDependencies": {
"@types/react": ">=16.8",
"immer": ">=9.0.6",
"react": ">=16.8"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"immer": {
"optional": true
},
"react": {
"optional": true
}
}
}
}
}
+6 -5
View File
@@ -9,14 +9,15 @@
"preview": "vite preview"
},
"dependencies": {
"dayjs": "^1.11.11",
"jspdf": "^2.5.1",
"jspdf-autotable": "^3.8.2",
"lucide-react": "^0.383.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.23.1",
"recharts": "^2.12.7",
"jspdf": "^2.5.1",
"jspdf-autotable": "^3.8.2",
"dayjs": "^1.11.11",
"lucide-react": "^0.383.0"
"reactflow": "^11.11.4",
"recharts": "^2.12.7"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.3.0",
+138 -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,27 +39,48 @@ 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'
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>
@@ -61,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?')) {
@@ -135,69 +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>
)
}
+422
View File
@@ -0,0 +1,422 @@
import { useState, useId, useMemo, useEffect } from 'react'
import { ChevronDown, ChevronUp } from 'lucide-react'
import { haystackForEmoji, matchesEmojiSearch } from './emojiIconPickerKeywords.js'
/**
* Kuratierte Emoji-Gruppen (viele Einzel-Glyphen für breite OS-Unterstützung).
* Erste Sport-Gruppe: typische Vereins-/Breitensportarten in Deutschland (DOSB/Nischensport mit abgedeckt).
* Erweiterbar: prop `extraGroups` an EmojiIconPicker, oder diese Konstante editieren.
*/
export const EMOJI_ICON_GROUPS = [
{
label: 'Sportarten (typisch Deutschland)',
emojis: [
// Vereins- & Breitensport (Reihenfolge: Fußball, Handball, Kampfsport Gi = Karate/Judo/…, …)
'⚽',
'🤾',
'🤾‍♂️',
'🤾‍♀️',
'🥋',
'🏐',
'🏀',
'🎾',
'🏓',
'🏸',
'🏒',
'🏑',
'🥍',
'🏈',
'🏉',
'⚾',
'🥎',
'⛹️',
'⛹️‍♂️',
'⛹️‍♀️',
'🥅',
'⛷️',
'🎿',
'🏂',
'🛷',
'⛸️',
'🥌',
'🚴',
'🚴‍♂️',
'🚴‍♀️',
'🚵',
'🚵‍♂️',
'🚵‍♀️',
'🏃',
'🏃‍♂️',
'🏃‍♀️',
'🏃‍➡️',
'🚶',
'🥾',
'🏊',
'🏊‍♂️',
'🏊‍♀️',
'🤽',
'🤽‍♂️',
'🤽‍♀️',
'🤿',
'🏄',
'🏄‍♂️',
'🏄‍♀️',
'🚣',
'🚣‍♂️',
'🚣‍♀️',
'⛵',
'🧗',
'🧗‍♂️',
'🧗‍♀️',
'🏋️',
'🏋️‍♂️',
'🏋️‍♀️',
'🤸',
'🤸‍♂️',
'🤸‍♀️',
'🥊',
'🤼',
'🤺',
'🏇',
'⛳',
'🏌️',
'🏌️‍♂️',
'🏌️‍♀️',
'💃',
'🕺',
'🧘',
'🧘‍♂️',
'🧘‍♀️',
'🛼',
'🛹',
'🎯',
'🎳',
'🏟️',
'🏆',
'🥇',
'🥈',
'🥉'
]
},
{
label: 'Weitere Sportarten & Hobbysport',
emojis: [
'🎱',
'🎣',
'🤹',
'🪁',
'🥏',
'🛶',
'🏹',
'🌊',
'🏖️',
'🛣️',
'🧭',
'🏕️',
'⛺'
]
},
{
label: 'Yoga, Geist, Balance',
emojis: [
'🧘', '🧘‍♂️', '🧘‍♀️', '🪷', '☯️', '🕉️', '🙏', '🧎', '🧍', '💭', '📿', '🎼',
'🎹', '🥁', '🎸', '🎺', '🔔', '✨', '🌟', '💫', '🔮'
]
},
{
label: 'Outdoor & Natur',
emojis: [
'⛰️', '🏔️', '🗻', '🌋', '🏕️', '⛺', '🧭', '🗺️', '🌲', '🌳', '🌴', '🍃',
'🍂', '🌿', '☘️', '🪨', '🏞️', '🏜️', '🏖️', '🌅', '🌄', '🌈', '⛅', '🌤️',
'☀️', '🌙', '⭐', '🌠', '❄️', '☃️', '⛄'
]
},
{
label: 'Körper & Medizin',
emojis: [
'💪', '🦾', '🦵', '🦶', '🖐️', '✋', '👣', '❤️', '🩷', '💙', '💚', '🫀',
'🫁', '🧠', '👁️', '👂', '🦷', '🦴', '🧬', '⚕️', '🩺', '🩹', '🩼', '💊',
'🌡️', '🔬', '🧪', '🧫', '♿', '⚖️', '📏', '📐'
]
},
{
label: 'Ernährung & Getränke',
emojis: [
'🍎', '🍐', '🍊', '🍋', '🍌', '🍉', '🍇', '🍓', '🫐', '🍒', '🍑', '🥭',
'🍍', '🥝', '🍅', '🥑', '🥦', '🥬', '🥒', '🌶️', '🫑', '🌽', '🥕', '🫒',
'🧄', '🧅', '🥔', '🍠', '🥐', '🍞', '🥖', '🥨', '🧀', '🥚', '🍳', '🧈',
'🥞', '🧇', '🥓', '🥩', '🍗', '🍖', '🌭', '🍔', '🍟', '🍕', '🫓', '🥙',
'🌮', '🌯', '🥗', '🍝', '🍜', '🍲', '🍛', '🍣', '🍱', '🥟', '🦪', '🍤',
'🍙', '🍚', '🍘', '🍥', '🥠', '🥮', '🍢', '🍡', '🍧', '🍨', '🍦', '🥧',
'🧁', '🍰', '🎂', '🍮', '🍭', '🍬', '🍫', '🍿', '🍩', '🍪', '🌰', '🥜',
'🍯', '🥛', '🍼', '🫖', '☕', '🍵', '🧃', '🥤', '🧋', '🍶', '🍺', '🍻',
'🥂', '🍷', '🥃', '🍸', '🍹', '🧉', '🍾', '💧', '🧊'
]
},
{
label: 'Schlaf & Erholung',
emojis: [
'😴', '🛌', '🛏️', '💤', '🌙', '🌛', '🌜', '💆', '💆‍♂️', '💆‍♀️', '🧖', '🧖‍♂️',
'🧖‍♀️', '🧴', '🛁', '🚿', '🪥', '🩴', '🧘', '🕯️'
]
},
{
label: 'Stimmung & Motivation Smileys',
emojis: [
'😊', '🙂', '😌', '😎', '🤩', '🥳', '😤', '💯', '🙌', '👏', '🤝', '👍',
'👎', '✊', '🤛', '🤜', '💪', '🦵', '🧗', '🔥', '💥', '⚡', '🎉', '🏆',
'🥇', '🥈', '🥉', '🎖️', '🏅', '😅', '🤔', '🧐', '😇'
]
},
{
label: 'Tiere (Maskottchen)',
emojis: [
'🐶', '🐱', '🐭', '🐹', '🐰', '🦊', '🐻', '🐼', '🐨', '🐯', '🦁', '🐮',
'🐷', '🐸', '🐵', '🐔', '🐧', '🐦', '🐤', '🦆', '🦅', '🦉', '🦇', '🐺',
'🐗', '🐴', '🦄', '🐝', '🐛', '🦋', '🐌', '🐞', '🐜', '🦗', '🕷️', '🦂',
'🐢', '🐍', '🦎', '🦖', '🦕', '🐙', '🦑', '🦐', '🦞', '🐠', '🐟', '🐬',
'🐳', '🐋', '🦈', '🐊'
]
},
{
label: 'Symbole & Pointers',
emojis: [
'🎯', '📊', '📈', '📉', '🧮', '📋', '📌', '📍', '🔖', '🏷️', '✏️', '✒️',
'🖊️', '📎', '🔗', '⛓️', '🔒', '🔓', '🔑', '🗝️', '🔨', '🛠️', '⚙️', '🧰',
'💡', '🔦', '🏮', '🪔', '📣', '📢', '🔔', '🔕', '⏱️', '⏰', '🕐', '📅',
'🗓️', '✅', '☑️', '✔️', '❌', '⭕', '❗', '❓', '💬', '🗨️', '📝', '📖',
'🪄', '🎪', '🎭', '🎬', '🎨', '🖼️', '🧩', '♟️', '🎲', '🧸'
]
},
{
label: 'Fahrzeuge & Weg',
emojis: [
'🚗', '🚕', '🚙', '🚌', '🚎', '🏎️', '🚓', '🚑', '🚒', '🚐', '🛻', '🚚',
'🚛', '🚜', '🛵', '🏍️', '🛺', '🚲', '🛴', '🛹', '🚁', '✈️', '🛫', '🛬',
'🪂', '🚀', '🛶', '⛵', '🚤', '🛥️', '🛳️', '⛴️', '🚢', '⚓', '🗼', '🏟️'
]
}
]
/**
* Wiederverwendbare Emoji-/Icon-Auswahl: Vorschau, Freitext (inkl. System-Emoji-Picker),
* optional ausklappbare Vorschläge.
*
* @param {string} value – aktueller Icon-String (meist ein Emoji)
* @param {(next: string) => void} onChange
* @param {string} [placeholder]
* @param {number} [maxLength=10]
* @param {boolean} [disabled]
* @param {string} [id] – optionale ID für das Textfeld (Label for=)
* @param {boolean} [defaultExpanded=false] – Vorschlags-Bereich initial offen
* @param {{ label: string, emojis: string[] }[]} [extraGroups=[]] – eigene Gruppe(n) anhängen (z. B. Projekt-Favoriten)
*/
export default function EmojiIconPicker({
value,
onChange,
placeholder = '📝',
maxLength = 10,
disabled = false,
id: idProp,
defaultExpanded = false,
extraGroups = []
}) {
const uid = useId()
const inputId = idProp || `emoji-icon-${uid}`
const searchInputId = `${inputId}-picker-search`
const [open, setOpen] = useState(defaultExpanded)
const [pickerSearch, setPickerSearch] = useState('')
const groups =
extraGroups.length > 0 ? [...EMOJI_ICON_GROUPS, ...extraGroups] : EMOJI_ICON_GROUPS
useEffect(() => {
if (!open) setPickerSearch('')
}, [open])
const filteredGroups = useMemo(() => {
const q = pickerSearch
if (!q.trim()) {
return groups
}
return groups
.map((g) => ({
...g,
emojis: g.emojis.filter((em) => matchesEmojiSearch(haystackForEmoji(em, g.label), q))
}))
.filter((g) => g.emojis.length > 0)
}, [groups, pickerSearch])
const handleInput = (e) => {
onChange(e.target.value.slice(0, maxLength))
}
const pick = (em) => {
onChange(em.slice(0, maxLength))
}
return (
<div className="emoji-icon-picker" style={{ width: '100%' }}>
<div
style={{
display: 'flex',
gap: 8,
alignItems: 'center',
flexWrap: 'wrap'
}}
>
<span
style={{
fontSize: 28,
lineHeight: 1,
minWidth: 40,
textAlign: 'center',
opacity: value ? 1 : 0.35
}}
aria-hidden
>
{value || '·'}
</span>
<input
id={inputId}
type="text"
className="form-input"
style={{ flex: 1, minWidth: 120 }}
value={value}
onChange={handleInput}
placeholder={placeholder}
maxLength={maxLength}
disabled={disabled}
autoComplete="off"
spellCheck={false}
inputMode="text"
/>
<button
type="button"
className="btn btn-secondary"
disabled={disabled}
onClick={() => setOpen((o) => !o)}
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 4,
padding: '8px 12px',
fontSize: 13
}}
aria-expanded={open}
>
{open ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
Vorschläge
</button>
{!!value && !disabled && (
<button
type="button"
className="btn btn-secondary"
onClick={() => onChange('')}
style={{ padding: '8px 12px', fontSize: 13 }}
>
Leeren
</button>
)}
</div>
{open && (
<div
role="listbox"
aria-label="Emoji-Vorschläge"
style={{
marginTop: 10,
padding: 12,
background: 'var(--surface2)',
borderRadius: 12,
border: '1px solid var(--border)',
maxHeight: 'min(72vh, 460px)',
overflowY: 'auto'
}}
>
<label htmlFor={searchInputId} className="form-label" style={{ marginBottom: 6 }}>
In Vorschlägen suchen
</label>
<input
id={searchInputId}
type="search"
className="form-input"
value={pickerSearch}
onChange={(e) => setPickerSearch(e.target.value)}
placeholder="z. B. rollschuh, karate, apfel…"
disabled={disabled}
autoComplete="off"
spellCheck={false}
inputMode="search"
style={{ width: '100%', marginBottom: 12, boxSizing: 'border-box' }}
/>
{filteredGroups.length === 0 && pickerSearch.trim() && (
<p
style={{
fontSize: 13,
color: 'var(--text2)',
margin: '0 0 12px 0',
lineHeight: 1.45
}}
>
Keine Treffer für „{pickerSearch.trim()}“. Andere Begriffe probieren oder oben ein Emoji
einfügen (z.&nbsp;B. Win&nbsp;+&nbsp;.).
</p>
)}
{filteredGroups.map((group, gi) => (
<div key={`${group.label}-${gi}`} style={{ marginBottom: 14 }}>
<div
style={{
fontSize: 11,
fontWeight: 600,
color: 'var(--text3)',
marginBottom: 8,
textTransform: 'uppercase',
letterSpacing: '0.04em'
}}
>
{group.label}
</div>
<div
style={{
display: 'flex',
flexWrap: 'wrap',
gap: 6
}}
>
{group.emojis.map((em, ei) => (
<button
key={`${group.label}-${gi}-${ei}-${em}`}
type="button"
onClick={() => pick(em)}
disabled={disabled}
title={em}
aria-label={`Icon wählen: ${em}`}
style={{
fontSize: 22,
lineHeight: 1,
padding: '8px 10px',
border: `1px solid ${value === em ? 'var(--accent)' : 'var(--border)'}`,
borderRadius: 8,
background:
value === em ? 'var(--accent-light)' : 'var(--surface)',
cursor: disabled ? 'not-allowed' : 'pointer',
opacity: disabled ? 0.5 : 1
}}
>
{em}
</button>
))}
</div>
</div>
))}
<p style={{ fontSize: 11, color: 'var(--text3)', margin: '12px 0 0 0', lineHeight: 1.5 }}>
Du kannst auch direkt in das Feld tippen oder das Betriebssystem-Emoji-Menü nutzen
(z.&nbsp;B. Win + . unter Windows). Mehrere Wörter verfeinern die Suche: jedes muss in den
Stichwörtern vorkommen.{' '}
<strong>Inline Skating:</strong> Es gibt kein separates Inliner-Emoji; 🛼 (Rollschuh) wird dafür oft genutzt – Suchbegriffe: rollschuh, inline, inliner.{' '}
<strong>Karate / Kampfsport mit Gi:</strong> 🥋 (gemeinsames Unicode-Symbol für u. a. Karate, Judo, Ju-Jitsu).
</p>
</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>
)
}
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff. Show more