Compare commits
26
Commits
V0.9h
...
9fa6c5dea7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9fa6c5dea7 | ||
|
|
949301a91d | ||
|
|
43e6c3e7f4 | ||
|
|
e3e635d9f5 | ||
|
|
289b132b8f | ||
|
|
919eae6053 | ||
|
|
91bafc6af1 | ||
|
|
10ea560fcf | ||
|
|
b230a03fdd | ||
|
|
02394ea19c | ||
|
|
dd3a4111fc | ||
|
|
4817fd2b29 | ||
|
|
53969f8768 | ||
|
|
6f94154b9e | ||
|
|
7d4f6fe726 | ||
|
|
4f365e9a69 | ||
|
|
bf0b32b536 | ||
|
|
09e6a5fbfb | ||
|
|
56933431f6 | ||
|
|
12d516c881 | ||
|
|
448f6ad4f4 | ||
|
|
e4a2b63a48 | ||
|
|
ce4cd7daf1 | ||
|
|
9ab36145e5 | ||
|
|
eb5c099eca | ||
|
|
37ea1f8537 |
No files matched your search
@@ -76,9 +76,40 @@ frontend/src/
|
||||
└── 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):**
|
||||
- Neue Seite für tägliche Werterfassung individueller Ziele
|
||||
- Dedizierte UI für custom goals (ohne automatische Datenquelle)
|
||||
|
||||
@@ -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',
|
||||
]
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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'
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
"""
|
||||
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',
|
||||
|
||||
# Nutrition → nutrition_score
|
||||
'protein_intake': 'nutrition',
|
||||
'calorie_balance': 'nutrition',
|
||||
'macro_consistency': 'nutrition',
|
||||
'meal_timing': 'nutrition',
|
||||
'hydration': 'nutrition',
|
||||
}
|
||||
|
||||
|
||||
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
@@ -13,11 +13,11 @@ Version History:
|
||||
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 decimal import Decimal
|
||||
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]:
|
||||
@@ -278,7 +278,7 @@ def _fetch_by_aggregation_method(
|
||||
- max_30d: Maximum value in last 30 days
|
||||
|
||||
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
|
||||
if not table or not column:
|
||||
@@ -412,7 +412,21 @@ def _fetch_by_aggregation_method(
|
||||
return None
|
||||
|
||||
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] 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
|
||||
|
||||
|
||||
@@ -502,3 +516,37 @@ def get_focus_weights_v2(conn, profile_id: str) -> Dict[str, float]:
|
||||
'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
|
||||
+6
-1
@@ -24,6 +24,7 @@ from routers import admin_activity_mappings, sleep, rest_days
|
||||
from routers import vitals_baseline, blood_pressure # v9d Phase 2d Refactored
|
||||
from routers import evaluation # v9d/v9e Training Type Profiles (#15)
|
||||
from routers import goals, focus_areas # v9e/v9g Goal System v2.0 (Dynamic Focus Areas)
|
||||
from routers import goal_types, goal_progress, training_phases, fitness_tests # v9h Goal System (Split routers)
|
||||
|
||||
# ── App Configuration ─────────────────────────────────────────────────────────
|
||||
DATA_DIR = Path(os.getenv("DATA_DIR", "./data"))
|
||||
@@ -98,7 +99,11 @@ 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(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(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 ──────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
-- Migration 033: Nutrition Focus Areas
|
||||
-- Date: 2026-03-28
|
||||
-- Purpose: Add missing nutrition category to complete focus area coverage
|
||||
|
||||
-- ============================================================================
|
||||
-- Part 1: Add Nutrition Focus Areas
|
||||
-- ============================================================================
|
||||
|
||||
INSERT INTO focus_area_definitions (key, name_de, name_en, icon, category, description) VALUES
|
||||
-- Nutrition Category
|
||||
('protein_intake', 'Proteinzufuhr', 'Protein Intake', '🥩', 'nutrition', 'Ausreichend Protein für Muskelaufbau/-erhalt'),
|
||||
('calorie_balance', 'Kalorienbilanz', 'Calorie Balance', '⚖️', 'nutrition', 'Energiebilanz passend zum Ziel (Defizit/Überschuss)'),
|
||||
('macro_consistency', 'Makro-Konsistenz', 'Macro Consistency', '📊', 'nutrition', 'Gleichmäßige Makronährstoff-Verteilung'),
|
||||
('meal_timing', 'Mahlzeiten-Timing', 'Meal Timing', '⏰', 'nutrition', 'Regelmäßige Mahlzeiten und optimales Timing'),
|
||||
('hydration', 'Flüssigkeitszufuhr', 'Hydration', '💧', 'nutrition', 'Ausreichende Flüssigkeitsaufnahme')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
|
||||
-- ============================================================================
|
||||
-- Part 2: Auto-Mapping for Nutrition-Related Goals
|
||||
-- ============================================================================
|
||||
|
||||
-- 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 Loss goals → calorie_balance (40%) + protein_intake (30%)
|
||||
-- (Already mapped to weight_loss in migration 031, adding nutrition aspects)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, fa.id,
|
||||
CASE fa.key
|
||||
WHEN 'calorie_balance' THEN 40.00
|
||||
WHEN 'protein_intake' THEN 30.00
|
||||
END
|
||||
FROM goals g
|
||||
CROSS JOIN focus_area_definitions fa
|
||||
WHERE g.goal_type = 'weight'
|
||||
AND fa.key IN ('calorie_balance', 'protein_intake')
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Body Fat goals → calorie_balance (30%) + protein_intake (40%)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, fa.id,
|
||||
CASE fa.key
|
||||
WHEN 'calorie_balance' THEN 30.00
|
||||
WHEN 'protein_intake' THEN 40.00
|
||||
END
|
||||
FROM goals g
|
||||
CROSS JOIN focus_area_definitions fa
|
||||
WHERE g.goal_type = 'body_fat'
|
||||
AND fa.key IN ('calorie_balance', 'protein_intake')
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Lean Mass goals → protein_intake (60%) + calorie_balance (20%)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, fa.id,
|
||||
CASE fa.key
|
||||
WHEN 'protein_intake' THEN 60.00
|
||||
WHEN 'calorie_balance' THEN 20.00
|
||||
END
|
||||
FROM goals g
|
||||
CROSS JOIN focus_area_definitions fa
|
||||
WHERE g.goal_type = 'lean_mass'
|
||||
AND fa.key IN ('protein_intake', 'calorie_balance')
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Strength goals → protein_intake (20%)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, get_focus_area_id('protein_intake'), 20.00
|
||||
FROM goals g
|
||||
WHERE g.goal_type = 'strength'
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Cleanup helper function
|
||||
DROP FUNCTION IF EXISTS get_focus_area_id(VARCHAR);
|
||||
|
||||
-- ============================================================================
|
||||
-- Summary
|
||||
-- ============================================================================
|
||||
|
||||
COMMENT ON COLUMN focus_area_definitions.category IS
|
||||
'Categories: body_composition, training, endurance, coordination, mental, recovery, health, nutrition';
|
||||
|
||||
-- Count nutrition focus areas
|
||||
DO $$
|
||||
DECLARE
|
||||
nutrition_count INT;
|
||||
BEGIN
|
||||
SELECT COUNT(*) INTO nutrition_count
|
||||
FROM focus_area_definitions
|
||||
WHERE category = 'nutrition';
|
||||
|
||||
RAISE NOTICE 'Migration 033 complete: % nutrition focus areas added', nutrition_count;
|
||||
END $$;
|
||||
@@ -464,6 +464,254 @@ def get_vitals_vo2_max(profile_id: str) -> str:
|
||||
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_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_30d}}': lambda pid: 'letzte 30 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)'),
|
||||
('kf_aktuell', 'Aktueller Körperfettanteil in %'),
|
||||
('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': [
|
||||
('kcal_avg', 'Durchschn. Kalorien (30d)'),
|
||||
('protein_avg', 'Durchschn. Protein in g (30d)'),
|
||||
('carb_avg', 'Durchschn. Kohlenhydrate 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': [
|
||||
('activity_summary', 'Aktivitäts-Zusammenfassung (7d)'),
|
||||
('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': [
|
||||
('sleep_avg_duration', 'Durchschn. Schlafdauer (7d)'),
|
||||
('sleep_avg_quality', 'Durchschn. Schlafqualität (7d)'),
|
||||
('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': [
|
||||
('vitals_avg_hr', 'Durchschn. Ruhepuls (7d)'),
|
||||
('vitals_avg_hrv', 'Durchschn. HRV (7d)'),
|
||||
('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': [
|
||||
('datum_heute', 'Heutiges Datum'),
|
||||
|
||||
@@ -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
|
||||
@@ -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"}
|
||||
@@ -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"}
|
||||
+13
-697
@@ -1,20 +1,23 @@
|
||||
"""
|
||||
Goals Router - Goal System (Strategic + Tactical)
|
||||
Goals Router - Core Goal CRUD & Focus Areas (Streamlined v2.0)
|
||||
|
||||
Endpoints for managing:
|
||||
- Strategic goal modes (weight_loss, strength, etc.)
|
||||
- Strategic focus areas (weighted multi-goal system)
|
||||
- Tactical goal targets (concrete values with deadlines)
|
||||
- Training phase detection
|
||||
- Fitness tests
|
||||
- Grouped goal views
|
||||
|
||||
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 pydantic import BaseModel
|
||||
from typing import Optional, List
|
||||
from datetime import date, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
import traceback
|
||||
from datetime import date, timedelta
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth
|
||||
@@ -69,62 +72,6 @@ class GoalUpdate(BaseModel):
|
||||
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
|
||||
# ============================================================================
|
||||
@@ -372,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")
|
||||
@@ -572,131 +519,10 @@ def delete_goal(goal_id: str, session: dict = Depends(require_auth)):
|
||||
|
||||
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")
|
||||
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:
|
||||
{
|
||||
@@ -777,134 +603,6 @@ def get_goals_grouped(session: dict = Depends(require_auth)):
|
||||
|
||||
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
|
||||
# ============================================================================
|
||||
@@ -955,385 +653,3 @@ def _update_goal_progress(conn, profile_id: str, goal: dict):
|
||||
# Check if on track
|
||||
if goal['target_date'] and goal['projection_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"}
|
||||
@@ -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"}
|
||||
@@ -1,684 +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).
|
||||
|
||||
Post-Migration-015: Routes to vitals_baseline (for RHR, HRV, etc.)
|
||||
Note: BP measurements should use /api/blood-pressure endpoint instead.
|
||||
"""
|
||||
pid = get_pid(x_profile_id, session)
|
||||
|
||||
# Validation: at least one baseline vital must be provided
|
||||
has_baseline = any([
|
||||
entry.resting_hr, entry.hrv, entry.vo2_max,
|
||||
entry.spo2, entry.respiratory_rate
|
||||
])
|
||||
|
||||
if not has_baseline:
|
||||
raise HTTPException(400, "Mindestens ein Vitalwert muss angegeben werden (RHR, HRV, VO2Max, SpO2, oder Atemfrequenz)")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Upsert into vitals_baseline (Migration 015)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO vitals_baseline (
|
||||
profile_id, date, resting_hr, hrv,
|
||||
vo2_max, spo2, respiratory_rate,
|
||||
note, source
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'manual')
|
||||
ON CONFLICT (profile_id, date)
|
||||
DO UPDATE SET
|
||||
resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_baseline.resting_hr),
|
||||
hrv = COALESCE(EXCLUDED.hrv, vitals_baseline.hrv),
|
||||
vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_baseline.vo2_max),
|
||||
spo2 = COALESCE(EXCLUDED.spo2, vitals_baseline.spo2),
|
||||
respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_baseline.respiratory_rate),
|
||||
note = COALESCE(EXCLUDED.note, vitals_baseline.note),
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
RETURNING id, profile_id, date, resting_hr, hrv,
|
||||
vo2_max, spo2, respiratory_rate,
|
||||
note, source, created_at, updated_at
|
||||
""",
|
||||
(pid, entry.date, entry.resting_hr, entry.hrv,
|
||||
entry.vo2_max, entry.spo2, entry.respiratory_rate,
|
||||
entry.note)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
|
||||
logger.info(f"[VITALS] Upserted baseline vitals for {pid} on {entry.date}")
|
||||
|
||||
# Return in legacy format for backward compatibility
|
||||
result = r2d(row)
|
||||
result['blood_pressure_systolic'] = None
|
||||
result['blood_pressure_diastolic'] = None
|
||||
result['pulse'] = None
|
||||
result['irregular_heartbeat'] = None
|
||||
result['possible_afib'] = None
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@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
|
||||
}
|
||||
@@ -99,52 +99,90 @@ def create_or_update_baseline(
|
||||
"""Create or update baseline entry (upsert on date)."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
# Build dynamic update columns (only non-None fields)
|
||||
fields = []
|
||||
values = [pid, entry.date]
|
||||
# Build dynamic INSERT columns, placeholders, UPDATE fields, and values list
|
||||
# All arrays must stay synchronized
|
||||
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:
|
||||
fields.append("resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_baseline.resting_hr)")
|
||||
values.append(entry.resting_hr)
|
||||
insert_cols.append("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:
|
||||
fields.append("hrv = COALESCE(EXCLUDED.hrv, vitals_baseline.hrv)")
|
||||
values.append(entry.hrv)
|
||||
insert_cols.append("hrv")
|
||||
insert_placeholders.append("%s")
|
||||
update_fields.append("hrv = EXCLUDED.hrv")
|
||||
param_values.append(entry.hrv)
|
||||
|
||||
if entry.vo2_max is not None:
|
||||
fields.append("vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_baseline.vo2_max)")
|
||||
values.append(entry.vo2_max)
|
||||
insert_cols.append("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:
|
||||
fields.append("spo2 = COALESCE(EXCLUDED.spo2, vitals_baseline.spo2)")
|
||||
values.append(entry.spo2)
|
||||
insert_cols.append("spo2")
|
||||
insert_placeholders.append("%s")
|
||||
update_fields.append("spo2 = EXCLUDED.spo2")
|
||||
param_values.append(entry.spo2)
|
||||
|
||||
if entry.respiratory_rate is not None:
|
||||
fields.append("respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_baseline.respiratory_rate)")
|
||||
values.append(entry.respiratory_rate)
|
||||
insert_cols.append("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:
|
||||
fields.append("body_temperature = COALESCE(EXCLUDED.body_temperature, vitals_baseline.body_temperature)")
|
||||
values.append(entry.body_temperature)
|
||||
insert_cols.append("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:
|
||||
fields.append("resting_metabolic_rate = COALESCE(EXCLUDED.resting_metabolic_rate, vitals_baseline.resting_metabolic_rate)")
|
||||
values.append(entry.resting_metabolic_rate)
|
||||
insert_cols.append("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:
|
||||
fields.append("note = COALESCE(EXCLUDED.note, vitals_baseline.note)")
|
||||
values.append(entry.note)
|
||||
insert_cols.append("note")
|
||||
insert_placeholders.append("%s")
|
||||
update_fields.append("note = EXCLUDED.note")
|
||||
param_values.append(entry.note)
|
||||
|
||||
# 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")
|
||||
|
||||
# Build value placeholders
|
||||
placeholders = ", ".join([f"${i}" for i in range(1, len(values) + 1)])
|
||||
|
||||
with get_db() as 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"""
|
||||
INSERT INTO vitals_baseline (profile_id, date, {', '.join([f.split('=')[0].strip() for f in fields])})
|
||||
VALUES ($1, $2, {', '.join([f'${i}' for i in range(3, len(values) + 1)])})
|
||||
INSERT INTO vitals_baseline ({all_cols})
|
||||
VALUES ({all_placeholders})
|
||||
ON CONFLICT (profile_id, date)
|
||||
DO UPDATE SET {', '.join(fields)}, updated_at = NOW()
|
||||
DO UPDATE SET {', '.join(update_fields)}, updated_at = NOW()
|
||||
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())
|
||||
|
||||
|
||||
@@ -161,32 +199,31 @@ def update_baseline(
|
||||
# Build SET clause dynamically
|
||||
updates = []
|
||||
values = []
|
||||
idx = 1
|
||||
|
||||
if entry.resting_hr is not None:
|
||||
updates.append(f"resting_hr = ${idx}")
|
||||
updates.append("resting_hr = %s")
|
||||
values.append(entry.resting_hr)
|
||||
idx += 1
|
||||
if entry.hrv is not None:
|
||||
updates.append(f"hrv = ${idx}")
|
||||
updates.append("hrv = %s")
|
||||
values.append(entry.hrv)
|
||||
idx += 1
|
||||
if entry.vo2_max is not None:
|
||||
updates.append(f"vo2_max = ${idx}")
|
||||
updates.append("vo2_max = %s")
|
||||
values.append(entry.vo2_max)
|
||||
idx += 1
|
||||
if entry.spo2 is not None:
|
||||
updates.append(f"spo2 = ${idx}")
|
||||
updates.append("spo2 = %s")
|
||||
values.append(entry.spo2)
|
||||
idx += 1
|
||||
if entry.respiratory_rate is not None:
|
||||
updates.append(f"respiratory_rate = ${idx}")
|
||||
updates.append("respiratory_rate = %s")
|
||||
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:
|
||||
updates.append(f"note = ${idx}")
|
||||
updates.append("note = %s")
|
||||
values.append(entry.note)
|
||||
idx += 1
|
||||
|
||||
if not updates:
|
||||
raise HTTPException(400, "No fields to update")
|
||||
@@ -199,7 +236,7 @@ def update_baseline(
|
||||
query = f"""
|
||||
UPDATE vitals_baseline
|
||||
SET {', '.join(updates)}
|
||||
WHERE id = ${idx} AND profile_id = ${idx + 1}
|
||||
WHERE id = %s AND profile_id = %s
|
||||
RETURNING *
|
||||
"""
|
||||
cur.execute(query, values)
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user