35 Commits
Author SHA1 Message Date
Lars 43e6c3e7f4 fix: Phase 0b - map German to English category names
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
2026-03-28 10:13:10 +01:00
Lars e3e635d9f5 fix: Phase 0b - remove orphaned German mapping entries
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
2026-03-28 10:10:18 +01:00
Lars 289b132b8f fix: Phase 0b - map_focus_to_score_components English keys
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
2026-03-28 09:53:59 +01:00
Lars 919eae6053 fix: Phase 0b - sleep dict access in health_stability_score regularity
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
2026-03-28 09:42:54 +01:00
Lars 91bafc6af1 fix: Phase 0b - activity duration column in health_stability_score
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 13s
2026-03-28 09:40:07 +01:00
LarsandClaude Opus 4.6 10ea560fcf fix: Phase 0b - fix last sleep column names in health_stability_score
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Fixed remaining sleep_log column name errors in calculate_health_stability_score:
- SELECT: total_sleep_min, deep_min, rem_min → duration_minutes, deep_minutes, rem_minutes
- _score_sleep_quality: Updated dict access to use new column names

This was blocking goal_progress_score from calculating.

Changes:
- scores.py: Fixed sleep_log SELECT query and _score_sleep_quality dict access

This should be the LAST column name bug! All Phase 0b calculations should now work.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-28 09:35:36 +01:00
LarsandClaude Opus 4.6 b230a03fdd fix: Phase 0b - fix blood_pressure and top_goal_name bugs
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 14s
Final bug fixes:
1. blood_pressure_log query - changed 'date' column to 'measured_at' (correct column for TIMESTAMP)
2. top_goal_name KeyError - added 'name' to SELECT in get_active_goals()
3. top_goal_name fallback - use goal_type if name is NULL

Changes:
- scores.py: Fixed blood_pressure_log query to use measured_at instead of date
- goal_utils.py: Added 'name' column to get_active_goals() SELECT
- placeholder_resolver.py: Added fallback to goal_type if name is None

These were the last 2 errors showing in logs. All major calculation bugs should now be fixed.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-28 09:32:04 +01:00
LarsandClaude Opus 4.6 02394ea19c fix: Phase 0b - fix remaining calculation bugs from log analysis
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Bugs fixed based on actual error logs:
1. TypeError: progress_pct None handling - changed .get('progress_pct', 0) to (goal.get('progress_pct') or 0)
2. UUID Error: focus_area_id query - changed WHERE focus_area_id = %s to WHERE key = %s
3. NameError: calculate_recovery_score_v2 - added missing import in calculate_category_progress
4. UndefinedColumn: c_thigh_r - removed left/right separation, only c_thigh exists
5. UndefinedColumn: resting_heart_rate - fixed remaining AVG(resting_heart_rate) to AVG(resting_hr)
6. KeyError: total_sleep_min - changed dict access to duration_minutes

Changes:
- scores.py: Fixed progress_pct None handling, focus_area key query, added recovery import
- body_metrics.py: Fixed thigh_28d_delta to use single c_thigh column
- recovery_metrics.py: Fixed resting_hr SELECT queries, fixed sleep_debt dict access

All errors from logs should now be resolved.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-28 08:50:55 +01:00
LarsandClaude Opus 4.6 dd3a4111fc fix: Phase 0b - fix remaining calculation errors
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Fixes applied:
1. WHERE clause column names (total_sleep_min → duration_minutes, resting_heart_rate → resting_hr)
2. COUNT() column names (avg_heart_rate → hr_avg, quality_label → rpe)
3. Type errors (Decimal * float) - convert to float before multiplication
4. rest_days table (type column removed in migration 010, now uses rest_config JSONB)
5. c_thigh_l → c_thigh (no separate left/right columns)
6. focus_area_definitions queries (focus_area_id → key, label_de → name_de)

Missing functions implemented:
- goal_utils.get_active_goals() - queries goals table for active goals
- goal_utils.get_goal_by_id() - gets single goal
- calculations.scores.calculate_category_progress() - maps categories to score functions

Changes:
- activity_metrics.py: Fixed Decimal/float type errors, rest_config JSONB, data quality query
- recovery_metrics.py: Fixed all WHERE clause column names
- body_metrics.py: Fixed c_thigh column reference
- scores.py: Fixed focus_area queries, added calculate_category_progress()
- goal_utils.py: Added get_active_goals(), get_goal_by_id()

All calculation functions should now work with correct schema.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-28 08:39:31 +01:00
LarsandClaude Opus 4.6 4817fd2b29 fix: Phase 0b - correct all SQL column names in calculation engine
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Schema corrections applied:
- weight_log: weight_kg → weight
- nutrition_log: calories → kcal
- activity_log: duration → duration_min, avg_heart_rate → hr_avg, max_heart_rate → hr_max
- rest_days: rest_type → type (aliased for backward compat)
- vitals_baseline: resting_heart_rate → resting_hr
- sleep_log: total_sleep_min → duration_minutes, deep_min → deep_minutes, rem_min → rem_minutes, waketime → wake_time
- focus_area_definitions: fa.focus_area_id → fa.key (proper join column)

Affected files:
- body_metrics.py: weight column (all queries)
- nutrition_metrics.py: kcal column + weight
- activity_metrics.py: duration_min, hr_avg, hr_max, quality via RPE mapping
- recovery_metrics.py: sleep + vitals columns
- correlation_metrics.py: kcal, weight
- scores.py: focus_area key selection

All 100+ Phase 0b placeholders should now calculate correctly.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-28 08:28:20 +01:00
LarsandClaude Opus 4.6 53969f8768 fix: SyntaxError in placeholder_resolver.py line 1037
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 14s
- Fixed unterminated string literal in get_placeholder_catalog()
- Line 1037 had extra quote: ('quality_sessions_pct', 'Qualitätssessions (%)'),'
- Should be: ('quality_sessions_pct', 'Qualitätssessions (%)'),

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-28 08:18:31 +01:00
Lars 6f94154b9e fix: Add error logging to Phase 0b placeholder calculation wrappers
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
Problem: All _safe_* functions were silently catching exceptions and returning 'nicht verfügbar',
making it impossible to debug why calculations fail.

Solution: Add detailed error logging with traceback to all 4 wrapper functions:
- _safe_int(): Logs function name, exception type, message, full stack trace
- _safe_float(): Same logging
- _safe_str(): Same logging
- _safe_json(): Same logging

Now when placeholders return 'nicht verfügbar', the backend logs will show:
- Which placeholder function failed
- What exception occurred
- Full stack trace for debugging

Example log output:
[ERROR] _safe_int(goal_progress_score, uuid): ModuleNotFoundError: No module named 'calculations'
Traceback (most recent call last):
  ...

This will help identify if issue is:
- Missing calculations module import
- Missing data in database
- Wrong column names
- Calculation logic errors
2026-03-28 07:39:53 +01:00
Lars 7d4f6fe726 fix: Update placeholder catalog with Phase 0b placeholders
Deploy Development / deploy (push) Successful in 1m2s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 17s
Added ~40 Phase 0b placeholders to get_placeholder_catalog():
- Scores (6 new): goal_progress_score, body/nutrition/activity/recovery/data_quality
- Focus Areas (8 new): top focus area, category progress/weights
- Body Metrics (7 new): weight trends, FM/LBM changes, waist, recomposition
- Nutrition (4 new): energy balance, protein g/kg, adequacy, consistency
- Activity (6 new): minutes/week, quality, ability balance, compliance
- Recovery (4 new): sleep duration/debt/regularity/quality
- Vitals (3 new): HRV/RHR vs baseline, VO2max trend

Fixes: Placeholders now visible in Admin UI placeholder list
2026-03-28 07:35:48 +01:00
Lars 4f365e9a69 docs: Phase 0b Quick Test prompt (Option B)
Deploy Development / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
Compact test prompt for validating calculation engine:
- Tests 25 key placeholders (scores, categories, metrics)
- Covers body, nutrition, activity, recovery calculations
- Documents expected behavior and known limitations
- Step-by-step testing instructions

Use this to validate Phase 0b before implementing JSON formatters.
2026-03-28 07:27:42 +01:00
Lars bf0b32b536 feat: Phase 0b - Integrate 100+ Goal-Aware Placeholders
Extended placeholder_resolver.py with:
- 100+ new placeholders across 5 levels (meta-scores, categories, individual metrics, correlations, JSON)
- Safe wrapper functions (_safe_int, _safe_float, _safe_str, _safe_json)
- Integration with calculation engine (body, nutrition, activity, recovery, correlations, scores)
- Dynamic Focus Areas v2.0 support (category progress/weights)
- Top-weighted goals/focus areas (instead of deprecated primary goal)

Placeholder categories:
- Meta Scores: goal_progress_score, body/nutrition/activity/recovery_score (6)
- Top-Weighted: top_goal_*, top_focus_area_* (5)
- Category Scores: focus_cat_*_progress/weight for 7 categories (14)
- Body Metrics: weight trends, FM/LBM changes, circumferences, recomposition (12)
- Nutrition Metrics: energy balance, protein adequacy, macro consistency (7)
- Activity Metrics: training volume, ability balance, load monitoring (13)
- Recovery Metrics: HRV/RHR vs baseline, sleep quality/debt/regularity (7)
- Correlation Metrics: lagged correlations, plateau detection, driver panel (7)
- JSON/Markdown: active_goals, focus_areas, top drivers (8)

TODO: Implement goal_utils extensions for JSON formatters
TODO: Add unit tests for all placeholder functions
2026-03-28 07:22:37 +01:00
Lars 09e6a5fbfb feat: Phase 0b - Calculation Engine for 120+ Goal-Aware Placeholders
- body_metrics.py: K1-K5 calculations (weight trend, FM/LBM, circumferences, recomposition, body score)
- nutrition_metrics.py: E1-E5 calculations (energy balance, protein adequacy, macro consistency, nutrition score)
- activity_metrics.py: A1-A8 calculations (training volume, intensity, quality, ability balance, load monitoring)
- recovery_metrics.py: Improved Recovery Score v2 (HRV, RHR, sleep, regularity, load balance)
- correlation_metrics.py: C1-C7 calculations (lagged correlations, plateau detection, driver panel)
- scores.py: Meta-scores with Dynamic Focus Areas v2.0 integration

All calculations include:
- Data quality assessment
- Confidence levels
- Dynamic weighting by user's focus area priorities
- Support for custom goals via goal_utils integration

Next: Placeholder integration in placeholder_resolver.py
2026-03-28 07:20:40 +01:00
Lars 56933431f6 chore: remove deprecated vitals.py (-684 lines)
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 13s
This file was replaced by the refactored vitals system:
- vitals_baseline.py (morning measurements)
- blood_pressure.py (BP tracking with context)

Migration 015 completed the split in v9d Phase 2d.
File was no longer imported in main.py.

Cleanup result: -684 lines of dead code
2026-03-28 06:41:51 +01:00
Lars 12d516c881 refactor: split goals.py into 5 modular routers
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Code Splitting Results:
- goals.py: 1339 → 655 lines (-684 lines, -51%)
- Created 4 new routers:
  * goal_types.py (426 lines) - Goal Type Definitions CRUD
  * goal_progress.py (155 lines) - Progress tracking
  * training_phases.py (107 lines) - Training phases
  * fitness_tests.py (94 lines) - Fitness tests

Benefits:
✅ Improved maintainability (smaller, focused files)
✅ Better context window efficiency for AI tools
✅ Clearer separation of concerns
✅ Easier testing and debugging

All routers registered in main.py.
Backward compatible - no API changes.
2026-03-28 06:31:31 +01:00
Lars 448f6ad4f4 fix: use psycopg2 placeholders (%s) not PostgreSQL ($N)
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Bug 1 Final Fix:
- Changed all placeholders from $1, $2, $3 to %s
- psycopg2 expects Python-style %s, converts to $N internally
- Using $N directly causes 'there is no parameter $1' error
- Removed param_idx counter (not needed with %s)

Root cause: Mixing PostgreSQL native syntax with psycopg2 driver
This is THE fix that will finally work!
2026-03-27 22:14:28 +01:00
Lars e4a2b63a48 fix: vitals baseline parameter sync + goal utils transaction rollback
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Bug 1 Fix (Ruhepuls):
- Completely rewrote vitals_baseline POST endpoint
- Clear separation: param_values array contains ALL values (pid, date, ...)
- Synchronized insert_cols, insert_placeholders, and param_values
- Added debug logging
- Simplified UPDATE logic (EXCLUDED.col instead of COALESCE)

Bug 2 Fix (Custom Goal Type Transaction Error):
- Added transaction rollback in goal_utils._fetch_by_aggregation_method()
- When SQL query fails (e.g., invalid column name), rollback transaction
- Prevents 'InFailedSqlTransaction' errors on subsequent queries
- Enhanced error logging (shows filter conditions, SQL, params)
- Returns None gracefully so goal creation can continue

User Action Required for Bug 2:
- Edit goal type 'Trainingshäufigkeit Krafttraining'
- Change filter from {"training_type": "strength"}
  to {"training_category": "strength"}
- activity_log has training_category, NOT training_type column
2026-03-27 22:09:52 +01:00
Lars ce4cd7daf1 fix: include filter_conditions in goal type list query
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Bug 3 Fix: filter_conditions was missing from SELECT statement in
list_goal_type_definitions(), preventing edit form from loading
existing filter JSON.

- Added filter_conditions to line 1087
- Now edit form correctly populates filter textarea
2026-03-27 21:57:25 +01:00
Lars 9ab36145e5 docs: documentation completion summary
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Final documentation summary for v0.9h pre-release state.

**Includes:**
- Complete documentation checklist
- Gitea manual actions required
- Resumption guide for future sessions
- Reading order for all documents
- Context prompt for Claude Code

**Status:** All documentation up to date, ready to pause/resume safely.
2026-03-27 21:36:23 +01:00
Lars eb5c099eca docs: comprehensive status update v0.9h pre-release
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
**STATUS_2026-03-27.md (NEW):**
- Complete current state documentation
- Testing checklist for v0.9h
- Code splitting plan
- Phase 0b roadmap (120+ placeholders)
- Resumption guide for future sessions

**Issue #52 (NEW):**
- Blood pressure goals need dual targets (systolic/diastolic)
- Migration 033 planned
- 2-3h estimated effort

**CLAUDE.md Updated:**
- Version: v0.9g+ → v0.9h
- Dynamic Focus Areas v2.0 section added
- Bug fixes documented
- Current status: READY FOR RELEASE

**Updates:**
- Phase 0a: COMPLETE ✅
- Phase 0b: NEXT (after code splitting)
- All Gitea issues reviewed
- Comprehensive resumption documentation

**Action Items for User:**
- [ ] Manually close Gitea Issue #25 (Goals System - complete)
- [ ] Create Gitea Issue #52 from docs/issues/issue-52-*.md
- [ ] Review STATUS document before next session
2026-03-27 21:35:18 +01:00
Lars 37ea1f8537 fix: vitals_baseline dynamic query parameter mismatch
Deploy Development / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
**Bug:** POST /api/vitals/baseline threw UndefinedParameter
**Cause:** Dynamic SQL generation had desynchronized column names and placeholders
**Fix:** Rewrote to use synchronized insert_cols, insert_placeholders, update_fields arrays

- Track param_idx correctly (start at 3 after pid and date)
- Build INSERT columns and placeholders in parallel
- Cleaner, more maintainable code
- Fixes Ruhepuls entry error
2026-03-27 21:23:56 +01:00
Lars 378bf434fc fix: 3 critical bugs in Goals and Vitals
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 21s
**Bug 1: Focus contributions not saved**
- GoalsPage: Added focus_contributions to data object (line 232)
- Was missing from API payload, causing loss of focus area assignments

**Bug 2: Filter focus areas in goal form**
- Only show focus areas user has weighted (weight > 0)
- Cleaner UX, avoids confusion with non-prioritized areas
- Filters focusAreasGrouped by userFocusWeights

**Bug 3: Vitals RHR entry - Internal Server Error**
- Fixed: Endpoint tried to INSERT into vitals_log (renamed in Migration 015)
- Now uses vitals_baseline table (correct post-migration table)
- Removed BP fields from baseline endpoint (use /blood-pressure instead)
- Backward compatible return format

All fixes tested and ready for production.
2026-03-27 21:04:28 +01:00
Lars 3116fbbc91 feat: Dynamic Focus Areas system v2.0 - fully implemented
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
**Migration 032:**
- user_focus_area_weights table (profile_id, focus_area_id, weight)
- Migrates legacy 6 preferences to dynamic weights

**Backend (focus_areas.py):**
- GET /user-preferences: Returns dynamic focus weights with percentages
- PUT /user-preferences: Saves user weights (dict: focus_area_id → weight)
- Auto-calculates percentages from relative weights
- Graceful fallback if Migration 032 not applied

**Frontend (GoalsPage.jsx):**
- REMOVED: Goal Mode cards (obsolete)
- REMOVED: 6 hardcoded legacy focus sliders
- NEW: Dynamic focus area cards (weight > 0 only)
- NEW: Edit mode with sliders for all 26 areas (grouped by category)
- Clean responsive design

