feat: introduce recovery dashboard visualization and refactor recovery charts
Deploy Development / deploy (push) Successful in 55s
Build Test / pytest-backend (push) Successful in 9s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 17s

- Added a new endpoint for the recovery dashboard visualization in `charts.py`, integrating multiple recovery metrics and insights.
- Implemented the `get_recovery_dashboard_viz` function to streamline data retrieval for recovery-related charts.
- Refactored the `RecoveryCharts` component to utilize the new `RecoveryDashboardOverview`, simplifying the component structure and enhancing maintainability.
- Updated the `RecoveryChartsPanelWidget` and `History` page to reflect the new recovery dashboard, improving user navigation and experience.
- Deprecated the old recovery charts component, encouraging the use of the new overview for better data presentation.
This commit is contained in:
Lars committed 2026-04-20 08:11:23 +02:00
1 parent bf84e3c2a5
commit f42d3a9c92
9 files changed
+1219 -857

No files matched your search

+41 -507
View File
@@ -34,6 +34,14 @@ from data_layer.body_metrics import (
from data_layer.body_viz import get_body_history_viz_bundle
from data_layer.nutrition_viz import get_nutrition_history_viz_bundle
from data_layer.fitness_viz import get_fitness_dashboard_viz_bundle
from data_layer.recovery_viz import get_recovery_dashboard_viz_bundle
from data_layer.recovery_chart_payloads import (
build_recovery_score_chart_payload,
build_hrv_rhr_baseline_chart_payload,
build_sleep_duration_quality_chart_payload,
build_sleep_debt_chart_payload,
build_vital_signs_matrix_chart_payload,
)
from data_layer.nutrition_metrics import (
get_nutrition_average_data,
get_protein_targets_data,
@@ -310,6 +318,24 @@ def get_fitness_dashboard_viz(
return serialize_dates(bundle)
@router.get("/recovery-dashboard-viz")
def get_recovery_dashboard_viz(
days: int = Query(
default=28,
ge=7,
le=9999,
description="Analysefenster in Tagen (9999 = lange Historie)",
),
session: dict = Depends(require_auth),
) -> Dict:
"""
Layer 2b: Recovery/Erholung — KPIs, Insights, Charts R1–R5 (recovery_metrics).
"""
profile_id = session["profile_id"]
bundle = get_recovery_dashboard_viz_bundle(profile_id, days)
return serialize_dates(bundle)
@router.get("/circumferences")
def get_circumferences_chart(
max_age_days: int = Query(default=90, ge=7, le=365),
@@ -1368,106 +1394,9 @@ def get_recovery_score_chart(
days: int = Query(default=28, ge=7, le=90),
session: dict = Depends(require_auth)
) -> Dict:
"""
Recovery score timeline (R1).
Shows daily recovery scores over time.
Args:
days: Analysis window (7-90 days, default 28)
session: Auth session (injected)
Returns:
Chart.js line chart with recovery scores
"""
profile_id = session['profile_id']
# For PoC: Use current recovery score and create synthetic timeline
# TODO: Store historical recovery scores for true timeline
current_score = calculate_recovery_score_v2(profile_id)
if current_score is None:
return {
"chart_type": "line",
"data": {
"labels": [],
"datasets": []
},
"metadata": {
"confidence": "insufficient",
"data_points": 0,
"message": "Keine Recovery-Daten vorhanden"
}
}
# Fetch vitals for timeline approximation
from db import get_db, get_cursor
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT date, resting_hr, hrv_ms
FROM vitals_baseline
WHERE profile_id=%s AND date >= %s
ORDER BY date""",
(profile_id, cutoff)
)
rows = cur.fetchall()
if not rows:
return {
"chart_type": "line",
"data": {
"labels": [datetime.now().strftime('%Y-%m-%d')],
"datasets": [
{
"label": "Recovery Score",
"data": [current_score],
"borderColor": "#1D9E75",
"backgroundColor": "rgba(29, 158, 117, 0.1)",
"borderWidth": 2,
"tension": 0.3,
"fill": True
}
]
},
"metadata": {
"confidence": "low",
"data_points": 1,
"current_score": current_score
}
}
# Simple proxy: Use HRV as recovery indicator (higher HRV = better recovery)
# This is a placeholder until we store actual recovery scores
labels = [row['date'].isoformat() for row in rows]
# Normalize HRV to 0-100 scale (assume typical range 20-100ms)
values = [min(100, max(0, safe_float(row['hrv_ms']) if row['hrv_ms'] else 50)) for row in rows]
return {
"chart_type": "line",
"data": {
"labels": labels,
"datasets": [
{
"label": "Recovery Score (proxy)",
"data": values,
"borderColor": "#1D9E75",
"backgroundColor": "rgba(29, 158, 117, 0.1)",
"borderWidth": 2,
"tension": 0.3,
"fill": True
}
]
},
"metadata": serialize_dates({
"confidence": calculate_confidence(len(rows), days, "general"),
"data_points": len(rows),
"current_score": current_score,
"note": "Score based on HRV proxy; true recovery score calculation in development"
})
}
"""Recovery score timeline (R1). Delegiert an recovery_chart_payloads."""
profile_id = session["profile_id"]
return build_recovery_score_chart_payload(profile_id, days)
@router.get("/hrv-rhr-baseline")
@@ -1475,101 +1404,9 @@ def get_hrv_rhr_baseline_chart(
days: int = Query(default=28, ge=7, le=90),
session: dict = Depends(require_auth)
) -> Dict:
"""
HRV/RHR vs baseline (R2).
Shows HRV and RHR trends vs. baseline values.
Args:
days: Analysis window (7-90 days, default 28)
session: Auth session (injected)
Returns:
Chart.js multi-line chart with HRV and RHR
"""
profile_id = session['profile_id']
from db import get_db, get_cursor
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT date, resting_hr, hrv_ms
FROM vitals_baseline
WHERE profile_id=%s AND date >= %s
ORDER BY date""",
(profile_id, cutoff)
)
rows = cur.fetchall()
if not rows:
return {
"chart_type": "line",
"data": {
"labels": [],
"datasets": []
},
"metadata": {
"confidence": "insufficient",
"data_points": 0,
"message": "Keine Vitalwerte vorhanden"
}
}
labels = [row['date'].isoformat() for row in rows]
hrv_values = [safe_float(row['hrv_ms']) if row['hrv_ms'] else None for row in rows]
rhr_values = [safe_float(row['resting_hr']) if row['resting_hr'] else None for row in rows]
# Calculate baselines (28d median)
hrv_baseline = calculate_hrv_vs_baseline_pct(profile_id) # This returns % deviation
rhr_baseline = calculate_rhr_vs_baseline_pct(profile_id) # This returns % deviation
# For chart, we need actual baseline values (approximation)
hrv_filtered = [v for v in hrv_values if v is not None]
rhr_filtered = [v for v in rhr_values if v is not None]
avg_hrv = sum(hrv_filtered) / len(hrv_filtered) if hrv_filtered else 50
avg_rhr = sum(rhr_filtered) / len(rhr_filtered) if rhr_filtered else 60
datasets = [
{
"label": "HRV (ms)",
"data": hrv_values,
"borderColor": "#1D9E75",
"backgroundColor": "rgba(29, 158, 117, 0.1)",
"borderWidth": 2,
"tension": 0.3,
"yAxisID": "y1",
"fill": False
},
{
"label": "RHR (bpm)",
"data": rhr_values,
"borderColor": "#3B82F6",
"backgroundColor": "rgba(59, 130, 246, 0.1)",
"borderWidth": 2,
"tension": 0.3,
"yAxisID": "y2",
"fill": False
}
]
return {
"chart_type": "line",
"data": {
"labels": labels,
"datasets": datasets
},
"metadata": serialize_dates({
"confidence": calculate_confidence(len(rows), days, "general"),
"data_points": len(rows),
"avg_hrv": round(avg_hrv, 1),
"avg_rhr": round(avg_rhr, 1),
"hrv_vs_baseline_pct": hrv_baseline,
"rhr_vs_baseline_pct": rhr_baseline
})
}
"""HRV/RHR vs baseline (R2)."""
profile_id = session["profile_id"]
return build_hrv_rhr_baseline_chart_payload(profile_id, days)
@router.get("/sleep-duration-quality")
@@ -1577,107 +1414,9 @@ def get_sleep_duration_quality_chart(
days: int = Query(default=28, ge=7, le=90),
session: dict = Depends(require_auth)
) -> Dict:
"""
Sleep duration + quality (R3).
Shows sleep duration and quality score over time.
Args:
days: Analysis window (7-90 days, default 28)
session: Auth session (injected)
Returns:
Chart.js multi-line chart with sleep metrics
"""
profile_id = session['profile_id']
duration_data = get_sleep_duration_data(profile_id, days)
quality_data = get_sleep_quality_data(profile_id, days)
if duration_data['confidence'] == 'insufficient':
return {
"chart_type": "line",
"data": {
"labels": [],
"datasets": []
},
"metadata": {
"confidence": "insufficient",
"data_points": 0,
"message": "Keine Schlafdaten vorhanden"
}
}
from db import get_db, get_cursor
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT date, total_sleep_min
FROM sleep_log
WHERE profile_id=%s AND date >= %s
ORDER BY date""",
(profile_id, cutoff)
)
rows = cur.fetchall()
if not rows:
return {
"chart_type": "line",
"data": {
"labels": [],
"datasets": []
},
"metadata": {
"confidence": "insufficient",
"data_points": 0,
"message": "Keine Schlafdaten"
}
}
labels = [row['date'].isoformat() for row in rows]
duration_hours = [safe_float(row['total_sleep_min']) / 60 if row['total_sleep_min'] else None for row in rows]
# Quality score (simple proxy: % of 8 hours)
quality_scores = [(d / 8 * 100) if d else None for d in duration_hours]
datasets = [
{
"label": "Schlafdauer (h)",
"data": duration_hours,
"borderColor": "#3B82F6",
"backgroundColor": "rgba(59, 130, 246, 0.1)",
"borderWidth": 2,
"tension": 0.3,
"yAxisID": "y1",
"fill": True
},
{
"label": "Qualität (%)",
"data": quality_scores,
"borderColor": "#1D9E75",
"backgroundColor": "rgba(29, 158, 117, 0.1)",
"borderWidth": 2,
"tension": 0.3,
"yAxisID": "y2",
"fill": False
}
]
return {
"chart_type": "line",
"data": {
"labels": labels,
"datasets": datasets
},
"metadata": serialize_dates({
"confidence": duration_data['confidence'],
"data_points": len(rows),
"avg_duration_hours": round(duration_data['avg_duration_hours'], 1),
"sleep_quality_score": quality_data.get('sleep_quality_score', 0)
})
}
"""Sleep duration + quality (R3)."""
profile_id = session["profile_id"]
return build_sleep_duration_quality_chart_payload(profile_id, days)
@router.get("/sleep-debt")
@@ -1685,100 +1424,9 @@ def get_sleep_debt_chart(
days: int = Query(default=28, ge=7, le=90),
session: dict = Depends(require_auth)
) -> Dict:
"""
Sleep debt accumulation (R4).
Shows cumulative sleep debt over time.
Args:
days: Analysis window (7-90 days, default 28)
session: Auth session (injected)
Returns:
Chart.js line chart with sleep debt
"""
profile_id = session['profile_id']
current_debt = calculate_sleep_debt_hours(profile_id)
if current_debt is None:
return {
"chart_type": "line",
"data": {
"labels": [],
"datasets": []
},
"metadata": {
"confidence": "insufficient",
"data_points": 0,
"message": "Keine Schlafdaten für Schulden-Berechnung"
}
}
from db import get_db, get_cursor
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT date, total_sleep_min
FROM sleep_log
WHERE profile_id=%s AND date >= %s
ORDER BY date""",
(profile_id, cutoff)
)
rows = cur.fetchall()
if not rows:
return {
"chart_type": "line",
"data": {
"labels": [],
"datasets": []
},
"metadata": {
"confidence": "insufficient",
"data_points": 0,
"message": "Keine Schlafdaten"
}
}
labels = [row['date'].isoformat() for row in rows]
# Calculate cumulative debt (target 8h/night)
target_hours = 8.0
cumulative_debt = 0
debt_values = []
for row in rows:
actual_hours = safe_float(row['total_sleep_min']) / 60 if row['total_sleep_min'] else 0
daily_deficit = target_hours - actual_hours
cumulative_debt += daily_deficit
debt_values.append(cumulative_debt)
return {
"chart_type": "line",
"data": {
"labels": labels,
"datasets": [
{
"label": "Schlafschuld (Stunden)",
"data": debt_values,
"borderColor": "#EF4444",
"backgroundColor": "rgba(239, 68, 68, 0.1)",
"borderWidth": 2,
"tension": 0.3,
"fill": True
}
]
},
"metadata": serialize_dates({
"confidence": calculate_confidence(len(rows), days, "general"),
"data_points": len(rows),
"current_debt_hours": round(current_debt, 1),
"final_debt_hours": round(cumulative_debt, 1)
})
}
"""Sleep debt (R4)."""
profile_id = session["profile_id"]
return build_sleep_debt_chart_payload(profile_id, days)
@router.get("/vital-signs-matrix")
@@ -1786,123 +1434,9 @@ def get_vital_signs_matrix_chart(
days: int = Query(default=7, ge=7, le=30),
session: dict = Depends(require_auth)
) -> Dict:
"""
Vital signs matrix (R5).
Shows latest vital signs as horizontal bar chart.
Args:
days: Max age of measurements (7-30 days, default 7)
session: Auth session (injected)
Returns:
Chart.js horizontal bar chart with vital signs
"""
profile_id = session['profile_id']
from db import get_db, get_cursor
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
# Get latest vitals
cur.execute(
"""SELECT resting_hr, hrv_ms, vo2_max, spo2, respiratory_rate
FROM vitals_baseline
WHERE profile_id=%s AND date >= %s
ORDER BY date DESC
LIMIT 1""",
(profile_id, cutoff)
)
vitals_row = cur.fetchone()
# Get latest blood pressure
cur.execute(
"""SELECT systolic, diastolic
FROM blood_pressure_log
WHERE profile_id=%s AND date >= %s
ORDER BY date DESC, time DESC
LIMIT 1""",
(profile_id, cutoff)
)
bp_row = cur.fetchone()
if not vitals_row and not bp_row:
return {
"chart_type": "bar",
"data": {
"labels": [],
"datasets": []
},
"metadata": {
"confidence": "insufficient",
"data_points": 0,
"message": "Keine aktuellen Vitalwerte"
}
}
labels = []
values = []
if vitals_row:
if vitals_row['resting_hr']:
labels.append("Ruhepuls (bpm)")
values.append(safe_float(vitals_row['resting_hr']))
if vitals_row['hrv_ms']:
labels.append("HRV (ms)")
values.append(safe_float(vitals_row['hrv_ms']))
if vitals_row['vo2_max']:
labels.append("VO2 Max")
values.append(safe_float(vitals_row['vo2_max']))
if vitals_row['spo2']:
labels.append("SpO2 (%)")
values.append(safe_float(vitals_row['spo2']))
if vitals_row['respiratory_rate']:
labels.append("Atemfrequenz")
values.append(safe_float(vitals_row['respiratory_rate']))
if bp_row:
if bp_row['systolic']:
labels.append("Blutdruck sys (mmHg)")
values.append(safe_float(bp_row['systolic']))
if bp_row['diastolic']:
labels.append("Blutdruck dia (mmHg)")
values.append(safe_float(bp_row['diastolic']))
if not labels:
return {
"chart_type": "bar",
"data": {
"labels": [],
"datasets": []
},
"metadata": {
"confidence": "insufficient",
"data_points": 0,
"message": "Keine Vitalwerte verfügbar"
}
}
return {
"chart_type": "bar",
"data": {
"labels": labels,
"datasets": [
{
"label": "Wert",
"data": values,
"backgroundColor": "#1D9E75",
"borderColor": "#085041",
"borderWidth": 1
}
]
},
"metadata": {
"confidence": "medium",
"data_points": len(values),
"note": "Latest measurements within last " + str(days) + " days"
}
}
"""Vital signs matrix (R5)."""
profile_id = session["profile_id"]
return build_vital_signs_matrix_chart_payload(profile_id, days)
# ── Correlation Charts ──────────────────────────────────────────────────────