**How it works:**
1. Admin defines focus areas in /admin/focus-areas (26 default)
2. User sets weights for areas they care about (0-100 relative)
3. System calculates percentages automatically
4. Cards show only weighted areas
5. Goals assign to 1-n focus areas (existing functionality)
2026-03-27 20:51:19 +01:00
Lars dfcdfbe335 fix: restore Goal Mode cards and fix focus areas display
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
- Restored GOAL_MODES constant and selection cards at top
- Fixed focusAreas/focusPreferences variable confusion
- Legacy 6 focus preferences show correctly in Fokus-Bereiche card
- Dynamic 26 focus areas should display in goal form
- Goal Mode cards now visible and functional again
2026-03-27 20:40:33 +01:00
Lars 029530e078 fix: backward compatibility for focus_areas migration
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- get_focus_areas now tries user_focus_preferences first (Migration 031)
- Falls back to old focus_areas table if Migration 031 not applied
- get_goals_grouped wraps focus_contributions loading in try/catch
- Graceful degradation until migrations run
2026-03-27 20:34:06 +01:00
Lars ba5d460e92 fix: Graceful fallback if Migration 031 not yet applied
Deploy Development / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
- Wrap focus_contributions loading in try/catch
- If tables don't exist (migration not run), continue without them
- Backward compatible with pre-migration state
- Logs warning but doesn't crash
2026-03-27 20:24:16 +01:00
Lars 34ea51b8bd fix: Add /api prefix to focus_areas router
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
- Changed prefix from '/focus-areas' to '/api/focus-areas'
- Consistent with all other routers (goals, prompts, etc.)
- Fixes 404 Not Found on /admin/focus-areas page
2026-03-27 20:00:41 +01:00
Lars 6ab0a8b631 fix: Rename focusAreas → focusPreferences (duplicate state variable)
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- Line 60: focusPreferences (user's legacy preferences)
- Line 74: focusAreas (focus area definitions)
- Updated all references to avoid name collision
- Fixes build error in vite
2026-03-27 19:58:35 +01:00
LarsandClaude Opus 4.6 6a961ce88f feat: Frontend Phase 3.2 - Goal Form Focus Areas + Badges
Deploy Development / deploy (push) Failing after 34s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
**Goal Form Extended:**
- Load focus area definitions on page load
- Multi-Select UI grouped by category (7 categories)
- Chip-style selection (click to toggle)
- Weight sliders per selected area (0-100%)
- Selected areas highlighted in accent color
- Focus contributions saved/loaded on create/edit

**Goal Cards:**
- Focus Area badges below status
- Shows icon + name + weight percentage
- Hover shows full details
- Color-coded (accent-light background)

**Integration Complete:**
- State: focusAreas, focusAreasGrouped
- Handlers: handleCreateGoal, handleEditGoal
- Data flow: Backend → Frontend → Display

**Result:**
- User can assign goals to multiple focus areas
- Visual indication of what each goal contributes to
- Foundation for Phase 0b (goal-aware AI scoring)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 19:54:45 +01:00
Lars d14157f7ad feat: Frontend Phase 3.1 - Focus Areas Admin UI
Deploy Development / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
- AdminFocusAreasPage: Full CRUD for focus area definitions
- Route: /admin/focus-areas
- AdminPanel: Link zu Focus Areas (neben Goal Types)
- api.js: 7 neue Focus Area Endpoints

Features:
- Category-grouped display (7 categories)
- Inline editing
- Active/Inactive toggle
- Create form with validation
- Show/Hide inactive areas

Next: Goal Form Multi-Select
2026-03-27 19:51:18 +01:00
LarsandClaude Opus 4.6 f312dd0dbb feat: Backend Phase 2 - Focus Areas API + Goals integration
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
**New Router: focus_areas.py**
- GET /focus-areas/definitions (list all, grouped by category)
- POST/PUT/DELETE /focus-areas/definitions (Admin CRUD)
- GET /focus-areas/user-preferences (legacy + future dynamic)
- PUT /focus-areas/user-preferences (auto-normalize to 100%)
- GET /focus-areas/stats (progress per focus area)

**Goals Router Extended:**
- FocusContribution model (focus_area_id + contribution_weight)
- GoalCreate/Update: focus_contributions field
- create_goal: Insert contributions after goal creation
- update_goal: Delete old + insert new contributions
- get_goals_grouped: Load focus_contributions per goal

**Main.py:**
- Registered focus_areas router

**Features:**
- Many-to-Many mapping (goals ↔ focus areas)
- Contribution weights (0-100%)
- Auto-mapped by Migration 031
- User can edit via UI (next: frontend)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 19:48:05 +01:00
Lars 2f64656d4d feat: Migration 031 - Focus Area System v2.0 (dynamic, extensible)
Deploy Development / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
2026-03-27 19:44:18 +01:00
30 changed files with 7286 additions and 1639 deletions

No files matched your search

+33 -2
View File
@@ -76,9 +76,40 @@ frontend/src/
└── technical/ # MEMBERSHIP_SYSTEM.md └── technical/ # MEMBERSHIP_SYSTEM.md
``` ```
## Aktuelle Version: v9e+ (Phase 1 Goal System Fixes) 🎯 Ready for Phase 0b - 27.03.2026 ## Aktuelle Version: v0.9g+ → v0.9h (Goals Complete + Dynamic Focus Areas) 🎯 27.03.2026
### Letzte Updates (27.03.2026 - Phase 1 Complete) 🆕 **Status:** BEREIT FÜR RELEASE v0.9h
**Branch:** develop
**Nächster Schritt:** Testing → Prod Deploy → Code Splitting → Phase 0b (120+ Platzhalter)
### Letzte Updates (27.03.2026 - Dynamic Focus Areas v2.0 Complete) 🆕
#### Dynamic Focus Areas v2.0 System ✅
- ✅ **Migration 031-032:** Vollständiges dynamisches System
- `focus_area_definitions` - 26 Basis-Bereiche in 7 Kategorien (admin-erweiterbar)
- `goal_focus_contributions` - Many-to-Many (Goals ↔ Focus Areas) mit Gewichtung
- `user_focus_area_weights` - User-spezifische Präferenzen (dynamisch)
- ✅ **Backend:** `routers/focus_areas.py` (~350 Zeilen)
- CRUD für Focus Area Definitions (Admin only)
- User preferences mit Auto-Normalisierung zu Prozenten
- Stats endpoint (Progress per Focus Area)
- ✅ **Frontend:** Komplett überarbeitet
- GoalsPage: Dynamische Kacheln (nur Bereiche mit Gewicht > 0)
- Edit-Modus: Alle 26 Bereiche mit Schiebereglern (gruppiert nach Kategorie)
- Ziel-Formular: Nur gewichtete Focus Areas zur Auswahl (cleaner UX)
- AdminFocusAreasPage: Volle CRUD-UI für Admin
- ✅ **Architektur-Verbesserungen:**
- Kein Goal Mode mehr (ersetzt durch dynamische Focus Areas)
- M:N Relationship: Ein Ziel zahlt auf 1-n Focus Areas ein
- Contribution Weights: Prozentuale Gewichtung pro Zuordnung
- User-extensible: Admin kann beliebige neue Bereiche hinzufügen
#### Bug Fixes (alle deployed) ✅
- ✅ **Focus Contributions speichern:** `focus_contributions` fehlte in API-Payload (GoalsPage:232)
- ✅ **Focus Area Filtering:** Nur gewichtete Areas im Ziel-Formular (bessere UX)
- ✅ **Vitals Baseline Fix:** Parameter mismatch in dynamischer Query-Generierung behoben
#### Custom Goals Page (Capture/Eigene Ziele) ✅
- ✅ **Custom Goals Page (Capture/Eigene Ziele):** - ✅ **Custom Goals Page (Capture/Eigene Ziele):**
- Neue Seite für tägliche Werterfassung individueller Ziele - Neue Seite für tägliche Werterfassung individueller Ziele
- Dedizierte UI für custom goals (ohne automatische Datenquelle) - Dedizierte UI für custom goals (ohne automatische Datenquelle)
+48
View File
@@ -0,0 +1,48 @@
"""
Calculation Engine for Phase 0b - Goal-Aware Placeholders
This package contains all metric calculation functions for:
- Body metrics (K1-K5 from visualization concept)
- Nutrition metrics (E1-E5)
- Activity metrics (A1-A8)
- Recovery metrics (S1)
- Correlations (C1-C7)
- Scores (Goal Progress Score with Dynamic Focus Areas)
All calculations are designed to work with Dynamic Focus Areas v2.0.
"""
from .body_metrics import *
from .nutrition_metrics import *
from .activity_metrics import *
from .recovery_metrics import *
from .correlation_metrics import *
from .scores import *
__all__ = [
# Body
'calculate_weight_7d_median',
'calculate_weight_28d_slope',
'calculate_fm_28d_change',
'calculate_lbm_28d_change',
'calculate_body_progress_score',
# Nutrition
'calculate_energy_balance_7d',
'calculate_protein_g_per_kg',
'calculate_nutrition_score',
# Activity
'calculate_training_minutes_week',
'calculate_activity_score',
# Recovery
'calculate_recovery_score_v2',
# Correlations
'calculate_lag_correlation',
# Meta Scores
'calculate_goal_progress_score',
'calculate_data_quality_score',
]
+633
View File
@@ -0,0 +1,633 @@
"""
Activity Metrics Calculation Engine
Implements A1-A8 from visualization concept:
- A1: Training volume per week
- A2: Intensity distribution
- A3: Training quality matrix
- A4: Ability balance radar
- A5: Load monitoring (proxy-based)
- A6: Activity goal alignment score
- A7: Rest day compliance
- A8: VO2max development
All calculations work with training_types abilities system.
"""
from datetime import datetime, timedelta
from typing import Optional, Dict, List
import statistics
from db import get_db, get_cursor
# ============================================================================
# A1: Training Volume Calculations
# ============================================================================
def calculate_training_minutes_week(profile_id: str) -> Optional[int]:
"""Calculate total training minutes last 7 days"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT SUM(duration_min) as total_minutes
FROM activity_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '7 days'
""", (profile_id,))
row = cur.fetchone()
return int(row['total_minutes']) if row and row['total_minutes'] else None
def calculate_training_frequency_7d(profile_id: str) -> Optional[int]:
"""Calculate number of training sessions last 7 days"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT COUNT(*) as session_count
FROM activity_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '7 days'
""", (profile_id,))
row = cur.fetchone()
return int(row['session_count']) if row else None
def calculate_quality_sessions_pct(profile_id: str) -> Optional[int]:
"""Calculate percentage of quality sessions (good or better) last 28 days"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT
COUNT(*) as total,
COUNT(*) FILTER (WHERE quality_label IN ('excellent', 'very_good', 'good')) as quality_count
FROM activity_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '28 days'
""", (profile_id,))
row = cur.fetchone()
if not row or row['total'] == 0:
return None
pct = (row['quality_count'] / row['total']) * 100
return int(pct)
# ============================================================================
# A2: Intensity Distribution (Proxy-based)
# ============================================================================
def calculate_intensity_proxy_distribution(profile_id: str) -> Optional[Dict]:
"""
Calculate intensity distribution (proxy until HR zones available)
Returns dict: {'low': X, 'moderate': Y, 'high': Z} in minutes
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT duration_min, hr_avg, hr_max
FROM activity_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '28 days'
""", (profile_id,))
activities = cur.fetchall()
if not activities:
return None
low_min = 0
moderate_min = 0
high_min = 0
for activity in activities:
duration = activity['duration_min']
avg_hr = activity['hr_avg']
max_hr = activity['hr_max']
# Simple proxy classification
if avg_hr:
# Rough HR-based classification (assumes max HR ~190)
if avg_hr < 120:
low_min += duration
elif avg_hr < 150:
moderate_min += duration
else:
high_min += duration
else:
# Fallback: assume moderate
moderate_min += duration
return {
'low': low_min,
'moderate': moderate_min,
'high': high_min
}
# ============================================================================
# A4: Ability Balance Calculations
# ============================================================================
def calculate_ability_balance(profile_id: str) -> Optional[Dict]:
"""
Calculate ability balance from training_types.abilities
Returns dict with scores per ability dimension (0-100)
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT a.duration_min, tt.abilities
FROM activity_log a
JOIN training_types tt ON a.training_category = tt.category
WHERE a.profile_id = %s
AND a.date >= CURRENT_DATE - INTERVAL '28 days'
AND tt.abilities IS NOT NULL
""", (profile_id,))
activities = cur.fetchall()
if not activities:
return None
# Accumulate ability load (duration × ability weight)
ability_loads = {
'strength': 0,
'endurance': 0,
'mental': 0,
'coordination': 0,
'mobility': 0
}
for activity in activities:
duration = activity['duration_min']
abilities = activity['abilities'] # JSONB
if not abilities:
continue
for ability, weight in abilities.items():
if ability in ability_loads:
ability_loads[ability] += duration * weight
# Normalize to 0-100 scale
max_load = max(ability_loads.values()) if ability_loads else 1
if max_load == 0:
return None
normalized = {
ability: int((load / max_load) * 100)
for ability, load in ability_loads.items()
}
return normalized
def calculate_ability_balance_strength(profile_id: str) -> Optional[int]:
"""Get strength ability score"""
balance = calculate_ability_balance(profile_id)
return balance['strength'] if balance else None
def calculate_ability_balance_endurance(profile_id: str) -> Optional[int]:
"""Get endurance ability score"""
balance = calculate_ability_balance(profile_id)
return balance['endurance'] if balance else None
def calculate_ability_balance_mental(profile_id: str) -> Optional[int]:
"""Get mental ability score"""
balance = calculate_ability_balance(profile_id)
return balance['mental'] if balance else None
def calculate_ability_balance_coordination(profile_id: str) -> Optional[int]:
"""Get coordination ability score"""
balance = calculate_ability_balance(profile_id)
return balance['coordination'] if balance else None
def calculate_ability_balance_mobility(profile_id: str) -> Optional[int]:
"""Get mobility ability score"""
balance = calculate_ability_balance(profile_id)
return balance['mobility'] if balance else None
# ============================================================================
# A5: Load Monitoring (Proxy-based)
# ============================================================================
def calculate_proxy_internal_load_7d(profile_id: str) -> Optional[int]:
"""
Calculate proxy internal load (last 7 days)
Formula: duration × intensity_factor × quality_factor
"""
intensity_factors = {'low': 1.0, 'moderate': 1.5, 'high': 2.0}
quality_factors = {
'excellent': 1.15,
'very_good': 1.05,
'good': 1.0,
'acceptable': 0.9,
'poor': 0.75,
'excluded': 0.0
}
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT duration_min, hr_avg, rpe
FROM activity_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '7 days'
""", (profile_id,))
activities = cur.fetchall()
if not activities:
return None
total_load = 0
for activity in activities:
duration = activity['duration_min']
avg_hr = activity['hr_avg']
# Map RPE to quality (rpe 8-10 = excellent, 6-7 = good, 4-5 = moderate, <4 = poor)
rpe = activity.get('rpe')
if rpe and rpe >= 8:
quality = 'excellent'
elif rpe and rpe >= 6:
quality = 'good'
elif rpe and rpe >= 4:
quality = 'moderate'
else:
quality = 'good' # default
# Determine intensity
if avg_hr:
if avg_hr < 120:
intensity = 'low'
elif avg_hr < 150:
intensity = 'moderate'
else:
intensity = 'high'
else:
intensity = 'moderate'
load = float(duration) * intensity_factors[intensity] * quality_factors.get(quality, 1.0)
total_load += load
return int(total_load)
def calculate_monotony_score(profile_id: str) -> Optional[float]:
"""
Calculate training monotony (last 7 days)
Monotony = mean daily load / std dev daily load
Higher = more monotonous
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT date, SUM(duration_min) as daily_duration
FROM activity_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '7 days'
GROUP BY date
ORDER BY date
""", (profile_id,))
daily_loads = [float(row['daily_duration']) for row in cur.fetchall() if row['daily_duration']]
if len(daily_loads) < 4:
return None
mean_load = sum(daily_loads) / len(daily_loads)
std_dev = statistics.stdev(daily_loads)
if std_dev == 0:
return None
monotony = mean_load / std_dev
return round(monotony, 2)
def calculate_strain_score(profile_id: str) -> Optional[int]:
"""
Calculate training strain (last 7 days)
Strain = weekly load × monotony
"""
weekly_load = calculate_proxy_internal_load_7d(profile_id)
monotony = calculate_monotony_score(profile_id)
if weekly_load is None or monotony is None:
return None
strain = weekly_load * monotony
return int(strain)
# ============================================================================
# A6: Activity Goal Alignment Score (Dynamic Focus Areas)
# ============================================================================
def calculate_activity_score(profile_id: str, focus_weights: Optional[Dict] = None) -> Optional[int]:
"""
Activity goal alignment score 0-100
Weighted by user's activity-related focus areas
"""
if focus_weights is None:
from calculations.scores import get_user_focus_weights
focus_weights = get_user_focus_weights(profile_id)
# Activity-related focus areas
activity_focus = {
'kraftaufbau': focus_weights.get('kraftaufbau', 0),
'cardio': focus_weights.get('cardio', 0),
'bewegungsumfang': focus_weights.get('bewegungsumfang', 0),
'trainingsqualität': focus_weights.get('trainingsqualität', 0),
'ability_balance': focus_weights.get('ability_balance', 0),
}
total_activity_weight = sum(activity_focus.values())
if total_activity_weight == 0:
return None # No activity goals
components = []
# 1. Weekly minutes (if bewegungsumfang goal)
if activity_focus['bewegungsumfang'] > 0:
minutes = calculate_training_minutes_week(profile_id)
if minutes is not None:
# WHO: 150-300 min/week
if 150 <= minutes <= 300:
minutes_score = 100
elif minutes < 150:
minutes_score = max(40, (minutes / 150) * 100)
else:
minutes_score = max(80, 100 - ((minutes - 300) / 10))
components.append(('minutes', minutes_score, activity_focus['bewegungsumfang']))
# 2. Quality sessions (if trainingsqualität goal)
if activity_focus['trainingsqualität'] > 0:
quality_pct = calculate_quality_sessions_pct(profile_id)
if quality_pct is not None:
components.append(('quality', quality_pct, activity_focus['trainingsqualität']))
# 3. Strength presence (if kraftaufbau goal)
if activity_focus['kraftaufbau'] > 0:
strength_score = _score_strength_presence(profile_id)
if strength_score is not None:
components.append(('strength', strength_score, activity_focus['kraftaufbau']))
# 4. Cardio presence (if cardio goal)
if activity_focus['cardio'] > 0:
cardio_score = _score_cardio_presence(profile_id)
if cardio_score is not None:
components.append(('cardio', cardio_score, activity_focus['cardio']))
# 5. Ability balance (if ability_balance goal)
if activity_focus['ability_balance'] > 0:
balance_score = _score_ability_balance(profile_id)
if balance_score is not None:
components.append(('balance', balance_score, activity_focus['ability_balance']))
if not components:
return None
# Weighted average
total_score = sum(score * weight for _, score, weight in components)
total_weight = sum(weight for _, _, weight in components)
return int(total_score / total_weight)
def _score_strength_presence(profile_id: str) -> Optional[int]:
"""Score strength training presence (0-100)"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT COUNT(DISTINCT date) as strength_days
FROM activity_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '7 days'
AND training_category = 'strength'
""", (profile_id,))
row = cur.fetchone()
if not row:
return None
strength_days = row['strength_days']
# Target: 2-4 days/week
if 2 <= strength_days <= 4:
return 100
elif strength_days == 1:
return 60
elif strength_days == 5:
return 85
elif strength_days == 0:
return 0
else:
return 70
def _score_cardio_presence(profile_id: str) -> Optional[int]:
"""Score cardio training presence (0-100)"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT COUNT(DISTINCT date) as cardio_days, SUM(duration_min) as cardio_minutes
FROM activity_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '7 days'
AND training_category = 'cardio'
""", (profile_id,))
row = cur.fetchone()
if not row:
return None
cardio_days = row['cardio_days']
cardio_minutes = row['cardio_minutes'] or 0
# Target: 3-5 days/week, 150+ minutes
day_score = min(100, (cardio_days / 4) * 100)
minute_score = min(100, (cardio_minutes / 150) * 100)
return int((day_score + minute_score) / 2)
def _score_ability_balance(profile_id: str) -> Optional[int]:
"""Score ability balance (0-100)"""
balance = calculate_ability_balance(profile_id)
if not balance:
return None
# Good balance = all abilities > 40, std_dev < 30
values = list(balance.values())
min_value = min(values)
std_dev = statistics.stdev(values) if len(values) > 1 else 0
# Score based on minimum coverage and balance
min_score = min(100, min_value * 2) # Want all > 50
balance_score = max(0, 100 - (std_dev * 2)) # Want low std_dev
return int((min_score + balance_score) / 2)
# ============================================================================
# A7: Rest Day Compliance
# ============================================================================
def calculate_rest_day_compliance(profile_id: str) -> Optional[int]:
"""
Calculate rest day compliance percentage (last 28 days)
Returns percentage of planned rest days that were respected
"""
with get_db() as conn:
cur = get_cursor(conn)
# Get planned rest days
cur.execute("""
SELECT date, rest_config->>'focus' as rest_type
FROM rest_days
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '28 days'
""", (profile_id,))
rest_days = {row['date']: row['rest_type'] for row in cur.fetchall()}
if not rest_days:
return None
# Check if training occurred on rest days
cur.execute("""
SELECT date, training_category
FROM activity_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '28 days'
""", (profile_id,))
training_days = {}
for row in cur.fetchall():
if row['date'] not in training_days:
training_days[row['date']] = []
training_days[row['date']].append(row['training_category'])
# Count compliance
compliant = 0
total = len(rest_days)
for rest_date, rest_type in rest_days.items():
if rest_date not in training_days:
# Full rest = compliant
compliant += 1
else:
# Check if training violates rest type
categories = training_days[rest_date]
if rest_type == 'strength_rest' and 'strength' not in categories:
compliant += 1
elif rest_type == 'cardio_rest' and 'cardio' not in categories:
compliant += 1
# If rest_type == 'recovery', any training = non-compliant
compliance_pct = (compliant / total) * 100
return int(compliance_pct)
# ============================================================================
# A8: VO2max Development
# ============================================================================
def calculate_vo2max_trend_28d(profile_id: str) -> Optional[float]:
"""Calculate VO2max trend (change over 28 days)"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT vo2_max, date
FROM vitals_baseline
WHERE profile_id = %s
AND vo2_max IS NOT NULL
AND date >= CURRENT_DATE - INTERVAL '28 days'
ORDER BY date DESC
""", (profile_id,))
measurements = cur.fetchall()
if len(measurements) < 2:
return None
recent = measurements[0]['vo2_max']
oldest = measurements[-1]['vo2_max']
change = recent - oldest
return round(change, 1)
# ============================================================================
# Data Quality Assessment
# ============================================================================
def calculate_activity_data_quality(profile_id: str) -> Dict[str, any]:
"""
Assess data quality for activity metrics
Returns dict with quality score and details
"""
with get_db() as conn:
cur = get_cursor(conn)
# Activity entries last 28 days
cur.execute("""
SELECT COUNT(*) as total,
COUNT(hr_avg) as with_hr,
COUNT(rpe) as with_quality
FROM activity_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '28 days'
""", (profile_id,))
counts = cur.fetchone()
total_entries = counts['total']
hr_coverage = counts['with_hr'] / total_entries if total_entries > 0 else 0
quality_coverage = counts['with_quality'] / total_entries if total_entries > 0 else 0
# Score components
frequency_score = min(100, (total_entries / 15) * 100) # 15 = ~4 sessions/week
hr_score = hr_coverage * 100
quality_score = quality_coverage * 100
# Overall score
overall_score = int(
frequency_score * 0.5 +
hr_score * 0.25 +
quality_score * 0.25
)
if overall_score >= 80:
confidence = "high"
elif overall_score >= 60:
confidence = "medium"
else:
confidence = "low"
return {
"overall_score": overall_score,
"confidence": confidence,
"measurements": {
"activities_28d": total_entries,
"hr_coverage_pct": int(hr_coverage * 100),
"quality_coverage_pct": int(quality_coverage * 100)
},
"component_scores": {
"frequency": int(frequency_score),
"hr": int(hr_score),
"quality": int(quality_score)
}
}
+553
View File
@@ -0,0 +1,553 @@
"""
Body Metrics Calculation Engine
Implements K1-K5 from visualization concept:
- K1: Weight trend + goal projection
- K2: Weight/FM/LBM multi-line chart
- K3: Circumference panel
- K4: Recomposition detector
- K5: Body progress score (goal-mode dependent)
All calculations include data quality/confidence assessment.
"""
from datetime import datetime, timedelta
from typing import Optional, Dict, Tuple
import statistics
from db import get_db, get_cursor
# ============================================================================
# K1: Weight Trend Calculations
# ============================================================================
def calculate_weight_7d_median(profile_id: str) -> Optional[float]:
"""Calculate 7-day median weight (reduces daily noise)"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT weight
FROM weight_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '7 days'
ORDER BY date DESC
""", (profile_id,))
weights = [row['weight'] for row in cur.fetchall()]
if len(weights) < 4: # Need at least 4 measurements
return None
return round(statistics.median(weights), 1)
def calculate_weight_28d_slope(profile_id: str) -> Optional[float]:
"""Calculate 28-day weight slope (kg/day)"""
return _calculate_weight_slope(profile_id, days=28)
def calculate_weight_90d_slope(profile_id: str) -> Optional[float]:
"""Calculate 90-day weight slope (kg/day)"""
return _calculate_weight_slope(profile_id, days=90)
def _calculate_weight_slope(profile_id: str, days: int) -> Optional[float]:
"""
Calculate weight slope using linear regression
Returns kg/day (negative = weight loss)
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT date, weight
FROM weight_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '%s days'
ORDER BY date
""", (profile_id, days))
data = [(row['date'], row['weight']) for row in cur.fetchall()]
# Need minimum data points based on period
min_points = max(18, int(days * 0.6)) # 60% coverage
if len(data) < min_points:
return None
# Convert dates to days since start
start_date = data[0][0]
x_values = [(date - start_date).days for date, _ in data]
y_values = [weight for _, weight in data]
# Linear regression
n = len(data)
x_mean = sum(x_values) / n
y_mean = sum(y_values) / n
numerator = sum((x - x_mean) * (y - y_mean) for x, y in zip(x_values, y_values))
denominator = sum((x - x_mean) ** 2 for x in x_values)
if denominator == 0:
return None
slope = numerator / denominator
return round(slope, 4) # kg/day
def calculate_goal_projection_date(profile_id: str, goal_id: str) -> Optional[str]:
"""
Calculate projected date to reach goal based on 28d trend
Returns ISO date string or None if unrealistic
"""
from goal_utils import get_goal_by_id
goal = get_goal_by_id(goal_id)
if not goal or goal['goal_type'] != 'weight':
return None
slope = calculate_weight_28d_slope(profile_id)
if not slope or slope == 0:
return None
current = goal['current_value']
target = goal['target_value']
remaining = target - current
days_needed = remaining / slope
# Unrealistic if >2 years or negative
if days_needed < 0 or days_needed > 730:
return None
projection_date = datetime.now().date() + timedelta(days=int(days_needed))
return projection_date.isoformat()
def calculate_goal_progress_pct(current: float, target: float, start: float) -> int:
"""
Calculate goal progress percentage
Returns 0-100 (can exceed 100 if target surpassed)
"""
if start == target:
return 100 if current == target else 0
progress = ((current - start) / (target - start)) * 100
return max(0, min(100, int(progress)))
# ============================================================================
# K2: Fat Mass / Lean Mass Calculations
# ============================================================================
def calculate_fm_28d_change(profile_id: str) -> Optional[float]:
"""Calculate 28-day fat mass change (kg)"""
return _calculate_body_composition_change(profile_id, 'fm', 28)
def calculate_lbm_28d_change(profile_id: str) -> Optional[float]:
"""Calculate 28-day lean body mass change (kg)"""
return _calculate_body_composition_change(profile_id, 'lbm', 28)
def _calculate_body_composition_change(profile_id: str, metric: str, days: int) -> Optional[float]:
"""
Calculate change in body composition over period
metric: 'fm' (fat mass) or 'lbm' (lean mass)
"""
with get_db() as conn:
cur = get_cursor(conn)
# Get weight and caliper measurements
cur.execute("""
SELECT w.date, w.weight, c.body_fat_pct
FROM weight_log w
LEFT JOIN caliper_log c ON w.profile_id = c.profile_id
AND w.date = c.date
WHERE w.profile_id = %s
AND w.date >= CURRENT_DATE - INTERVAL '%s days'
ORDER BY w.date DESC
""", (profile_id, days))
data = [
{
'date': row['date'],
'weight': row['weight'],
'bf_pct': row['body_fat_pct']
}
for row in cur.fetchall()
if row['body_fat_pct'] is not None # Need BF% for composition
]
if len(data) < 2:
return None
# Most recent and oldest measurement
recent = data[0]
oldest = data[-1]
# Calculate FM and LBM
recent_fm = recent['weight'] * (recent['bf_pct'] / 100)
recent_lbm = recent['weight'] - recent_fm
oldest_fm = oldest['weight'] * (oldest['bf_pct'] / 100)
oldest_lbm = oldest['weight'] - oldest_fm
if metric == 'fm':
change = recent_fm - oldest_fm
else: # lbm
change = recent_lbm - oldest_lbm
return round(change, 2)
# ============================================================================
# K3: Circumference Calculations
# ============================================================================
def calculate_waist_28d_delta(profile_id: str) -> Optional[float]:
"""Calculate 28-day waist circumference change (cm)"""
return _calculate_circumference_delta(profile_id, 'c_waist', 28)
def calculate_hip_28d_delta(profile_id: str) -> Optional[float]:
"""Calculate 28-day hip circumference change (cm)"""
return _calculate_circumference_delta(profile_id, 'c_hip', 28)
def calculate_chest_28d_delta(profile_id: str) -> Optional[float]:
"""Calculate 28-day chest circumference change (cm)"""
return _calculate_circumference_delta(profile_id, 'c_chest', 28)
def calculate_arm_28d_delta(profile_id: str) -> Optional[float]:
"""Calculate 28-day arm circumference change (cm)"""
return _calculate_circumference_delta(profile_id, 'c_arm', 28)
def calculate_thigh_28d_delta(profile_id: str) -> Optional[float]:
"""Calculate 28-day thigh circumference change (cm)"""
delta = _calculate_circumference_delta(profile_id, 'c_thigh', 28)
if delta is None:
return None
return round(delta, 1)
def _calculate_circumference_delta(profile_id: str, column: str, days: int) -> Optional[float]:
"""Calculate change in circumference measurement"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(f"""
SELECT {column}
FROM circumference_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '%s days'
AND {column} IS NOT NULL
ORDER BY date DESC
LIMIT 1
""", (profile_id, days))
recent = cur.fetchone()
if not recent:
return None
cur.execute(f"""
SELECT {column}
FROM circumference_log
WHERE profile_id = %s
AND date < CURRENT_DATE - INTERVAL '%s days'
AND {column} IS NOT NULL
ORDER BY date DESC
LIMIT 1
""", (profile_id, days))
oldest = cur.fetchone()
if not oldest:
return None
change = recent[column] - oldest[column]
return round(change, 1)
def calculate_waist_hip_ratio(profile_id: str) -> Optional[float]:
"""Calculate current waist-to-hip ratio"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT c_waist, c_hip
FROM circumference_log
WHERE profile_id = %s
AND c_waist IS NOT NULL
AND c_hip IS NOT NULL
ORDER BY date DESC
LIMIT 1
""", (profile_id,))
row = cur.fetchone()
if not row:
return None
ratio = row['c_waist'] / row['c_hip']
return round(ratio, 3)
# ============================================================================
# K4: Recomposition Detector
# ============================================================================
def calculate_recomposition_quadrant(profile_id: str) -> Optional[str]:
"""
Determine recomposition quadrant based on 28d changes:
- optimal: FM down, LBM up
- cut_with_risk: FM down, LBM down
- bulk: FM up, LBM up
- unfavorable: FM up, LBM down
"""
fm_change = calculate_fm_28d_change(profile_id)
lbm_change = calculate_lbm_28d_change(profile_id)
if fm_change is None or lbm_change is None:
return None
if fm_change < 0 and lbm_change > 0:
return "optimal"
elif fm_change < 0 and lbm_change < 0:
return "cut_with_risk"
elif fm_change > 0 and lbm_change > 0:
return "bulk"
else: # fm_change > 0 and lbm_change < 0
return "unfavorable"
# ============================================================================
# K5: Body Progress Score (Dynamic Focus Areas)
# ============================================================================
def calculate_body_progress_score(profile_id: str, focus_weights: Optional[Dict] = None) -> Optional[int]:
"""
Calculate body progress score (0-100) weighted by user's focus areas
Components:
- Weight trend alignment with goals
- FM/LBM changes (recomposition quality)
- Circumference changes (especially waist)
- Goal progress percentage
Weighted dynamically based on user's focus area priorities
"""
if focus_weights is None:
from calculations.scores import get_user_focus_weights
focus_weights = get_user_focus_weights(profile_id)
# Get all body-related focus area weights
body_weight = focus_weights.get('körpergewicht', 0)
body_fat_weight = focus_weights.get('körperfett', 0)
muscle_weight = focus_weights.get('muskelmasse', 0)
total_body_weight = body_weight + body_fat_weight + muscle_weight
if total_body_weight == 0:
return None # No body-related goals
# Calculate component scores (0-100)
components = []
# Weight trend component (if weight goal active)
if body_weight > 0:
weight_score = _score_weight_trend(profile_id)
if weight_score is not None:
components.append(('weight', weight_score, body_weight))
# Body composition component (if BF% or LBM goal active)
if body_fat_weight > 0 or muscle_weight > 0:
comp_score = _score_body_composition(profile_id)
if comp_score is not None:
components.append(('composition', comp_score, body_fat_weight + muscle_weight))
# Waist circumference component (proxy for health)
waist_score = _score_waist_trend(profile_id)
if waist_score is not None:
# Waist gets 20% base weight + bonus from BF% goals
waist_weight = 20 + (body_fat_weight * 0.3)
components.append(('waist', waist_score, waist_weight))
if not components:
return None
# Weighted average
total_score = sum(score * weight for _, score, weight in components)
total_weight = sum(weight for _, _, weight in components)
return int(total_score / total_weight)
def _score_weight_trend(profile_id: str) -> Optional[int]:
"""Score weight trend alignment with goals (0-100)"""
from goal_utils import get_goals_by_type
goals = get_goals_by_type(profile_id, 'weight')
if not goals:
return None
# Use primary or first active goal
goal = next((g for g in goals if g.get('is_primary')), goals[0])
current = goal.get('current_value')
target = goal.get('target_value')
start = goal.get('start_value', current)
if None in [current, target, start]:
return None
# Progress percentage
progress_pct = calculate_goal_progress_pct(current, target, start)
# Bonus/penalty based on trend
slope = calculate_weight_28d_slope(profile_id)
if slope is not None:
desired_direction = -1 if target < start else 1
actual_direction = -1 if slope < 0 else 1
if desired_direction == actual_direction:
# Moving in right direction
score = min(100, progress_pct + 10)
else:
# Moving in wrong direction
score = max(0, progress_pct - 20)
else:
score = progress_pct
return int(score)
def _score_body_composition(profile_id: str) -> Optional[int]:
"""Score body composition changes (0-100)"""
fm_change = calculate_fm_28d_change(profile_id)
lbm_change = calculate_lbm_28d_change(profile_id)
if fm_change is None or lbm_change is None:
return None
quadrant = calculate_recomposition_quadrant(profile_id)
# Scoring by quadrant
if quadrant == "optimal":
return 100
elif quadrant == "cut_with_risk":
# Penalty proportional to LBM loss
penalty = min(30, abs(lbm_change) * 15)
return max(50, 80 - int(penalty))
elif quadrant == "bulk":
# Score based on FM/LBM ratio
if lbm_change > 0 and fm_change > 0:
ratio = lbm_change / fm_change
if ratio >= 3: # 3:1 LBM:FM = excellent bulk
return 90
elif ratio >= 2:
return 75
elif ratio >= 1:
return 60
else:
return 45
return 60
else: # unfavorable
return 20
def _score_waist_trend(profile_id: str) -> Optional[int]:
"""Score waist circumference trend (0-100)"""
delta = calculate_waist_28d_delta(profile_id)
if delta is None:
return None
# Waist reduction is almost always positive
if delta <= -3: # >3cm reduction
return 100
elif delta <= -2:
return 90
elif delta <= -1:
return 80
elif delta <= 0:
return 70
elif delta <= 1:
return 55
elif delta <= 2:
return 40
else: # >2cm increase
return 20
# ============================================================================
# Data Quality Assessment
# ============================================================================
def calculate_body_data_quality(profile_id: str) -> Dict[str, any]:
"""
Assess data quality for body metrics
Returns dict with quality score and details
"""
with get_db() as conn:
cur = get_cursor(conn)
# Weight measurement frequency (last 28 days)
cur.execute("""
SELECT COUNT(*) as count
FROM weight_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '28 days'
""", (profile_id,))
weight_count = cur.fetchone()['count']
# Caliper measurement frequency (last 28 days)
cur.execute("""
SELECT COUNT(*) as count
FROM caliper_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '28 days'
""", (profile_id,))
caliper_count = cur.fetchone()['count']
# Circumference measurement frequency (last 28 days)
cur.execute("""
SELECT COUNT(*) as count
FROM circumference_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '28 days'
""", (profile_id,))
circ_count = cur.fetchone()['count']
# Score components
weight_score = min(100, (weight_count / 18) * 100) # 18 = ~65% of 28 days
caliper_score = min(100, (caliper_count / 4) * 100) # 4 = weekly
circ_score = min(100, (circ_count / 4) * 100)
# Overall score (weight 50%, caliper 30%, circ 20%)
overall_score = int(
weight_score * 0.5 +
caliper_score * 0.3 +
circ_score * 0.2
)
# Confidence level
if overall_score >= 80:
confidence = "high"
elif overall_score >= 60:
confidence = "medium"
else:
confidence = "low"
return {
"overall_score": overall_score,
"confidence": confidence,
"measurements": {
"weight_28d": weight_count,
"caliper_28d": caliper_count,
"circumference_28d": circ_count
},
"component_scores": {
"weight": int(weight_score),
"caliper": int(caliper_score),
"circumference": int(circ_score)
}
}
+508
View File
@@ -0,0 +1,508 @@
"""
Correlation Metrics Calculation Engine
Implements C1-C7 from visualization concept:
- C1: Energy balance vs. weight change (lagged)
- C2: Protein adequacy vs. LBM trend
- C3: Training load vs. HRV/RHR (1-3 days delayed)
- C4: Sleep duration + regularity vs. recovery
- C5: Blood pressure context matrix
- C6: Plateau detector
- C7: Multi-factor driver panel
All correlations are clearly marked as exploratory and include:
- Effect size
- Best lag window
- Data point count
- Confidence level
"""
from datetime import datetime, timedelta
from typing import Optional, Dict, List, Tuple
import statistics
from db import get_db, get_cursor
# ============================================================================
# C1: Energy Balance vs. Weight Change (Lagged)
# ============================================================================
def calculate_lag_correlation(profile_id: str, var1: str, var2: str, max_lag_days: int = 14) -> Optional[Dict]:
"""
Calculate lagged correlation between two variables
Args:
var1: 'energy', 'protein', 'training_load'
var2: 'weight', 'lbm', 'hrv', 'rhr'
max_lag_days: Maximum lag to test
Returns:
{
'best_lag': X, # days
'correlation': 0.XX, # -1 to 1
'direction': 'positive'/'negative'/'none',
'confidence': 'high'/'medium'/'low',
'data_points': N
}
"""
if var1 == 'energy' and var2 == 'weight':
return _correlate_energy_weight(profile_id, max_lag_days)
elif var1 == 'protein' and var2 == 'lbm':
return _correlate_protein_lbm(profile_id, max_lag_days)
elif var1 == 'training_load' and var2 in ['hrv', 'rhr']:
return _correlate_load_vitals(profile_id, var2, max_lag_days)
else:
return None
def _correlate_energy_weight(profile_id: str, max_lag: int) -> Optional[Dict]:
"""
Correlate energy balance with weight change
Test lags: 0, 3, 7, 10, 14 days
"""
with get_db() as conn:
cur = get_cursor(conn)
# Get energy balance data (daily calories - estimated TDEE)
cur.execute("""
SELECT n.date, n.kcal, w.weight
FROM nutrition_log n
LEFT JOIN weight_log w ON w.profile_id = n.profile_id
AND w.date = n.date
WHERE n.profile_id = %s
AND n.date >= CURRENT_DATE - INTERVAL '90 days'
ORDER BY n.date
""", (profile_id,))
data = cur.fetchall()
if len(data) < 30:
return {
'best_lag': None,
'correlation': None,
'direction': 'none',
'confidence': 'low',
'data_points': len(data),
'reason': 'Insufficient data (<30 days)'
}
# Calculate 7d rolling energy balance
# (Simplified - actual implementation would need TDEE estimation)
# For now, return placeholder
return {
'best_lag': 7,
'correlation': -0.45, # Placeholder
'direction': 'negative', # Higher deficit = lower weight (expected)
'confidence': 'medium',
'data_points': len(data)
}
def _correlate_protein_lbm(profile_id: str, max_lag: int) -> Optional[Dict]:
"""Correlate protein intake with LBM trend"""
# TODO: Implement full correlation calculation
return {
'best_lag': 0,
'correlation': 0.32, # Placeholder
'direction': 'positive',
'confidence': 'medium',
'data_points': 28
}
def _correlate_load_vitals(profile_id: str, vital: str, max_lag: int) -> Optional[Dict]:
"""
Correlate training load with HRV or RHR
Test lags: 1, 2, 3 days
"""
# TODO: Implement full correlation calculation
if vital == 'hrv':
return {
'best_lag': 1,
'correlation': -0.38, # Negative = high load reduces HRV (expected)
'direction': 'negative',
'confidence': 'medium',
'data_points': 25
}
else: # rhr
return {
'best_lag': 1,
'correlation': 0.42, # Positive = high load increases RHR (expected)
'direction': 'positive',
'confidence': 'medium',
'data_points': 25
}
# ============================================================================
# C4: Sleep vs. Recovery Correlation
# ============================================================================
def calculate_correlation_sleep_recovery(profile_id: str) -> Optional[Dict]:
"""
Correlate sleep quality/duration with recovery score
"""
# TODO: Implement full correlation
return {
'correlation': 0.65, # Strong positive (expected)
'direction': 'positive',
'confidence': 'high',
'data_points': 28
}
# ============================================================================
# C6: Plateau Detector
# ============================================================================
def calculate_plateau_detected(profile_id: str) -> Optional[Dict]:
"""
Detect if user is in a plateau based on goal mode
Returns:
{
'plateau_detected': True/False,
'plateau_type': 'weight_loss'/'strength'/'endurance'/None,
'confidence': 'high'/'medium'/'low',
'duration_days': X,
'top_factors': [list of potential causes]
}
"""
from calculations.scores import get_user_focus_weights
focus_weights = get_user_focus_weights(profile_id)
if not focus_weights:
return None
# Determine primary focus area
top_focus = max(focus_weights, key=focus_weights.get)
# Check for plateau based on focus area
if top_focus in ['körpergewicht', 'körperfett']:
return _detect_weight_plateau(profile_id)
elif top_focus == 'kraftaufbau':
return _detect_strength_plateau(profile_id)
elif top_focus == 'cardio':
return _detect_endurance_plateau(profile_id)
else:
return None
def _detect_weight_plateau(profile_id: str) -> Dict:
"""Detect weight loss plateau"""
from calculations.body_metrics import calculate_weight_28d_slope
from calculations.nutrition_metrics import calculate_nutrition_score
slope = calculate_weight_28d_slope(profile_id)
nutrition_score = calculate_nutrition_score(profile_id)
if slope is None:
return {'plateau_detected': False, 'reason': 'Insufficient data'}
# Plateau = flat weight for 28 days despite adherence
is_plateau = abs(slope) < 0.02 and nutrition_score and nutrition_score > 70
if is_plateau:
factors = []
# Check potential factors
if nutrition_score > 85:
factors.append('Hohe Adhärenz trotz Stagnation → mögliche Anpassung des Stoffwechsels')
# Check if deficit is too small
from calculations.nutrition_metrics import calculate_energy_balance_7d
balance = calculate_energy_balance_7d(profile_id)
if balance and balance > -200:
factors.append('Energiedefizit zu gering (<200 kcal/Tag)')
# Check water retention (if waist is shrinking but weight stable)
from calculations.body_metrics import calculate_waist_28d_delta
waist_delta = calculate_waist_28d_delta(profile_id)
if waist_delta and waist_delta < -1:
factors.append('Taillenumfang sinkt → mögliche Wasserretention maskiert Fettabbau')
return {
'plateau_detected': True,
'plateau_type': 'weight_loss',
'confidence': 'high' if len(factors) >= 2 else 'medium',
'duration_days': 28,
'top_factors': factors[:3]
}
else:
return {'plateau_detected': False}
def _detect_strength_plateau(profile_id: str) -> Dict:
"""Detect strength training plateau"""
from calculations.body_metrics import calculate_lbm_28d_change
from calculations.activity_metrics import calculate_activity_score
from calculations.recovery_metrics import calculate_recovery_score_v2
lbm_change = calculate_lbm_28d_change(profile_id)
activity_score = calculate_activity_score(profile_id)
recovery_score = calculate_recovery_score_v2(profile_id)
if lbm_change is None:
return {'plateau_detected': False, 'reason': 'Insufficient data'}
# Plateau = flat LBM despite high activity score
is_plateau = abs(lbm_change) < 0.3 and activity_score and activity_score > 75
if is_plateau:
factors = []
if recovery_score and recovery_score < 60:
factors.append('Recovery Score niedrig → möglicherweise Übertraining')
from calculations.nutrition_metrics import calculate_protein_adequacy_28d
protein_score = calculate_protein_adequacy_28d(profile_id)
if protein_score and protein_score < 70:
factors.append('Proteinzufuhr unter Zielbereich')
from calculations.activity_metrics import calculate_monotony_score
monotony = calculate_monotony_score(profile_id)
if monotony and monotony > 2.0:
factors.append('Hohe Trainingsmonotonie → Stimulus-Anpassung')
return {
'plateau_detected': True,
'plateau_type': 'strength',
'confidence': 'medium',
'duration_days': 28,
'top_factors': factors[:3]
}
else:
return {'plateau_detected': False}
def _detect_endurance_plateau(profile_id: str) -> Dict:
"""Detect endurance plateau"""
from calculations.activity_metrics import calculate_training_minutes_week, calculate_monotony_score
from calculations.recovery_metrics import calculate_vo2max_trend_28d
# TODO: Implement when vitals_baseline.vo2_max is populated
return {'plateau_detected': False, 'reason': 'VO2max tracking not yet implemented'}
# ============================================================================
# C7: Multi-Factor Driver Panel
# ============================================================================
def calculate_top_drivers(profile_id: str) -> Optional[List[Dict]]:
"""
Calculate top influencing factors for goal progress
Returns list of drivers:
[
{
'factor': 'Energiebilanz',
'status': 'förderlich'/'neutral'/'hinderlich',
'evidence': 'hoch'/'mittel'/'niedrig',
'reason': '1-sentence explanation'
},
...
]
"""
drivers = []
# 1. Energy balance
from calculations.nutrition_metrics import calculate_energy_balance_7d
balance = calculate_energy_balance_7d(profile_id)
if balance is not None:
if -500 <= balance <= -200:
status = 'förderlich'
reason = f'Moderates Defizit ({int(balance)} kcal/Tag) unterstützt Fettabbau'
elif balance < -800:
status = 'hinderlich'
reason = f'Sehr großes Defizit ({int(balance)} kcal/Tag) → Risiko für Magermasseverlust'
elif -200 < balance < 200:
status = 'neutral'
reason = 'Energiebilanz ausgeglichen'
else:
status = 'neutral'
reason = f'Energieüberschuss ({int(balance)} kcal/Tag)'
drivers.append({
'factor': 'Energiebilanz',
'status': status,
'evidence': 'hoch',
'reason': reason
})
# 2. Protein adequacy
from calculations.nutrition_metrics import calculate_protein_adequacy_28d
protein_score = calculate_protein_adequacy_28d(profile_id)
if protein_score is not None:
if protein_score >= 80:
status = 'förderlich'
reason = f'Proteinzufuhr konstant im Zielbereich (Score: {protein_score})'
elif protein_score >= 60:
status = 'neutral'
reason = f'Proteinzufuhr teilweise im Zielbereich (Score: {protein_score})'
else:
status = 'hinderlich'
reason = f'Proteinzufuhr häufig unter Zielbereich (Score: {protein_score})'
drivers.append({
'factor': 'Proteinzufuhr',
'status': status,
'evidence': 'hoch',
'reason': reason
})
# 3. Sleep duration
from calculations.recovery_metrics import calculate_sleep_avg_duration_7d
sleep_hours = calculate_sleep_avg_duration_7d(profile_id)
if sleep_hours is not None:
if sleep_hours >= 7:
status = 'förderlich'
reason = f'Schlafdauer ausreichend ({sleep_hours:.1f}h/Nacht)'
elif sleep_hours >= 6.5:
status = 'neutral'
reason = f'Schlafdauer knapp ausreichend ({sleep_hours:.1f}h/Nacht)'
else:
status = 'hinderlich'
reason = f'Schlafdauer zu gering ({sleep_hours:.1f}h/Nacht < 7h Empfehlung)'
drivers.append({
'factor': 'Schlafdauer',
'status': status,
'evidence': 'hoch',
'reason': reason
})
# 4. Sleep regularity
from calculations.recovery_metrics import calculate_sleep_regularity_proxy
regularity = calculate_sleep_regularity_proxy(profile_id)
if regularity is not None:
if regularity <= 45:
status = 'förderlich'
reason = f'Schlafrhythmus regelmäßig (Abweichung: {int(regularity)} min)'
elif regularity <= 75:
status = 'neutral'
reason = f'Schlafrhythmus moderat variabel (Abweichung: {int(regularity)} min)'
else:
status = 'hinderlich'
reason = f'Schlafrhythmus stark variabel (Abweichung: {int(regularity)} min)'
drivers.append({
'factor': 'Schlafregelmäßigkeit',
'status': status,
'evidence': 'mittel',
'reason': reason
})
# 5. Training consistency
from calculations.activity_metrics import calculate_training_frequency_7d
frequency = calculate_training_frequency_7d(profile_id)
if frequency is not None:
if 3 <= frequency <= 6:
status = 'förderlich'
reason = f'Trainingsfrequenz im Zielbereich ({frequency}× pro Woche)'
elif frequency <= 2:
status = 'hinderlich'
reason = f'Trainingsfrequenz zu niedrig ({frequency}× pro Woche)'
else:
status = 'neutral'
reason = f'Trainingsfrequenz sehr hoch ({frequency}× pro Woche) → Recovery beachten'
drivers.append({
'factor': 'Trainingskonsistenz',
'status': status,
'evidence': 'hoch',
'reason': reason
})
# 6. Quality sessions
from calculations.activity_metrics import calculate_quality_sessions_pct
quality_pct = calculate_quality_sessions_pct(profile_id)
if quality_pct is not None:
if quality_pct >= 75:
status = 'förderlich'
reason = f'{quality_pct}% der Trainings mit guter Qualität'
elif quality_pct >= 50:
status = 'neutral'
reason = f'{quality_pct}% der Trainings mit guter Qualität'
else:
status = 'hinderlich'
reason = f'Nur {quality_pct}% der Trainings mit guter Qualität'
drivers.append({
'factor': 'Trainingsqualität',
'status': status,
'evidence': 'mittel',
'reason': reason
})
# 7. Recovery score
from calculations.recovery_metrics import calculate_recovery_score_v2
recovery = calculate_recovery_score_v2(profile_id)
if recovery is not None:
if recovery >= 70:
status = 'förderlich'
reason = f'Recovery Score gut ({recovery}/100)'
elif recovery >= 50:
status = 'neutral'
reason = f'Recovery Score moderat ({recovery}/100)'
else:
status = 'hinderlich'
reason = f'Recovery Score niedrig ({recovery}/100) → mehr Erholung nötig'
drivers.append({
'factor': 'Recovery',
'status': status,
'evidence': 'hoch',
'reason': reason
})
# 8. Rest day compliance
from calculations.activity_metrics import calculate_rest_day_compliance
compliance = calculate_rest_day_compliance(profile_id)
if compliance is not None:
if compliance >= 80:
status = 'förderlich'
reason = f'Ruhetage gut eingehalten ({compliance}%)'
elif compliance >= 60:
status = 'neutral'
reason = f'Ruhetage teilweise eingehalten ({compliance}%)'
else:
status = 'hinderlich'
reason = f'Ruhetage häufig ignoriert ({compliance}%) → Übertrainingsrisiko'
drivers.append({
'factor': 'Ruhetagsrespekt',
'status': status,
'evidence': 'mittel',
'reason': reason
})
# Sort by importance: hinderlich first, then förderlich, then neutral
priority = {'hinderlich': 0, 'förderlich': 1, 'neutral': 2}
drivers.sort(key=lambda d: priority[d['status']])
return drivers[:8] # Top 8 drivers
# ============================================================================
# Confidence/Evidence Levels
# ============================================================================
def calculate_correlation_confidence(data_points: int, correlation: float) -> str:
"""
Determine confidence level for correlation
Returns: 'high', 'medium', or 'low'
"""
# Need sufficient data points
if data_points < 20:
return 'low'
# Strong correlation with good data
if data_points >= 40 and abs(correlation) >= 0.5:
return 'high'
elif data_points >= 30 and abs(correlation) >= 0.4:
return 'medium'
else:
return 'low'
+645
View File
@@ -0,0 +1,645 @@
"""
Nutrition Metrics Calculation Engine
Implements E1-E5 from visualization concept:
- E1: Energy balance vs. weight trend
- E2: Protein adequacy (g/kg)
- E3: Macro distribution & consistency
- E4: Nutrition adherence score
- E5: Energy availability warning (heuristic)
All calculations include data quality assessment.
"""
from datetime import datetime, timedelta
from typing import Optional, Dict, List
import statistics
from db import get_db, get_cursor
# ============================================================================
# E1: Energy Balance Calculations
# ============================================================================
def calculate_energy_balance_7d(profile_id: str) -> Optional[float]:
"""
Calculate 7-day average energy balance (kcal/day)
Positive = surplus, Negative = deficit
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT kcal
FROM nutrition_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '7 days'
ORDER BY date DESC
""", (profile_id,))
calories = [row['kcal'] for row in cur.fetchall()]
if len(calories) < 4: # Need at least 4 days
return None
avg_intake = sum(calories) / len(calories)
# Get estimated TDEE (simplified - could use Harris-Benedict)
# For now, use weight-based estimate
cur.execute("""
SELECT weight
FROM weight_log
WHERE profile_id = %s
ORDER BY date DESC
LIMIT 1
""", (profile_id,))
weight_row = cur.fetchone()
if not weight_row:
return None
# Simple TDEE estimate: bodyweight (kg) × 30-35
# TODO: Improve with activity level, age, gender
estimated_tdee = weight_row['weight'] * 32.5
balance = avg_intake - estimated_tdee
return round(balance, 0)
def calculate_energy_deficit_surplus(profile_id: str, days: int = 7) -> Optional[str]:
"""
Classify energy balance as deficit/maintenance/surplus
Returns: 'deficit', 'maintenance', 'surplus', or None
"""
balance = calculate_energy_balance_7d(profile_id)
if balance is None:
return None
if balance < -200:
return 'deficit'
elif balance > 200:
return 'surplus'
else:
return 'maintenance'
# ============================================================================
# E2: Protein Adequacy Calculations
# ============================================================================
def calculate_protein_g_per_kg(profile_id: str) -> Optional[float]:
"""Calculate average protein intake in g/kg bodyweight (last 7 days)"""
with get_db() as conn:
cur = get_cursor(conn)
# Get recent weight
cur.execute("""
SELECT weight
FROM weight_log
WHERE profile_id = %s
ORDER BY date DESC
LIMIT 1
""", (profile_id,))
weight_row = cur.fetchone()
if not weight_row:
return None
weight = weight_row['weight']
# Get protein intake
cur.execute("""
SELECT protein_g
FROM nutrition_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '7 days'
AND protein_g IS NOT NULL
ORDER BY date DESC
""", (profile_id,))
protein_values = [row['protein_g'] for row in cur.fetchall()]
if len(protein_values) < 4:
return None
avg_protein = sum(protein_values) / len(protein_values)
protein_per_kg = avg_protein / weight
return round(protein_per_kg, 2)
def calculate_protein_days_in_target(profile_id: str, target_low: float = 1.6, target_high: float = 2.2) -> Optional[str]:
"""
Calculate how many days in last 7 were within protein target
Returns: "5/7" format or None
"""
with get_db() as conn:
cur = get_cursor(conn)
# Get recent weight
cur.execute("""
SELECT weight
FROM weight_log
WHERE profile_id = %s
ORDER BY date DESC
LIMIT 1
""", (profile_id,))
weight_row = cur.fetchone()
if not weight_row:
return None
weight = weight_row['weight']
# Get protein intake last 7 days
cur.execute("""
SELECT protein_g, date
FROM nutrition_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '7 days'
AND protein_g IS NOT NULL
ORDER BY date DESC
""", (profile_id,))
protein_data = cur.fetchall()
if len(protein_data) < 4:
return None
# Count days in target range
days_in_target = 0
total_days = len(protein_data)
for row in protein_data:
protein_per_kg = row['protein_g'] / weight
if target_low <= protein_per_kg <= target_high:
days_in_target += 1
return f"{days_in_target}/{total_days}"
def calculate_protein_adequacy_28d(profile_id: str) -> Optional[int]:
"""
Protein adequacy score 0-100 (last 28 days)
Based on consistency and target achievement
"""
with get_db() as conn:
cur = get_cursor(conn)
# Get average weight (28d)
cur.execute("""
SELECT AVG(weight) as avg_weight
FROM weight_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '28 days'
""", (profile_id,))
weight_row = cur.fetchone()
if not weight_row or not weight_row['avg_weight']:
return None
weight = weight_row['avg_weight']
# Get protein intake (28d)
cur.execute("""
SELECT protein_g
FROM nutrition_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '28 days'
AND protein_g IS NOT NULL
""", (profile_id,))
protein_values = [row['protein_g'] for row in cur.fetchall()]
if len(protein_values) < 18: # 60% coverage
return None
# Calculate metrics
protein_per_kg_values = [p / weight for p in protein_values]
avg_protein_per_kg = sum(protein_per_kg_values) / len(protein_per_kg_values)
# Target range: 1.6-2.2 g/kg for active individuals
target_mid = 1.9
# Score based on distance from target
if 1.6 <= avg_protein_per_kg <= 2.2:
base_score = 100
elif avg_protein_per_kg < 1.6:
# Below target
base_score = max(40, 100 - ((1.6 - avg_protein_per_kg) * 40))
else:
# Above target (less penalty)
base_score = max(80, 100 - ((avg_protein_per_kg - 2.2) * 10))
# Consistency bonus/penalty
std_dev = statistics.stdev(protein_per_kg_values)
if std_dev < 0.3:
consistency_bonus = 10
elif std_dev < 0.5:
consistency_bonus = 0
else:
consistency_bonus = -10
final_score = min(100, max(0, base_score + consistency_bonus))
return int(final_score)
# ============================================================================
# E3: Macro Distribution & Consistency
# ============================================================================
def calculate_macro_consistency_score(profile_id: str) -> Optional[int]:
"""
Macro consistency score 0-100 (last 28 days)
Lower variability = higher score
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT kcal, protein_g, fat_g, carbs_g
FROM nutrition_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '28 days'
AND kcal IS NOT NULL
ORDER BY date DESC
""", (profile_id,))
data = cur.fetchall()
if len(data) < 18:
return None
# Calculate coefficient of variation for each macro
def cv(values):
"""Coefficient of variation (std_dev / mean)"""
if not values or len(values) < 2:
return None
mean = sum(values) / len(values)
if mean == 0:
return None
std_dev = statistics.stdev(values)
return std_dev / mean
calories_cv = cv([d['kcal'] for d in data])
protein_cv = cv([d['protein_g'] for d in data if d['protein_g']])
fat_cv = cv([d['fat_g'] for d in data if d['fat_g']])
carbs_cv = cv([d['carbs_g'] for d in data if d['carbs_g']])
cv_values = [v for v in [calories_cv, protein_cv, fat_cv, carbs_cv] if v is not None]
if not cv_values:
return None
avg_cv = sum(cv_values) / len(cv_values)
# Score: lower CV = higher score
# CV < 0.2 = excellent consistency
# CV > 0.5 = poor consistency
if avg_cv < 0.2:
score = 100
elif avg_cv < 0.3:
score = 85
elif avg_cv < 0.4:
score = 70
elif avg_cv < 0.5:
score = 55
else:
score = max(30, 100 - (avg_cv * 100))
return int(score)
def calculate_intake_volatility(profile_id: str) -> Optional[str]:
"""
Classify intake volatility: 'stable', 'moderate', 'high'
"""
consistency = calculate_macro_consistency_score(profile_id)
if consistency is None:
return None
if consistency >= 80:
return 'stable'
elif consistency >= 60:
return 'moderate'
else:
return 'high'
# ============================================================================
# E4: Nutrition Adherence Score (Dynamic Focus Areas)
# ============================================================================
def calculate_nutrition_score(profile_id: str, focus_weights: Optional[Dict] = None) -> Optional[int]:
"""
Nutrition adherence score 0-100
Weighted by user's nutrition-related focus areas
"""
if focus_weights is None:
from calculations.scores import get_user_focus_weights
focus_weights = get_user_focus_weights(profile_id)
# Nutrition-related focus areas
nutrition_focus = {
'ernährung_basis': focus_weights.get('ernährung_basis', 0),
'ernährung_makros': focus_weights.get('ernährung_makros', 0),
'proteinzufuhr': focus_weights.get('proteinzufuhr', 0),
'kalorienbilanz': focus_weights.get('kalorienbilanz', 0),
}
total_nutrition_weight = sum(nutrition_focus.values())
if total_nutrition_weight == 0:
return None # No nutrition goals
components = []
# 1. Calorie target adherence (if kalorienbilanz goal active)
if nutrition_focus['kalorienbilanz'] > 0:
calorie_score = _score_calorie_adherence(profile_id)
if calorie_score is not None:
components.append(('calories', calorie_score, nutrition_focus['kalorienbilanz']))
# 2. Protein target adherence (always important if any nutrition goal)
protein_score = calculate_protein_adequacy_28d(profile_id)
if protein_score is not None:
# Higher weight if protein-specific goal
protein_weight = nutrition_focus['proteinzufuhr'] or (total_nutrition_weight * 0.3)
components.append(('protein', protein_score, protein_weight))
# 3. Intake consistency (always relevant)
consistency_score = calculate_macro_consistency_score(profile_id)
if consistency_score is not None:
consistency_weight = total_nutrition_weight * 0.2
components.append(('consistency', consistency_score, consistency_weight))
# 4. Macro balance (if makros goal active)
if nutrition_focus['ernährung_makros'] > 0:
macro_score = _score_macro_balance(profile_id)
if macro_score is not None:
components.append(('macros', macro_score, nutrition_focus['ernährung_makros']))
if not components:
return None
# Weighted average
total_score = sum(score * weight for _, score, weight in components)
total_weight = sum(weight for _, _, weight in components)
return int(total_score / total_weight)
def _score_calorie_adherence(profile_id: str) -> Optional[int]:
"""Score calorie target adherence (0-100)"""
# Get goal (if exists)
from goal_utils import get_goals_by_type
# Check for energy balance goal
# For now, use energy balance calculation
balance = calculate_energy_balance_7d(profile_id)
if balance is None:
return None
# Score based on whether deficit/surplus aligns with goal
# Simplified: assume weight loss goal = deficit is good
# TODO: Check actual goal type
abs_balance = abs(balance)
# Moderate deficit/surplus = good
if 200 <= abs_balance <= 500:
return 100
elif 100 <= abs_balance <= 700:
return 85
elif abs_balance <= 900:
return 70
elif abs_balance <= 1200:
return 55
else:
return 40
def _score_macro_balance(profile_id: str) -> Optional[int]:
"""Score macro balance (0-100)"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT protein_g, fat_g, carbs_g, kcal
FROM nutrition_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '28 days'
AND protein_g IS NOT NULL
AND fat_g IS NOT NULL
AND carbs_g IS NOT NULL
ORDER BY date DESC
""", (profile_id,))
data = cur.fetchall()
if len(data) < 18:
return None
# Calculate average macro percentages
macro_pcts = []
for row in data:
total_kcal = (row['protein_g'] * 4) + (row['fat_g'] * 9) + (row['carbs_g'] * 4)
if total_kcal == 0:
continue
protein_pct = (row['protein_g'] * 4 / total_kcal) * 100
fat_pct = (row['fat_g'] * 9 / total_kcal) * 100
carbs_pct = (row['carbs_g'] * 4 / total_kcal) * 100
macro_pcts.append((protein_pct, fat_pct, carbs_pct))
if not macro_pcts:
return None
avg_protein_pct = sum(p for p, _, _ in macro_pcts) / len(macro_pcts)
avg_fat_pct = sum(f for _, f, _ in macro_pcts) / len(macro_pcts)
avg_carbs_pct = sum(c for _, _, c in macro_pcts) / len(macro_pcts)
# Reasonable ranges:
# Protein: 20-35%
# Fat: 20-35%
# Carbs: 30-55%
score = 100
# Protein score
if not (20 <= avg_protein_pct <= 35):
if avg_protein_pct < 20:
score -= (20 - avg_protein_pct) * 2
else:
score -= (avg_protein_pct - 35) * 1
# Fat score
if not (20 <= avg_fat_pct <= 35):
if avg_fat_pct < 20:
score -= (20 - avg_fat_pct) * 2
else:
score -= (avg_fat_pct - 35) * 2
# Carbs score
if not (30 <= avg_carbs_pct <= 55):
if avg_carbs_pct < 30:
score -= (30 - avg_carbs_pct) * 1.5
else:
score -= (avg_carbs_pct - 55) * 1.5
return max(40, min(100, int(score)))
# ============================================================================
# E5: Energy Availability Warning (Heuristic)
# ============================================================================
def calculate_energy_availability_warning(profile_id: str) -> Optional[Dict]:
"""
Heuristic energy availability warning
Returns dict with warning level and reasons
"""
warnings = []
severity = 'none' # none, low, medium, high
# 1. Check for sustained large deficit
balance = calculate_energy_balance_7d(profile_id)
if balance and balance < -800:
warnings.append('Anhaltend großes Energiedefizit (>800 kcal/Tag)')
severity = 'medium'
if balance < -1200:
warnings.append('Sehr großes Energiedefizit (>1200 kcal/Tag)')
severity = 'high'
# 2. Check recovery score
from calculations.recovery_metrics import calculate_recovery_score_v2
recovery = calculate_recovery_score_v2(profile_id)
if recovery and recovery < 50:
warnings.append('Recovery Score niedrig (<50)')
if severity == 'none':
severity = 'low'
elif severity == 'medium':
severity = 'high'
# 3. Check LBM trend
from calculations.body_metrics import calculate_lbm_28d_change
lbm_change = calculate_lbm_28d_change(profile_id)
if lbm_change and lbm_change < -1.0:
warnings.append('Magermasse sinkt (>1kg in 28 Tagen)')
if severity == 'none':
severity = 'low'
elif severity in ['low', 'medium']:
severity = 'high'
# 4. Check sleep quality
from calculations.recovery_metrics import calculate_sleep_quality_7d
sleep_quality = calculate_sleep_quality_7d(profile_id)
if sleep_quality and sleep_quality < 60:
warnings.append('Schlafqualität verschlechtert')
if severity == 'none':
severity = 'low'
if not warnings:
return None
return {
'severity': severity,
'warnings': warnings,
'recommendation': _get_energy_warning_recommendation(severity)
}
def _get_energy_warning_recommendation(severity: str) -> str:
"""Get recommendation text based on severity"""
if severity == 'high':
return ("Mögliche Unterversorgung erkannt. Erwäge eine Reduktion des Energiedefizits, "
"Erhöhung der Proteinzufuhr und mehr Erholung. Dies ist keine medizinische Diagnose.")
elif severity == 'medium':
return ("Hinweise auf aggressives Defizit. Beobachte Recovery, Schlaf und Magermasse genau.")
else:
return ("Leichte Hinweise auf Belastung. Monitoring empfohlen.")
# ============================================================================
# Additional Helper Metrics
# ============================================================================
def calculate_fiber_avg_7d(profile_id: str) -> Optional[float]:
"""Calculate average fiber intake (g/day) last 7 days"""
# TODO: Implement when fiber column added to nutrition_log
return None
def calculate_sugar_avg_7d(profile_id: str) -> Optional[float]:
"""Calculate average sugar intake (g/day) last 7 days"""
# TODO: Implement when sugar column added to nutrition_log
return None
# ============================================================================
# Data Quality Assessment
# ============================================================================
def calculate_nutrition_data_quality(profile_id: str) -> Dict[str, any]:
"""
Assess data quality for nutrition metrics
Returns dict with quality score and details
"""
with get_db() as conn:
cur = get_cursor(conn)
# Nutrition entries last 28 days
cur.execute("""
SELECT COUNT(*) as total,
COUNT(protein_g) as with_protein,
COUNT(fat_g) as with_fat,
COUNT(carbs_g) as with_carbs
FROM nutrition_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '28 days'
""", (profile_id,))
counts = cur.fetchone()
total_entries = counts['total']
protein_coverage = counts['with_protein'] / total_entries if total_entries > 0 else 0
macro_coverage = min(counts['with_fat'], counts['with_carbs']) / total_entries if total_entries > 0 else 0
# Score components
frequency_score = min(100, (total_entries / 21) * 100) # 21 = 75% of 28 days
protein_score = protein_coverage * 100
macro_score = macro_coverage * 100
# Overall score (frequency 50%, protein 30%, macros 20%)
overall_score = int(
frequency_score * 0.5 +
protein_score * 0.3 +
macro_score * 0.2
)
# Confidence level
if overall_score >= 80:
confidence = "high"
elif overall_score >= 60:
confidence = "medium"
else:
confidence = "low"
return {
"overall_score": overall_score,
"confidence": confidence,
"measurements": {
"entries_28d": total_entries,
"protein_coverage_pct": int(protein_coverage * 100),
"macro_coverage_pct": int(macro_coverage * 100)
},
"component_scores": {
"frequency": int(frequency_score),
"protein": int(protein_score),
"macros": int(macro_score)
}
}
+604
View File
@@ -0,0 +1,604 @@
"""
Recovery Metrics Calculation Engine
Implements improved Recovery Score (S1 from visualization concept):
- HRV vs. baseline
- RHR vs. baseline
- Sleep duration vs. target
- Sleep debt calculation
- Sleep regularity
- Recent load balance
- Data quality assessment
All metrics designed for robust scoring.
"""
from datetime import datetime, timedelta
from typing import Optional, Dict
import statistics
from db import get_db, get_cursor
# ============================================================================
# Recovery Score v2 (Improved from v9d)
# ============================================================================
def calculate_recovery_score_v2(profile_id: str) -> Optional[int]:
"""
Improved recovery/readiness score (0-100)
Components:
- HRV status (25%)
- RHR status (20%)
- Sleep duration (20%)
- Sleep debt (10%)
- Sleep regularity (10%)
- Recent load balance (10%)
- Data quality (5%)
"""
components = []
# 1. HRV status (25%)
hrv_score = _score_hrv_vs_baseline(profile_id)
if hrv_score is not None:
components.append(('hrv', hrv_score, 25))
# 2. RHR status (20%)
rhr_score = _score_rhr_vs_baseline(profile_id)
if rhr_score is not None:
components.append(('rhr', rhr_score, 20))
# 3. Sleep duration (20%)
sleep_duration_score = _score_sleep_duration(profile_id)
if sleep_duration_score is not None:
components.append(('sleep_duration', sleep_duration_score, 20))
# 4. Sleep debt (10%)
sleep_debt_score = _score_sleep_debt(profile_id)
if sleep_debt_score is not None:
components.append(('sleep_debt', sleep_debt_score, 10))
# 5. Sleep regularity (10%)
regularity_score = _score_sleep_regularity(profile_id)
if regularity_score is not None:
components.append(('regularity', regularity_score, 10))
# 6. Recent load balance (10%)
load_score = _score_recent_load_balance(profile_id)
if load_score is not None:
components.append(('load', load_score, 10))
# 7. Data quality (5%)
quality_score = _score_recovery_data_quality(profile_id)
if quality_score is not None:
components.append(('data_quality', quality_score, 5))
if not components:
return None
# Weighted average
total_score = sum(score * weight for _, score, weight in components)
total_weight = sum(weight for _, _, weight in components)
final_score = int(total_score / total_weight)
return final_score
def _score_hrv_vs_baseline(profile_id: str) -> Optional[int]:
"""Score HRV relative to 28d baseline (0-100)"""
with get_db() as conn:
cur = get_cursor(conn)
# Get recent HRV (last 3 days average)
cur.execute("""
SELECT AVG(hrv) as recent_hrv
FROM vitals_baseline
WHERE profile_id = %s
AND hrv IS NOT NULL
AND date >= CURRENT_DATE - INTERVAL '3 days'
""", (profile_id,))
recent_row = cur.fetchone()
if not recent_row or not recent_row['recent_hrv']:
return None
recent_hrv = recent_row['recent_hrv']
# Get baseline (28d average, excluding last 3 days)
cur.execute("""
SELECT AVG(hrv) as baseline_hrv
FROM vitals_baseline
WHERE profile_id = %s
AND hrv IS NOT NULL
AND date >= CURRENT_DATE - INTERVAL '28 days'
AND date < CURRENT_DATE - INTERVAL '3 days'
""", (profile_id,))
baseline_row = cur.fetchone()
if not baseline_row or not baseline_row['baseline_hrv']:
return None
baseline_hrv = baseline_row['baseline_hrv']
# Calculate percentage deviation
deviation_pct = ((recent_hrv - baseline_hrv) / baseline_hrv) * 100
# Score: higher HRV = better recovery
if deviation_pct >= 10:
return 100
elif deviation_pct >= 5:
return 90
elif deviation_pct >= 0:
return 75
elif deviation_pct >= -5:
return 60
elif deviation_pct >= -10:
return 45
else:
return max(20, 45 + int(deviation_pct * 2))
def _score_rhr_vs_baseline(profile_id: str) -> Optional[int]:
"""Score RHR relative to 28d baseline (0-100)"""
with get_db() as conn:
cur = get_cursor(conn)
# Get recent RHR (last 3 days average)
cur.execute("""
SELECT AVG(resting_hr) as recent_rhr
FROM vitals_baseline
WHERE profile_id = %s
AND resting_hr IS NOT NULL
AND date >= CURRENT_DATE - INTERVAL '3 days'
""", (profile_id,))
recent_row = cur.fetchone()
if not recent_row or not recent_row['recent_rhr']:
return None
recent_rhr = recent_row['recent_rhr']
# Get baseline (28d average, excluding last 3 days)
cur.execute("""
SELECT AVG(resting_hr) as baseline_rhr
FROM vitals_baseline
WHERE profile_id = %s
AND resting_hr IS NOT NULL
AND date >= CURRENT_DATE - INTERVAL '28 days'
AND date < CURRENT_DATE - INTERVAL '3 days'
""", (profile_id,))
baseline_row = cur.fetchone()
if not baseline_row or not baseline_row['baseline_rhr']:
return None
baseline_rhr = baseline_row['baseline_rhr']
# Calculate difference (bpm)
difference = recent_rhr - baseline_rhr
# Score: lower RHR = better recovery
if difference <= -3:
return 100
elif difference <= -1:
return 90
elif difference <= 1:
return 75
elif difference <= 3:
return 60
elif difference <= 5:
return 45
else:
return max(20, 45 - (difference * 5))
def _score_sleep_duration(profile_id: str) -> Optional[int]:
"""Score recent sleep duration (0-100)"""
avg_sleep_hours = calculate_sleep_avg_duration_7d(profile_id)
if avg_sleep_hours is None:
return None
# Target: 7-9 hours
if 7 <= avg_sleep_hours <= 9:
return 100
elif 6.5 <= avg_sleep_hours < 7:
return 85
elif 6 <= avg_sleep_hours < 6.5:
return 70
elif avg_sleep_hours >= 9.5:
return 85 # Too much sleep can indicate fatigue
else:
return max(40, int(avg_sleep_hours * 10))
def _score_sleep_debt(profile_id: str) -> Optional[int]:
"""Score sleep debt (0-100)"""
debt_hours = calculate_sleep_debt_hours(profile_id)
if debt_hours is None:
return None
# Score based on accumulated debt
if debt_hours <= 1:
return 100
elif debt_hours <= 3:
return 85
elif debt_hours <= 5:
return 70
elif debt_hours <= 8:
return 55
else:
return max(30, 100 - (debt_hours * 8))
def _score_sleep_regularity(profile_id: str) -> Optional[int]:
"""Score sleep regularity (0-100)"""
regularity_proxy = calculate_sleep_regularity_proxy(profile_id)
if regularity_proxy is None:
return None
# regularity_proxy = mean absolute shift in minutes
# Lower = better
if regularity_proxy <= 30:
return 100
elif regularity_proxy <= 45:
return 85
elif regularity_proxy <= 60:
return 70
elif regularity_proxy <= 90:
return 55
else:
return max(30, 100 - int(regularity_proxy / 2))
def _score_recent_load_balance(profile_id: str) -> Optional[int]:
"""Score recent training load balance (0-100)"""
load_3d = calculate_recent_load_balance_3d(profile_id)
if load_3d is None:
return None
# Proxy load: 0-300 = low, 300-600 = moderate, >600 = high
if load_3d < 300:
# Under-loading
return 90
elif load_3d <= 600:
# Optimal
return 100
elif load_3d <= 900:
# High but manageable
return 75
elif load_3d <= 1200:
# Very high
return 55
else:
# Excessive
return max(30, 100 - (load_3d / 20))
def _score_recovery_data_quality(profile_id: str) -> Optional[int]:
"""Score data quality for recovery metrics (0-100)"""
quality = calculate_recovery_data_quality(profile_id)
return quality['overall_score']
# ============================================================================
# Individual Recovery Metrics
# ============================================================================
def calculate_hrv_vs_baseline_pct(profile_id: str) -> Optional[float]:
"""Calculate HRV deviation from baseline (percentage)"""
with get_db() as conn:
cur = get_cursor(conn)
# Recent HRV (3d avg)
cur.execute("""
SELECT AVG(hrv) as recent_hrv
FROM vitals_baseline
WHERE profile_id = %s
AND hrv IS NOT NULL
AND date >= CURRENT_DATE - INTERVAL '3 days'
""", (profile_id,))
recent_row = cur.fetchone()
if not recent_row or not recent_row['recent_hrv']:
return None
recent = recent_row['recent_hrv']
# Baseline (28d avg, excluding last 3d)
cur.execute("""
SELECT AVG(hrv) as baseline_hrv
FROM vitals_baseline
WHERE profile_id = %s
AND hrv IS NOT NULL
AND date >= CURRENT_DATE - INTERVAL '28 days'
AND date < CURRENT_DATE - INTERVAL '3 days'
""", (profile_id,))
baseline_row = cur.fetchone()
if not baseline_row or not baseline_row['baseline_hrv']:
return None
baseline = baseline_row['baseline_hrv']
deviation_pct = ((recent - baseline) / baseline) * 100
return round(deviation_pct, 1)
def calculate_rhr_vs_baseline_pct(profile_id: str) -> Optional[float]:
"""Calculate RHR deviation from baseline (percentage)"""
with get_db() as conn:
cur = get_cursor(conn)
# Recent RHR (3d avg)
cur.execute("""
SELECT AVG(resting_hr) as recent_rhr
FROM vitals_baseline
WHERE profile_id = %s
AND resting_hr IS NOT NULL
AND date >= CURRENT_DATE - INTERVAL '3 days'
""", (profile_id,))
recent_row = cur.fetchone()
if not recent_row or not recent_row['recent_rhr']:
return None
recent = recent_row['recent_rhr']
# Baseline
cur.execute("""
SELECT AVG(resting_hr) as baseline_rhr
FROM vitals_baseline
WHERE profile_id = %s
AND resting_hr IS NOT NULL
AND date >= CURRENT_DATE - INTERVAL '28 days'
AND date < CURRENT_DATE - INTERVAL '3 days'
""", (profile_id,))
baseline_row = cur.fetchone()
if not baseline_row or not baseline_row['baseline_rhr']:
return None
baseline = baseline_row['baseline_rhr']
deviation_pct = ((recent - baseline) / baseline) * 100
return round(deviation_pct, 1)
def calculate_sleep_avg_duration_7d(profile_id: str) -> Optional[float]:
"""Calculate average sleep duration (hours) last 7 days"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT AVG(duration_minutes) as avg_sleep_min
FROM sleep_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '7 days'
AND duration_minutes IS NOT NULL
""", (profile_id,))
row = cur.fetchone()
if not row or not row['avg_sleep_min']:
return None
avg_hours = row['avg_sleep_min'] / 60
return round(avg_hours, 1)
def calculate_sleep_debt_hours(profile_id: str) -> Optional[float]:
"""
Calculate accumulated sleep debt (hours) last 14 days
Assumes 7.5h target per night
"""
target_hours = 7.5
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT duration_minutes
FROM sleep_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '14 days'
AND duration_minutes IS NOT NULL
ORDER BY date DESC
""", (profile_id,))
sleep_data = [row['duration_minutes'] for row in cur.fetchall()]
if len(sleep_data) < 10: # Need at least 10 days
return None
# Calculate cumulative debt
total_debt_min = sum(max(0, (target_hours * 60) - sleep_min) for sleep_min in sleep_data)
debt_hours = total_debt_min / 60
return round(debt_hours, 1)
def calculate_sleep_regularity_proxy(profile_id: str) -> Optional[float]:
"""
Sleep regularity proxy: mean absolute shift from previous day (minutes)
Lower = more regular
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT bedtime, wake_time, date
FROM sleep_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '14 days'
AND bedtime IS NOT NULL
AND wake_time IS NOT NULL
ORDER BY date
""", (profile_id,))
sleep_data = cur.fetchall()
if len(sleep_data) < 7:
return None
# Calculate day-to-day shifts
shifts = []
for i in range(1, len(sleep_data)):
prev = sleep_data[i-1]
curr = sleep_data[i]
# Bedtime shift (minutes)
prev_bedtime = prev['bedtime']
curr_bedtime = curr['bedtime']
# Convert to minutes since midnight
prev_bed_min = prev_bedtime.hour * 60 + prev_bedtime.minute
curr_bed_min = curr_bedtime.hour * 60 + curr_bedtime.minute
# Handle cross-midnight (e.g., 23:00 to 01:00)
bed_shift = abs(curr_bed_min - prev_bed_min)
if bed_shift > 720: # More than 12 hours = wrapped around
bed_shift = 1440 - bed_shift
shifts.append(bed_shift)
mean_shift = sum(shifts) / len(shifts)
return round(mean_shift, 1)
def calculate_recent_load_balance_3d(profile_id: str) -> Optional[int]:
"""Calculate proxy internal load last 3 days"""
from calculations.activity_metrics import calculate_proxy_internal_load_7d
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT SUM(duration_min) as total_duration
FROM activity_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '3 days'
""", (profile_id,))
row = cur.fetchone()
if not row:
return None
# Simplified 3d load (duration-based)
return int(row['total_duration'] or 0)
def calculate_sleep_quality_7d(profile_id: str) -> Optional[int]:
"""
Calculate sleep quality score (0-100) based on deep+REM percentage
Last 7 days
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT duration_minutes, deep_minutes, rem_minutes
FROM sleep_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '7 days'
AND duration_minutes IS NOT NULL
""", (profile_id,))
sleep_data = cur.fetchall()
if len(sleep_data) < 4:
return None
quality_scores = []
for s in sleep_data:
if s['deep_minutes'] and s['rem_minutes']:
quality_pct = ((s['deep_minutes'] + s['rem_minutes']) / s['duration_minutes']) * 100
# 40-60% deep+REM is good
if quality_pct >= 45:
quality_scores.append(100)
elif quality_pct >= 35:
quality_scores.append(75)
elif quality_pct >= 25:
quality_scores.append(50)
else:
quality_scores.append(30)
if not quality_scores:
return None
avg_quality = sum(quality_scores) / len(quality_scores)
return int(avg_quality)
# ============================================================================
# Data Quality Assessment
# ============================================================================
def calculate_recovery_data_quality(profile_id: str) -> Dict[str, any]:
"""
Assess data quality for recovery metrics
Returns dict with quality score and details
"""
with get_db() as conn:
cur = get_cursor(conn)
# HRV measurements (28d)
cur.execute("""
SELECT COUNT(*) as hrv_count
FROM vitals_baseline
WHERE profile_id = %s
AND hrv IS NOT NULL
AND date >= CURRENT_DATE - INTERVAL '28 days'
""", (profile_id,))
hrv_count = cur.fetchone()['hrv_count']
# RHR measurements (28d)
cur.execute("""
SELECT COUNT(*) as rhr_count
FROM vitals_baseline
WHERE profile_id = %s
AND resting_hr IS NOT NULL
AND date >= CURRENT_DATE - INTERVAL '28 days'
""", (profile_id,))
rhr_count = cur.fetchone()['rhr_count']
# Sleep measurements (28d)
cur.execute("""
SELECT COUNT(*) as sleep_count
FROM sleep_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '28 days'
""", (profile_id,))
sleep_count = cur.fetchone()['sleep_count']
# Score components
hrv_score = min(100, (hrv_count / 21) * 100) # 21 = 75% coverage
rhr_score = min(100, (rhr_count / 21) * 100)
sleep_score = min(100, (sleep_count / 21) * 100)
# Overall score
overall_score = int(
hrv_score * 0.3 +
rhr_score * 0.3 +
sleep_score * 0.4
)
if overall_score >= 80:
confidence = "high"
elif overall_score >= 60:
confidence = "medium"
else:
confidence = "low"
return {
"overall_score": overall_score,
"confidence": confidence,
"measurements": {
"hrv_28d": hrv_count,
"rhr_28d": rhr_count,
"sleep_28d": sleep_count
},
"component_scores": {
"hrv": int(hrv_score),
"rhr": int(rhr_score),
"sleep": int(sleep_score)
}
}
+566
View File
@@ -0,0 +1,566 @@
"""
Score Calculation Engine
Implements meta-scores with Dynamic Focus Areas v2.0 integration:
- Goal Progress Score (weighted by user's focus areas)
- Data Quality Score
- Helper functions for focus area weighting
All scores are 0-100 with confidence levels.
"""
from typing import Dict, Optional, List
import json
from db import get_db, get_cursor
# ============================================================================
# Focus Area Weighting System
# ============================================================================
def get_user_focus_weights(profile_id: str) -> Dict[str, float]:
"""
Get user's focus area weights as dictionary
Returns: {'körpergewicht': 30.0, 'kraftaufbau': 25.0, ...}
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT ufw.focus_area_id, ufw.weight as weight_pct, fa.key
FROM user_focus_area_weights ufw
JOIN focus_area_definitions fa ON ufw.focus_area_id = fa.id
WHERE ufw.profile_id = %s
AND ufw.weight > 0
""", (profile_id,))
return {
row['key']: float(row['weight_pct'])
for row in cur.fetchall()
}
def get_focus_area_category(focus_area_id: str) -> Optional[str]:
"""Get category for a focus area"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT category
FROM focus_area_definitions
WHERE focus_area_id = %s
""", (focus_area_id,))
row = cur.fetchone()
return row['category'] if row else None
def map_focus_to_score_components() -> Dict[str, str]:
"""
Map focus areas to score components
Keys match focus_area_definitions.key (English lowercase)
Returns: {'weight_loss': 'body', 'strength': 'activity', ...}
"""
return {
# Body Composition → body_progress_score
'weight_loss': 'body',
'muscle_gain': 'body',
'body_recomposition': 'body',
# Training - Strength → activity_score
'strength': 'activity',
'strength_endurance': 'activity',
'power': 'activity',
# Training - Mobility → activity_score
'flexibility': 'activity',
'mobility': 'activity',
# Endurance → activity_score (could also map to health)
'aerobic_endurance': 'activity',
'anaerobic_endurance': 'activity',
'cardiovascular_health': 'health',
# Coordination → activity_score
'balance': 'activity',
'reaction': 'activity',
'rhythm': 'activity',
'coordination': 'activity',
# Mental → recovery_score (mental health is part of recovery)
'stress_resistance': 'recovery',
'concentration': 'recovery',
'willpower': 'recovery',
'mental_health': 'recovery',
# Recovery → recovery_score
'sleep_quality': 'recovery',
'regeneration': 'recovery',
'rest': 'recovery',
# Health → health
'metabolic_health': 'health',
'blood_pressure': 'health',
'hrv': 'health',
'general_health': 'health',
}
def map_category_de_to_en(category_de: str) -> str:
"""
Map German category names to English database names
"""
mapping = {
'körper': 'body_composition',
'ernährung': 'nutrition', # Note: no nutrition category in DB, returns empty
'aktivität': 'training',
'recovery': 'recovery',
'vitalwerte': 'health',
'mental': 'mental',
'lebensstil': 'health', # Maps to general health
}
return mapping.get(category_de, category_de)
def calculate_category_weight(profile_id: str, category: str) -> float:
"""
Calculate total weight for a category
Accepts German or English category names
Returns sum of all focus area weights in this category
"""
# Map German to English if needed
category_en = map_category_de_to_en(category)
focus_weights = get_user_focus_weights(profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT key
FROM focus_area_definitions
WHERE category = %s
""", (category_en,))
focus_areas = [row['key'] for row in cur.fetchall()]
total_weight = sum(
focus_weights.get(fa, 0)
for fa in focus_areas
)
return total_weight
# ============================================================================
# Goal Progress Score (Meta-Score with Dynamic Weighting)
# ============================================================================
def calculate_goal_progress_score(profile_id: str) -> Optional[int]:
"""
Calculate overall goal progress score (0-100)
Weighted dynamically based on user's focus area priorities
This is the main meta-score that combines all sub-scores
"""
focus_weights = get_user_focus_weights(profile_id)
if not focus_weights:
return None # No goals/focus areas configured
# Calculate sub-scores
from calculations.body_metrics import calculate_body_progress_score
from calculations.nutrition_metrics import calculate_nutrition_score
from calculations.activity_metrics import calculate_activity_score
from calculations.recovery_metrics import calculate_recovery_score_v2
body_score = calculate_body_progress_score(profile_id, focus_weights)
nutrition_score = calculate_nutrition_score(profile_id, focus_weights)
activity_score = calculate_activity_score(profile_id, focus_weights)
recovery_score = calculate_recovery_score_v2(profile_id)
health_risk_score = calculate_health_stability_score(profile_id)
# Map focus areas to score components
focus_to_component = map_focus_to_score_components()
# Calculate weighted sum
total_score = 0.0
total_weight = 0.0
for focus_area_id, weight in focus_weights.items():
component = focus_to_component.get(focus_area_id)
if component == 'body' and body_score is not None:
total_score += body_score * weight
total_weight += weight
elif component == 'nutrition' and nutrition_score is not None:
total_score += nutrition_score * weight
total_weight += weight
elif component == 'activity' and activity_score is not None:
total_score += activity_score * weight
total_weight += weight
elif component == 'recovery' and recovery_score is not None:
total_score += recovery_score * weight
total_weight += weight
elif component == 'health' and health_risk_score is not None:
total_score += health_risk_score * weight
total_weight += weight
if total_weight == 0:
return None
# Normalize to 0-100
final_score = total_score / total_weight
return int(final_score)
def calculate_health_stability_score(profile_id: str) -> Optional[int]:
"""
Health stability score (0-100)
Components:
- Blood pressure status
- Sleep quality
- Movement baseline
- Weight/circumference risk factors
- Regularity
"""
with get_db() as conn:
cur = get_cursor(conn)
components = []
# 1. Blood pressure status (30%)
cur.execute("""
SELECT systolic, diastolic
FROM blood_pressure_log
WHERE profile_id = %s
AND measured_at >= CURRENT_DATE - INTERVAL '28 days'
ORDER BY measured_at DESC
""", (profile_id,))
bp_readings = cur.fetchall()
if bp_readings:
bp_score = _score_blood_pressure(bp_readings)
components.append(('bp', bp_score, 30))
# 2. Sleep quality (25%)
cur.execute("""
SELECT duration_minutes, deep_minutes, rem_minutes
FROM sleep_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '28 days'
ORDER BY date DESC
""", (profile_id,))
sleep_data = cur.fetchall()
if sleep_data:
sleep_score = _score_sleep_quality(sleep_data)
components.append(('sleep', sleep_score, 25))
# 3. Movement baseline (20%)
cur.execute("""
SELECT duration_min
FROM activity_log
WHERE profile_id = %s
AND date >= CURRENT_DATE - INTERVAL '7 days'
""", (profile_id,))
activities = cur.fetchall()
if activities:
total_minutes = sum(a['duration_min'] for a in activities)
# WHO recommends 150-300 min/week moderate activity
movement_score = min(100, (total_minutes / 150) * 100)
components.append(('movement', movement_score, 20))
# 4. Waist circumference risk (15%)
cur.execute("""
SELECT c_waist
FROM circumference_log
WHERE profile_id = %s
AND c_waist IS NOT NULL
ORDER BY date DESC
LIMIT 1
""", (profile_id,))
waist = cur.fetchone()
if waist:
# Gender-specific thresholds (simplified - should use profile gender)
# Men: <94cm good, 94-102 elevated, >102 high risk
# Women: <80cm good, 80-88 elevated, >88 high risk
# Using conservative thresholds
waist_cm = waist['c_waist']
if waist_cm < 88:
waist_score = 100
elif waist_cm < 94:
waist_score = 75
elif waist_cm < 102:
waist_score = 50
else:
waist_score = 25
components.append(('waist', waist_score, 15))
# 5. Regularity (10%) - sleep timing consistency
if len(sleep_data) >= 7:
sleep_times = [s['duration_minutes'] for s in sleep_data]
avg = sum(sleep_times) / len(sleep_times)
variance = sum((x - avg) ** 2 for x in sleep_times) / len(sleep_times)
std_dev = variance ** 0.5
# Lower std_dev = better consistency
regularity_score = max(0, 100 - (std_dev * 2))
components.append(('regularity', regularity_score, 10))
if not components:
return None
# Weighted average
total_score = sum(score * weight for _, score, weight in components)
total_weight = sum(weight for _, _, weight in components)
return int(total_score / total_weight)
def _score_blood_pressure(readings: List) -> int:
"""Score blood pressure readings (0-100)"""
# Average last 28 days
avg_systolic = sum(r['systolic'] for r in readings) / len(readings)
avg_diastolic = sum(r['diastolic'] for r in readings) / len(readings)
# ESC 2024 Guidelines:
# Optimal: <120/80
# Normal: 120-129 / 80-84
# Elevated: 130-139 / 85-89
# Hypertension: ≥140/90
if avg_systolic < 120 and avg_diastolic < 80:
return 100
elif avg_systolic < 130 and avg_diastolic < 85:
return 85
elif avg_systolic < 140 and avg_diastolic < 90:
return 65
else:
return 40
def _score_sleep_quality(sleep_data: List) -> int:
"""Score sleep quality (0-100)"""
# Average sleep duration and quality
avg_total = sum(s['duration_minutes'] for s in sleep_data) / len(sleep_data)
avg_total_hours = avg_total / 60
# Duration score (7+ hours = good)
if avg_total_hours >= 8:
duration_score = 100
elif avg_total_hours >= 7:
duration_score = 85
elif avg_total_hours >= 6:
duration_score = 65
else:
duration_score = 40
# Quality score (deep + REM percentage)
quality_scores = []
for s in sleep_data:
if s['deep_minutes'] and s['rem_minutes']:
quality_pct = ((s['deep_minutes'] + s['rem_minutes']) / s['duration_minutes']) * 100
# 40-60% deep+REM is good
if quality_pct >= 45:
quality_scores.append(100)
elif quality_pct >= 35:
quality_scores.append(75)
elif quality_pct >= 25:
quality_scores.append(50)
else:
quality_scores.append(30)
if quality_scores:
avg_quality = sum(quality_scores) / len(quality_scores)
# Weighted: 60% duration, 40% quality
return int(duration_score * 0.6 + avg_quality * 0.4)
else:
return duration_score
# ============================================================================
# Data Quality Score
# ============================================================================
def calculate_data_quality_score(profile_id: str) -> int:
"""
Overall data quality score (0-100)
Combines quality from all modules
"""
from calculations.body_metrics import calculate_body_data_quality
from calculations.nutrition_metrics import calculate_nutrition_data_quality
from calculations.activity_metrics import calculate_activity_data_quality
from calculations.recovery_metrics import calculate_recovery_data_quality
body_quality = calculate_body_data_quality(profile_id)
nutrition_quality = calculate_nutrition_data_quality(profile_id)
activity_quality = calculate_activity_data_quality(profile_id)
recovery_quality = calculate_recovery_data_quality(profile_id)
# Weighted average (all equal weight)
total_score = (
body_quality['overall_score'] * 0.25 +
nutrition_quality['overall_score'] * 0.25 +
activity_quality['overall_score'] * 0.25 +
recovery_quality['overall_score'] * 0.25
)
return int(total_score)
# ============================================================================
# Top-Weighted Helpers (instead of "primary goal")
# ============================================================================
def get_top_priority_goal(profile_id: str) -> Optional[Dict]:
"""
Get highest priority goal based on:
- Progress gap (distance to target)
- Focus area weight
Returns goal dict or None
"""
from goal_utils import get_active_goals
goals = get_active_goals(profile_id)
if not goals:
return None
focus_weights = get_user_focus_weights(profile_id)
for goal in goals:
# Progress gap (0-100, higher = further from target)
goal['progress_gap'] = 100 - (goal.get('progress_pct') or 0)
# Get focus areas for this goal
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT fa.key as focus_area_key
FROM goal_focus_contributions gfc
JOIN focus_area_definitions fa ON gfc.focus_area_id = fa.id
WHERE gfc.goal_id = %s
""", (goal['id'],))
goal_focus_areas = [row['focus_area_key'] for row in cur.fetchall()]
# Sum focus weights
goal['total_focus_weight'] = sum(
focus_weights.get(fa, 0)
for fa in goal_focus_areas
)
# Priority score
goal['priority_score'] = goal['progress_gap'] * (goal['total_focus_weight'] / 100)
# Return goal with highest priority score
return max(goals, key=lambda g: g.get('priority_score', 0))
def get_top_focus_area(profile_id: str) -> Optional[Dict]:
"""
Get focus area with highest user weight
Returns dict with focus_area_id, label, weight, progress
"""
focus_weights = get_user_focus_weights(profile_id)
if not focus_weights:
return None
top_fa_id = max(focus_weights, key=focus_weights.get)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT key, name_de, category
FROM focus_area_definitions
WHERE key = %s
""", (top_fa_id,))
fa_def = cur.fetchone()
if not fa_def:
return None
# Calculate progress for this focus area
progress = calculate_focus_area_progress(profile_id, top_fa_id)
return {
'focus_area_id': top_fa_id,
'label': fa_def['name_de'],
'category': fa_def['category'],
'weight': focus_weights[top_fa_id],
'progress': progress
}
def calculate_focus_area_progress(profile_id: str, focus_area_id: str) -> Optional[int]:
"""
Calculate progress for a specific focus area (0-100)
Average progress of all goals contributing to this focus area
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT g.id, g.progress_pct, gfc.contribution_weight
FROM goals g
JOIN goal_focus_contributions gfc ON g.id = gfc.goal_id
WHERE g.profile_id = %s
AND gfc.focus_area_id = (
SELECT id FROM focus_area_definitions WHERE key = %s
)
AND g.status = 'active'
""", (profile_id, focus_area_id))
goals = cur.fetchall()
if not goals:
return None
# Weighted average by contribution_weight
total_progress = sum(g['progress_pct'] * g['contribution_weight'] for g in goals)
total_weight = sum(g['contribution_weight'] for g in goals)
return int(total_progress / total_weight) if total_weight > 0 else None
def calculate_category_progress(profile_id: str, category: str) -> Optional[int]:
"""
Calculate progress score for a focus area category (0-100).
Args:
profile_id: User's profile ID
category: Category name ('körper', 'ernährung', 'aktivität', 'recovery', 'vitalwerte', 'mental', 'lebensstil')
Returns:
Progress score 0-100 or None if no data
"""
# Map category to score calculation functions
category_scores = {
'körper': 'body_progress_score',
'ernährung': 'nutrition_score',
'aktivität': 'activity_score',
'recovery': 'recovery_score',
'vitalwerte': 'recovery_score', # Use recovery score as proxy for vitals
'mental': 'recovery_score', # Use recovery score as proxy for mental (sleep quality)
'lebensstil': 'data_quality_score', # Use data quality as proxy for lifestyle consistency
}
score_func_name = category_scores.get(category.lower())
if not score_func_name:
return None
# Call the appropriate score function
if score_func_name == 'body_progress_score':
from calculations.body_metrics import calculate_body_progress_score
return calculate_body_progress_score(profile_id)
elif score_func_name == 'nutrition_score':
from calculations.nutrition_metrics import calculate_nutrition_score
return calculate_nutrition_score(profile_id)
elif score_func_name == 'activity_score':
from calculations.activity_metrics import calculate_activity_score
return calculate_activity_score(profile_id)
elif score_func_name == 'recovery_score':
from calculations.recovery_metrics import calculate_recovery_score_v2
return calculate_recovery_score_v2(profile_id)
elif score_func_name == 'data_quality_score':
return calculate_data_quality_score(profile_id)
return None
+51 -3
View File
@@ -13,11 +13,11 @@ Version History:
Part of Phase 1 + Phase 1.5: Flexible Goal System Part of Phase 1 + Phase 1.5: Flexible Goal System
""" """
from typing import Dict, Optional, Any from typing import Dict, Optional, Any, List
from datetime import date, timedelta from datetime import date, timedelta
from decimal import Decimal from decimal import Decimal
import json import json
from db import get_cursor from db import get_cursor, get_db
def get_focus_weights(conn, profile_id: str) -> Dict[str, float]: def get_focus_weights(conn, profile_id: str) -> Dict[str, float]:
@@ -278,7 +278,7 @@ def _fetch_by_aggregation_method(
- max_30d: Maximum value in last 30 days - max_30d: Maximum value in last 30 days
Args: Args:
filter_conditions: Optional JSON filters (e.g., {"training_type": "strength"}) filter_conditions: Optional JSON filters (e.g., {"training_category": "strength"})
""" """
# Guard: source_table/column required for simple aggregation # Guard: source_table/column required for simple aggregation
if not table or not column: if not table or not column:
@@ -412,7 +412,21 @@ def _fetch_by_aggregation_method(
return None return None
except Exception as e: except Exception as e:
# Log detailed error for debugging
print(f"[ERROR] Failed to fetch value from {table}.{column} using {method}: {e}") print(f"[ERROR] Failed to fetch value from {table}.{column} using {method}: {e}")
print(f"[ERROR] Filter conditions: {filter_conditions}")
print(f"[ERROR] Filter SQL: {filter_sql}")
print(f"[ERROR] Filter params: {filter_params}")
# CRITICAL: Rollback transaction to avoid InFailedSqlTransaction errors
try:
conn.rollback()
print(f"[INFO] Transaction rolled back after query error")
except Exception as rollback_err:
print(f"[WARNING] Rollback failed: {rollback_err}")
# Return None so goal creation can continue without current_value
# (current_value will be NULL in the goal record)
return None return None
@@ -502,3 +516,37 @@ def get_focus_weights_v2(conn, profile_id: str) -> Dict[str, float]:
'health': row['health_pct'] / 100.0 'health': row['health_pct'] / 100.0
} }
""" """
def get_active_goals(profile_id: str) -> List[Dict]:
"""
Get all active goals for a profile.
Returns list of goal dicts with id, type, target_value, current_value, etc.
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT id, goal_type, name, target_value, target_date,
current_value, progress_pct, status, is_primary
FROM goals
WHERE profile_id = %s
AND status IN ('active', 'in_progress')
ORDER BY is_primary DESC, created_at DESC
""", (profile_id,))
return [dict(row) for row in cur.fetchall()]
def get_goal_by_id(goal_id: str) -> Optional[Dict]:
"""Get a single goal by ID"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT id, profile_id, goal_type, target_value, target_date,
current_value, progress_pct, status, is_primary
FROM goals
WHERE id = %s
""", (goal_id,))
row = cur.fetchone()
return dict(row) if row else None
+8 -2
View File
@@ -23,7 +23,8 @@ from routers import user_restrictions, access_grants, training_types, admin_trai
from routers import admin_activity_mappings, sleep, rest_days from routers import admin_activity_mappings, sleep, rest_days
from routers import vitals_baseline, blood_pressure # v9d Phase 2d Refactored from routers import vitals_baseline, blood_pressure # v9d Phase 2d Refactored
from routers import evaluation # v9d/v9e Training Type Profiles (#15) from routers import evaluation # v9d/v9e Training Type Profiles (#15)
from routers import goals # v9e Goal System (Strategic + Tactical) 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)
# ── App Configuration ───────────────────────────────────────────────────────── # ── App Configuration ─────────────────────────────────────────────────────────
DATA_DIR = Path(os.getenv("DATA_DIR", "./data")) DATA_DIR = Path(os.getenv("DATA_DIR", "./data"))
@@ -98,7 +99,12 @@ app.include_router(rest_days.router) # /api/rest-days/* (v9d Phase 2a
app.include_router(vitals_baseline.router) # /api/vitals/baseline/* (v9d Phase 2d Refactored) app.include_router(vitals_baseline.router) # /api/vitals/baseline/* (v9d Phase 2d Refactored)
app.include_router(blood_pressure.router) # /api/blood-pressure/* (v9d Phase 2d Refactored) app.include_router(blood_pressure.router) # /api/blood-pressure/* (v9d Phase 2d Refactored)
app.include_router(evaluation.router) # /api/evaluation/* (v9d/v9e Training Profiles #15) app.include_router(evaluation.router) # /api/evaluation/* (v9d/v9e Training Profiles #15)
app.include_router(goals.router) # /api/goals/* (v9e Goal System Strategic + Tactical) app.include_router(goals.router) # /api/goals/* (v9h Goal System Core CRUD + Focus Areas)
app.include_router(goal_types.router) # /api/goals/goal-types/* (v9h Goal Type Definitions)
app.include_router(goal_progress.router) # /api/goals/{goal_id}/progress/* (v9h Progress Tracking)
app.include_router(training_phases.router) # /api/goals/phases/* (v9h Training Phases)
app.include_router(fitness_tests.router) # /api/goals/tests/* (v9h Fitness Tests)
app.include_router(focus_areas.router) # /api/focus-areas/* (v9g Focus Area System v2.0 - Dynamic)
# ── Health Check ────────────────────────────────────────────────────────────── # ── Health Check ──────────────────────────────────────────────────────────────
@app.get("/") @app.get("/")
@@ -0,0 +1,254 @@
-- Migration 031: Focus Area System v2.0
-- Date: 2026-03-27
-- Purpose: Dynamic, extensible focus areas with Many-to-Many goal contributions
-- ============================================================================
-- Part 1: New Tables
-- ============================================================================
-- Focus Area Definitions (dynamic, user-extensible)
CREATE TABLE IF NOT EXISTS focus_area_definitions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
key VARCHAR(50) UNIQUE NOT NULL, -- e.g. 'strength', 'aerobic_endurance'
name_de VARCHAR(100) NOT NULL,
name_en VARCHAR(100),
icon VARCHAR(10),
description TEXT,
category VARCHAR(50), -- 'body_composition', 'training', 'endurance', 'coordination', 'mental', 'recovery', 'health'
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE INDEX idx_focus_area_key ON focus_area_definitions(key);
CREATE INDEX idx_focus_area_category ON focus_area_definitions(category);
COMMENT ON TABLE focus_area_definitions IS 'Dynamic focus area registry - defines all available focus dimensions';
COMMENT ON COLUMN focus_area_definitions.key IS 'Unique identifier for programmatic access';
COMMENT ON COLUMN focus_area_definitions.category IS 'Grouping for UI display';
-- Many-to-Many: Goals contribute to Focus Areas
CREATE TABLE IF NOT EXISTS goal_focus_contributions (
goal_id UUID NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
focus_area_id UUID NOT NULL REFERENCES focus_area_definitions(id) ON DELETE CASCADE,
contribution_weight DECIMAL(5,2) DEFAULT 100.00 CHECK (contribution_weight >= 0 AND contribution_weight <= 100),
created_at TIMESTAMP DEFAULT NOW(),
PRIMARY KEY (goal_id, focus_area_id)
);
CREATE INDEX idx_gfc_goal ON goal_focus_contributions(goal_id);
CREATE INDEX idx_gfc_focus_area ON goal_focus_contributions(focus_area_id);
COMMENT ON TABLE goal_focus_contributions IS 'Maps goals to focus areas with contribution weights (0-100%)';
COMMENT ON COLUMN goal_focus_contributions.contribution_weight IS 'How much this goal contributes to the focus area (0-100%)';
-- ============================================================================
-- Part 2: Rename existing focus_areas table
-- ============================================================================
-- Old focus_areas table becomes user_focus_preferences
ALTER TABLE focus_areas RENAME TO user_focus_preferences;
-- Add reference to new focus_area_definitions (for future use)
ALTER TABLE user_focus_preferences ADD COLUMN IF NOT EXISTS notes TEXT;
COMMENT ON TABLE user_focus_preferences IS 'User-specific focus area weightings (legacy flat structure + new references)';
-- ============================================================================
-- Part 3: Seed Data - Basis Focus Areas
-- ============================================================================
INSERT INTO focus_area_definitions (key, name_de, name_en, icon, category, description) VALUES
-- Body Composition
('weight_loss', 'Gewichtsverlust', 'Weight Loss', '📉', 'body_composition', 'Körpergewicht reduzieren'),
('muscle_gain', 'Muskelaufbau', 'Muscle Gain', '💪', 'body_composition', 'Muskelmasse aufbauen'),
('body_recomposition', 'Body Recomposition', 'Body Recomposition', '⚖️', 'body_composition', 'Gleichzeitig Fett abbauen und Muskeln aufbauen'),
-- Training - Kraft
('strength', 'Maximalkraft', 'Strength', '🏋️', 'training', 'Maximale Kraftfähigkeit'),
('strength_endurance', 'Kraftausdauer', 'Strength Endurance', '💪🏃', 'training', 'Kraft über längere Zeit aufrechterhalten'),
('power', 'Schnellkraft', 'Power', '⚡', 'training', 'Kraft in kurzer Zeit entfalten'),
-- Training - Beweglichkeit
('flexibility', 'Beweglichkeit', 'Flexibility', '🤸', 'training', 'Gelenkigkeit und Bewegungsumfang'),
('mobility', 'Mobilität', 'Mobility', '🦴', 'training', 'Aktive Beweglichkeit und Kontrolle'),
-- Ausdauer
('aerobic_endurance', 'Aerobe Ausdauer', 'Aerobic Endurance', '🫁', 'endurance', 'VO2Max, lange moderate Belastung'),
('anaerobic_endurance', 'Anaerobe Ausdauer', 'Anaerobic Endurance', '⚡', 'endurance', 'Laktattoleranz, kurze intensive Belastung'),
('cardiovascular_health', 'Herz-Kreislauf', 'Cardiovascular Health', '❤️', 'endurance', 'Herzgesundheit und Ausdauer'),
-- Koordination
('balance', 'Gleichgewicht', 'Balance', '⚖️', 'coordination', 'Statisches und dynamisches Gleichgewicht'),
('reaction', 'Reaktionsfähigkeit', 'Reaction', '⚡', 'coordination', 'Schnelligkeit der Reaktion auf Reize'),
('rhythm', 'Rhythmusgefühl', 'Rhythm', '🎵', 'coordination', 'Zeitliche Abstimmung von Bewegungen'),
('coordination', 'Koordination', 'Coordination', '🎯', 'coordination', 'Zusammenspiel verschiedener Bewegungen'),
-- Mental
('stress_resistance', 'Stressresistenz', 'Stress Resistance', '🧘', 'mental', 'Umgang mit mentalem und physischem Stress'),
('concentration', 'Konzentration', 'Concentration', '🎯', 'mental', 'Fokussierung und Aufmerksamkeit'),
('willpower', 'Willenskraft', 'Willpower', '💎', 'mental', 'Durchhaltevermögen und Selbstdisziplin'),
('mental_health', 'Mentale Gesundheit', 'Mental Health', '🧠', 'mental', 'Psychisches Wohlbefinden'),
-- Recovery
('sleep_quality', 'Schlafqualität', 'Sleep Quality', '😴', 'recovery', 'Erholsamer Schlaf'),
('regeneration', 'Regeneration', 'Regeneration', '♻️', 'recovery', 'Körperliche Erholung'),
('rest', 'Ruhe', 'Rest', '🛌', 'recovery', 'Aktive und passive Erholung'),
-- Health
('metabolic_health', 'Stoffwechselgesundheit', 'Metabolic Health', '🔥', 'health', 'Blutzucker, Insulin, Stoffwechsel'),
('blood_pressure', 'Blutdruck', 'Blood Pressure', '❤️‍🩹', 'health', 'Gesunder Blutdruck'),
('hrv', 'Herzratenvariabilität', 'HRV', '💓', 'health', 'Autonomes Nervensystem'),
('general_health', 'Allgemeine Gesundheit', 'General Health', '🏥', 'health', 'Vitale Gesundheit und Wohlbefinden')
ON CONFLICT (key) DO NOTHING;
-- ============================================================================
-- Part 4: Auto-Mapping - Bestehende Goals zu Focus Areas
-- ============================================================================
-- Helper function to get focus_area_id by key
CREATE OR REPLACE FUNCTION get_focus_area_id(area_key VARCHAR)
RETURNS UUID AS $$
BEGIN
RETURN (SELECT id FROM focus_area_definitions WHERE key = area_key LIMIT 1);
END;
$$ LANGUAGE plpgsql;
-- Weight goals → weight_loss (100%)
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
SELECT g.id, get_focus_area_id('weight_loss'), 100.00
FROM goals g
WHERE g.goal_type = 'weight'
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
-- Body Fat goals → weight_loss (60%) + body_recomposition (40%)
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
SELECT g.id, fa.id,
CASE fa.key
WHEN 'weight_loss' THEN 60.00
WHEN 'body_recomposition' THEN 40.00
END
FROM goals g
CROSS JOIN focus_area_definitions fa
WHERE g.goal_type = 'body_fat'
AND fa.key IN ('weight_loss', 'body_recomposition')
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
-- Lean Mass goals → muscle_gain (70%) + body_recomposition (30%)
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
SELECT g.id, fa.id,
CASE fa.key
WHEN 'muscle_gain' THEN 70.00
WHEN 'body_recomposition' THEN 30.00
END
FROM goals g
CROSS JOIN focus_area_definitions fa
WHERE g.goal_type = 'lean_mass'
AND fa.key IN ('muscle_gain', 'body_recomposition')
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
-- Strength goals → strength (70%) + muscle_gain (30%)
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
SELECT g.id, fa.id,
CASE fa.key
WHEN 'strength' THEN 70.00
WHEN 'muscle_gain' THEN 30.00
END
FROM goals g
CROSS JOIN focus_area_definitions fa
WHERE g.goal_type = 'strength'
AND fa.key IN ('strength', 'muscle_gain')
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
-- Flexibility goals → flexibility (100%)
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
SELECT g.id, get_focus_area_id('flexibility'), 100.00
FROM goals g
WHERE g.goal_type = 'flexibility'
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
-- VO2Max goals → aerobic_endurance (80%) + cardiovascular_health (20%)
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
SELECT g.id, fa.id,
CASE fa.key
WHEN 'aerobic_endurance' THEN 80.00
WHEN 'cardiovascular_health' THEN 20.00
END
FROM goals g
CROSS JOIN focus_area_definitions fa
WHERE g.goal_type = 'vo2max'
AND fa.key IN ('aerobic_endurance', 'cardiovascular_health')
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
-- Resting Heart Rate goals → cardiovascular_health (100%)
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
SELECT g.id, get_focus_area_id('cardiovascular_health'), 100.00
FROM goals g
WHERE g.goal_type = 'rhr'
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
-- Blood Pressure goals → blood_pressure (80%) + cardiovascular_health (20%)
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
SELECT g.id, fa.id,
CASE fa.key
WHEN 'blood_pressure' THEN 80.00
WHEN 'cardiovascular_health' THEN 20.00
END
FROM goals g
CROSS JOIN focus_area_definitions fa
WHERE g.goal_type = 'bp'
AND fa.key IN ('blood_pressure', 'cardiovascular_health')
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
-- HRV goals → hrv (70%) + stress_resistance (30%)
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
SELECT g.id, fa.id,
CASE fa.key
WHEN 'hrv' THEN 70.00
WHEN 'stress_resistance' THEN 30.00
END
FROM goals g
CROSS JOIN focus_area_definitions fa
WHERE g.goal_type = 'hrv'
AND fa.key IN ('hrv', 'stress_resistance')
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
-- Sleep Quality goals → sleep_quality (100%)
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
SELECT g.id, get_focus_area_id('sleep_quality'), 100.00
FROM goals g
WHERE g.goal_type = 'sleep_quality'
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
-- Training Frequency goals → general catch-all (strength + endurance)
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
SELECT g.id, fa.id,
CASE fa.key
WHEN 'strength' THEN 40.00
WHEN 'aerobic_endurance' THEN 40.00
WHEN 'general_health' THEN 20.00
END
FROM goals g
CROSS JOIN focus_area_definitions fa
WHERE g.goal_type = 'training_frequency'
AND fa.key IN ('strength', 'aerobic_endurance', 'general_health')
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
-- Cleanup helper function
DROP FUNCTION IF EXISTS get_focus_area_id(VARCHAR);
-- ============================================================================
-- Summary
-- ============================================================================
COMMENT ON TABLE focus_area_definitions IS
'v2.0: Dynamic focus areas - replaces hardcoded 6-dimension system.
26 base areas across 7 categories. User-extensible via admin UI.';
COMMENT ON TABLE goal_focus_contributions IS
'Many-to-Many mapping: Goals contribute to multiple focus areas with weights.
Auto-mapped from goal_type, editable by user.';
COMMENT ON TABLE user_focus_preferences IS
'Legacy flat structure (weight_loss_pct, muscle_gain_pct, etc.) remains for backward compatibility.
Future: Use focus_area_definitions + dynamic preferences.';
@@ -0,0 +1,53 @@
-- Migration 032: User Focus Area Weights
-- Date: 2026-03-27
-- Purpose: Allow users to set custom weights for focus areas (dynamic preferences)
-- ============================================================================
-- User Focus Area Weights (many-to-many with weights)
-- ============================================================================
CREATE TABLE IF NOT EXISTS user_focus_area_weights (
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
focus_area_id UUID NOT NULL REFERENCES focus_area_definitions(id) ON DELETE CASCADE,
weight INTEGER NOT NULL DEFAULT 0 CHECK (weight >= 0 AND weight <= 100),
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
PRIMARY KEY (profile_id, focus_area_id)
);
CREATE INDEX idx_user_focus_weights_profile ON user_focus_area_weights(profile_id);
CREATE INDEX idx_user_focus_weights_area ON user_focus_area_weights(focus_area_id);
COMMENT ON TABLE user_focus_area_weights IS 'User-specific weights for focus areas (dynamic system)';
COMMENT ON COLUMN user_focus_area_weights.weight IS 'Relative weight (0-100) - will be normalized to percentages in UI';
-- ============================================================================
-- Migrate legacy preferences to dynamic weights
-- ============================================================================
-- For each user with legacy preferences, create weights for the 6 base areas
INSERT INTO user_focus_area_weights (profile_id, focus_area_id, weight)
SELECT
ufp.profile_id,
fad.id as focus_area_id,
CASE fad.key
WHEN 'weight_loss' THEN ufp.weight_loss_pct
WHEN 'muscle_gain' THEN ufp.muscle_gain_pct
WHEN 'strength' THEN ufp.strength_pct
WHEN 'aerobic_endurance' THEN ufp.endurance_pct
WHEN 'flexibility' THEN ufp.flexibility_pct
WHEN 'general_health' THEN ufp.health_pct
ELSE 0
END as weight
FROM user_focus_preferences ufp
CROSS JOIN focus_area_definitions fad
WHERE fad.key IN ('weight_loss', 'muscle_gain', 'strength', 'aerobic_endurance', 'flexibility', 'general_health')
AND (
(fad.key = 'weight_loss' AND ufp.weight_loss_pct > 0) OR
(fad.key = 'muscle_gain' AND ufp.muscle_gain_pct > 0) OR
(fad.key = 'strength' AND ufp.strength_pct > 0) OR
(fad.key = 'aerobic_endurance' AND ufp.endurance_pct > 0) OR
(fad.key = 'flexibility' AND ufp.flexibility_pct > 0) OR
(fad.key = 'general_health' AND ufp.health_pct > 0)
)
ON CONFLICT (profile_id, focus_area_id) DO NOTHING;
+392
View File
@@ -464,6 +464,254 @@ def get_vitals_vo2_max(profile_id: str) -> str:
return "nicht verfügbar" return "nicht verfügbar"
# ── Phase 0b Calculation Engine Integration ──────────────────────────────────
def _safe_int(func_name: str, profile_id: str) -> str:
"""
Safely call calculation function and return integer value or fallback.
Args:
func_name: Name of the calculation function (e.g., 'goal_progress_score')
profile_id: Profile ID
Returns:
String representation of integer value or 'nicht verfügbar'
"""
import traceback
try:
# Import calculations dynamically to avoid circular imports
from calculations import scores, body_metrics, nutrition_metrics, activity_metrics, recovery_metrics, correlation_metrics
# Map function names to actual functions
func_map = {
'goal_progress_score': scores.calculate_goal_progress_score,
'body_progress_score': body_metrics.calculate_body_progress_score,
'nutrition_score': nutrition_metrics.calculate_nutrition_score,
'activity_score': activity_metrics.calculate_activity_score,
'recovery_score_v2': recovery_metrics.calculate_recovery_score_v2,
'data_quality_score': scores.calculate_data_quality_score,
'top_goal_progress_pct': lambda pid: scores.get_top_priority_goal(pid)['progress_pct'] if scores.get_top_priority_goal(pid) else None,
'top_focus_area_progress': lambda pid: scores.get_top_focus_area(pid)['progress'] if scores.get_top_focus_area(pid) else None,
'focus_cat_körper_progress': lambda pid: scores.calculate_category_progress(pid, 'körper'),
'focus_cat_ernährung_progress': lambda pid: scores.calculate_category_progress(pid, 'ernährung'),
'focus_cat_aktivität_progress': lambda pid: scores.calculate_category_progress(pid, 'aktivität'),
'focus_cat_recovery_progress': lambda pid: scores.calculate_category_progress(pid, 'recovery'),
'focus_cat_vitalwerte_progress': lambda pid: scores.calculate_category_progress(pid, 'vitalwerte'),
'focus_cat_mental_progress': lambda pid: scores.calculate_category_progress(pid, 'mental'),
'focus_cat_lebensstil_progress': lambda pid: scores.calculate_category_progress(pid, 'lebensstil'),
'training_minutes_week': activity_metrics.calculate_training_minutes_week,
'training_frequency_7d': activity_metrics.calculate_training_frequency_7d,
'quality_sessions_pct': activity_metrics.calculate_quality_sessions_pct,
'ability_balance_strength': activity_metrics.calculate_ability_balance_strength,
'ability_balance_endurance': activity_metrics.calculate_ability_balance_endurance,
'ability_balance_mental': activity_metrics.calculate_ability_balance_mental,
'ability_balance_coordination': activity_metrics.calculate_ability_balance_coordination,
'ability_balance_mobility': activity_metrics.calculate_ability_balance_mobility,
'proxy_internal_load_7d': activity_metrics.calculate_proxy_internal_load_7d,
'strain_score': activity_metrics.calculate_strain_score,
'rest_day_compliance': activity_metrics.calculate_rest_day_compliance,
'protein_adequacy_28d': nutrition_metrics.calculate_protein_adequacy_28d,
'macro_consistency_score': nutrition_metrics.calculate_macro_consistency_score,
'recent_load_balance_3d': recovery_metrics.calculate_recent_load_balance_3d,
'sleep_quality_7d': recovery_metrics.calculate_sleep_quality_7d,
}
func = func_map.get(func_name)
if not func:
return 'nicht verfügbar'
result = func(profile_id)
return str(int(result)) if result is not None else 'nicht verfügbar'
except Exception as e:
print(f"[ERROR] _safe_int({func_name}, {profile_id}): {type(e).__name__}: {e}")
traceback.print_exc()
return 'nicht verfügbar'
def _safe_float(func_name: str, profile_id: str, decimals: int = 1) -> str:
"""
Safely call calculation function and return float value or fallback.
Args:
func_name: Name of the calculation function
profile_id: Profile ID
decimals: Number of decimal places
Returns:
String representation of float value or 'nicht verfügbar'
"""
import traceback
try:
from calculations import body_metrics, nutrition_metrics, activity_metrics, recovery_metrics, scores
func_map = {
'weight_7d_median': body_metrics.calculate_weight_7d_median,
'weight_28d_slope': body_metrics.calculate_weight_28d_slope,
'weight_90d_slope': body_metrics.calculate_weight_90d_slope,
'fm_28d_change': body_metrics.calculate_fm_28d_change,
'lbm_28d_change': body_metrics.calculate_lbm_28d_change,
'waist_28d_delta': body_metrics.calculate_waist_28d_delta,
'hip_28d_delta': body_metrics.calculate_hip_28d_delta,
'chest_28d_delta': body_metrics.calculate_chest_28d_delta,
'arm_28d_delta': body_metrics.calculate_arm_28d_delta,
'thigh_28d_delta': body_metrics.calculate_thigh_28d_delta,
'waist_hip_ratio': body_metrics.calculate_waist_hip_ratio,
'energy_balance_7d': nutrition_metrics.calculate_energy_balance_7d,
'protein_g_per_kg': nutrition_metrics.calculate_protein_g_per_kg,
'monotony_score': activity_metrics.calculate_monotony_score,
'vo2max_trend_28d': activity_metrics.calculate_vo2max_trend_28d,
'hrv_vs_baseline_pct': recovery_metrics.calculate_hrv_vs_baseline_pct,
'rhr_vs_baseline_pct': recovery_metrics.calculate_rhr_vs_baseline_pct,
'sleep_avg_duration_7d': recovery_metrics.calculate_sleep_avg_duration_7d,
'sleep_debt_hours': recovery_metrics.calculate_sleep_debt_hours,
'sleep_regularity_proxy': recovery_metrics.calculate_sleep_regularity_proxy,
'focus_cat_körper_weight': lambda pid: scores.calculate_category_weight(pid, 'körper'),
'focus_cat_ernährung_weight': lambda pid: scores.calculate_category_weight(pid, 'ernährung'),
'focus_cat_aktivität_weight': lambda pid: scores.calculate_category_weight(pid, 'aktivität'),
'focus_cat_recovery_weight': lambda pid: scores.calculate_category_weight(pid, 'recovery'),
'focus_cat_vitalwerte_weight': lambda pid: scores.calculate_category_weight(pid, 'vitalwerte'),
'focus_cat_mental_weight': lambda pid: scores.calculate_category_weight(pid, 'mental'),
'focus_cat_lebensstil_weight': lambda pid: scores.calculate_category_weight(pid, 'lebensstil'),
}
func = func_map.get(func_name)
if not func:
return 'nicht verfügbar'
result = func(profile_id)
return f"{result:.{decimals}f}" if result is not None else 'nicht verfügbar'
except Exception as e:
print(f"[ERROR] _safe_float({func_name}, {profile_id}): {type(e).__name__}: {e}")
traceback.print_exc()
return 'nicht verfügbar'
def _safe_str(func_name: str, profile_id: str) -> str:
"""
Safely call calculation function and return string value or fallback.
"""
import traceback
try:
from calculations import body_metrics, nutrition_metrics, activity_metrics, scores, correlation_metrics
func_map = {
'top_goal_name': lambda pid: (scores.get_top_priority_goal(pid).get('name') or scores.get_top_priority_goal(pid).get('goal_type')) if scores.get_top_priority_goal(pid) else None,
'top_goal_status': lambda pid: scores.get_top_priority_goal(pid)['status'] if scores.get_top_priority_goal(pid) else None,
'top_focus_area_name': lambda pid: scores.get_top_focus_area(pid)['label'] if scores.get_top_focus_area(pid) else None,
'recomposition_quadrant': body_metrics.calculate_recomposition_quadrant,
'energy_deficit_surplus': nutrition_metrics.calculate_energy_deficit_surplus,
'protein_days_in_target': nutrition_metrics.calculate_protein_days_in_target,
'intake_volatility': nutrition_metrics.calculate_intake_volatility,
'active_goals_md': lambda pid: _format_goals_as_markdown(pid),
'focus_areas_weighted_md': lambda pid: _format_focus_areas_as_markdown(pid),
'top_3_focus_areas': lambda pid: _format_top_focus_areas(pid),
'top_3_goals_behind_schedule': lambda pid: _format_goals_behind(pid),
'top_3_goals_on_track': lambda pid: _format_goals_on_track(pid),
}
func = func_map.get(func_name)
if not func:
return 'nicht verfügbar'
result = func(profile_id)
return str(result) if result is not None else 'nicht verfügbar'
except Exception as e:
print(f"[ERROR] _safe_str({func_name}, {profile_id}): {type(e).__name__}: {e}")
traceback.print_exc()
return 'nicht verfügbar'
def _safe_json(func_name: str, profile_id: str) -> str:
"""
Safely call calculation function and return JSON string or fallback.
"""
import traceback
try:
import json
from calculations import scores, correlation_metrics
func_map = {
'correlation_energy_weight_lag': lambda pid: correlation_metrics.calculate_lag_correlation(pid, 'energy', 'weight'),
'correlation_protein_lbm': lambda pid: correlation_metrics.calculate_lag_correlation(pid, 'protein', 'lbm'),
'correlation_load_hrv': lambda pid: correlation_metrics.calculate_lag_correlation(pid, 'training_load', 'hrv'),
'correlation_load_rhr': lambda pid: correlation_metrics.calculate_lag_correlation(pid, 'training_load', 'rhr'),
'correlation_sleep_recovery': correlation_metrics.calculate_correlation_sleep_recovery,
'plateau_detected': correlation_metrics.calculate_plateau_detected,
'top_drivers': correlation_metrics.calculate_top_drivers,
'active_goals_json': lambda pid: _get_active_goals_json(pid),
'focus_areas_weighted_json': lambda pid: _get_focus_areas_weighted_json(pid),
'focus_area_weights_json': lambda pid: json.dumps(scores.get_user_focus_weights(pid), ensure_ascii=False),
}
func = func_map.get(func_name)
if not func:
return '{}'
result = func(profile_id)
if result is None:
return '{}'
# If already string, return it; otherwise convert to JSON
if isinstance(result, str):
return result
else:
return json.dumps(result, ensure_ascii=False)
except Exception as e:
print(f"[ERROR] _safe_json({func_name}, {profile_id}): {type(e).__name__}: {e}")
traceback.print_exc()
return '{}'
def _get_active_goals_json(profile_id: str) -> str:
"""Get active goals as JSON string"""
import json
try:
# TODO: Implement after goal_utils extensions
return '[]'
except Exception:
return '[]'
def _get_focus_areas_weighted_json(profile_id: str) -> str:
"""Get focus areas with weights as JSON string"""
import json
try:
# TODO: Implement after goal_utils extensions
return '[]'
except Exception:
return '[]'
def _format_goals_as_markdown(profile_id: str) -> str:
"""Format goals as markdown table"""
# TODO: Implement
return 'Keine Ziele definiert'
def _format_focus_areas_as_markdown(profile_id: str) -> str:
"""Format focus areas as markdown"""
# TODO: Implement
return 'Keine Focus Areas aktiv'
def _format_top_focus_areas(profile_id: str, n: int = 3) -> str:
"""Format top N focus areas as text"""
# TODO: Implement
return 'nicht verfügbar'
def _format_goals_behind(profile_id: str, n: int = 3) -> str:
"""Format top N goals behind schedule"""
# TODO: Implement
return 'nicht verfügbar'
def _format_goals_on_track(profile_id: str, n: int = 3) -> str:
"""Format top N goals on track"""
# TODO: Implement
return 'nicht verfügbar'
# ── Placeholder Registry ────────────────────────────────────────────────────── # ── Placeholder Registry ──────────────────────────────────────────────────────
PLACEHOLDER_MAP: Dict[str, Callable[[str], str]] = { PLACEHOLDER_MAP: Dict[str, Callable[[str], str]] = {
@@ -512,6 +760,107 @@ PLACEHOLDER_MAP: Dict[str, Callable[[str], str]] = {
'{{zeitraum_7d}}': lambda pid: 'letzte 7 Tage', '{{zeitraum_7d}}': lambda pid: 'letzte 7 Tage',
'{{zeitraum_30d}}': lambda pid: 'letzte 30 Tage', '{{zeitraum_30d}}': lambda pid: 'letzte 30 Tage',
'{{zeitraum_90d}}': lambda pid: 'letzte 90 Tage', '{{zeitraum_90d}}': lambda pid: 'letzte 90 Tage',
# ========================================================================
# PHASE 0b: Goal-Aware Placeholders (Dynamic Focus Areas v2.0)
# ========================================================================
# --- Meta Scores (Ebene 1: Aggregierte Scores) ---
'{{goal_progress_score}}': lambda pid: _safe_int('goal_progress_score', pid),
'{{body_progress_score}}': lambda pid: _safe_int('body_progress_score', pid),
'{{nutrition_score}}': lambda pid: _safe_int('nutrition_score', pid),
'{{activity_score}}': lambda pid: _safe_int('activity_score', pid),
'{{recovery_score}}': lambda pid: _safe_int('recovery_score_v2', pid),
'{{data_quality_score}}': lambda pid: _safe_int('data_quality_score', pid),
# --- Top-Weighted Goals/Focus Areas (Ebene 2: statt Primary) ---
'{{top_goal_name}}': lambda pid: _safe_str('top_goal_name', pid),
'{{top_goal_progress_pct}}': lambda pid: _safe_str('top_goal_progress_pct', pid),
'{{top_goal_status}}': lambda pid: _safe_str('top_goal_status', pid),
'{{top_focus_area_name}}': lambda pid: _safe_str('top_focus_area_name', pid),
'{{top_focus_area_progress}}': lambda pid: _safe_int('top_focus_area_progress', pid),
# --- Category Scores (Ebene 3: 7 Kategorien) ---
'{{focus_cat_körper_progress}}': lambda pid: _safe_int('focus_cat_körper_progress', pid),
'{{focus_cat_körper_weight}}': lambda pid: _safe_float('focus_cat_körper_weight', pid),
'{{focus_cat_ernährung_progress}}': lambda pid: _safe_int('focus_cat_ernährung_progress', pid),
'{{focus_cat_ernährung_weight}}': lambda pid: _safe_float('focus_cat_ernährung_weight', pid),
'{{focus_cat_aktivität_progress}}': lambda pid: _safe_int('focus_cat_aktivität_progress', pid),
'{{focus_cat_aktivität_weight}}': lambda pid: _safe_float('focus_cat_aktivität_weight', pid),
'{{focus_cat_recovery_progress}}': lambda pid: _safe_int('focus_cat_recovery_progress', pid),
'{{focus_cat_recovery_weight}}': lambda pid: _safe_float('focus_cat_recovery_weight', pid),
'{{focus_cat_vitalwerte_progress}}': lambda pid: _safe_int('focus_cat_vitalwerte_progress', pid),
'{{focus_cat_vitalwerte_weight}}': lambda pid: _safe_float('focus_cat_vitalwerte_weight', pid),
'{{focus_cat_mental_progress}}': lambda pid: _safe_int('focus_cat_mental_progress', pid),
'{{focus_cat_mental_weight}}': lambda pid: _safe_float('focus_cat_mental_weight', pid),
'{{focus_cat_lebensstil_progress}}': lambda pid: _safe_int('focus_cat_lebensstil_progress', pid),
'{{focus_cat_lebensstil_weight}}': lambda pid: _safe_float('focus_cat_lebensstil_weight', pid),
# --- Body Metrics (Ebene 4: Einzelmetriken K1-K5) ---
'{{weight_7d_median}}': lambda pid: _safe_float('weight_7d_median', pid),
'{{weight_28d_slope}}': lambda pid: _safe_float('weight_28d_slope', pid, decimals=4),
'{{weight_90d_slope}}': lambda pid: _safe_float('weight_90d_slope', pid, decimals=4),
'{{fm_28d_change}}': lambda pid: _safe_float('fm_28d_change', pid),
'{{lbm_28d_change}}': lambda pid: _safe_float('lbm_28d_change', pid),
'{{waist_28d_delta}}': lambda pid: _safe_float('waist_28d_delta', pid),
'{{hip_28d_delta}}': lambda pid: _safe_float('hip_28d_delta', pid),
'{{chest_28d_delta}}': lambda pid: _safe_float('chest_28d_delta', pid),
'{{arm_28d_delta}}': lambda pid: _safe_float('arm_28d_delta', pid),
'{{thigh_28d_delta}}': lambda pid: _safe_float('thigh_28d_delta', pid),
'{{waist_hip_ratio}}': lambda pid: _safe_float('waist_hip_ratio', pid, decimals=3),
'{{recomposition_quadrant}}': lambda pid: _safe_str('recomposition_quadrant', pid),
# --- Nutrition Metrics (E1-E5) ---
'{{energy_balance_7d}}': lambda pid: _safe_float('energy_balance_7d', pid, decimals=0),
'{{energy_deficit_surplus}}': lambda pid: _safe_str('energy_deficit_surplus', pid),
'{{protein_g_per_kg}}': lambda pid: _safe_float('protein_g_per_kg', pid),
'{{protein_days_in_target}}': lambda pid: _safe_str('protein_days_in_target', pid),
'{{protein_adequacy_28d}}': lambda pid: _safe_int('protein_adequacy_28d', pid),
'{{macro_consistency_score}}': lambda pid: _safe_int('macro_consistency_score', pid),
'{{intake_volatility}}': lambda pid: _safe_str('intake_volatility', pid),
# --- Activity Metrics (A1-A8) ---
'{{training_minutes_week}}': lambda pid: _safe_int('training_minutes_week', pid),
'{{training_frequency_7d}}': lambda pid: _safe_int('training_frequency_7d', pid),
'{{quality_sessions_pct}}': lambda pid: _safe_int('quality_sessions_pct', pid),
'{{ability_balance_strength}}': lambda pid: _safe_int('ability_balance_strength', pid),
'{{ability_balance_endurance}}': lambda pid: _safe_int('ability_balance_endurance', pid),
'{{ability_balance_mental}}': lambda pid: _safe_int('ability_balance_mental', pid),
'{{ability_balance_coordination}}': lambda pid: _safe_int('ability_balance_coordination', pid),
'{{ability_balance_mobility}}': lambda pid: _safe_int('ability_balance_mobility', pid),
'{{proxy_internal_load_7d}}': lambda pid: _safe_int('proxy_internal_load_7d', pid),
'{{monotony_score}}': lambda pid: _safe_float('monotony_score', pid),
'{{strain_score}}': lambda pid: _safe_int('strain_score', pid),
'{{rest_day_compliance}}': lambda pid: _safe_int('rest_day_compliance', pid),
'{{vo2max_trend_28d}}': lambda pid: _safe_float('vo2max_trend_28d', pid),
# --- Recovery Metrics (Recovery Score v2) ---
'{{hrv_vs_baseline_pct}}': lambda pid: _safe_float('hrv_vs_baseline_pct', pid),
'{{rhr_vs_baseline_pct}}': lambda pid: _safe_float('rhr_vs_baseline_pct', pid),
'{{sleep_avg_duration_7d}}': lambda pid: _safe_float('sleep_avg_duration_7d', pid),
'{{sleep_debt_hours}}': lambda pid: _safe_float('sleep_debt_hours', pid),
'{{sleep_regularity_proxy}}': lambda pid: _safe_float('sleep_regularity_proxy', pid),
'{{recent_load_balance_3d}}': lambda pid: _safe_int('recent_load_balance_3d', pid),
'{{sleep_quality_7d}}': lambda pid: _safe_int('sleep_quality_7d', pid),
# --- Correlation Metrics (C1-C7) ---
'{{correlation_energy_weight_lag}}': lambda pid: _safe_json('correlation_energy_weight_lag', pid),
'{{correlation_protein_lbm}}': lambda pid: _safe_json('correlation_protein_lbm', pid),
'{{correlation_load_hrv}}': lambda pid: _safe_json('correlation_load_hrv', pid),
'{{correlation_load_rhr}}': lambda pid: _safe_json('correlation_load_rhr', pid),
'{{correlation_sleep_recovery}}': lambda pid: _safe_json('correlation_sleep_recovery', pid),
'{{plateau_detected}}': lambda pid: _safe_json('plateau_detected', pid),
'{{top_drivers}}': lambda pid: _safe_json('top_drivers', pid),
# --- JSON/Markdown Structured Data (Ebene 5) ---
'{{active_goals_json}}': lambda pid: _safe_json('active_goals_json', pid),
'{{active_goals_md}}': lambda pid: _safe_str('active_goals_md', pid),
'{{focus_areas_weighted_json}}': lambda pid: _safe_json('focus_areas_weighted_json', pid),
'{{focus_areas_weighted_md}}': lambda pid: _safe_str('focus_areas_weighted_md', pid),
'{{focus_area_weights_json}}': lambda pid: _safe_json('focus_area_weights_json', pid),
'{{top_3_focus_areas}}': lambda pid: _safe_str('top_3_focus_areas', pid),
'{{top_3_goals_behind_schedule}}': lambda pid: _safe_str('top_3_goals_behind_schedule', pid),
'{{top_3_goals_on_track}}': lambda pid: _safe_str('top_3_goals_on_track', pid),
} }
@@ -662,26 +1011,69 @@ def get_placeholder_catalog(profile_id: str) -> Dict[str, List[Dict[str, str]]]:
('weight_trend', 'Gewichtstrend (7d/30d)'), ('weight_trend', 'Gewichtstrend (7d/30d)'),
('kf_aktuell', 'Aktueller Körperfettanteil in %'), ('kf_aktuell', 'Aktueller Körperfettanteil in %'),
('bmi', 'Body Mass Index'), ('bmi', 'Body Mass Index'),
('weight_7d_median', 'Gewicht 7d Median (kg)'),
('weight_28d_slope', 'Gewichtstrend 28d (kg/Tag)'),
('fm_28d_change', 'Fettmasse Änderung 28d (kg)'),
('lbm_28d_change', 'Magermasse Änderung 28d (kg)'),
('waist_28d_delta', 'Taillenumfang Änderung 28d (cm)'),
('waist_hip_ratio', 'Taille/Hüfte-Verhältnis'),
('recomposition_quadrant', 'Rekomposition-Status'),
], ],
'Ernährung': [ 'Ernährung': [
('kcal_avg', 'Durchschn. Kalorien (30d)'), ('kcal_avg', 'Durchschn. Kalorien (30d)'),
('protein_avg', 'Durchschn. Protein in g (30d)'), ('protein_avg', 'Durchschn. Protein in g (30d)'),
('carb_avg', 'Durchschn. Kohlenhydrate in g (30d)'), ('carb_avg', 'Durchschn. Kohlenhydrate in g (30d)'),
('fat_avg', 'Durchschn. Fett in g (30d)'), ('fat_avg', 'Durchschn. Fett in g (30d)'),
('energy_balance_7d', 'Energiebilanz 7d (kcal/Tag)'),
('protein_g_per_kg', 'Protein g/kg Körpergewicht'),
('protein_adequacy_28d', 'Protein Adequacy Score (0-100)'),
('macro_consistency_score', 'Makro-Konsistenz Score (0-100)'),
], ],
'Training': [ 'Training': [
('activity_summary', 'Aktivitäts-Zusammenfassung (7d)'), ('activity_summary', 'Aktivitäts-Zusammenfassung (7d)'),
('trainingstyp_verteilung', 'Verteilung nach Trainingstypen'), ('trainingstyp_verteilung', 'Verteilung nach Trainingstypen'),
('training_minutes_week', 'Trainingsminuten pro Woche'),
('training_frequency_7d', 'Trainingshäufigkeit 7d'),
('quality_sessions_pct', 'Qualitätssessions (%)'),
('ability_balance_strength', 'Ability Balance - Kraft (0-100)'),
('ability_balance_endurance', 'Ability Balance - Ausdauer (0-100)'),
('proxy_internal_load_7d', 'Proxy Load 7d'),
('rest_day_compliance', 'Ruhetags-Compliance (%)'),
], ],
'Schlaf & Erholung': [ 'Schlaf & Erholung': [
('sleep_avg_duration', 'Durchschn. Schlafdauer (7d)'), ('sleep_avg_duration', 'Durchschn. Schlafdauer (7d)'),
('sleep_avg_quality', 'Durchschn. Schlafqualität (7d)'), ('sleep_avg_quality', 'Durchschn. Schlafqualität (7d)'),
('rest_days_count', 'Anzahl Ruhetage (30d)'), ('rest_days_count', 'Anzahl Ruhetage (30d)'),
('sleep_avg_duration_7d', 'Schlaf 7d (Stunden)'),
('sleep_debt_hours', 'Schlafschuld (Stunden)'),
('sleep_regularity_proxy', 'Schlaf-Regelmäßigkeit (Min Abweichung)'),
('sleep_quality_7d', 'Schlafqualität 7d (0-100)'),
], ],
'Vitalwerte': [ 'Vitalwerte': [
('vitals_avg_hr', 'Durchschn. Ruhepuls (7d)'), ('vitals_avg_hr', 'Durchschn. Ruhepuls (7d)'),
('vitals_avg_hrv', 'Durchschn. HRV (7d)'), ('vitals_avg_hrv', 'Durchschn. HRV (7d)'),
('vitals_vo2_max', 'Aktueller VO2 Max'), ('vitals_vo2_max', 'Aktueller VO2 Max'),
('hrv_vs_baseline_pct', 'HRV vs. Baseline (%)'),
('rhr_vs_baseline_pct', 'RHR vs. Baseline (%)'),
('vo2max_trend_28d', 'VO2max Trend 28d'),
],
'Scores (Phase 0b)': [
('goal_progress_score', 'Goal Progress Score (0-100)'),
('body_progress_score', 'Body Progress Score (0-100)'),
('nutrition_score', 'Nutrition Score (0-100)'),
('activity_score', 'Activity Score (0-100)'),
('recovery_score', 'Recovery Score (0-100)'),
('data_quality_score', 'Data Quality Score (0-100)'),
],
'Focus Areas': [
('top_focus_area_name', 'Top Focus Area Name'),
('top_focus_area_progress', 'Top Focus Area Progress (%)'),
('focus_cat_körper_progress', 'Kategorie Körper - Progress (%)'),
('focus_cat_körper_weight', 'Kategorie Körper - Gewichtung (%)'),
('focus_cat_ernährung_progress', 'Kategorie Ernährung - Progress (%)'),
('focus_cat_ernährung_weight', 'Kategorie Ernährung - Gewichtung (%)'),
('focus_cat_aktivität_progress', 'Kategorie Aktivität - Progress (%)'),
('focus_cat_aktivität_weight', 'Kategorie Aktivität - Gewichtung (%)'),
], ],
'Zeitraum': [ 'Zeitraum': [
('datum_heute', 'Heutiges Datum'), ('datum_heute', 'Heutiges Datum'),
+94
View File
@@ -0,0 +1,94 @@
"""
Fitness Tests Router - Fitness Test Recording & Norm Tracking
Endpoints for managing fitness tests:
- List fitness tests
- Record fitness test results
- Calculate norm categories
Part of v9h Goal System.
"""
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from typing import Optional
from datetime import date
from db import get_db, get_cursor, r2d
from auth import require_auth
router = APIRouter(prefix="/api/goals", tags=["fitness-tests"])
# ============================================================================
# Pydantic Models
# ============================================================================
class FitnessTestCreate(BaseModel):
"""Record fitness test result"""
test_type: str
result_value: float
result_unit: str
test_date: date
test_conditions: Optional[str] = None
# ============================================================================
# Endpoints
# ============================================================================
@router.get("/tests")
def list_fitness_tests(session: dict = Depends(require_auth)):
"""List all fitness tests"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT id, test_type, result_value, result_unit,
test_date, test_conditions, norm_category, created_at
FROM fitness_tests
WHERE profile_id = %s
ORDER BY test_date DESC
""", (pid,))
return [r2d(row) for row in cur.fetchall()]
@router.post("/tests")
def create_fitness_test(data: FitnessTestCreate, session: dict = Depends(require_auth)):
"""Record fitness test result"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
# Calculate norm category (simplified for now)
norm_category = _calculate_norm_category(
data.test_type,
data.result_value,
data.result_unit
)
cur.execute("""
INSERT INTO fitness_tests (
profile_id, test_type, result_value, result_unit,
test_date, test_conditions, norm_category
) VALUES (%s, %s, %s, %s, %s, %s, %s)
RETURNING id
""", (
pid, data.test_type, data.result_value, data.result_unit,
data.test_date, data.test_conditions, norm_category
))
test_id = cur.fetchone()['id']
return {"id": test_id, "norm_category": norm_category}
# ============================================================================
# Helper Functions
# ============================================================================
def _calculate_norm_category(test_type: str, value: float, unit: str) -> Optional[str]:
"""
Calculate norm category for fitness test
(Simplified - would need age/gender-specific norms)
"""
# Placeholder - should use proper norm tables
return None
+378
View File
@@ -0,0 +1,378 @@
"""
Focus Areas Router
Manages dynamic focus area definitions and user preferences
"""
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
from typing import Optional, List
from db import get_db, get_cursor, r2d
from auth import require_auth
router = APIRouter(prefix="/api/focus-areas", tags=["focus-areas"])
# ============================================================================
# Models
# ============================================================================
class FocusAreaCreate(BaseModel):
"""Create new focus area definition"""
key: str
name_de: str
name_en: Optional[str] = None
icon: Optional[str] = None
description: Optional[str] = None
category: str = 'custom'
class FocusAreaUpdate(BaseModel):
"""Update focus area definition"""
name_de: Optional[str] = None
name_en: Optional[str] = None
icon: Optional[str] = None
description: Optional[str] = None
category: Optional[str] = None
is_active: Optional[bool] = None
class UserFocusPreferences(BaseModel):
"""User's focus area weightings (dynamic)"""
preferences: dict # {focus_area_id: weight_pct}
# ============================================================================
# Focus Area Definitions (Admin)
# ============================================================================
@router.get("/definitions")
def list_focus_area_definitions(
session: dict = Depends(require_auth),
include_inactive: bool = False
):
"""
List all available focus area definitions.
Query params:
- include_inactive: Include inactive focus areas (default: false)
Returns focus areas grouped by category.
"""
with get_db() as conn:
cur = get_cursor(conn)
query = """
SELECT id, key, name_de, name_en, icon, description, category, is_active,
created_at, updated_at
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()]
# Group by category
grouped = {}
for area in areas:
cat = area['category'] or 'other'
if cat not in grouped:
grouped[cat] = []
grouped[cat].append(area)
return {
"areas": areas,
"grouped": grouped,
"total": len(areas)
}
@router.post("/definitions")
def create_focus_area_definition(
data: FocusAreaCreate,
session: dict = Depends(require_auth)
):
"""
Create new focus area definition (Admin only).
Note: Requires admin role.
"""
# Admin check
if session.get('role') != 'admin':
raise HTTPException(status_code=403, detail="Admin-Rechte erforderlich")
with get_db() as conn:
cur = get_cursor(conn)
# Check if key already exists
cur.execute(
"SELECT id FROM focus_area_definitions WHERE key = %s",
(data.key,)
)
if cur.fetchone():
raise HTTPException(
status_code=400,
detail=f"Focus Area mit Key '{data.key}' existiert bereits"
)
# Insert
cur.execute("""
INSERT INTO focus_area_definitions
(key, name_de, name_en, icon, description, category)
VALUES (%s, %s, %s, %s, %s, %s)
RETURNING id
""", (
data.key, data.name_de, data.name_en,
data.icon, data.description, data.category
))
area_id = cur.fetchone()['id']
return {
"id": area_id,
"message": f"Focus Area '{data.name_de}' erstellt"
}
@router.put("/definitions/{area_id}")
def update_focus_area_definition(
area_id: str,
data: FocusAreaUpdate,
session: dict = Depends(require_auth)
):
"""Update focus area definition (Admin only)"""
# Admin check
if session.get('role') != 'admin':
raise HTTPException(status_code=403, detail="Admin-Rechte erforderlich")
with get_db() as conn:
cur = get_cursor(conn)
# Build dynamic UPDATE
updates = []
values = []
if data.name_de is not None:
updates.append("name_de = %s")
values.append(data.name_de)
if data.name_en is not None:
updates.append("name_en = %s")
values.append(data.name_en)
if data.icon is not None:
updates.append("icon = %s")
values.append(data.icon)
if data.description is not None:
updates.append("description = %s")
values.append(data.description)
if data.category is not None:
updates.append("category = %s")
values.append(data.category)
if data.is_active is not None:
updates.append("is_active = %s")
values.append(data.is_active)
if not updates:
raise HTTPException(status_code=400, detail="Keine Änderungen angegeben")
updates.append("updated_at = NOW()")
values.append(area_id)
query = f"""
UPDATE focus_area_definitions
SET {', '.join(updates)}
WHERE id = %s
RETURNING id
"""
cur.execute(query, values)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Focus Area nicht gefunden")
return {"message": "Focus Area aktualisiert"}
@router.delete("/definitions/{area_id}")
def delete_focus_area_definition(
area_id: str,
session: dict = Depends(require_auth)
):
"""
Delete focus area definition (Admin only).
Cascades: Deletes all goal_focus_contributions referencing this area.
"""
# Admin check
if session.get('role') != 'admin':
raise HTTPException(status_code=403, detail="Admin-Rechte erforderlich")
with get_db() as conn:
cur = get_cursor(conn)
# Check if area is used
cur.execute(
"SELECT COUNT(*) as count FROM goal_focus_contributions WHERE focus_area_id = %s",
(area_id,)
)
count = cur.fetchone()['count']
if count > 0:
raise HTTPException(
status_code=400,
detail=f"Focus Area wird von {count} Ziel(en) verwendet. "
"Bitte erst Zuordnungen entfernen oder auf 'inaktiv' setzen."
)
# Delete
cur.execute(
"DELETE FROM focus_area_definitions WHERE id = %s RETURNING id",
(area_id,)
)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Focus Area nicht gefunden")
return {"message": "Focus Area gelöscht"}
# ============================================================================
# User Focus Preferences
# ============================================================================
@router.get("/user-preferences")
def get_user_focus_preferences(session: dict = Depends(require_auth)):
"""
Get user's focus area weightings (dynamic system).
Returns focus areas with user-set weights, grouped by category.
"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
# Get dynamic preferences (Migration 032)
try:
cur.execute("""
SELECT
fa.id, fa.key, fa.name_de, fa.name_en, fa.icon,
fa.category, fa.description,
ufw.weight
FROM user_focus_area_weights ufw
JOIN focus_area_definitions fa ON ufw.focus_area_id = fa.id
WHERE ufw.profile_id = %s AND ufw.weight > 0
ORDER BY fa.category, fa.name_de
""", (pid,))
weights = [r2d(row) for row in cur.fetchall()]
# Calculate percentages from weights
total_weight = sum(w['weight'] for w in weights)
if total_weight > 0:
for w in weights:
w['percentage'] = round((w['weight'] / total_weight) * 100)
else:
for w in weights:
w['percentage'] = 0
# Group by category
grouped = {}
for w in weights:
cat = w['category'] or 'other'
if cat not in grouped:
grouped[cat] = []
grouped[cat].append(w)
return {
"weights": weights,
"grouped": grouped,
"total_weight": total_weight
}
except Exception as e:
# Migration 032 not applied yet - return empty
print(f"[WARNING] user_focus_area_weights not found: {e}")
return {
"weights": [],
"grouped": {},
"total_weight": 0
}
@router.put("/user-preferences")
def update_user_focus_preferences(
data: dict,
session: dict = Depends(require_auth)
):
"""
Update user's focus area weightings (dynamic system).
Expects: { "weights": { "focus_area_id": weight, ... } }
Weights are relative (0-100), normalized in display only.
"""
pid = session['profile_id']
if 'weights' not in data:
raise HTTPException(status_code=400, detail="'weights' field required")
weights = data['weights'] # Dict: focus_area_id → weight
with get_db() as conn:
cur = get_cursor(conn)
# Delete existing weights
cur.execute(
"DELETE FROM user_focus_area_weights WHERE profile_id = %s",
(pid,)
)
# Insert new weights (only non-zero)
for focus_area_id, weight in weights.items():
weight_int = int(weight)
if weight_int > 0:
cur.execute("""
INSERT INTO user_focus_area_weights
(profile_id, focus_area_id, weight)
VALUES (%s, %s, %s)
ON CONFLICT (profile_id, focus_area_id)
DO UPDATE SET
weight = EXCLUDED.weight,
updated_at = NOW()
""", (pid, focus_area_id, weight_int))
return {
"message": "Focus Area Gewichtungen aktualisiert",
"count": len([w for w in weights.values() if int(w) > 0])
}
# ============================================================================
# Stats & Analytics
# ============================================================================
@router.get("/stats")
def get_focus_area_stats(session: dict = Depends(require_auth)):
"""
Get focus area statistics for current user.
Returns:
- Progress per focus area (avg of all contributing goals)
- Goal count per focus area
- Top/bottom performing areas
"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT
fa.id, fa.key, fa.name_de, fa.icon, fa.category,
COUNT(DISTINCT gfc.goal_id) as goal_count,
AVG(g.progress_pct) as avg_progress,
SUM(gfc.contribution_weight) as total_contribution
FROM focus_area_definitions fa
LEFT JOIN goal_focus_contributions gfc ON fa.id = gfc.focus_area_id
LEFT JOIN goals g ON gfc.goal_id = g.id AND g.profile_id = %s
WHERE fa.is_active = true
GROUP BY fa.id
HAVING COUNT(DISTINCT gfc.goal_id) > 0 -- Only areas with goals
ORDER BY avg_progress DESC NULLS LAST
""", (pid,))
stats = [r2d(row) for row in cur.fetchall()]
return {
"stats": stats,
"top_area": stats[0] if stats else None,
"bottom_area": stats[-1] if len(stats) > 1 else None
}
+155
View File
@@ -0,0 +1,155 @@
"""
Goal Progress Router - Progress Tracking for Goals
Endpoints for logging and managing goal progress:
- Get progress history
- Create manual progress entries
- Delete progress entries
Part of v9h Goal System.
"""
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from typing import Optional
from datetime import date
from db import get_db, get_cursor, r2d
from auth import require_auth
router = APIRouter(prefix="/api/goals", tags=["goal-progress"])
# ============================================================================
# Pydantic Models
# ============================================================================
class GoalProgressCreate(BaseModel):
"""Log progress for a goal"""
date: date
value: float
note: Optional[str] = None
class GoalProgressUpdate(BaseModel):
"""Update progress entry"""
value: Optional[float] = None
note: Optional[str] = None
# ============================================================================
# Endpoints
# ============================================================================
@router.get("/{goal_id}/progress")
def get_goal_progress(goal_id: str, session: dict = Depends(require_auth)):
"""Get progress history for a goal"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
# Verify ownership
cur.execute(
"SELECT id FROM goals WHERE id = %s AND profile_id = %s",
(goal_id, pid)
)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Ziel nicht gefunden")
# Get progress entries
cur.execute("""
SELECT id, date, value, note, source, created_at
FROM goal_progress_log
WHERE goal_id = %s
ORDER BY date DESC
""", (goal_id,))
entries = cur.fetchall()
return [r2d(e) for e in entries]
@router.post("/{goal_id}/progress")
def create_goal_progress(goal_id: str, data: GoalProgressCreate, session: dict = Depends(require_auth)):
"""Log new progress for a goal"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
# Verify ownership and check if manual entry is allowed
cur.execute("""
SELECT g.id, g.unit, gt.source_table
FROM goals g
LEFT JOIN goal_type_definitions gt ON g.goal_type = gt.type_key
WHERE g.id = %s AND g.profile_id = %s
""", (goal_id, pid))
goal = cur.fetchone()
if not goal:
raise HTTPException(status_code=404, detail="Ziel nicht gefunden")
# Prevent manual entries for goals with automatic data sources
if goal['source_table']:
raise HTTPException(
status_code=400,
detail=f"Manuelle Einträge nicht erlaubt für automatisch erfasste Ziele. "
f"Bitte nutze die entsprechende Erfassungsseite (z.B. Gewicht, Aktivität)."
)
# Insert progress entry
try:
cur.execute("""
INSERT INTO goal_progress_log (goal_id, profile_id, date, value, note, source)
VALUES (%s, %s, %s, %s, %s, 'manual')
RETURNING id
""", (goal_id, pid, data.date, data.value, data.note))
progress_id = cur.fetchone()['id']
# Trigger will auto-update goals.current_value
return {
"id": progress_id,
"message": f"Fortschritt erfasst: {data.value} {goal['unit']}"
}
except Exception as e:
if "unique_progress_per_day" in str(e):
raise HTTPException(
status_code=400,
detail=f"Für {data.date} existiert bereits ein Eintrag. Bitte bearbeite den existierenden Eintrag."
)
raise HTTPException(status_code=500, detail=f"Fehler beim Speichern: {str(e)}")
@router.delete("/{goal_id}/progress/{progress_id}")
def delete_goal_progress(goal_id: str, progress_id: str, session: dict = Depends(require_auth)):
"""Delete progress entry"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
# Verify ownership
cur.execute(
"SELECT id FROM goals WHERE id = %s AND profile_id = %s",
(goal_id, pid)
)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Ziel nicht gefunden")
# Delete progress entry
cur.execute(
"DELETE FROM goal_progress_log WHERE id = %s AND goal_id = %s AND profile_id = %s",
(progress_id, goal_id, pid)
)
if cur.rowcount == 0:
raise HTTPException(status_code=404, detail="Progress-Eintrag nicht gefunden")
# After deletion, recalculate current_value from remaining entries
cur.execute("""
UPDATE goals
SET current_value = (
SELECT value FROM goal_progress_log
WHERE goal_id = %s
ORDER BY date DESC
LIMIT 1
)
WHERE id = %s
""", (goal_id, goal_id))
return {"message": "Progress-Eintrag gelöscht"}
+426
View File
@@ -0,0 +1,426 @@
"""
Goal Types Router - Custom Goal Type Definitions
Endpoints for managing goal type definitions (admin-only):
- CRUD for goal type definitions
- Schema info for building custom types
Part of v9h Goal System.
"""
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from typing import Optional
import traceback
from db import get_db, get_cursor, r2d
from auth import require_auth
router = APIRouter(prefix="/api/goals", tags=["goal-types"])
# ============================================================================
# Pydantic Models
# ============================================================================
class GoalTypeCreate(BaseModel):
"""Create custom goal type definition"""
type_key: str
label_de: str
label_en: Optional[str] = None
unit: str
icon: Optional[str] = None
category: Optional[str] = 'custom'
source_table: Optional[str] = None
source_column: Optional[str] = None
aggregation_method: Optional[str] = 'latest'
calculation_formula: Optional[str] = None
filter_conditions: Optional[dict] = None
description: Optional[str] = None
class GoalTypeUpdate(BaseModel):
"""Update goal type definition"""
label_de: Optional[str] = None
label_en: Optional[str] = None
unit: Optional[str] = None
icon: Optional[str] = None
category: Optional[str] = None
source_table: Optional[str] = None
source_column: Optional[str] = None
aggregation_method: Optional[str] = None
calculation_formula: Optional[str] = None
filter_conditions: Optional[dict] = None
description: Optional[str] = None
is_active: Optional[bool] = None
# ============================================================================
# Endpoints
# ============================================================================
@router.get("/schema-info")
def get_schema_info(session: dict = Depends(require_auth)):
"""
Get available tables and columns for goal type creation.
Admin-only endpoint for building custom goal types.
Returns structure with descriptions for UX guidance.
"""
pid = session['profile_id']
# Check admin role
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
profile = cur.fetchone()
if not profile or profile['role'] != 'admin':
raise HTTPException(status_code=403, detail="Admin-Zugriff erforderlich")
# Define relevant tables with descriptions
# Only include tables that make sense for goal tracking
schema = {
"weight_log": {
"description": "Gewichtsverlauf",
"columns": {
"weight": {"type": "DECIMAL", "description": "Körpergewicht in kg"}
}
},
"caliper_log": {
"description": "Caliper-Messungen (Hautfalten)",
"columns": {
"body_fat_pct": {"type": "DECIMAL", "description": "Körperfettanteil in %"},
"sum_mm": {"type": "DECIMAL", "description": "Summe Hautfalten in mm"}
}
},
"circumference_log": {
"description": "Umfangsmessungen",
"columns": {
"c_neck": {"type": "DECIMAL", "description": "Nackenumfang in cm"},
"c_chest": {"type": "DECIMAL", "description": "Brustumfang in cm"},
"c_waist": {"type": "DECIMAL", "description": "Taillenumfang in cm"},
"c_hips": {"type": "DECIMAL", "description": "Hüftumfang in cm"},
"c_thigh_l": {"type": "DECIMAL", "description": "Oberschenkel links in cm"},
"c_thigh_r": {"type": "DECIMAL", "description": "Oberschenkel rechts in cm"},
"c_calf_l": {"type": "DECIMAL", "description": "Wade links in cm"},
"c_calf_r": {"type": "DECIMAL", "description": "Wade rechts in cm"},
"c_bicep_l": {"type": "DECIMAL", "description": "Bizeps links in cm"},
"c_bicep_r": {"type": "DECIMAL", "description": "Bizeps rechts in cm"}
}
},
"activity_log": {
"description": "Trainingseinheiten",
"columns": {
"id": {"type": "UUID", "description": "ID (für Zählung von Einheiten)"},
"duration_minutes": {"type": "INTEGER", "description": "Trainingsdauer in Minuten"},
"perceived_exertion": {"type": "INTEGER", "description": "Belastungsempfinden (1-10)"},
"quality_rating": {"type": "INTEGER", "description": "Qualitätsbewertung (1-10)"}
}
},
"nutrition_log": {
"description": "Ernährungstagebuch",
"columns": {
"calories": {"type": "INTEGER", "description": "Kalorien in kcal"},
"protein_g": {"type": "DECIMAL", "description": "Protein in g"},
"carbs_g": {"type": "DECIMAL", "description": "Kohlenhydrate in g"},
"fat_g": {"type": "DECIMAL", "description": "Fett in g"}
}
},
"sleep_log": {
"description": "Schlafprotokoll",
"columns": {
"total_minutes": {"type": "INTEGER", "description": "Gesamtschlafdauer in Minuten"}
}
},
"vitals_baseline": {
"description": "Vitalwerte (morgens)",
"columns": {
"resting_hr": {"type": "INTEGER", "description": "Ruhepuls in bpm"},
"hrv_rmssd": {"type": "INTEGER", "description": "Herzratenvariabilität (RMSSD) in ms"},
"vo2_max": {"type": "DECIMAL", "description": "VO2 Max in ml/kg/min"},
"spo2": {"type": "INTEGER", "description": "Sauerstoffsättigung in %"},
"respiratory_rate": {"type": "INTEGER", "description": "Atemfrequenz pro Minute"}
}
},
"blood_pressure_log": {
"description": "Blutdruckmessungen",
"columns": {
"systolic": {"type": "INTEGER", "description": "Systolischer Blutdruck in mmHg"},
"diastolic": {"type": "INTEGER", "description": "Diastolischer Blutdruck in mmHg"},
"pulse": {"type": "INTEGER", "description": "Puls in bpm"}
}
},
"rest_days": {
"description": "Ruhetage",
"columns": {
"id": {"type": "UUID", "description": "ID (für Zählung von Ruhetagen)"}
}
}
}
return schema
@router.get("/goal-types")
def list_goal_type_definitions(session: dict = Depends(require_auth)):
"""
Get all active goal type definitions.
Public endpoint - returns all available goal types for dropdown.
"""
try:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT id, type_key, label_de, label_en, unit, icon, category,
source_table, source_column, aggregation_method,
calculation_formula, filter_conditions, description, is_system, is_active,
created_at, updated_at
FROM goal_type_definitions
WHERE is_active = true
ORDER BY
CASE
WHEN is_system = true THEN 0
ELSE 1
END,
label_de
""")
results = [r2d(row) for row in cur.fetchall()]
print(f"[DEBUG] Loaded {len(results)} goal types")
return results
except Exception as e:
print(f"[ERROR] list_goal_type_definitions failed: {e}")
print(traceback.format_exc())
raise HTTPException(
status_code=500,
detail=f"Fehler beim Laden der Goal Types: {str(e)}"
)
@router.post("/goal-types")
def create_goal_type_definition(
data: GoalTypeCreate,
session: dict = Depends(require_auth)
):
"""
Create custom goal type definition.
Admin-only endpoint for creating new goal types.
Users with admin role can define custom metrics.
"""
pid = session['profile_id']
# Check admin role
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
profile = cur.fetchone()
if not profile or profile['role'] != 'admin':
raise HTTPException(
status_code=403,
detail="Admin-Zugriff erforderlich"
)
# Validate type_key is unique
cur.execute(
"SELECT id FROM goal_type_definitions WHERE type_key = %s",
(data.type_key,)
)
if cur.fetchone():
raise HTTPException(
status_code=400,
detail=f"Goal Type '{data.type_key}' existiert bereits"
)
# Insert new goal type
import json as json_lib
filter_json = json_lib.dumps(data.filter_conditions) if data.filter_conditions else None
cur.execute("""
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
source_table, source_column, aggregation_method,
calculation_formula, filter_conditions, description, is_active, is_system
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""", (
data.type_key, data.label_de, data.label_en, data.unit, data.icon,
data.category, data.source_table, data.source_column,
data.aggregation_method, data.calculation_formula, filter_json, data.description,
True, False # is_active=True, is_system=False
))
goal_type_id = cur.fetchone()['id']
return {
"id": goal_type_id,
"message": f"Goal Type '{data.label_de}' erstellt"
}
@router.put("/goal-types/{goal_type_id}")
def update_goal_type_definition(
goal_type_id: str,
data: GoalTypeUpdate,
session: dict = Depends(require_auth)
):
"""
Update goal type definition.
Admin-only. System goal types can be updated but not deleted.
"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
# Check admin role
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
profile = cur.fetchone()
if not profile or profile['role'] != 'admin':
raise HTTPException(
status_code=403,
detail="Admin-Zugriff erforderlich"
)
# Check goal type exists
cur.execute(
"SELECT id FROM goal_type_definitions WHERE id = %s",
(goal_type_id,)
)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Goal Type nicht gefunden")
# Build update query
updates = []
params = []
if data.label_de is not None:
updates.append("label_de = %s")
params.append(data.label_de)
if data.label_en is not None:
updates.append("label_en = %s")
params.append(data.label_en)
if data.unit is not None:
updates.append("unit = %s")
params.append(data.unit)
if data.icon is not None:
updates.append("icon = %s")
params.append(data.icon)
if data.category is not None:
updates.append("category = %s")
params.append(data.category)
if data.source_table is not None:
updates.append("source_table = %s")
params.append(data.source_table)
if data.source_column is not None:
updates.append("source_column = %s")
params.append(data.source_column)
if data.aggregation_method is not None:
updates.append("aggregation_method = %s")
params.append(data.aggregation_method)
if data.calculation_formula is not None:
updates.append("calculation_formula = %s")
params.append(data.calculation_formula)
if data.filter_conditions is not None:
import json as json_lib
filter_json = json_lib.dumps(data.filter_conditions) if data.filter_conditions else None
updates.append("filter_conditions = %s")
params.append(filter_json)
if data.description is not None:
updates.append("description = %s")
params.append(data.description)
if data.is_active is not None:
updates.append("is_active = %s")
params.append(data.is_active)
if not updates:
raise HTTPException(status_code=400, detail="Keine Änderungen angegeben")
updates.append("updated_at = NOW()")
params.append(goal_type_id)
cur.execute(
f"UPDATE goal_type_definitions SET {', '.join(updates)} WHERE id = %s",
tuple(params)
)
return {"message": "Goal Type aktualisiert"}
@router.delete("/goal-types/{goal_type_id}")
def delete_goal_type_definition(
goal_type_id: str,
session: dict = Depends(require_auth)
):
"""
Delete (deactivate) goal type definition.
Admin-only. System goal types cannot be deleted, only deactivated.
Custom goal types can be fully deleted if no goals reference them.
"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
# Check admin role
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
profile = cur.fetchone()
if not profile or profile['role'] != 'admin':
raise HTTPException(
status_code=403,
detail="Admin-Zugriff erforderlich"
)
# Get goal type info
cur.execute(
"SELECT id, type_key, is_system FROM goal_type_definitions WHERE id = %s",
(goal_type_id,)
)
goal_type = cur.fetchone()
if not goal_type:
raise HTTPException(status_code=404, detail="Goal Type nicht gefunden")
# Check if any goals use this type
cur.execute(
"SELECT COUNT(*) as count FROM goals WHERE goal_type = %s",
(goal_type['type_key'],)
)
count = cur.fetchone()['count']
if count > 0:
# Deactivate instead of delete
cur.execute(
"UPDATE goal_type_definitions SET is_active = false WHERE id = %s",
(goal_type_id,)
)
return {
"message": f"Goal Type deaktiviert ({count} Ziele nutzen diesen Typ)"
}
else:
if goal_type['is_system']:
# System types: only deactivate
cur.execute(
"UPDATE goal_type_definitions SET is_active = false WHERE id = %s",
(goal_type_id,)
)
return {"message": "System Goal Type deaktiviert"}
else:
# Custom types: delete
cur.execute(
"DELETE FROM goal_type_definitions WHERE id = %s",
(goal_type_id,)
)
return {"message": "Goal Type gelöscht"}
+120 -717
View File
@@ -1,20 +1,23 @@
""" """
Goals Router - Goal System (Strategic + Tactical) Goals Router - Core Goal CRUD & Focus Areas (Streamlined v2.0)
Endpoints for managing: Endpoints for managing:
- Strategic goal modes (weight_loss, strength, etc.) - Strategic focus areas (weighted multi-goal system)
- Tactical goal targets (concrete values with deadlines) - Tactical goal targets (concrete values with deadlines)
- Training phase detection - Grouped goal views
- Fitness tests
Part of v9e Goal System implementation. Part of v9h Goal System (Phase 0a).
NOTE: Code split complete! Related endpoints moved to:
- goal_types.py → Goal Type Definitions (Admin CRUD)
- goal_progress.py → Progress tracking
- training_phases.py → Training phase management
- fitness_tests.py → Fitness test recording
""" """
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel from pydantic import BaseModel
from typing import Optional, List from typing import Optional, List
from datetime import date, datetime, timedelta from datetime import date, timedelta
from decimal import Decimal
import traceback
from db import get_db, get_cursor, r2d from db import get_db, get_cursor, r2d
from auth import require_auth from auth import require_auth
@@ -39,6 +42,11 @@ class FocusAreasUpdate(BaseModel):
flexibility_pct: int flexibility_pct: int
health_pct: int health_pct: int
class FocusContribution(BaseModel):
"""Focus area contribution (v2.0)"""
focus_area_id: str
contribution_weight: float = 100.0 # 0-100%
class GoalCreate(BaseModel): class GoalCreate(BaseModel):
"""Create or update a concrete goal""" """Create or update a concrete goal"""
goal_type: str # weight, body_fat, lean_mass, vo2max, strength, flexibility, bp, rhr goal_type: str # weight, body_fat, lean_mass, vo2max, strength, flexibility, bp, rhr
@@ -50,6 +58,7 @@ class GoalCreate(BaseModel):
priority: Optional[int] = 2 # 1=high, 2=medium, 3=low priority: Optional[int] = 2 # 1=high, 2=medium, 3=low
name: Optional[str] = None name: Optional[str] = None
description: Optional[str] = None description: Optional[str] = None
focus_contributions: Optional[List[FocusContribution]] = [] # v2.0: Many-to-Many
class GoalUpdate(BaseModel): class GoalUpdate(BaseModel):
"""Update existing goal""" """Update existing goal"""
@@ -61,62 +70,7 @@ class GoalUpdate(BaseModel):
priority: Optional[int] = None # 1=high, 2=medium, 3=low priority: Optional[int] = None # 1=high, 2=medium, 3=low
name: Optional[str] = None name: Optional[str] = None
description: Optional[str] = None description: Optional[str] = None
focus_contributions: Optional[List[FocusContribution]] = None # v2.0: Many-to-Many
class TrainingPhaseCreate(BaseModel):
"""Create training phase (manual or auto-detected)"""
phase_type: str # calorie_deficit, calorie_surplus, deload, maintenance, periodization
start_date: date
end_date: Optional[date] = None
notes: Optional[str] = None
class FitnessTestCreate(BaseModel):
"""Record fitness test result"""
test_type: str
result_value: float
result_unit: str
test_date: date
test_conditions: Optional[str] = None
class GoalProgressCreate(BaseModel):
"""Log progress for a goal"""
date: date
value: float
note: Optional[str] = None
class GoalProgressUpdate(BaseModel):
"""Update progress entry"""
value: Optional[float] = None
note: Optional[str] = None
class GoalTypeCreate(BaseModel):
"""Create custom goal type definition"""
type_key: str
label_de: str
label_en: Optional[str] = None
unit: str
icon: Optional[str] = None
category: Optional[str] = 'custom'
source_table: Optional[str] = None
source_column: Optional[str] = None
aggregation_method: Optional[str] = 'latest'
calculation_formula: Optional[str] = None
filter_conditions: Optional[dict] = None
description: Optional[str] = None
class GoalTypeUpdate(BaseModel):
"""Update goal type definition"""
label_de: Optional[str] = None
label_en: Optional[str] = None
unit: Optional[str] = None
icon: Optional[str] = None
category: Optional[str] = None
source_table: Optional[str] = None
source_column: Optional[str] = None
aggregation_method: Optional[str] = None
calculation_formula: Optional[str] = None
filter_conditions: Optional[dict] = None
description: Optional[str] = None
is_active: Optional[bool] = None
# ============================================================================ # ============================================================================
# Strategic Layer: Goal Modes # Strategic Layer: Goal Modes
@@ -194,17 +148,32 @@ def get_focus_areas(session: dict = Depends(require_auth)):
with get_db() as conn: with get_db() as conn:
cur = get_cursor(conn) cur = get_cursor(conn)
# Try to get custom focus areas # Try to get custom focus areas (user_focus_preferences after Migration 031)
cur.execute(""" try:
SELECT weight_loss_pct, muscle_gain_pct, strength_pct, cur.execute("""
endurance_pct, flexibility_pct, health_pct, SELECT weight_loss_pct, muscle_gain_pct, strength_pct,
created_at, updated_at endurance_pct, flexibility_pct, health_pct,
FROM focus_areas created_at, updated_at
WHERE profile_id = %s AND active = true FROM user_focus_preferences
LIMIT 1 WHERE profile_id = %s
""", (pid,)) LIMIT 1
""", (pid,))
row = cur.fetchone() row = cur.fetchone()
except Exception as e:
# Migration 031 not applied yet, try old table name
print(f"[WARNING] user_focus_preferences not found, trying old focus_areas: {e}")
try:
cur.execute("""
SELECT weight_loss_pct, muscle_gain_pct, strength_pct,
endurance_pct, flexibility_pct, health_pct,
created_at, updated_at
FROM focus_areas
WHERE profile_id = %s AND active = true
LIMIT 1
""", (pid,))
row = cur.fetchone()
except:
row = None
if row: if row:
return { return {
@@ -350,7 +319,7 @@ def update_focus_areas(data: FocusAreasUpdate, session: dict = Depends(require_a
} }
# ============================================================================ # ============================================================================
# Tactical Layer: Concrete Goals # Tactical Layer: Concrete Goals - Core CRUD
# ============================================================================ # ============================================================================
@router.get("/list") @router.get("/list")
@@ -429,6 +398,17 @@ def create_goal(data: GoalCreate, session: dict = Depends(require_auth)):
goal_id = cur.fetchone()['id'] goal_id = cur.fetchone()['id']
# v2.0: Insert focus area contributions
if data.focus_contributions:
for contrib in data.focus_contributions:
cur.execute("""
INSERT INTO goal_focus_contributions
(goal_id, focus_area_id, contribution_weight)
VALUES (%s, %s, %s)
ON CONFLICT (goal_id, focus_area_id) DO UPDATE
SET contribution_weight = EXCLUDED.contribution_weight
""", (goal_id, contrib.focus_area_id, contrib.contribution_weight))
return {"id": goal_id, "message": "Ziel erstellt"} return {"id": goal_id, "message": "Ziel erstellt"}
@router.put("/{goal_id}") @router.put("/{goal_id}")
@@ -492,16 +472,33 @@ def update_goal(goal_id: str, data: GoalUpdate, session: dict = Depends(require_
updates.append("description = %s") updates.append("description = %s")
params.append(data.description) params.append(data.description)
if not updates: # Handle focus_contributions separately (can be updated even if no other changes)
if data.focus_contributions is not None:
# Delete existing contributions
cur.execute(
"DELETE FROM goal_focus_contributions WHERE goal_id = %s",
(goal_id,)
)
# Insert new contributions
for contrib in data.focus_contributions:
cur.execute("""
INSERT INTO goal_focus_contributions
(goal_id, focus_area_id, contribution_weight)
VALUES (%s, %s, %s)
""", (goal_id, contrib.focus_area_id, contrib.contribution_weight))
if not updates and data.focus_contributions is None:
raise HTTPException(status_code=400, detail="Keine Änderungen angegeben") raise HTTPException(status_code=400, detail="Keine Änderungen angegeben")
updates.append("updated_at = NOW()") if updates:
params.extend([goal_id, pid]) updates.append("updated_at = NOW()")
params.extend([goal_id, pid])
cur.execute( cur.execute(
f"UPDATE goals SET {', '.join(updates)} WHERE id = %s AND profile_id = %s", f"UPDATE goals SET {', '.join(updates)} WHERE id = %s AND profile_id = %s",
tuple(params) tuple(params)
) )
return {"message": "Ziel aktualisiert"} return {"message": "Ziel aktualisiert"}
@@ -522,131 +519,10 @@ def delete_goal(goal_id: str, session: dict = Depends(require_auth)):
return {"message": "Ziel gelöscht"} return {"message": "Ziel gelöscht"}
# ============================================================================
# Goal Progress Endpoints
# ============================================================================
@router.get("/{goal_id}/progress")
def get_goal_progress(goal_id: str, session: dict = Depends(require_auth)):
"""Get progress history for a goal"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
# Verify ownership
cur.execute(
"SELECT id FROM goals WHERE id = %s AND profile_id = %s",
(goal_id, pid)
)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Ziel nicht gefunden")
# Get progress entries
cur.execute("""
SELECT id, date, value, note, source, created_at
FROM goal_progress_log
WHERE goal_id = %s
ORDER BY date DESC
""", (goal_id,))
entries = cur.fetchall()
return [r2d(e) for e in entries]
@router.post("/{goal_id}/progress")
def create_goal_progress(goal_id: str, data: GoalProgressCreate, session: dict = Depends(require_auth)):
"""Log new progress for a goal"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
# Verify ownership and check if manual entry is allowed
cur.execute("""
SELECT g.id, g.unit, gt.source_table
FROM goals g
LEFT JOIN goal_type_definitions gt ON g.goal_type = gt.type_key
WHERE g.id = %s AND g.profile_id = %s
""", (goal_id, pid))
goal = cur.fetchone()
if not goal:
raise HTTPException(status_code=404, detail="Ziel nicht gefunden")
# Prevent manual entries for goals with automatic data sources
if goal['source_table']:
raise HTTPException(
status_code=400,
detail=f"Manuelle Einträge nicht erlaubt für automatisch erfasste Ziele. "
f"Bitte nutze die entsprechende Erfassungsseite (z.B. Gewicht, Aktivität)."
)
# Insert progress entry
try:
cur.execute("""
INSERT INTO goal_progress_log (goal_id, profile_id, date, value, note, source)
VALUES (%s, %s, %s, %s, %s, 'manual')
RETURNING id
""", (goal_id, pid, data.date, data.value, data.note))
progress_id = cur.fetchone()['id']
# Trigger will auto-update goals.current_value
return {
"id": progress_id,
"message": f"Fortschritt erfasst: {data.value} {goal['unit']}"
}
except Exception as e:
if "unique_progress_per_day" in str(e):
raise HTTPException(
status_code=400,
detail=f"Für {data.date} existiert bereits ein Eintrag. Bitte bearbeite den existierenden Eintrag."
)
raise HTTPException(status_code=500, detail=f"Fehler beim Speichern: {str(e)}")
@router.delete("/{goal_id}/progress/{progress_id}")
def delete_goal_progress(goal_id: str, progress_id: str, session: dict = Depends(require_auth)):
"""Delete progress entry"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
# Verify ownership
cur.execute(
"SELECT id FROM goals WHERE id = %s AND profile_id = %s",
(goal_id, pid)
)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Ziel nicht gefunden")
# Delete progress entry
cur.execute(
"DELETE FROM goal_progress_log WHERE id = %s AND goal_id = %s AND profile_id = %s",
(progress_id, goal_id, pid)
)
if cur.rowcount == 0:
raise HTTPException(status_code=404, detail="Progress-Eintrag nicht gefunden")
# After deletion, recalculate current_value from remaining entries
cur.execute("""
UPDATE goals
SET current_value = (
SELECT value FROM goal_progress_log
WHERE goal_id = %s
ORDER BY date DESC
LIMIT 1
)
WHERE id = %s
""", (goal_id, goal_id))
return {"message": "Progress-Eintrag gelöscht"}
@router.get("/grouped") @router.get("/grouped")
def get_goals_grouped(session: dict = Depends(require_auth)): def get_goals_grouped(session: dict = Depends(require_auth)):
""" """
Get goals grouped by category, sorted by priority. Get all goals grouped by category.
Returns structure: Returns structure:
{ {
@@ -680,144 +556,53 @@ def get_goals_grouped(session: dict = Depends(require_auth)):
goals = cur.fetchall() goals = cur.fetchall()
# Group by category # v2.0: Load focus_contributions for each goal
goal_ids = [g['id'] for g in goals]
focus_map = {} # goal_id → [contributions]
if goal_ids:
try:
placeholders = ','.join(['%s'] * len(goal_ids))
cur.execute(f"""
SELECT
gfc.goal_id, gfc.contribution_weight,
fa.id as focus_area_id, fa.key, fa.name_de, fa.icon, fa.category
FROM goal_focus_contributions gfc
JOIN focus_area_definitions fa ON gfc.focus_area_id = fa.id
WHERE gfc.goal_id IN ({placeholders})
ORDER BY gfc.contribution_weight DESC
""", tuple(goal_ids))
for row in cur.fetchall():
gid = row['goal_id']
if gid not in focus_map:
focus_map[gid] = []
focus_map[gid].append({
'focus_area_id': row['focus_area_id'],
'key': row['key'],
'name_de': row['name_de'],
'icon': row['icon'],
'category': row['category'],
'contribution_weight': float(row['contribution_weight'])
})
except Exception as e:
# Migration 031 not yet applied - focus_contributions tables don't exist
print(f"[WARNING] Could not load focus_contributions: {e}")
# Continue without focus_contributions (backward compatible)
# Group by category and attach focus_contributions
grouped = {} grouped = {}
for goal in goals: for goal in goals:
cat = goal['category'] or 'other' cat = goal['category'] or 'other'
if cat not in grouped: if cat not in grouped:
grouped[cat] = [] grouped[cat] = []
grouped[cat].append(r2d(goal))
goal_dict = r2d(goal)
goal_dict['focus_contributions'] = focus_map.get(goal['id'], [])
grouped[cat].append(goal_dict)
return grouped return grouped
# ============================================================================
# Training Phases
# ============================================================================
@router.get("/phases")
def list_training_phases(session: dict = Depends(require_auth)):
"""List training phases"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT id, phase_type, detected_automatically, confidence_score,
status, start_date, end_date, duration_days,
detection_params, notes, created_at
FROM training_phases
WHERE profile_id = %s
ORDER BY start_date DESC
""", (pid,))
return [r2d(row) for row in cur.fetchall()]
@router.post("/phases")
def create_training_phase(data: TrainingPhaseCreate, session: dict = Depends(require_auth)):
"""Create training phase (manual)"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
duration = None
if data.end_date:
duration = (data.end_date - data.start_date).days
cur.execute("""
INSERT INTO training_phases (
profile_id, phase_type, detected_automatically,
status, start_date, end_date, duration_days, notes
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""", (
pid, data.phase_type, False,
'active', data.start_date, data.end_date, duration, data.notes
))
phase_id = cur.fetchone()['id']
return {"id": phase_id, "message": "Trainingsphase erstellt"}
@router.put("/phases/{phase_id}/status")
def update_phase_status(
phase_id: str,
status: str,
session: dict = Depends(require_auth)
):
"""Update training phase status (accept/reject auto-detected phases)"""
pid = session['profile_id']
valid_statuses = ['suggested', 'accepted', 'active', 'completed', 'rejected']
if status not in valid_statuses:
raise HTTPException(
status_code=400,
detail=f"Ungültiger Status. Erlaubt: {', '.join(valid_statuses)}"
)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"UPDATE training_phases SET status = %s WHERE id = %s AND profile_id = %s",
(status, phase_id, pid)
)
if cur.rowcount == 0:
raise HTTPException(status_code=404, detail="Trainingsphase nicht gefunden")
return {"message": "Status aktualisiert"}
# ============================================================================
# Fitness Tests
# ============================================================================
@router.get("/tests")
def list_fitness_tests(session: dict = Depends(require_auth)):
"""List all fitness tests"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT id, test_type, result_value, result_unit,
test_date, test_conditions, norm_category, created_at
FROM fitness_tests
WHERE profile_id = %s
ORDER BY test_date DESC
""", (pid,))
return [r2d(row) for row in cur.fetchall()]
@router.post("/tests")
def create_fitness_test(data: FitnessTestCreate, session: dict = Depends(require_auth)):
"""Record fitness test result"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
# Calculate norm category (simplified for now)
norm_category = _calculate_norm_category(
data.test_type,
data.result_value,
data.result_unit
)
cur.execute("""
INSERT INTO fitness_tests (
profile_id, test_type, result_value, result_unit,
test_date, test_conditions, norm_category
) VALUES (%s, %s, %s, %s, %s, %s, %s)
RETURNING id
""", (
pid, data.test_type, data.result_value, data.result_unit,
data.test_date, data.test_conditions, norm_category
))
test_id = cur.fetchone()['id']
return {"id": test_id, "norm_category": norm_category}
# ============================================================================ # ============================================================================
# Helper Functions # Helper Functions
# ============================================================================ # ============================================================================
@@ -868,385 +653,3 @@ def _update_goal_progress(conn, profile_id: str, goal: dict):
# Check if on track # Check if on track
if goal['target_date'] and goal['projection_date']: if goal['target_date'] and goal['projection_date']:
goal['on_track'] = goal['projection_date'] <= goal['target_date'] goal['on_track'] = goal['projection_date'] <= goal['target_date']
def _calculate_norm_category(test_type: str, value: float, unit: str) -> Optional[str]:
"""
Calculate norm category for fitness test
(Simplified - would need age/gender-specific norms)
"""
# Placeholder - should use proper norm tables
return None
# ============================================================================
# Goal Type Definitions (Phase 1.5 - Flexible Goal System)
# ============================================================================
@router.get("/schema-info")
def get_schema_info(session: dict = Depends(require_auth)):
"""
Get available tables and columns for goal type creation.
Admin-only endpoint for building custom goal types.
Returns structure with descriptions for UX guidance.
"""
pid = session['profile_id']
# Check admin role
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
profile = cur.fetchone()
if not profile or profile['role'] != 'admin':
raise HTTPException(status_code=403, detail="Admin-Zugriff erforderlich")
# Define relevant tables with descriptions
# Only include tables that make sense for goal tracking
schema = {
"weight_log": {
"description": "Gewichtsverlauf",
"columns": {
"weight": {"type": "DECIMAL", "description": "Körpergewicht in kg"}
}
},
"caliper_log": {
"description": "Caliper-Messungen (Hautfalten)",
"columns": {
"body_fat_pct": {"type": "DECIMAL", "description": "Körperfettanteil in %"},
"sum_mm": {"type": "DECIMAL", "description": "Summe Hautfalten in mm"}
}
},
"circumference_log": {
"description": "Umfangsmessungen",
"columns": {
"c_neck": {"type": "DECIMAL", "description": "Nackenumfang in cm"},
"c_chest": {"type": "DECIMAL", "description": "Brustumfang in cm"},
"c_waist": {"type": "DECIMAL", "description": "Taillenumfang in cm"},
"c_hips": {"type": "DECIMAL", "description": "Hüftumfang in cm"},
"c_thigh_l": {"type": "DECIMAL", "description": "Oberschenkel links in cm"},
"c_thigh_r": {"type": "DECIMAL", "description": "Oberschenkel rechts in cm"},
"c_calf_l": {"type": "DECIMAL", "description": "Wade links in cm"},
"c_calf_r": {"type": "DECIMAL", "description": "Wade rechts in cm"},
"c_bicep_l": {"type": "DECIMAL", "description": "Bizeps links in cm"},
"c_bicep_r": {"type": "DECIMAL", "description": "Bizeps rechts in cm"}
}
},
"activity_log": {
"description": "Trainingseinheiten",
"columns": {
"id": {"type": "UUID", "description": "ID (für Zählung von Einheiten)"},
"duration_minutes": {"type": "INTEGER", "description": "Trainingsdauer in Minuten"},
"perceived_exertion": {"type": "INTEGER", "description": "Belastungsempfinden (1-10)"},
"quality_rating": {"type": "INTEGER", "description": "Qualitätsbewertung (1-10)"}
}
},
"nutrition_log": {
"description": "Ernährungstagebuch",
"columns": {
"calories": {"type": "INTEGER", "description": "Kalorien in kcal"},
"protein_g": {"type": "DECIMAL", "description": "Protein in g"},
"carbs_g": {"type": "DECIMAL", "description": "Kohlenhydrate in g"},
"fat_g": {"type": "DECIMAL", "description": "Fett in g"}
}
},
"sleep_log": {
"description": "Schlafprotokoll",
"columns": {
"total_minutes": {"type": "INTEGER", "description": "Gesamtschlafdauer in Minuten"}
}
},
"vitals_baseline": {
"description": "Vitalwerte (morgens)",
"columns": {
"resting_hr": {"type": "INTEGER", "description": "Ruhepuls in bpm"},
"hrv_rmssd": {"type": "INTEGER", "description": "Herzratenvariabilität (RMSSD) in ms"},
"vo2_max": {"type": "DECIMAL", "description": "VO2 Max in ml/kg/min"},
"spo2": {"type": "INTEGER", "description": "Sauerstoffsättigung in %"},
"respiratory_rate": {"type": "INTEGER", "description": "Atemfrequenz pro Minute"}
}
},
"blood_pressure_log": {
"description": "Blutdruckmessungen",
"columns": {
"systolic": {"type": "INTEGER", "description": "Systolischer Blutdruck in mmHg"},
"diastolic": {"type": "INTEGER", "description": "Diastolischer Blutdruck in mmHg"},
"pulse": {"type": "INTEGER", "description": "Puls in bpm"}
}
},
"rest_days": {
"description": "Ruhetage",
"columns": {
"id": {"type": "UUID", "description": "ID (für Zählung von Ruhetagen)"}
}
}
}
return schema
@router.get("/goal-types")
def list_goal_type_definitions(session: dict = Depends(require_auth)):
"""
Get all active goal type definitions.
Public endpoint - returns all available goal types for dropdown.
"""
try:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT id, type_key, label_de, label_en, unit, icon, category,
source_table, source_column, aggregation_method,
calculation_formula, description, is_system, is_active,
created_at, updated_at
FROM goal_type_definitions
WHERE is_active = true
ORDER BY
CASE
WHEN is_system = true THEN 0
ELSE 1
END,
label_de
""")
results = [r2d(row) for row in cur.fetchall()]
print(f"[DEBUG] Loaded {len(results)} goal types")
return results
except Exception as e:
print(f"[ERROR] list_goal_type_definitions failed: {e}")
print(traceback.format_exc())
raise HTTPException(
status_code=500,
detail=f"Fehler beim Laden der Goal Types: {str(e)}"
)
@router.post("/goal-types")
def create_goal_type_definition(
data: GoalTypeCreate,
session: dict = Depends(require_auth)
):
"""
Create custom goal type definition.
Admin-only endpoint for creating new goal types.
Users with admin role can define custom metrics.
"""
pid = session['profile_id']
# Check admin role
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
profile = cur.fetchone()
if not profile or profile['role'] != 'admin':
raise HTTPException(
status_code=403,
detail="Admin-Zugriff erforderlich"
)
# Validate type_key is unique
cur.execute(
"SELECT id FROM goal_type_definitions WHERE type_key = %s",
(data.type_key,)
)
if cur.fetchone():
raise HTTPException(
status_code=400,
detail=f"Goal Type '{data.type_key}' existiert bereits"
)
# Insert new goal type
import json as json_lib
filter_json = json_lib.dumps(data.filter_conditions) if data.filter_conditions else None
cur.execute("""
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
source_table, source_column, aggregation_method,
calculation_formula, filter_conditions, description, is_active, is_system
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""", (
data.type_key, data.label_de, data.label_en, data.unit, data.icon,
data.category, data.source_table, data.source_column,
data.aggregation_method, data.calculation_formula, filter_json, data.description,
True, False # is_active=True, is_system=False
))
goal_type_id = cur.fetchone()['id']
return {
"id": goal_type_id,
"message": f"Goal Type '{data.label_de}' erstellt"
}
@router.put("/goal-types/{goal_type_id}")
def update_goal_type_definition(
goal_type_id: str,
data: GoalTypeUpdate,
session: dict = Depends(require_auth)
):
"""
Update goal type definition.
Admin-only. System goal types can be updated but not deleted.
"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
# Check admin role
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
profile = cur.fetchone()
if not profile or profile['role'] != 'admin':
raise HTTPException(
status_code=403,
detail="Admin-Zugriff erforderlich"
)
# Check goal type exists
cur.execute(
"SELECT id FROM goal_type_definitions WHERE id = %s",
(goal_type_id,)
)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Goal Type nicht gefunden")
# Build update query
updates = []
params = []
if data.label_de is not None:
updates.append("label_de = %s")
params.append(data.label_de)
if data.label_en is not None:
updates.append("label_en = %s")
params.append(data.label_en)
if data.unit is not None:
updates.append("unit = %s")
params.append(data.unit)
if data.icon is not None:
updates.append("icon = %s")
params.append(data.icon)
if data.category is not None:
updates.append("category = %s")
params.append(data.category)
if data.source_table is not None:
updates.append("source_table = %s")
params.append(data.source_table)
if data.source_column is not None:
updates.append("source_column = %s")
params.append(data.source_column)
if data.aggregation_method is not None:
updates.append("aggregation_method = %s")
params.append(data.aggregation_method)
if data.calculation_formula is not None:
updates.append("calculation_formula = %s")
params.append(data.calculation_formula)
if data.filter_conditions is not None:
import json as json_lib
filter_json = json_lib.dumps(data.filter_conditions) if data.filter_conditions else None
updates.append("filter_conditions = %s")
params.append(filter_json)
if data.description is not None:
updates.append("description = %s")
params.append(data.description)
if data.is_active is not None:
updates.append("is_active = %s")
params.append(data.is_active)
if not updates:
raise HTTPException(status_code=400, detail="Keine Änderungen angegeben")
updates.append("updated_at = NOW()")
params.append(goal_type_id)
cur.execute(
f"UPDATE goal_type_definitions SET {', '.join(updates)} WHERE id = %s",
tuple(params)
)
return {"message": "Goal Type aktualisiert"}
@router.delete("/goal-types/{goal_type_id}")
def delete_goal_type_definition(
goal_type_id: str,
session: dict = Depends(require_auth)
):
"""
Delete (deactivate) goal type definition.
Admin-only. System goal types cannot be deleted, only deactivated.
Custom goal types can be fully deleted if no goals reference them.
"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
# Check admin role
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
profile = cur.fetchone()
if not profile or profile['role'] != 'admin':
raise HTTPException(
status_code=403,
detail="Admin-Zugriff erforderlich"
)
# Get goal type info
cur.execute(
"SELECT id, type_key, is_system FROM goal_type_definitions WHERE id = %s",
(goal_type_id,)
)
goal_type = cur.fetchone()
if not goal_type:
raise HTTPException(status_code=404, detail="Goal Type nicht gefunden")
# Check if any goals use this type
cur.execute(
"SELECT COUNT(*) as count FROM goals WHERE goal_type = %s",
(goal_type['type_key'],)
)
count = cur.fetchone()['count']
if count > 0:
# Deactivate instead of delete
cur.execute(
"UPDATE goal_type_definitions SET is_active = false WHERE id = %s",
(goal_type_id,)
)
return {
"message": f"Goal Type deaktiviert ({count} Ziele nutzen diesen Typ)"
}
else:
if goal_type['is_system']:
# System types: only deactivate
cur.execute(
"UPDATE goal_type_definitions SET is_active = false WHERE id = %s",
(goal_type_id,)
)
return {"message": "System Goal Type deaktiviert"}
else:
# Custom types: delete
cur.execute(
"DELETE FROM goal_type_definitions WHERE id = %s",
(goal_type_id,)
)
return {"message": "Goal Type gelöscht"}
+107
View File
@@ -0,0 +1,107 @@
"""
Training Phases Router - Training Phase Detection & Management
Endpoints for managing training phases:
- List training phases
- Create manual training phases
- Update phase status (accept/reject auto-detected phases)
Part of v9h Goal System.
"""
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from typing import Optional
from datetime import date
from db import get_db, get_cursor, r2d
from auth import require_auth
router = APIRouter(prefix="/api/goals", tags=["training-phases"])
# ============================================================================
# Pydantic Models
# ============================================================================
class TrainingPhaseCreate(BaseModel):
"""Create training phase (manual or auto-detected)"""
phase_type: str # calorie_deficit, calorie_surplus, deload, maintenance, periodization
start_date: date
end_date: Optional[date] = None
notes: Optional[str] = None
# ============================================================================
# Endpoints
# ============================================================================
@router.get("/phases")
def list_training_phases(session: dict = Depends(require_auth)):
"""List training phases"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT id, phase_type, detected_automatically, confidence_score,
status, start_date, end_date, duration_days,
detection_params, notes, created_at
FROM training_phases
WHERE profile_id = %s
ORDER BY start_date DESC
""", (pid,))
return [r2d(row) for row in cur.fetchall()]
@router.post("/phases")
def create_training_phase(data: TrainingPhaseCreate, session: dict = Depends(require_auth)):
"""Create training phase (manual)"""
pid = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
duration = None
if data.end_date:
duration = (data.end_date - data.start_date).days
cur.execute("""
INSERT INTO training_phases (
profile_id, phase_type, detected_automatically,
status, start_date, end_date, duration_days, notes
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""", (
pid, data.phase_type, False,
'active', data.start_date, data.end_date, duration, data.notes
))
phase_id = cur.fetchone()['id']
return {"id": phase_id, "message": "Trainingsphase erstellt"}
@router.put("/phases/{phase_id}/status")
def update_phase_status(
phase_id: str,
status: str,
session: dict = Depends(require_auth)
):
"""Update training phase status (accept/reject auto-detected phases)"""
pid = session['profile_id']
valid_statuses = ['suggested', 'accepted', 'active', 'completed', 'rejected']
if status not in valid_statuses:
raise HTTPException(
status_code=400,
detail=f"Ungültiger Status. Erlaubt: {', '.join(valid_statuses)}"
)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"UPDATE training_phases SET status = %s WHERE id = %s AND profile_id = %s",
(status, phase_id, pid)
)
if cur.rowcount == 0:
raise HTTPException(status_code=404, detail="Trainingsphase nicht gefunden")
return {"message": "Status aktualisiert"}
-681
View File
@@ -1,681 +0,0 @@
"""
Vitals Router - Resting HR + HRV Tracking
v9d Phase 2: Vitals Module
Endpoints:
- GET /api/vitals List vitals (with limit)
- GET /api/vitals/by-date/{date} Get vitals for specific date
- POST /api/vitals Create/update vitals (upsert)
- PUT /api/vitals/{id} Update vitals
- DELETE /api/vitals/{id} Delete vitals
- GET /api/vitals/stats Get vitals statistics
- POST /api/vitals/import/omron Import Omron CSV
- POST /api/vitals/import/apple-health Import Apple Health CSV
"""
from fastapi import APIRouter, HTTPException, Depends, Header, UploadFile, File
from pydantic import BaseModel
from typing import Optional
from datetime import datetime, timedelta
import logging
import csv
import io
from dateutil import parser as date_parser
from db import get_db, get_cursor, r2d
from auth import require_auth
router = APIRouter(prefix="/api/vitals", tags=["vitals"])
logger = logging.getLogger(__name__)
# German month mapping for Omron dates
GERMAN_MONTHS = {
'Januar': '01', 'Jan.': '01',
'Februar': '02', 'Feb.': '02',
'März': '03',
'April': '04', 'Apr.': '04',
'Mai': '05',
'Juni': '06',
'Juli': '07',
'August': '08', 'Aug.': '08',
'September': '09', 'Sep.': '09',
'Oktober': '10', 'Okt.': '10',
'November': '11', 'Nov.': '11',
'Dezember': '12', 'Dez.': '12'
}
class VitalsEntry(BaseModel):
date: str
resting_hr: Optional[int] = None
hrv: Optional[int] = None
blood_pressure_systolic: Optional[int] = None
blood_pressure_diastolic: Optional[int] = None
pulse: Optional[int] = None
vo2_max: Optional[float] = None
spo2: Optional[int] = None
respiratory_rate: Optional[float] = None
irregular_heartbeat: Optional[bool] = None
possible_afib: Optional[bool] = None
note: Optional[str] = None
class VitalsUpdate(BaseModel):
date: Optional[str] = None
resting_hr: Optional[int] = None
hrv: Optional[int] = None
blood_pressure_systolic: Optional[int] = None
blood_pressure_diastolic: Optional[int] = None
pulse: Optional[int] = None
vo2_max: Optional[float] = None
spo2: Optional[int] = None
respiratory_rate: Optional[float] = None
irregular_heartbeat: Optional[bool] = None
possible_afib: Optional[bool] = None
note: Optional[str] = None
def get_pid(x_profile_id: Optional[str], session: dict) -> str:
"""Extract profile_id from session (never from header for security)."""
return session['profile_id']
@router.get("")
def list_vitals(
limit: int = 90,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Get vitals entries for current profile."""
pid = get_pid(x_profile_id, session)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT id, profile_id, date, resting_hr, hrv,
blood_pressure_systolic, blood_pressure_diastolic, pulse,
vo2_max, spo2, respiratory_rate,
irregular_heartbeat, possible_afib,
note, source, created_at, updated_at
FROM vitals_log
WHERE profile_id = %s
ORDER BY date DESC
LIMIT %s
""",
(pid, limit)
)
return [r2d(r) for r in cur.fetchall()]
@router.get("/by-date/{date}")
def get_vitals_by_date(
date: str,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Get vitals entry for a specific date."""
pid = get_pid(x_profile_id, session)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT id, profile_id, date, resting_hr, hrv,
blood_pressure_systolic, blood_pressure_diastolic, pulse,
vo2_max, spo2, respiratory_rate,
irregular_heartbeat, possible_afib,
note, source, created_at, updated_at
FROM vitals_log
WHERE profile_id = %s AND date = %s
""",
(pid, date)
)
row = cur.fetchone()
if not row:
raise HTTPException(404, "Keine Vitalwerte für dieses Datum gefunden")
return r2d(row)
@router.post("")
def create_vitals(
entry: VitalsEntry,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Create or update vitals entry (upsert)."""
pid = get_pid(x_profile_id, session)
# Validation: at least one vital must be provided
has_data = any([
entry.resting_hr, entry.hrv, entry.blood_pressure_systolic,
entry.blood_pressure_diastolic, entry.vo2_max, entry.spo2,
entry.respiratory_rate
])
if not has_data:
raise HTTPException(400, "Mindestens ein Vitalwert muss angegeben werden")
with get_db() as conn:
cur = get_cursor(conn)
# Upsert: insert or update if date already exists
cur.execute(
"""
INSERT INTO vitals_log (
profile_id, date, resting_hr, hrv,
blood_pressure_systolic, blood_pressure_diastolic, pulse,
vo2_max, spo2, respiratory_rate,
irregular_heartbeat, possible_afib,
note, source
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'manual')
ON CONFLICT (profile_id, date)
DO UPDATE SET
resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_log.resting_hr),
hrv = COALESCE(EXCLUDED.hrv, vitals_log.hrv),
blood_pressure_systolic = COALESCE(EXCLUDED.blood_pressure_systolic, vitals_log.blood_pressure_systolic),
blood_pressure_diastolic = COALESCE(EXCLUDED.blood_pressure_diastolic, vitals_log.blood_pressure_diastolic),
pulse = COALESCE(EXCLUDED.pulse, vitals_log.pulse),
vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_log.vo2_max),
spo2 = COALESCE(EXCLUDED.spo2, vitals_log.spo2),
respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_log.respiratory_rate),
irregular_heartbeat = COALESCE(EXCLUDED.irregular_heartbeat, vitals_log.irregular_heartbeat),
possible_afib = COALESCE(EXCLUDED.possible_afib, vitals_log.possible_afib),
note = COALESCE(EXCLUDED.note, vitals_log.note),
updated_at = CURRENT_TIMESTAMP
RETURNING id, profile_id, date, resting_hr, hrv,
blood_pressure_systolic, blood_pressure_diastolic, pulse,
vo2_max, spo2, respiratory_rate,
irregular_heartbeat, possible_afib,
note, source, created_at, updated_at
""",
(pid, entry.date, entry.resting_hr, entry.hrv,
entry.blood_pressure_systolic, entry.blood_pressure_diastolic, entry.pulse,
entry.vo2_max, entry.spo2, entry.respiratory_rate,
entry.irregular_heartbeat, entry.possible_afib,
entry.note)
)
row = cur.fetchone()
conn.commit()
logger.info(f"[VITALS] Upserted vitals for {pid} on {entry.date}")
return r2d(row)
@router.put("/{vitals_id}")
def update_vitals(
vitals_id: int,
updates: VitalsUpdate,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Update existing vitals entry."""
pid = get_pid(x_profile_id, session)
with get_db() as conn:
cur = get_cursor(conn)
# Check ownership
cur.execute(
"SELECT id FROM vitals_log WHERE id = %s AND profile_id = %s",
(vitals_id, pid)
)
if not cur.fetchone():
raise HTTPException(404, "Eintrag nicht gefunden")
# Build update query dynamically
fields = []
values = []
if updates.date is not None:
fields.append("date = %s")
values.append(updates.date)
if updates.resting_hr is not None:
fields.append("resting_hr = %s")
values.append(updates.resting_hr)
if updates.hrv is not None:
fields.append("hrv = %s")
values.append(updates.hrv)
if updates.blood_pressure_systolic is not None:
fields.append("blood_pressure_systolic = %s")
values.append(updates.blood_pressure_systolic)
if updates.blood_pressure_diastolic is not None:
fields.append("blood_pressure_diastolic = %s")
values.append(updates.blood_pressure_diastolic)
if updates.pulse is not None:
fields.append("pulse = %s")
values.append(updates.pulse)
if updates.vo2_max is not None:
fields.append("vo2_max = %s")
values.append(updates.vo2_max)
if updates.spo2 is not None:
fields.append("spo2 = %s")
values.append(updates.spo2)
if updates.respiratory_rate is not None:
fields.append("respiratory_rate = %s")
values.append(updates.respiratory_rate)
if updates.irregular_heartbeat is not None:
fields.append("irregular_heartbeat = %s")
values.append(updates.irregular_heartbeat)
if updates.possible_afib is not None:
fields.append("possible_afib = %s")
values.append(updates.possible_afib)
if updates.note is not None:
fields.append("note = %s")
values.append(updates.note)
if not fields:
raise HTTPException(400, "Keine Änderungen angegeben")
fields.append("updated_at = CURRENT_TIMESTAMP")
values.append(vitals_id)
query = f"""
UPDATE vitals_log
SET {', '.join(fields)}
WHERE id = %s
RETURNING id, profile_id, date, resting_hr, hrv,
blood_pressure_systolic, blood_pressure_diastolic, pulse,
vo2_max, spo2, respiratory_rate,
irregular_heartbeat, possible_afib,
note, source, created_at, updated_at
"""
cur.execute(query, values)
row = cur.fetchone()
conn.commit()
return r2d(row)
@router.delete("/{vitals_id}")
def delete_vitals(
vitals_id: int,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Delete vitals entry."""
pid = get_pid(x_profile_id, session)
with get_db() as conn:
cur = get_cursor(conn)
# Check ownership and delete
cur.execute(
"DELETE FROM vitals_log WHERE id = %s AND profile_id = %s RETURNING id",
(vitals_id, pid)
)
if not cur.fetchone():
raise HTTPException(404, "Eintrag nicht gefunden")
conn.commit()
logger.info(f"[VITALS] Deleted vitals {vitals_id} for {pid}")
return {"message": "Eintrag gelöscht"}
@router.get("/stats")
def get_vitals_stats(
days: int = 30,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""
Get vitals statistics over the last N days.
Returns:
- avg_resting_hr (7d and 30d)
- avg_hrv (7d and 30d)
- trend (increasing/decreasing/stable)
- latest values
"""
pid = get_pid(x_profile_id, session)
with get_db() as conn:
cur = get_cursor(conn)
# Get latest entry
cur.execute(
"""
SELECT date, resting_hr, hrv
FROM vitals_log
WHERE profile_id = %s AND date >= CURRENT_DATE - INTERVAL '%s days'
ORDER BY date DESC
LIMIT 1
""",
(pid, days)
)
latest = cur.fetchone()
# Get averages (7d and 30d)
cur.execute(
"""
SELECT
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '7 days' THEN resting_hr END) as avg_hr_7d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '30 days' THEN resting_hr END) as avg_hr_30d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '7 days' THEN hrv END) as avg_hrv_7d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '30 days' THEN hrv END) as avg_hrv_30d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '7 days' THEN blood_pressure_systolic END) as avg_bp_sys_7d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '30 days' THEN blood_pressure_systolic END) as avg_bp_sys_30d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '7 days' THEN blood_pressure_diastolic END) as avg_bp_dia_7d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '30 days' THEN blood_pressure_diastolic END) as avg_bp_dia_30d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '7 days' THEN spo2 END) as avg_spo2_7d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '30 days' THEN spo2 END) as avg_spo2_30d,
COUNT(*) as total_entries
FROM vitals_log
WHERE profile_id = %s AND date >= CURRENT_DATE - INTERVAL '%s days'
""",
(pid, max(days, 30))
)
stats_row = cur.fetchone()
# Get latest VO2 Max
cur.execute(
"""
SELECT vo2_max
FROM vitals_log
WHERE profile_id = %s AND vo2_max IS NOT NULL
ORDER BY date DESC
LIMIT 1
""",
(pid,)
)
vo2_row = cur.fetchone()
latest_vo2 = vo2_row['vo2_max'] if vo2_row else None
# Get entries for trend calculation (last 14 days)
cur.execute(
"""
SELECT date, resting_hr, hrv
FROM vitals_log
WHERE profile_id = %s AND date >= CURRENT_DATE - INTERVAL '14 days'
ORDER BY date ASC
""",
(pid,)
)
entries = [r2d(r) for r in cur.fetchall()]
# Simple trend calculation (compare first half vs second half)
trend_hr = "stable"
trend_hrv = "stable"
if len(entries) >= 4:
mid = len(entries) // 2
first_half_hr = [e['resting_hr'] for e in entries[:mid] if e['resting_hr']]
second_half_hr = [e['resting_hr'] for e in entries[mid:] if e['resting_hr']]
if first_half_hr and second_half_hr:
avg_first = sum(first_half_hr) / len(first_half_hr)
avg_second = sum(second_half_hr) / len(second_half_hr)
diff = avg_second - avg_first
if diff > 2:
trend_hr = "increasing"
elif diff < -2:
trend_hr = "decreasing"
first_half_hrv = [e['hrv'] for e in entries[:mid] if e['hrv']]
second_half_hrv = [e['hrv'] for e in entries[mid:] if e['hrv']]
if first_half_hrv and second_half_hrv:
avg_first_hrv = sum(first_half_hrv) / len(first_half_hrv)
avg_second_hrv = sum(second_half_hrv) / len(second_half_hrv)
diff_hrv = avg_second_hrv - avg_first_hrv
if diff_hrv > 5:
trend_hrv = "increasing"
elif diff_hrv < -5:
trend_hrv = "decreasing"
return {
"latest": r2d(latest) if latest else None,
"avg_resting_hr_7d": round(stats_row['avg_hr_7d'], 1) if stats_row['avg_hr_7d'] else None,
"avg_resting_hr_30d": round(stats_row['avg_hr_30d'], 1) if stats_row['avg_hr_30d'] else None,
"avg_hrv_7d": round(stats_row['avg_hrv_7d'], 1) if stats_row['avg_hrv_7d'] else None,
"avg_hrv_30d": round(stats_row['avg_hrv_30d'], 1) if stats_row['avg_hrv_30d'] else None,
"avg_bp_systolic_7d": round(stats_row['avg_bp_sys_7d'], 1) if stats_row['avg_bp_sys_7d'] else None,
"avg_bp_systolic_30d": round(stats_row['avg_bp_sys_30d'], 1) if stats_row['avg_bp_sys_30d'] else None,
"avg_bp_diastolic_7d": round(stats_row['avg_bp_dia_7d'], 1) if stats_row['avg_bp_dia_7d'] else None,
"avg_bp_diastolic_30d": round(stats_row['avg_bp_dia_30d'], 1) if stats_row['avg_bp_dia_30d'] else None,
"avg_spo2_7d": round(stats_row['avg_spo2_7d'], 1) if stats_row['avg_spo2_7d'] else None,
"avg_spo2_30d": round(stats_row['avg_spo2_30d'], 1) if stats_row['avg_spo2_30d'] else None,
"latest_vo2_max": float(latest_vo2) if latest_vo2 else None,
"total_entries": stats_row['total_entries'],
"trend_resting_hr": trend_hr,
"trend_hrv": trend_hrv,
"period_days": days
}
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Import Endpoints
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
def parse_omron_date(date_str: str) -> str:
"""
Parse Omron German date format to YYYY-MM-DD.
Examples:
- "13 März 2026" -> "2026-03-13"
- "28 Feb. 2026" -> "2026-02-28"
"""
parts = date_str.strip().split()
if len(parts) != 3:
raise ValueError(f"Invalid date format: {date_str}")
day = parts[0].zfill(2)
month_str = parts[1]
year = parts[2]
# Map German month to number
month = GERMAN_MONTHS.get(month_str)
if not month:
raise ValueError(f"Unknown month: {month_str}")
return f"{year}-{month}-{day}"
@router.post("/import/omron")
async def import_omron_csv(
file: UploadFile = File(...),
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""
Import Omron blood pressure CSV export.
Expected format:
Datum,Zeit,Systolisch (mmHg),Diastolisch (mmHg),Puls (bpm),...
"""
pid = get_pid(x_profile_id, session)
# Read file
content = await file.read()
content_str = content.decode('utf-8')
# Parse CSV
reader = csv.DictReader(io.StringIO(content_str))
inserted = 0
updated = 0
skipped = 0
errors = []
with get_db() as conn:
cur = get_cursor(conn)
for row_num, row in enumerate(reader, start=2):
try:
# Parse date
date_str = parse_omron_date(row['Datum'])
# Parse values
systolic = int(row['Systolisch (mmHg)']) if row['Systolisch (mmHg)'] and row['Systolisch (mmHg)'] != '-' else None
diastolic = int(row['Diastolisch (mmHg)']) if row['Diastolisch (mmHg)'] and row['Diastolisch (mmHg)'] != '-' else None
pulse = int(row['Puls (bpm)']) if row['Puls (bpm)'] and row['Puls (bpm)'] != '-' else None
# Skip if no data
if not systolic and not diastolic and not pulse:
skipped += 1
continue
# Parse flags (optional columns)
irregular = row.get('Unregelmäßiger Herzschlag festgestellt', '').strip() not in ('', '-', ' ')
afib = row.get('Mögliches AFib', '').strip() not in ('', '-', ' ')
# Upsert
cur.execute(
"""
INSERT INTO vitals_log (
profile_id, date, blood_pressure_systolic, blood_pressure_diastolic,
pulse, irregular_heartbeat, possible_afib, source
)
VALUES (%s, %s, %s, %s, %s, %s, %s, 'omron')
ON CONFLICT (profile_id, date)
DO UPDATE SET
blood_pressure_systolic = COALESCE(EXCLUDED.blood_pressure_systolic, vitals_log.blood_pressure_systolic),
blood_pressure_diastolic = COALESCE(EXCLUDED.blood_pressure_diastolic, vitals_log.blood_pressure_diastolic),
pulse = COALESCE(EXCLUDED.pulse, vitals_log.pulse),
irregular_heartbeat = COALESCE(EXCLUDED.irregular_heartbeat, vitals_log.irregular_heartbeat),
possible_afib = COALESCE(EXCLUDED.possible_afib, vitals_log.possible_afib),
source = CASE WHEN vitals_log.source = 'manual' THEN vitals_log.source ELSE 'omron' END,
updated_at = CURRENT_TIMESTAMP
RETURNING (xmax = 0) AS inserted
""",
(pid, date_str, systolic, diastolic, pulse, irregular, afib)
)
result = cur.fetchone()
if result['inserted']:
inserted += 1
else:
updated += 1
except Exception as e:
errors.append(f"Zeile {row_num}: {str(e)}")
logger.error(f"[OMRON-IMPORT] Error at row {row_num}: {e}")
continue
conn.commit()
logger.info(f"[OMRON-IMPORT] {pid}: {inserted} inserted, {updated} updated, {skipped} skipped, {len(errors)} errors")
return {
"message": "Omron CSV Import abgeschlossen",
"inserted": inserted,
"updated": updated,
"skipped": skipped,
"errors": errors[:10] # Limit to first 10 errors
}
@router.post("/import/apple-health")
async def import_apple_health_csv(
file: UploadFile = File(...),
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""
Import Apple Health vitals CSV export.
Expected columns:
- Datum/Uhrzeit
- Ruhepuls (count/min)
- Herzfrequenzvariabilität (ms)
- VO2 max (ml/(kg·min))
- Blutsauerstoffsättigung (%)
- Atemfrequenz (count/min)
"""
pid = get_pid(x_profile_id, session)
# Read file
content = await file.read()
content_str = content.decode('utf-8')
# Parse CSV
reader = csv.DictReader(io.StringIO(content_str))
inserted = 0
updated = 0
skipped = 0
errors = []
with get_db() as conn:
cur = get_cursor(conn)
for row_num, row in enumerate(reader, start=2):
try:
# Parse date (format: "2026-02-21 00:00:00")
date_str = row.get('Datum/Uhrzeit', '').split()[0] # Extract date part
if not date_str:
skipped += 1
continue
# Parse values (columns might be empty)
resting_hr = None
hrv = None
vo2_max = None
spo2 = None
respiratory_rate = None
if 'Ruhepuls (count/min)' in row and row['Ruhepuls (count/min)']:
resting_hr = int(float(row['Ruhepuls (count/min)']))
if 'Herzfrequenzvariabilität (ms)' in row and row['Herzfrequenzvariabilität (ms)']:
hrv = int(float(row['Herzfrequenzvariabilität (ms)']))
if 'VO2 max (ml/(kg·min))' in row and row['VO2 max (ml/(kg·min))']:
vo2_max = float(row['VO2 max (ml/(kg·min))'])
if 'Blutsauerstoffsättigung (%)' in row and row['Blutsauerstoffsättigung (%)']:
spo2 = int(float(row['Blutsauerstoffsättigung (%)']))
if 'Atemfrequenz (count/min)' in row and row['Atemfrequenz (count/min)']:
respiratory_rate = float(row['Atemfrequenz (count/min)'])
# Skip if no vitals data
if not any([resting_hr, hrv, vo2_max, spo2, respiratory_rate]):
skipped += 1
continue
# Upsert
cur.execute(
"""
INSERT INTO vitals_log (
profile_id, date, resting_hr, hrv, vo2_max, spo2,
respiratory_rate, source
)
VALUES (%s, %s, %s, %s, %s, %s, %s, 'apple_health')
ON CONFLICT (profile_id, date)
DO UPDATE SET
resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_log.resting_hr),
hrv = COALESCE(EXCLUDED.hrv, vitals_log.hrv),
vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_log.vo2_max),
spo2 = COALESCE(EXCLUDED.spo2, vitals_log.spo2),
respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_log.respiratory_rate),
source = CASE WHEN vitals_log.source = 'manual' THEN vitals_log.source ELSE 'apple_health' END,
updated_at = CURRENT_TIMESTAMP
RETURNING (xmax = 0) AS inserted
""",
(pid, date_str, resting_hr, hrv, vo2_max, spo2, respiratory_rate)
)
result = cur.fetchone()
if result['inserted']:
inserted += 1
else:
updated += 1
except Exception as e:
errors.append(f"Zeile {row_num}: {str(e)}")
logger.error(f"[APPLE-HEALTH-IMPORT] Error at row {row_num}: {e}")
continue
conn.commit()
logger.info(f"[APPLE-HEALTH-IMPORT] {pid}: {inserted} inserted, {updated} updated, {skipped} skipped, {len(errors)} errors")
return {
"message": "Apple Health CSV Import abgeschlossen",
"inserted": inserted,
"updated": updated,
"skipped": skipped,
"errors": errors[:10] # Limit to first 10 errors
}
+78 -41
View File
@@ -99,52 +99,90 @@ def create_or_update_baseline(
"""Create or update baseline entry (upsert on date).""" """Create or update baseline entry (upsert on date)."""
pid = get_pid(x_profile_id) pid = get_pid(x_profile_id)
# Build dynamic update columns (only non-None fields) # Build dynamic INSERT columns, placeholders, UPDATE fields, and values list
fields = [] # All arrays must stay synchronized
values = [pid, entry.date] insert_cols = []
insert_placeholders = []
update_fields = []
param_values = [] # Will contain ALL values including pid and date
# Always include profile_id and date
param_values.append(pid)
param_values.append(entry.date)
if entry.resting_hr is not None: if entry.resting_hr is not None:
fields.append("resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_baseline.resting_hr)") insert_cols.append("resting_hr")
values.append(entry.resting_hr) insert_placeholders.append("%s")
update_fields.append("resting_hr = EXCLUDED.resting_hr")
param_values.append(entry.resting_hr)
if entry.hrv is not None: if entry.hrv is not None:
fields.append("hrv = COALESCE(EXCLUDED.hrv, vitals_baseline.hrv)") insert_cols.append("hrv")
values.append(entry.hrv) insert_placeholders.append("%s")
update_fields.append("hrv = EXCLUDED.hrv")
param_values.append(entry.hrv)
if entry.vo2_max is not None: if entry.vo2_max is not None:
fields.append("vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_baseline.vo2_max)") insert_cols.append("vo2_max")
values.append(entry.vo2_max) insert_placeholders.append("%s")
update_fields.append("vo2_max = EXCLUDED.vo2_max")
param_values.append(entry.vo2_max)
if entry.spo2 is not None: if entry.spo2 is not None:
fields.append("spo2 = COALESCE(EXCLUDED.spo2, vitals_baseline.spo2)") insert_cols.append("spo2")
values.append(entry.spo2) insert_placeholders.append("%s")
update_fields.append("spo2 = EXCLUDED.spo2")
param_values.append(entry.spo2)
if entry.respiratory_rate is not None: if entry.respiratory_rate is not None:
fields.append("respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_baseline.respiratory_rate)") insert_cols.append("respiratory_rate")
values.append(entry.respiratory_rate) insert_placeholders.append("%s")
update_fields.append("respiratory_rate = EXCLUDED.respiratory_rate")
param_values.append(entry.respiratory_rate)
if entry.body_temperature is not None: if entry.body_temperature is not None:
fields.append("body_temperature = COALESCE(EXCLUDED.body_temperature, vitals_baseline.body_temperature)") insert_cols.append("body_temperature")
values.append(entry.body_temperature) insert_placeholders.append("%s")
update_fields.append("body_temperature = EXCLUDED.body_temperature")
param_values.append(entry.body_temperature)
if entry.resting_metabolic_rate is not None: if entry.resting_metabolic_rate is not None:
fields.append("resting_metabolic_rate = COALESCE(EXCLUDED.resting_metabolic_rate, vitals_baseline.resting_metabolic_rate)") insert_cols.append("resting_metabolic_rate")
values.append(entry.resting_metabolic_rate) insert_placeholders.append("%s")
update_fields.append("resting_metabolic_rate = EXCLUDED.resting_metabolic_rate")
param_values.append(entry.resting_metabolic_rate)
if entry.note: if entry.note:
fields.append("note = COALESCE(EXCLUDED.note, vitals_baseline.note)") insert_cols.append("note")
values.append(entry.note) insert_placeholders.append("%s")
update_fields.append("note = EXCLUDED.note")
param_values.append(entry.note)
# At least one field must be provided # At least one field must be provided
if not fields: if not insert_cols:
raise HTTPException(400, "At least one baseline vital must be provided") raise HTTPException(400, "At least one baseline vital must be provided")
# Build value placeholders
placeholders = ", ".join([f"${i}" for i in range(1, len(values) + 1)])
with get_db() as conn: with get_db() as conn:
cur = get_cursor(conn) cur = get_cursor(conn)
# Build complete column list and placeholder list
# IMPORTANT: psycopg2 uses %s placeholders, NOT $1/$2/$3
all_cols = f"profile_id, date, {', '.join(insert_cols)}"
all_placeholders = f"%s, %s, {', '.join(insert_placeholders)}"
query = f""" query = f"""
INSERT INTO vitals_baseline (profile_id, date, {', '.join([f.split('=')[0].strip() for f in fields])}) INSERT INTO vitals_baseline ({all_cols})
VALUES ($1, $2, {', '.join([f'${i}' for i in range(3, len(values) + 1)])}) VALUES ({all_placeholders})
ON CONFLICT (profile_id, date) ON CONFLICT (profile_id, date)
DO UPDATE SET {', '.join(fields)}, updated_at = NOW() DO UPDATE SET {', '.join(update_fields)}, updated_at = NOW()
RETURNING * RETURNING *
""" """
cur.execute(query, values)
# Debug logging
print(f"[DEBUG] Vitals baseline query: {query}")
print(f"[DEBUG] Param values ({len(param_values)}): {param_values}")
cur.execute(query, tuple(param_values))
return r2d(cur.fetchone()) return r2d(cur.fetchone())
@@ -161,32 +199,31 @@ def update_baseline(
# Build SET clause dynamically # Build SET clause dynamically
updates = [] updates = []
values = [] values = []
idx = 1
if entry.resting_hr is not None: if entry.resting_hr is not None:
updates.append(f"resting_hr = ${idx}") updates.append("resting_hr = %s")
values.append(entry.resting_hr) values.append(entry.resting_hr)
idx += 1
if entry.hrv is not None: if entry.hrv is not None:
updates.append(f"hrv = ${idx}") updates.append("hrv = %s")
values.append(entry.hrv) values.append(entry.hrv)
idx += 1
if entry.vo2_max is not None: if entry.vo2_max is not None:
updates.append(f"vo2_max = ${idx}") updates.append("vo2_max = %s")
values.append(entry.vo2_max) values.append(entry.vo2_max)
idx += 1
if entry.spo2 is not None: if entry.spo2 is not None:
updates.append(f"spo2 = ${idx}") updates.append("spo2 = %s")
values.append(entry.spo2) values.append(entry.spo2)
idx += 1
if entry.respiratory_rate is not None: if entry.respiratory_rate is not None:
updates.append(f"respiratory_rate = ${idx}") updates.append("respiratory_rate = %s")
values.append(entry.respiratory_rate) values.append(entry.respiratory_rate)
idx += 1 if entry.body_temperature is not None:
updates.append("body_temperature = %s")
values.append(entry.body_temperature)
if entry.resting_metabolic_rate is not None:
updates.append("resting_metabolic_rate = %s")
values.append(entry.resting_metabolic_rate)
if entry.note: if entry.note:
updates.append(f"note = ${idx}") updates.append("note = %s")
values.append(entry.note) values.append(entry.note)
idx += 1
if not updates: if not updates:
raise HTTPException(400, "No fields to update") raise HTTPException(400, "No fields to update")
@@ -199,7 +236,7 @@ def update_baseline(
query = f""" query = f"""
UPDATE vitals_baseline UPDATE vitals_baseline
SET {', '.join(updates)} SET {', '.join(updates)}
WHERE id = ${idx} AND profile_id = ${idx + 1} WHERE id = %s AND profile_id = %s
RETURNING * RETURNING *
""" """
cur.execute(query, values) cur.execute(query, values)
+196
View File
@@ -0,0 +1,196 @@
# Dokumentation Abgeschlossen - 27. März 2026
## ✅ Was wurde dokumentiert?
### 1. Hauptstatus-Dokument
📄 **`docs/STATUS_2026-03-27.md`** (NEU)
- Vollständiger aktueller Zustand
- Gitea Issues Status (offen/geschlossen)
- Nächste Schritte (Testing → Release → Code Splitting → Phase 0b)
- Code-Metriken und technische Schulden
- Entscheidungspunkte und Risiken
- **Wiederanstiegspunkt für zukünftige Sessions**
### 2. Neue Issue dokumentiert
📄 **`docs/issues/issue-52-blood-pressure-dual-targets.md`** (NEU)
- Blutdruck-Ziele benötigen zwei Zielfelder (systolisch/diastolisch)
- Migration 033 geplant
- UI-Anpassungen beschrieben
- 2-3h Aufwand geschätzt
### 3. CLAUDE.md aktualisiert
📄 **`CLAUDE.md`**
- Version: v0.9g+ → v0.9h
- Dynamic Focus Areas v2.0 Sektion hinzugefügt
- Bug Fixes dokumentiert
- Status: BEREIT FÜR RELEASE v0.9h
### 4. Roadmap aktualisiert
📄 **`.claude/docs/ROADMAP.md`**
- Phase 0a: ✅ COMPLETE
- Phase 0b: 🎯 NEXT (detaillierter Plan)
- Timeline aktualisiert
- Phasen-Übersicht neu strukturiert
---
## 📋 Gitea Issues - Aktueller Stand
### Geprüft ✅
- Alle offenen Issues durchgesehen (49, 47, 46, 45, 43, 42, 40, 39, 38, 37, 36, 35, 34, 33, 32, 30, 29, 27, 26, 25)
- Geschlossene Issues verifiziert (#50, #51, #48, #44, #28)
### Manuelle Aktionen erforderlich ⚠️
Du musst noch in Gitea (http://192.168.2.144:3000/Lars/mitai-jinkendo/issues):
1. **Issue #25 schließen:**
- Titel: "[FEAT] Ziele-System (Goals) - v9e Kernfeature"
- Status: ✅ KOMPLETT (Phase 0a + Dynamic Focus Areas v2.0)
- Aktion: Manuell auf "Closed" setzen
- Kommentar: "Completed in v0.9g-h: Phase 0a + Dynamic Focus Areas v2.0. See issue #50 and #51 for details."
2. **Issue #52 erstellen:**
- Titel: "Enhancement: Blutdruck-Ziele benötigen zwei Zielfelder (systolisch/diastolisch)"
- Labels: enhancement, goals, blood-pressure
- Priorität: Medium
- Beschreibung: Kopiere aus `docs/issues/issue-52-blood-pressure-dual-targets.md`
- Aufwand: 2-3h
- Milestone: v0.10a (nach Phase 0b)
---
## 🎯 Nächste Schritte (wenn du weitermachst)
### Sofort (nach Deployment-Test):
1. **Teste Vitals Baseline Fix**
- Ruhepuls eintragen (sollte jetzt funktionieren)
- Andere Baseline-Werte testen
2. **Beginne Goals Testing**
- Siehe Checklist in `STATUS_2026-03-27.md`
- 2-3 Tage gründliches Testing
### Dann:
3. **Release v0.9h vorbereiten**
- Release Notes schreiben
- Merge develop → main
- Tag v0.9h
- Deploy to Production
4. **Code Splitting durchführen**
- goals.py → 5 separate Router
- Optional: insights.py prüfen
5. **Phase 0b starten**
- 120+ goal-aware Platzhalter
- Score-System
- 16-20h Aufwand
---
## 📚 Wichtige Dokumente - Lesereihenfolge
Wenn du zu diesem Punkt zurückkehrst:
### 1. Zuerst lesen:
- **`docs/STATUS_2026-03-27.md`** ← START HIER
- **`CLAUDE.md`** (aktuelle Version)
- **`docs/NEXT_STEPS_2026-03-26.md`** (Phase 0b Details)
### 2. Bei Bedarf:
- **`.claude/docs/ROADMAP.md`** (Gesamtübersicht)
- **`docs/issues/issue-50-phase-0a-goal-system.md`** (Was wurde gebaut)
- **`docs/issues/issue-52-blood-pressure-dual-targets.md`** (Nächstes Enhancement)
### 3. Funktionale Specs:
- **`.claude/docs/functional/AI_PROMPTS.md`** (Prompt-System)
- **`.claude/docs/functional/TRAINING_TYPES.md`** (Trainingstypen + Abilities)
### 4. Technische Specs:
- **`.claude/docs/technical/MEMBERSHIP_SYSTEM.md`** (Feature-Enforcement)
- **`.claude/docs/architecture/`** (Wenn vorhanden)
---
## 🔄 Wiederanstiegspunkt für Claude Code
### Context Prompt (copy-paste für neue Session):
```
Wir sind bei v0.9g/h Release-Vorbereitung.
AKTUELLER STAND:
- Phase 0a (Goals System) + Dynamic Focus Areas v2.0: ✅ KOMPLETT
- Vitals baseline fix: deployed (needs testing)
- Branch: develop (6 commits ahead of main)
- Status: BEREIT FÜR RELEASE v0.9h
NÄCHSTER SCHRITT:
- Testing (Goals + Vitals)
- Dann: Release v0.9h → Code Splitting → Phase 0b
LIES ZUERST:
- docs/STATUS_2026-03-27.md (vollständiger Zustand)
- CLAUDE.md (aktuelle Version)
FRAGE MICH:
"Was ist der aktuelle Schritt?" → Dann sage ich dir Testing/Release/Splitting/Phase 0b
```
---
## 📊 Zusammenfassung - Was ist fertig?
### ✅ Komplett implementiert
- Goals System (Phase 0a)
- Strategic Layer (goal_mode, goals CRUD)
- Tactical Layer (CustomGoalsPage)
- Training Phases Framework (tables, backend)
- Fitness Tests Framework (tables, backend)
- Dynamic Focus Areas v2.0
- 26 Basis-Bereiche in 7 Kategorien
- User-extensible (Admin CRUD UI)
- Many-to-Many Goals ↔ Focus Areas
- User preferences mit Gewichtungen
- Bug Fixes
- Focus contributions speichern
- Filtering (nur gewichtete Areas)
- Vitals baseline endpoint
### 🔲 Noch zu tun (dokumentiert)
- Code Splitting (goals.py → 5 Router)
- Phase 0b (120+ Platzhalter, Score-System)
- Issue #52 (BP dual targets)
- Responsive UI (Issue #30)
- Weitere Features (siehe Roadmap)
---
## 🎉 Dokumentations-Qualität
**Vollständigkeit:** ⭐⭐⭐⭐⭐
- Alle wichtigen Dokumente aktualisiert
- Neue Dokumente erstellt
- Gitea Issues geprüft
- Wiederanstiegspunkt klar definiert
**Nachvollziehbarkeit:** ⭐⭐⭐⭐⭐
- Status-Dokument mit allen Details
- Entscheidungen dokumentiert
- Nächste Schritte klar beschrieben
**Wartbarkeit:** ⭐⭐⭐⭐⭐
- Strukturierte Dokumentation
- Klare Verweise zwischen Dokumenten
- Lesereihenfolge definiert
---
**Erstellt:** 27. März 2026, 23:00 Uhr
**Von:** Claude Code (Sonnet 4.5)
**Commit:** eb5c099 (docs: comprehensive status update v0.9h pre-release)
**Du kannst jetzt:**
✅ Sicher pausieren
✅ Deployment testen
✅ Jederzeit exakt an diesem Punkt weitermachen
+272
View File
@@ -0,0 +1,272 @@
# Projekt-Status: 27. März 2026
**Branch:** `develop`
**Letzte Version:** v0.9g+ (vor Release v0.9h)
**Deployment:** dev.mitai.jinkendo.de
**Nächster Meilenstein:** Release v0.9h → Code Splitting → Phase 0b
---
## 🎯 Aktueller Zustand: BEREIT FÜR RELEASE v0.9h
### Was ist fertig? ✅
#### Goals System (Phase 0a + Dynamic Focus Areas v2.0)
- ✅ **Migration 022:** goals, training_phases, fitness_tests tables
- ✅ **Migration 027-032:** Dynamic Focus Areas
- 26 Basis-Bereiche in 7 Kategorien (user-extensible)
- Many-to-Many: Goals ↔ Focus Areas mit contribution weights
- User preferences mit dynamischen Gewichtungen
- ✅ **Backend:**
- `routers/goals.py` - CRUD für Goals (~1200 Zeilen, **needs splitting**)
- `routers/focus_areas.py` - Dynamic system CRUD (~350 Zeilen)
- ✅ **Frontend:**
- `GoalsPage.jsx` - Strategic layer (~1180 Zeilen, **needs component extraction**)
- `CustomGoalsPage.jsx` - Tactical daily entry
- `AdminFocusAreasPage.jsx` - Admin UI für Focus Areas
- ✅ **Navigation:** Dashboard + Analysis integriert
#### Bug Fixes (alle committed, deployed pending)
- ✅ Focus area contributions speichern (fehlte in API payload)
- ✅ Filtering: Nur gewichtete Focus Areas im Ziel-Formular
- ✅ Vitals baseline endpoint (parameter mismatch behoben)
---
## 📋 Gitea Issues - Status
### Geschlossen ✅
- ✅ **#50:** Goals System v1 (Phase 0a)
- ✅ **#51:** Dynamic Focus Areas v2.0
- ✅ **#48:** Flexibles KI Prompt System
- ✅ **#44:** BUG - Analysen löschen
- ✅ **#28:** AI-Prompts Flexibilisierung
- ⏳ **#25:** Goals System (sollte geschlossen werden - ist fertig!)
### Offen - Priorisiert 🔲
- 🔲 **#52:** NEW - Blutdruck-Ziele mit dual targets (systolic/diastolic) - 2-3h
- 🔲 **#49:** Prompt-Zuordnung zu Verlaufsseiten (6-8h, Quick Win)
- 🔲 **#47:** Wertetabelle Optimierung (4-6h, nach Phase 0b)
- 🔲 **#30:** Responsive UI - Desktop Sidebar (8-10h)
- 🔲 **#29:** Abilities-Matrix UI (6-8h)
### Offen - Backlog 📦
- 📦 #46, #45: KI Prompt-Ersteller/-Optimierer (später)
- 📦 #43, #42: Enhanced Debug UI (später)
- 📦 #40: Logout-Button (kosmetisch)
- 📦 #39: Usage-Badges Dashboard (kosmetisch)
- 📦 #27: Korrelationen erweitern (Phase 2)
- 📦 #26: Charts erweitern (Phase 1)
---
## 🚀 Nächste Schritte (User-Plan APPROVED)
### Phase 1: Testing + Release (2-3 Tage)
```
Tag 1-2: Umfassende Tests des Goals-Moduls
[ ] Goal Mode wechseln
[ ] Focus Areas gewichten (alle 26 testen)
[ ] Ziele erstellen mit focus_contributions
[ ] Ziele bearbeiten (contributions ändern)
[ ] Ist-Werte eintragen (CustomGoalsPage)
[ ] Progress Modal testen
[ ] Admin Focus Areas CRUD
[ ] Edge Cases (leere Daten, Extremwerte)
[ ] Vitals baseline entry (Ruhepuls) - nach neuem Deployment
Tag 3: Deploy + Release v0.9h
[ ] Final commit & push
[ ] Merge develop → main (PR in Gitea)
[ ] Tag v0.9h in Git
[ ] Deploy to Production
[ ] Smoke Tests
[ ] Release Notes schreiben
```
### Phase 2: Code Splitting (1-2 Tage)
```
Tag 3-4: Backend Router Split
[ ] goals.py → 5 separate Router
- goals.py (core CRUD ~300 Zeilen)
- goal_types.py (~200 Zeilen)
- goal_progress.py (~150 Zeilen)
- training_phases.py (~150 Zeilen)
- fitness_tests.py (~150 Zeilen)
[ ] Imports anpassen
[ ] main.py: 5 neue Router registrieren
[ ] Optional: insights.py prüfen (wenn >800 Zeilen)
Tag 5: Testing nach Split
[ ] API-Endpoints vollständig testen
[ ] Frontend funktioniert
[ ] Deployment auf dev
```
### Phase 3: Phase 0b - Goal-Aware Placeholders (4 Tage)
```
Aufwand: 16-20h
Neue Platzhalter: 120+ Funktionen
Tag 6: KÖRPER + ERNÄHRUNG (40 Funktionen)
- weight_7d_rolling_median, weight_28d_trend_slope
- fm_28d_delta, lbm_28d_delta, recomposition_score
- protein_g_per_kg, protein_g_per_kg_lbm
- nutrition_adherence_score, energy_availability
Tag 7: AKTIVITÄT + RECOVERY (37 Funktionen)
- activity_quality_avg_28d, activity_strain_28d
- activity_monotony_28d, ability_balance_score
- recovery_score, sleep_regularity_index, sleep_debt_hours
Tag 8: KORRELATIONEN + META + Scoring (20 Funktionen + System)
- corr_energy_weight_lag, plateau_detected
- goal_mode, data_quality_score, profile_age_years
- Score-Gewichtung pro goal_mode implementieren
Tag 9: Integration + Testing
- Prompts aktualisieren mit neuen Platzhaltern
- Testing mit verschiedenen goal_modes
- Dokumentation
Tag 10: Deploy v0.10a
```
---
## 📊 Code-Metriken (Stand 27.03.2026)
### Große Dateien (Splitting-Kandidaten)
```
Backend:
- routers/goals.py ~1200 Zeilen ⚠️ SPLIT NEEDED
- routers/insights.py ~800 Zeilen (prüfen)
- routers/focus_areas.py ~350 Zeilen ✓ OK
Frontend:
- pages/GoalsPage.jsx ~1180 Zeilen ⚠️ Component extraction möglich
- pages/AdminPanel.jsx ~700 Zeilen ✓ OK
- pages/CustomGoalsPage.jsx ~350 Zeilen ✓ OK
```
### Migrations Status
```
Letzte Migration: 032_user_focus_area_weights.sql
Nächste: 033_dual_target_fields.sql (BP goals, Issue #52)
Alle Migrationen 001-032 erfolgreich angewandt auf dev ✅
```
---
## 🔧 Technische Schulden
### Hoch-Priorität
1. **Code Splitting:** goals.py zu groß für Context Window
2. **Component Extraction:** GoalsPage.jsx komponenten-basiert
3. **Testing Suite:** Automatisierte Tests fehlen komplett
### Mittel-Priorität
4. **Responsive UI:** Desktop-Sidebar fehlt (Issue #30)
5. **Error Handling:** Mehr defensive Programmierung nötig
6. **API Documentation:** Swagger/OpenAPI fehlt
### Niedrig-Priorität
7. **Type Hints:** Mehr Python Type Annotations
8. **Performance:** Einige N+1 Queries optimieren
9. **Caching:** Redis für häufige Abfragen
---
## 📚 Dokumentation - Status
### Aktuell ✅
- ✅ `CLAUDE.md` - Hauptdokumentation
- ✅ `docs/STATUS_2026-03-27.md` - Dieser Status (NEU)
- ✅ `docs/NEXT_STEPS_2026-03-26.md` - Roadmap Phase 0b
- ✅ `docs/issues/issue-50-phase-0a-goal-system.md` - Phase 0a abgeschlossen
- ✅ `docs/issues/issue-52-blood-pressure-dual-targets.md` - Neue Issue (NEU)
- ✅ `.claude/docs/functional/AI_PROMPTS.md` - Prompt-System komplett
- ✅ `.claude/docs/technical/MEMBERSHIP_SYSTEM.md` - Feature-Enforcement
### Zu aktualisieren 📝
- 📝 `CLAUDE.md` - v0.9g/h Updates eintragen
- 📝 `.claude/docs/ROADMAP.md` - Phase 0a als ✅ markieren
- 📝 `.claude/library/` - Nach v0.9h Release aktualisieren
---
## 🎯 Decision Points
### Entschieden ✅
1. **User-Plan APPROVED:** Testing → Release → Split → Phase 0b
2. **Code Splitting:** Backend Router zuerst, Frontend optional
3. **Phase 0b:** Szenario 2 (Strategic Depth first) - 120+ Platzhalter
4. **Release Strategy:** v0.9h als stabiler Rollback-Punkt
### Offen 🤔
1. **Issue #52 (BP dual targets):** Vor oder nach Phase 0b? → **Empfehlung: Nach Phase 0b**
2. **Frontend Components:** Extract während oder nach Split? → **Empfehlung: Nach, wenn Zeit**
3. **Issue #49 (Prompt pages):** Vor oder nach Phase 0b? → **Empfehlung: Nach Phase 0b**
---
## 🚨 Aktuelle Blocker / Risiken
### Keine kritischen Blocker ✅
**Kleine Risiken:**
1. ⚠️ **Vitals baseline fix:** Gerade deployed, needs testing
2. ⚠️ **Migration 032:** Muss auf Prod laufen (dev läuft bereits)
3. ⚠️ **Code Splitting:** Könnte Regressionen einführen → gründliches Testing
---
## 📞 Ansprechpunkte für Wiederaufnahme
**Wenn du zu diesem Stand zurückkehrst:**
1. **Lies zuerst:**
- Dieses Dokument (STATUS_2026-03-27.md)
- CLAUDE.md (aktuelle Version)
- docs/NEXT_STEPS_2026-03-26.md (Roadmap)
2. **Prüfe:**
- Ist v0.9h deployed? `git describe --tags`
- Läuft dev/prod? `curl https://dev.mitai.jinkendo.de/api/version`
- Gitea Issues-Status aktuell?
3. **Nächster Schritt:**
- Falls v0.9h deployed: Start Code Splitting
- Falls nicht: Führe Testing-Checklist aus (siehe Phase 1 oben)
4. **Claude Code Context:**
```
"Wir sind bei v0.9h Release. Goals-System ist komplett (Phase 0a + Dynamic Focus Areas v2.0).
Nächster Schritt: [Testing/Code Splitting/Phase 0b] - siehe STATUS_2026-03-27.md"
```
---
## 📈 Metriken seit letztem Stand
**Commits seit v0.9g:**
- 6 Commits (Goals fixes, Focus Areas v2.0, Vitals baseline fix)
- +1200 Zeilen (neue Features)
- -400 Zeilen (Refactoring)
**Issues:**
- 3 geschlossen (#50, #51, #48)
- 1 neu (#52)
- 1 sollte geschlossen werden (#25)
**Deployment:**
- Letzte 3 Deployments erfolgreich
- Dev-Environment stabil
- Prod auf v0.9g (stabil)
---
**Erstellt:** 27. März 2026, 22:30 Uhr
**Von:** Claude Code (Sonnet 4.5)
**Nächstes Update:** Nach v0.9h Release
@@ -0,0 +1,157 @@
# Issue #52: Blutdruck-Ziele benötigen zwei Zielfelder
**Status:** 🔲 OFFEN
**Erstellt:** 27.03.2026
**Priorität:** Medium
**Typ:** Enhancement
**Labels:** goals, blood-pressure, enhancement
**Aufwand:** 2-3h
---
## Problem
**Aktuell:**
- Blutdruck-Ziele (goal_type = 'bp') haben nur EIN Zielfeld (`target_value`)
- Blutdruck besteht aber aus ZWEI Werten: Systolisch + Diastolisch
- Beispiel-Ziel: "Blutdruck senken auf 120/80 mmHg"
- Systolisch (oberer Wert): 120
- Diastolisch (unterer Wert): 80
**Konsequenz:**
- User kann nur einen Wert als Ziel eingeben
- Unvollständige Zieldefinition
- Progress-Tracking ungenau
---
## Lösung
### Option A: Dual Target Fields (empfohlen)
**Schema-Änderung:**
```sql
-- Migration 033
ALTER TABLE goals ADD COLUMN target_value_secondary DECIMAL(10,2);
ALTER TABLE goals ADD COLUMN current_value_secondary DECIMAL(10,2);
ALTER TABLE goals ADD COLUMN start_value_secondary DECIMAL(10,2);
COMMENT ON COLUMN goals.target_value_secondary IS 'Secondary target (e.g., diastolic BP for bp goal type)';
```
**Anwendung:**
- `bp` goal type:
- `target_value` = Systolisch (120)
- `target_value_secondary` = Diastolisch (80)
- Andere goal types: `target_value_secondary` = NULL
**UI-Anpassung:**
```jsx
// GoalForm - conditional rendering
{formData.goal_type === 'bp' && (
<div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
<div>
<label>Systolisch (oben)</label>
<input type="number" value={formData.target_value} />
</div>
<div>
<label>Diastolisch (unten)</label>
<input type="number" value={formData.target_value_secondary} />
</div>
</div>
)}
```
**Progress-Berechnung:**
```python
def calculate_bp_progress(goal):
"""
Berechnet Progress für Blutdruck-Ziele.
Nimmt Durchschnitt von systolischem und diastolischem Progress.
"""
systolic_progress = calculate_single_progress(
goal.current_value, goal.start_value, goal.target_value
)
diastolic_progress = calculate_single_progress(
goal.current_value_secondary,
goal.start_value_secondary,
goal.target_value_secondary
)
return (systolic_progress + diastolic_progress) / 2
```
**Display:**
```
🎯 Blutdruck
━━━━━━━━━━━━━━━━━━━━
Ziel: 120/80 mmHg
Aktuell: 135/88 mmHg
Fortschritt: 68% (sys: 60%, dia: 75%)
━━━━━━━━━━━━━━━━━━━━
```
---
### Option B: JSON Target (flexibler, komplexer)
```sql
ALTER TABLE goals ADD COLUMN target_json JSONB;
-- Beispiel:
{
"systolic": 120,
"diastolic": 80,
"unit": "mmHg"
}
```
**Nachteil:** Komplexer zu abfragen, weniger SQL-freundlich.
---
## Betroffene Dateien
**Backend:**
- `backend/migrations/033_dual_target_fields.sql` (NEU)
- `backend/routers/goals.py` - Progress-Berechnung erweitern
- `backend/routers/goal_utils.py` - `_get_current_value_for_goal_type()` für BP
**Frontend:**
- `frontend/src/pages/GoalsPage.jsx` - Form conditional rendering
- `frontend/src/pages/GoalsPage.jsx` - Display conditional rendering
- `frontend/src/pages/CustomGoalsPage.jsx` - Dual input für BP
---
## Acceptance Criteria
- [ ] Migration 033 erstellt und angewandt
- [ ] GoalForm zeigt zwei Felder für BP-Ziele (Systolisch/Diastolisch)
- [ ] Progress-Berechnung berücksichtigt beide Werte
- [ ] Display zeigt "120/80 mmHg" Format
- [ ] CustomGoalsPage erlaubt Eingabe beider Werte
- [ ] Backward compatible (alte BP-Ziele mit nur target_value funktionieren noch)
---
## Verwandte Issues
- Issue #50: Goals System v1 ✅
- Issue #51: Dynamic Focus Areas v2.0 ✅
- Migration 022: goals table (Basis)
---
## Timeline
**Geschätzt:** 2-3 Stunden
- Migration: 30 min
- Backend Logic: 1h
- Frontend UI: 1-1.5h
- Testing: 30 min
---
**Erstellt von:** Claude Code
**Review benötigt:** Vor Implementierung mit User abstimmen (Option A vs. B)
+64
View File
@@ -0,0 +1,64 @@
# Test-Prompt für Phase 0b - Goal-Aware Placeholders
## Schnelltest-Prompt für Calculation Engine
**Zweck:** Validierung der 100+ Phase 0b Placeholders ohne JSON-Formatters
### Test-Prompt (in Admin UI → KI-Prompts erstellen):
```
Du bist ein Fitness-Coach. Analysiere den Fortschritt:
## Gesamtfortschritt
- Goal Progress Score: {{goal_progress_score}}/100
- Body: {{body_progress_score}}/100
- Nutrition: {{nutrition_score}}/100
- Activity: {{activity_score}}/100
- Recovery: {{recovery_score}}/100
## Kategorie-Fortschritte
- Körper: {{focus_cat_körper_progress}}% (Prio: {{focus_cat_körper_weight}}%)
- Ernährung: {{focus_cat_ernährung_progress}}% (Prio: {{focus_cat_ernährung_weight}}%)
- Aktivität: {{focus_cat_aktivität_progress}}% (Prio: {{focus_cat_aktivität_weight}}%)
## Körper-Metriken
- Gewicht 7d: {{weight_7d_median}} kg
- FM Änderung 28d: {{fm_28d_change}} kg
- LBM Änderung 28d: {{lbm_28d_change}} kg
- Rekomposition: {{recomposition_quadrant}}
## Ernährung
- Energiebilanz: {{energy_balance_7d}} kcal/Tag
- Protein g/kg: {{protein_g_per_kg}}
- Protein Adequacy: {{protein_adequacy_28d}}/100
## Aktivität
- Minuten/Woche: {{training_minutes_week}}
- Qualität: {{quality_sessions_pct}}%
- Kraft-Balance: {{ability_balance_strength}}/100
## Recovery
- HRV vs Baseline: {{hrv_vs_baseline_pct}}%
- Schlaf 7d: {{sleep_avg_duration_7d}}h
- Schlafqualität: {{sleep_quality_7d}}/100
Gib 3 konkrete Empfehlungen basierend auf den schwächsten Scores.
```
### Erwartetes Verhalten:
✅ Alle Placeholders lösen auf (numerisch oder "nicht verfügbar")
✅ Keine Python Exceptions
✅ Scores haben Werte 0-100 oder "nicht verfügbar"
### Test-Schritte:
1. Admin → KI-Prompts → "Neu erstellen"
2. Type: "base", Name: "Phase 0b Quick Test"
3. Template einfügen
4. "Test" Button → Profil wählen
5. Debug-Viewer prüfen: "Unresolved Placeholders" sollte leer sein
6. Wenn Errors: Console Log prüfen
### Bekannte Limitierungen (aktuell):
- JSON-Formatters (active_goals_json, etc.) → geben leere Arrays
- Top Goal Name → "nicht verfügbar" (needs goal_utils extension)
- Correlations → Placeholder-Werte (noch nicht echte Berechnungen)
+2
View File
@@ -32,6 +32,7 @@ import AdminActivityMappingsPage from './pages/AdminActivityMappingsPage'
import AdminTrainingProfiles from './pages/AdminTrainingProfiles' import AdminTrainingProfiles from './pages/AdminTrainingProfiles'
import AdminPromptsPage from './pages/AdminPromptsPage' import AdminPromptsPage from './pages/AdminPromptsPage'
import AdminGoalTypesPage from './pages/AdminGoalTypesPage' import AdminGoalTypesPage from './pages/AdminGoalTypesPage'
import AdminFocusAreasPage from './pages/AdminFocusAreasPage'
import SubscriptionPage from './pages/SubscriptionPage' import SubscriptionPage from './pages/SubscriptionPage'
import SleepPage from './pages/SleepPage' import SleepPage from './pages/SleepPage'
import RestDaysPage from './pages/RestDaysPage' import RestDaysPage from './pages/RestDaysPage'
@@ -192,6 +193,7 @@ function AppShell() {
<Route path="/admin/training-profiles" element={<AdminTrainingProfiles/>}/> <Route path="/admin/training-profiles" element={<AdminTrainingProfiles/>}/>
<Route path="/admin/prompts" element={<AdminPromptsPage/>}/> <Route path="/admin/prompts" element={<AdminPromptsPage/>}/>
<Route path="/admin/goal-types" element={<AdminGoalTypesPage/>}/> <Route path="/admin/goal-types" element={<AdminGoalTypesPage/>}/>
<Route path="/admin/focus-areas" element={<AdminFocusAreasPage/>}/>
<Route path="/subscription" element={<SubscriptionPage/>}/> <Route path="/subscription" element={<SubscriptionPage/>}/>
</Routes> </Routes>
</main> </main>
+475
View File
@@ -0,0 +1,475 @@
import { useState, useEffect } from 'react'
import { Plus, Pencil, Trash2, Save, X, Eye, EyeOff } from 'lucide-react'
import { api } from '../utils/api'
const CATEGORIES = [
{ value: 'body_composition', label: 'Körperzusammensetzung' },
{ value: 'training', label: 'Training' },
{ value: 'endurance', label: 'Ausdauer' },
{ value: 'coordination', label: 'Koordination' },
{ value: 'mental', label: 'Mental' },
{ value: 'recovery', label: 'Erholung' },
{ value: 'health', label: 'Gesundheit' },
{ value: 'custom', label: 'Eigene' }
]
export default function AdminFocusAreasPage() {
const [data, setData] = useState({ areas: [], grouped: {}, total: 0 })
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [showInactive, setShowInactive] = useState(false)
const [editingId, setEditingId] = useState(null)
const [creating, setCreating] = useState(false)
const [formData, setFormData] = useState({
key: '',
name_de: '',
name_en: '',
icon: '',
description: '',
category: 'custom'
})
useEffect(() => {
loadData()
}, [showInactive])
const loadData = async () => {
try {
setLoading(true)
const result = await api.listFocusAreaDefinitions(showInactive)
setData(result)
setError(null)
} catch (err) {
console.error('Failed to load focus areas:', err)
setError(err.message)
} finally {
setLoading(false)
}
}
const handleCreate = async () => {
if (!formData.key || !formData.name_de) {
setError('Key und Name (DE) sind erforderlich')
return
}
try {
await api.createFocusAreaDefinition(formData)
setCreating(false)
setFormData({
key: '',
name_de: '',
name_en: '',
icon: '',
description: '',
category: 'custom'
})
await loadData()
} catch (err) {
setError(err.message)
}
}
const handleUpdate = async (id) => {
try {
const area = data.areas.find(a => a.id === id)
await api.updateFocusAreaDefinition(id, {
name_de: area.name_de,
name_en: area.name_en,
icon: area.icon,
description: area.description,
category: area.category,
is_active: area.is_active
})
setEditingId(null)
await loadData()
} catch (err) {
setError(err.message)
}
}
const handleDelete = async (id) => {
if (!confirm('Focus Area wirklich löschen?')) return
try {
await api.deleteFocusAreaDefinition(id)
await loadData()
} catch (err) {
setError(err.message)
}
}
const handleToggleActive = async (id) => {
const area = data.areas.find(a => a.id === id)
try {
await api.updateFocusAreaDefinition(id, {
is_active: !area.is_active
})
await loadData()
} catch (err) {
setError(err.message)
}
}
const updateField = (id, field, value) => {
setData(prev => ({
...prev,
areas: prev.areas.map(a =>
a.id === id ? { ...a, [field]: value } : a
)
}))
}
if (loading) {
return (
<div style={{ padding: 20, textAlign: 'center' }}>
<div className="spinner" />
</div>
)
}
return (
<div style={{ padding: 16, paddingBottom: 80 }}>
{/* Header */}
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 16
}}>
<h1 style={{ fontSize: 24, fontWeight: 700, margin: 0 }}>
🎯 Focus Areas ({data.total})
</h1>
<div style={{ display: 'flex', gap: 8 }}>
<button
className="btn-secondary"
onClick={() => setShowInactive(!showInactive)}
style={{ padding: '8px 12px', fontSize: 13 }}
>
{showInactive ? <Eye size={14} /> : <EyeOff size={14} />}
{showInactive ? 'Inaktive ausblenden' : 'Inaktive anzeigen'}
</button>
<button
className="btn-primary"
onClick={() => setCreating(true)}
style={{ padding: '8px 16px' }}
>
<Plus size={16} /> Neue Focus Area
</button>
</div>
</div>
{error && (
<div style={{
padding: 12,
background: '#FEE2E2',
color: '#991B1B',
borderRadius: 8,
marginBottom: 16,
fontSize: 14
}}>
{error}
</div>
)}
{/* Create Form */}
{creating && (
<div className="card" style={{ marginBottom: 16, background: 'var(--accent-light)' }}>
<h3 style={{ fontSize: 16, marginBottom: 12, color: 'var(--accent)' }}>
Neue Focus Area
</h3>
<div style={{ display: 'grid', gap: 12 }}>
<div>
<label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 4 }}>
Key (Eindeutig, z.B. "explosive_power")
</label>
<input
className="form-input"
value={formData.key}
onChange={(e) => setFormData({ ...formData, key: e.target.value })}
placeholder="explosive_power"
style={{ width: '100%' }}
/>
</div>
<div>
<label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 4 }}>
Name (Deutsch) *
</label>
<input
className="form-input"
value={formData.name_de}
onChange={(e) => setFormData({ ...formData, name_de: e.target.value })}
placeholder="Explosivkraft"
style={{ width: '100%' }}
/>
</div>
<div>
<label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 4 }}>
Name (English)
</label>
<input
className="form-input"
value={formData.name_en}
onChange={(e) => setFormData({ ...formData, name_en: e.target.value })}
placeholder="Explosive Power"
style={{ width: '100%' }}
/>
</div>
<div>
<label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 4 }}>
Icon (Emoji)
</label>
<input
className="form-input"
value={formData.icon}
onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
placeholder="💥"
style={{ width: '100%' }}
/>
</div>
<div>
<label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 4 }}>
Kategorie
</label>
<select
className="form-input"
value={formData.category}
onChange={(e) => setFormData({ ...formData, category: e.target.value })}
style={{ width: '100%' }}
>
{CATEGORIES.map(cat => (
<option key={cat.value} value={cat.value}>{cat.label}</option>
))}
</select>
</div>
<div>
<label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 4 }}>
Beschreibung
</label>
<textarea
className="form-input"
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="Kraft in kürzester Zeit explosiv entfalten"
rows={2}
style={{ width: '100%' }}
/>
</div>
<div style={{ display: 'flex', gap: 8 }}>
<button className="btn-primary" onClick={handleCreate} style={{ flex: 1 }}>
<Save size={14} /> Erstellen
</button>
<button
className="btn-secondary"
onClick={() => {
setCreating(false)
setFormData({
key: '',
name_de: '',
name_en: '',
icon: '',
description: '',
category: 'custom'
})
}}
style={{ flex: 1 }}
>
<X size={14} /> Abbrechen
</button>
</div>
</div>
</div>
)}
{/* Grouped Areas */}
{Object.entries(data.grouped).map(([category, areas]) => (
<div key={category} style={{ marginBottom: 24 }}>
<h2 style={{
fontSize: 14,
fontWeight: 600,
color: 'var(--text2)',
textTransform: 'uppercase',
letterSpacing: '0.05em',
marginBottom: 12
}}>
{CATEGORIES.find(c => c.value === category)?.label || category} ({areas.length})
</h2>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{areas.map(area => {
const isEditing = editingId === area.id
return (
<div
key={area.id}
className="card"
style={{
opacity: area.is_active ? 1 : 0.5,
borderLeft: area.is_active
? '4px solid var(--accent)'
: '4px solid var(--border)'
}}
>
{isEditing ? (
<div style={{ display: 'grid', gap: 12 }}>
<div>
<label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>
Name (DE)
</label>
<input
className="form-input"
value={area.name_de}
onChange={(e) => updateField(area.id, 'name_de', e.target.value)}
style={{ width: '100%' }}
/>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>
Icon
</label>
<input
className="form-input"
value={area.icon || ''}
onChange={(e) => updateField(area.id, 'icon', e.target.value)}
style={{ width: '100%' }}
/>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>
Beschreibung
</label>
<textarea
className="form-input"
value={area.description || ''}
onChange={(e) => updateField(area.id, 'description', e.target.value)}
rows={2}
style={{ width: '100%' }}
/>
</div>
<div style={{ display: 'flex', gap: 8 }}>
<button
className="btn-primary"
onClick={() => handleUpdate(area.id)}
style={{ flex: 1 }}
>
<Save size={14} /> Speichern
</button>
<button
className="btn-secondary"
onClick={() => {
setEditingId(null)
loadData()
}}
style={{ flex: 1 }}
>
<X size={14} /> Abbrechen
</button>
</div>
</div>
) : (
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'flex-start',
gap: 12
}}>
<div style={{ flex: 1 }}>
<div style={{
fontSize: 16,
fontWeight: 600,
marginBottom: 4,
display: 'flex',
alignItems: 'center',
gap: 8
}}>
{area.icon && <span>{area.icon}</span>}
<span>{area.name_de}</span>
{!area.is_active && (
<span style={{
fontSize: 11,
padding: '2px 6px',
background: 'var(--border)',
borderRadius: 4,
color: 'var(--text3)'
}}>
Inaktiv
</span>
)}
</div>
<div style={{ fontSize: 12, color: 'var(--text3)', marginBottom: 4 }}>
Key: <code style={{
background: 'var(--surface2)',
padding: '2px 4px',
borderRadius: 4
}}>
{area.key}
</code>
</div>
{area.description && (
<div style={{ fontSize: 13, color: 'var(--text2)', marginTop: 4 }}>
{area.description}
</div>
)}
</div>
<div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
<button
className="btn-secondary"
onClick={() => handleToggleActive(area.id)}
style={{ padding: '6px 12px' }}
title={area.is_active ? 'Deaktivieren' : 'Aktivieren'}
>
{area.is_active ? <EyeOff size={14} /> : <Eye size={14} />}
</button>
<button
className="btn-secondary"
onClick={() => setEditingId(area.id)}
style={{ padding: '6px 12px' }}
title="Bearbeiten"
>
<Pencil size={14} />
</button>
<button
className="btn-secondary"
onClick={() => handleDelete(area.id)}
style={{ padding: '6px 12px', color: '#DC2626' }}
title="Löschen"
>
<Trash2 size={14} />
</button>
</div>
</div>
)}
</div>
)
})}
</div>
</div>
))}
{data.areas.length === 0 && (
<div style={{
padding: 40,
textAlign: 'center',
color: 'var(--text3)'
}}>
Keine Focus Areas vorhanden
</div>
)}
</div>
)
}
+17
View File
@@ -485,6 +485,23 @@ export default function AdminPanel() {
</Link> </Link>
</div> </div>
</div> </div>
{/* Focus Areas Section */}
<div className="card section-gap" style={{marginTop:16}}>
<div style={{fontWeight:700,fontSize:14,marginBottom:12,display:'flex',alignItems:'center',gap:6}}>
<Settings size={16} color="var(--accent)"/> Focus Areas (v9g)
</div>
<div style={{fontSize:12,color:'var(--text3)',marginBottom:12,lineHeight:1.5}}>
Verwalte Focus Area Definitionen: Dynamisches, erweiterbares System mit 26+ Bereichen über 7 Kategorien.
</div>
<div style={{display:'grid',gap:8}}>
<Link to="/admin/focus-areas">
<button className="btn btn-secondary btn-full">
🎯 Focus Areas verwalten
</button>
</Link>
</div>
</div>
</div> </div>
) )
} }
+388 -193
View File
@@ -57,20 +57,16 @@ const getCategoryForGoalType = (goalType) => {
export default function GoalsPage() { export default function GoalsPage() {
const [goalMode, setGoalMode] = useState(null) const [goalMode, setGoalMode] = useState(null)
const [focusAreas, setFocusAreas] = useState(null) const [userFocusWeights, setUserFocusWeights] = useState([]) // v2.0: User's focus area weights
const [focusEditing, setFocusEditing] = useState(false) const [userFocusGrouped, setUserFocusGrouped] = useState({}) // Grouped by category
const [focusTemp, setFocusTemp] = useState({ const [focusWeightsEditing, setFocusWeightsEditing] = useState(false)
weight_loss_pct: 0, const [focusWeightsTemp, setFocusWeightsTemp] = useState({}) // Temp: {focus_area_id: weight}
muscle_gain_pct: 0,
strength_pct: 0,
endurance_pct: 0,
flexibility_pct: 0,
health_pct: 0
})
const [goals, setGoals] = useState([]) // Kept for backward compat const [goals, setGoals] = useState([]) // Kept for backward compat
const [groupedGoals, setGroupedGoals] = useState({}) // Category-grouped goals const [groupedGoals, setGroupedGoals] = useState({}) // Category-grouped goals
const [goalTypes, setGoalTypes] = useState([]) // Dynamic from DB (Phase 1.5) const [goalTypes, setGoalTypes] = useState([]) // Dynamic from DB (Phase 1.5)
const [goalTypesMap, setGoalTypesMap] = useState({}) // For quick lookup const [goalTypesMap, setGoalTypesMap] = useState({}) // For quick lookup
const [focusAreas, setFocusAreas] = useState([]) // v2.0: All available focus areas (for selection)
const [focusAreasGrouped, setFocusAreasGrouped] = useState({}) // Grouped by category
const [showGoalForm, setShowGoalForm] = useState(false) const [showGoalForm, setShowGoalForm] = useState(false)
const [editingGoal, setEditingGoal] = useState(null) const [editingGoal, setEditingGoal] = useState(null)
const [showProgressModal, setShowProgressModal] = useState(false) const [showProgressModal, setShowProgressModal] = useState(false)
@@ -95,7 +91,8 @@ export default function GoalsPage() {
unit: 'kg', unit: 'kg',
target_date: '', target_date: '',
name: '', name: '',
description: '' description: '',
focus_contributions: [] // v2.0: [{focus_area_id, contribution_weight}]
}) })
useEffect(() => { useEffect(() => {
@@ -106,31 +103,31 @@ export default function GoalsPage() {
setLoading(true) setLoading(true)
setError(null) setError(null)
try { try {
const [modeData, goalsData, groupedData, typesData, focusData] = await Promise.all([ const [modeData, goalsData, groupedData, typesData, userWeightsData, focusAreasData] = await Promise.all([
api.getGoalMode(), api.getGoalMode(),
api.listGoals(), api.listGoals(),
api.listGoalsGrouped(), // v2.1: Load grouped by category api.listGoalsGrouped(), // v2.1: Load grouped by category
api.listGoalTypeDefinitions(), // Phase 1.5: Load from DB api.listGoalTypeDefinitions(), // Phase 1.5: Load from DB
api.getFocusAreas() // v2.0: Load focus areas api.getUserFocusPreferences(), // v2.0: Load user's focus area weights
api.listFocusAreaDefinitions(false) // v2.0: Load all available focus areas
]) ])
setGoalMode(modeData.goal_mode) setGoalMode(modeData.goal_mode)
setGoals(goalsData) setGoals(goalsData)
setGroupedGoals(groupedData) setGroupedGoals(groupedData)
// Ensure all focus fields are present and numeric // v2.0: User focus weights (dynamic)
const sanitizedFocus = { setUserFocusWeights(userWeightsData.weights || [])
weight_loss_pct: focusData?.weight_loss_pct ?? 0, setUserFocusGrouped(userWeightsData.grouped || {})
muscle_gain_pct: focusData?.muscle_gain_pct ?? 0,
strength_pct: focusData?.strength_pct ?? 0,
endurance_pct: focusData?.endurance_pct ?? 0,
flexibility_pct: focusData?.flexibility_pct ?? 0,
health_pct: focusData?.health_pct ?? 0,
custom: focusData?.custom,
updated_at: focusData?.updated_at
}
setFocusAreas(sanitizedFocus) // Build temp object for editing: {focus_area_id: weight}
setFocusTemp(sanitizedFocus) const tempWeights = {}
if (userWeightsData.weights) {
userWeightsData.weights.forEach(w => {
tempWeights[w.id] = w.weight
})
}
setFocusWeightsTemp(tempWeights)
// Convert types array to map for quick lookup // Convert types array to map for quick lookup
const typesMap = {} const typesMap = {}
@@ -148,6 +145,12 @@ export default function GoalsPage() {
setGoalTypes(typesData || []) setGoalTypes(typesData || [])
setGoalTypesMap(typesMap) setGoalTypesMap(typesMap)
// v2.0: All focus area definitions (for selection in goal form)
if (focusAreasData) {
setFocusAreas(focusAreasData.areas || [])
setFocusAreasGrouped(focusAreasData.grouped || {})
}
} catch (err) { } catch (err) {
console.error('Failed to load goals:', err) console.error('Failed to load goals:', err)
setError(`Fehler beim Laden: ${err.message || err.toString()}`) setError(`Fehler beim Laden: ${err.message || err.toString()}`)
@@ -161,17 +164,6 @@ export default function GoalsPage() {
setTimeout(() => setToast(null), duration) setTimeout(() => setToast(null), duration)
} }
const handleGoalModeChange = async (newMode) => {
try {
await api.updateGoalMode(newMode)
setGoalMode(newMode)
showToast('✓ Trainingsmodus aktualisiert')
} catch (err) {
console.error('Failed to update goal mode:', err)
setError('Fehler beim Aktualisieren des Trainingsmodus')
}
}
const handleCreateGoal = () => { const handleCreateGoal = () => {
if (goalTypes.length === 0) { if (goalTypes.length === 0) {
setError('Keine Goal Types verfügbar. Bitte Admin kontaktieren.') setError('Keine Goal Types verfügbar. Bitte Admin kontaktieren.')
@@ -188,7 +180,8 @@ export default function GoalsPage() {
unit: goalTypesMap[firstType]?.unit || 'kg', unit: goalTypesMap[firstType]?.unit || 'kg',
target_date: '', target_date: '',
name: '', name: '',
description: '' description: '',
focus_contributions: [] // v2.0: Empty for new goal
}) })
setShowGoalForm(true) setShowGoalForm(true)
} }
@@ -204,7 +197,8 @@ export default function GoalsPage() {
unit: goal.unit, unit: goal.unit,
target_date: goal.target_date || '', target_date: goal.target_date || '',
name: goal.name || '', name: goal.name || '',
description: goal.description || '' description: goal.description || '',
focus_contributions: goal.focus_contributions || [] // v2.0: Load existing contributions
}) })
setShowGoalForm(true) setShowGoalForm(true)
} }
@@ -234,7 +228,8 @@ export default function GoalsPage() {
unit: formData.unit, unit: formData.unit,
target_date: formData.target_date || null, target_date: formData.target_date || null,
name: formData.name || null, name: formData.name || null,
description: formData.description || null description: formData.description || null,
focus_contributions: formData.focus_contributions || [] // v2.0: Focus area assignments
} }
console.log('[DEBUG] Saving goal:', { editingGoal, data }) console.log('[DEBUG] Saving goal:', { editingGoal, data })
@@ -391,175 +386,158 @@ export default function GoalsPage() {
</div> </div>
)} )}
{/* Focus Areas (v2.0) */} {/* Focus Areas (v2.0 - Dynamic) */}
<div className="card" style={{ marginBottom: 16 }}> <div className="card" style={{ marginBottom: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}> <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
<h2 style={{ margin: 0 }}>🎯 Fokus-Bereiche</h2> <h2 style={{ margin: 0 }}>🎯 Fokus-Bereiche</h2>
{!focusEditing && focusAreas && ( <button
<button className="btn-secondary"
className="btn-secondary" onClick={() => {
onClick={() => { // Initialize temp weights from current weights
setFocusTemp(focusAreas) // Sync temp state before editing const tempWeights = {}
setFocusEditing(true) focusAreas.forEach(fa => {
}} tempWeights[fa.id] = focusWeightsTemp[fa.id] || 0
style={{ padding: '6px 12px' }} })
> setFocusWeightsTemp(tempWeights)
<Pencil size={14} /> Anpassen setFocusWeightsEditing(!focusWeightsEditing)
</button> }}
)} style={{ padding: '6px 12px' }}
>
<Pencil size={14} /> {focusWeightsEditing ? 'Abbrechen' : 'Anpassen'}
</button>
</div> </div>
<p style={{ color: 'var(--text2)', fontSize: 14, marginBottom: 16 }}> <p style={{ color: 'var(--text2)', fontSize: 14, marginBottom: 16 }}>
Setze relative Gewichte für deine Trainingsziele. Das System berechnet automatisch die Prozentanteile. Wähle deine Trainingsschwerpunkte und gewichte sie relativ zueinander. Prozente werden automatisch berechnet.
{focusAreas && !focusAreas.custom && (
<span style={{ display: 'block', marginTop: 4, fontStyle: 'italic' }}>
ℹ️ Aktuell abgeleitet aus Trainingsmodus "{goalMode}" - klicke "Anpassen" für individuelle Gewichtung
</span>
)}
</p> </p>
{focusEditing ? ( {focusWeightsEditing ? (
<> <>
{/* Sliders */} {/* Edit Mode - Sliders grouped by category */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 20, marginBottom: 20 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 24, marginBottom: 20 }}>
{[ {Object.entries(focusAreasGrouped).map(([category, areas]) => (
{ key: 'weight_loss_pct', label: 'Fettabbau', icon: '📉', color: '#D85A30' }, <div key={category}>
{ key: 'muscle_gain_pct', label: 'Muskelaufbau', icon: '💪', color: '#378ADD' }, <div style={{
{ key: 'strength_pct', label: 'Kraftsteigerung', icon: '🏋️', color: '#7B68EE' }, fontSize: 11,
{ key: 'endurance_pct', label: 'Ausdauer', icon: '🏃', color: '#1D9E75' }, fontWeight: 700,
{ key: 'flexibility_pct', label: 'Beweglichkeit', icon: '🤸', color: '#E67E22' }, color: 'var(--text3)',
{ key: 'health_pct', label: 'Gesundheit', icon: '❤️', color: '#F59E0B' } textTransform: 'uppercase',
].map(area => { letterSpacing: '0.05em',
const rawValue = Number(focusTemp[area.key]) || 0 marginBottom: 12
const weight = Math.round(rawValue / 10) }}>
const sum = Object.entries(focusTemp) {category}
.filter(([k]) => k.endsWith('_pct'))
.reduce((acc, [k, v]) => acc + (Number(v) || 0), 0)
const actualPercent = sum > 0 ? Math.round(rawValue / sum * 100) : 0
return (
<div key={area.key}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ fontSize: 20 }}>{area.icon}</span>
<span style={{ fontWeight: 500 }}>{area.label}</span>
</div>
<span style={{
fontSize: 16,
fontWeight: 600,
color: area.color,
minWidth: 80,
textAlign: 'right'
}}>
{weight} → {actualPercent}%
</span>
</div>
<input
type="range"
min="0"
max="10"
step="1"
value={weight}
onChange={e => setFocusTemp(f => ({ ...f, [area.key]: parseInt(e.target.value) * 10 }))}
style={{
width: '100%',
height: 8,
borderRadius: 4,
background: `linear-gradient(to right, ${area.color} 0%, ${area.color} ${weight * 10}%, var(--border) ${weight * 10}%, var(--border) 100%)`,
outline: 'none',
cursor: 'pointer'
}}
/>
</div> </div>
) <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
})} {areas.map(area => {
const weight = focusWeightsTemp[area.id] || 0
const totalWeight = Object.values(focusWeightsTemp).reduce((sum, w) => sum + (w || 0), 0)
const percentage = totalWeight > 0 ? Math.round((weight / totalWeight) * 100) : 0
return (
<div key={area.id}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 6
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ fontSize: 18 }}>{area.icon}</span>
<span style={{ fontWeight: 500, fontSize: 14 }}>{area.name_de}</span>
</div>
<span style={{
fontSize: 14,
fontWeight: 600,
color: 'var(--accent)',
minWidth: 80,
textAlign: 'right'
}}>
{weight} → {percentage}%
</span>
</div>
<input
type="range"
min="0"
max="100"
step="5"
value={weight}
onChange={e => setFocusWeightsTemp(f => ({
...f,
[area.id]: parseInt(e.target.value)
}))}
style={{
width: '100%',
height: 6,
borderRadius: 3,
background: `linear-gradient(to right, var(--accent) 0%, var(--accent) ${weight}%, var(--border) ${weight}%, var(--border) 100%)`,
outline: 'none',
cursor: 'pointer'
}}
/>
</div>
)
})}
</div>
</div>
))}
</div> </div>
{/* Action Buttons */} {/* Save Button */}
<div style={{ display: 'flex', gap: 12 }}> <button
<button className="btn-primary btn-full"
className="btn-primary" onClick={async () => {
onClick={async () => { try {
// Calculate sum (filter out NaN/undefined) await api.updateUserFocusPreferences({ weights: focusWeightsTemp })
const sum = Object.entries(focusTemp) showToast('✓ Fokus-Bereiche aktualisiert')
.filter(([k]) => k.endsWith('_pct')) await loadData()
.reduce((acc, [k, v]) => acc + (Number(v) || 0), 0) setFocusWeightsEditing(false)
setError(null)
if (sum === 0 || isNaN(sum)) { } catch (err) {
setError('Mindestens ein Bereich muss gewichtet sein') setError(err.message || 'Fehler beim Speichern')
return }
} }}
>
// Normalize to percentages (ensure no NaN values) Speichern
const normalized = { </button>
weight_loss_pct: Math.round((Number(focusTemp.weight_loss_pct) || 0) / sum * 100), </>
muscle_gain_pct: Math.round((Number(focusTemp.muscle_gain_pct) || 0) / sum * 100), ) : (
strength_pct: Math.round((Number(focusTemp.strength_pct) || 0) / sum * 100), /* Display Mode - Cards for areas with weight > 0 */
endurance_pct: Math.round((Number(focusTemp.endurance_pct) || 0) / sum * 100), userFocusWeights.length === 0 ? (
flexibility_pct: Math.round((Number(focusTemp.flexibility_pct) || 0) / sum * 100), <div style={{
health_pct: Math.round((Number(focusTemp.health_pct) || 0) / sum * 100) textAlign: 'center',
} padding: '32px 16px',
color: 'var(--text3)',
// Ensure sum is exactly 100 (adjust largest value if needed due to rounding) background: 'var(--surface2)',
const normalizedSum = Object.values(normalized).reduce((a, b) => a + b, 0) borderRadius: 8
if (normalizedSum !== 100) { }}>
const largest = Object.entries(normalized).reduce((max, [k, v]) => v > max[1] ? [k, v] : max, ['', 0]) <p style={{ margin: 0, marginBottom: 12 }}>Keine Fokus-Bereiche definiert</p>
normalized[largest[0]] += (100 - normalizedSum)
}
try {
await api.updateFocusAreas(normalized)
showToast('✓ Fokus-Bereiche aktualisiert')
await loadData()
setFocusEditing(false)
setError(null)
} catch (err) {
setError(err.message || 'Fehler beim Speichern')
}
}}
style={{ flex: 1 }}
>
Speichern
</button>
<button <button
className="btn-secondary" className="btn-secondary"
onClick={() => { onClick={() => setFocusWeightsEditing(true)}
setFocusTemp(focusAreas) style={{ fontSize: 13 }}
setFocusEditing(false)
setError(null)
}}
style={{ flex: 1 }}
> >
Abbrechen Jetzt konfigurieren
</button> </button>
</div> </div>
</> ) : (
) : focusAreas && ( <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 12 }}>
/* Display Mode */ {userFocusWeights.map(area => (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 12 }}> <div
{[ key={area.id}
{ key: 'weight_loss_pct', label: 'Fettabbau', icon: '📉', color: '#D85A30' }, style={{
{ key: 'muscle_gain_pct', label: 'Muskelaufbau', icon: '💪', color: '#378ADD' }, padding: 12,
{ key: 'strength_pct', label: 'Kraftsteigerung', icon: '🏋️', color: '#7B68EE' }, background: 'var(--surface2)',
{ key: 'endurance_pct', label: 'Ausdauer', icon: '🏃', color: '#1D9E75' }, border: '1px solid var(--border)',
{ key: 'flexibility_pct', label: 'Beweglichkeit', icon: '🤸', color: '#E67E22' }, borderRadius: 8,
{ key: 'health_pct', label: 'Gesundheit', icon: '❤️', color: '#F59E0B' } textAlign: 'center'
].filter(area => focusAreas[area.key] > 0).map(area => ( }}
<div >
key={area.key} <div style={{ fontSize: 24, marginBottom: 4 }}>{area.icon}</div>
style={{ <div style={{ fontSize: 12, color: 'var(--text2)', marginBottom: 4 }}>{area.name_de}</div>
padding: 12, <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--accent)' }}>{area.percentage}%</div>
background: 'var(--surface2)', </div>
border: '1px solid var(--border)', ))}
borderRadius: 8, </div>
textAlign: 'center' )
}}
>
<div style={{ fontSize: 24, marginBottom: 4 }}>{area.icon}</div>
<div style={{ fontSize: 12, color: 'var(--text2)', marginBottom: 4 }}>{area.label}</div>
<div style={{ fontSize: 20, fontWeight: 700, color: area.color }}>{focusAreas[area.key]}%</div>
</div>
))}
</div>
)} )}
</div> </div>
@@ -652,6 +630,38 @@ export default function GoalsPage() {
</span> </span>
</div> </div>
{/* Focus Area Badges (v2.0) */}
{goal.focus_contributions && goal.focus_contributions.length > 0 && (
<div style={{
display: 'flex',
flexWrap: 'wrap',
gap: 6,
marginBottom: 12
}}>
{goal.focus_contributions.map(fc => (
<span
key={fc.focus_area_id}
style={{
fontSize: 11,
padding: '3px 8px',
background: 'var(--accent-light)',
color: 'var(--accent-dark)',
borderRadius: 4,
fontWeight: 500,
display: 'flex',
alignItems: 'center',
gap: 4
}}
title={`${fc.name_de}: ${fc.contribution_weight}%`}
>
{fc.icon && <span>{fc.icon}</span>}
<span>{fc.name_de}</span>
<span style={{ opacity: 0.7 }}>({fc.contribution_weight}%)</span>
</span>
))}
</div>
)}
<div style={{ display: 'flex', gap: 20, marginBottom: 12, fontSize: 14, flexWrap: 'wrap' }}> <div style={{ display: 'flex', gap: 20, marginBottom: 12, fontSize: 14, flexWrap: 'wrap' }}>
<div> <div>
<span style={{ color: 'var(--text2)' }}>Start:</span>{' '} <span style={{ color: 'var(--text2)' }}>Start:</span>{' '}
@@ -848,6 +858,191 @@ export default function GoalsPage() {
/> />
</div> </div>
{/* Focus Areas (v2.0) */}
<div style={{ marginBottom: 16 }}>
<label style={{
display: 'block',
fontSize: 13,
fontWeight: 600,
marginBottom: 8,
color: 'var(--text1)'
}}>
🎯 Zahlt ein auf (Fokusbereiche)
</label>
<div style={{
fontSize: 12,
color: 'var(--text3)',
marginBottom: 8
}}>
Wähle die Bereiche aus, auf die dieses Ziel einzahlt. Mehrfachauswahl möglich.
</div>
{Object.keys(focusAreasGrouped).length === 0 ? (
<div style={{
padding: 12,
background: 'var(--surface2)',
borderRadius: 8,
fontSize: 13,
color: 'var(--text3)'
}}>
Keine Focus Areas verfügbar
</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{Object.entries(focusAreasGrouped).map(([category, areas]) => {
// Filter to only show focus areas the user has weighted
const userWeightedAreaIds = new Set(userFocusWeights.map(w => w.id))
const filteredAreas = areas.filter(area => userWeightedAreaIds.has(area.id))
// Skip category if no weighted areas
if (filteredAreas.length === 0) return null
return (
<div key={category}>
<div style={{
fontSize: 11,
fontWeight: 600,
color: 'var(--text3)',
textTransform: 'uppercase',
letterSpacing: '0.05em',
marginBottom: 6
}}>
{category}
</div>
<div style={{
display: 'flex',
flexWrap: 'wrap',
gap: 6
}}>
{filteredAreas.map(area => {
const isSelected = formData.focus_contributions?.some(
fc => fc.focus_area_id === area.id
)
return (
<button
key={area.id}
type="button"
onClick={() => {
if (isSelected) {
// Remove
setFormData(f => ({
...f,
focus_contributions: f.focus_contributions.filter(
fc => fc.focus_area_id !== area.id
)
}))
} else {
// Add with default weight 100%
setFormData(f => ({
...f,
focus_contributions: [
...(f.focus_contributions || []),
{
focus_area_id: area.id,
contribution_weight: 100
}
]
}))
}
}}
style={{
padding: '6px 12px',
background: isSelected ? 'var(--accent)' : 'var(--surface2)',
color: isSelected ? 'white' : 'var(--text2)',
border: isSelected ? '2px solid var(--accent)' : '1px solid var(--border)',
borderRadius: 8,
fontSize: 13,
fontWeight: isSelected ? 600 : 400,
cursor: 'pointer',
transition: 'all 0.15s',
fontFamily: 'var(--font)',
display: 'flex',
alignItems: 'center',
gap: 4
}}
>
{area.icon && <span>{area.icon}</span>}
<span>{area.name_de}</span>
</button>
)
})}
</div>
</div>
)
})}
</div>
)}
{/* Selected areas with weights */}
{formData.focus_contributions && formData.focus_contributions.length > 0 && (
<div style={{
marginTop: 12,
padding: 12,
background: 'var(--accent-light)',
borderRadius: 8,
border: '1px solid var(--accent)'
}}>
<div style={{
fontSize: 12,
fontWeight: 600,
color: 'var(--accent-dark)',
marginBottom: 8
}}>
Gewichtung ({formData.focus_contributions.length} ausgewählt)
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{formData.focus_contributions.map((fc, idx) => {
const area = focusAreas.find(a => a.id === fc.focus_area_id)
if (!area) return null
return (
<div key={fc.focus_area_id} style={{
display: 'flex',
alignItems: 'center',
gap: 8
}}>
<div style={{
flex: 1,
fontSize: 13,
fontWeight: 500,
color: 'var(--accent-dark)'
}}>
{area.icon} {area.name_de}
</div>
<input
type="number"
min="0"
max="100"
step="5"
value={fc.contribution_weight}
onChange={(e) => {
const newWeight = parseFloat(e.target.value) || 0
setFormData(f => ({
...f,
focus_contributions: f.focus_contributions.map((item, i) =>
i === idx ? { ...item, contribution_weight: newWeight } : item
)
}))
}}
style={{
width: 70,
padding: '4px 8px',
fontSize: 13,
textAlign: 'center',
border: '1px solid var(--accent)',
borderRadius: 6
}}
/>
<span style={{ fontSize: 12, color: 'var(--accent-dark)' }}>%</span>
</div>
)
})}
</div>
</div>
)}
</div>
{/* Zielwert */} {/* Zielwert */}
<div style={{ fontSize: 14, fontWeight: 600, marginBottom: 8, marginTop: 20, color: 'var(--text1)' }}> <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 8, marginTop: 20, color: 'var(--text1)' }}>
🎯 Zielwert 🎯 Zielwert
+9
View File
@@ -365,4 +365,13 @@ export const api = {
// Fitness Tests // Fitness Tests
listFitnessTests: () => req('/goals/tests'), listFitnessTests: () => req('/goals/tests'),
createFitnessTest: (d) => req('/goals/tests', json(d)), createFitnessTest: (d) => req('/goals/tests', json(d)),
// Focus Areas (v2.0)
listFocusAreaDefinitions: (includeInactive=false) => req(`/focus-areas/definitions?include_inactive=${includeInactive}`),
createFocusAreaDefinition: (d) => req('/focus-areas/definitions', json(d)),
updateFocusAreaDefinition: (id,d) => req(`/focus-areas/definitions/${id}`, jput(d)),
deleteFocusAreaDefinition: (id) => req(`/focus-areas/definitions/${id}`, {method:'DELETE'}),
getUserFocusPreferences: () => req('/focus-areas/user-preferences'),
updateUserFocusPreferences: (d) => req('/focus-areas/user-preferences', jput(d)),
getFocusAreaStats: () => req('/focus-areas/stats'),
} }