feat: enhance recovery metrics and dashboard with sleep debt calculations and improved visualizations
Deploy Development / deploy (push) Successful in 1m2s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s

- Introduced new constants for sleep debt calculations, including target hours and rolling window days.
- Added a function to calculate sleep debt over a specified window, aligning with KPI logic.
- Updated SQL queries in recovery chart payloads to ensure accurate data retrieval for sleep metrics.
- Enhanced the RecoveryDashboardOverview component to reflect changes in sleep debt visualization and descriptions, improving user understanding of metrics.
- Refined chart labels and notes for clarity, ensuring users can easily interpret recovery and sleep data.
This commit is contained in:
Lars committed 2026-04-20 12:47:03 +02:00
1 parent 61738cecb7
commit 6c962bf6e5
3 files changed
+129 -46

No files matched your search

+37 -21
View File
@@ -11,12 +11,15 @@ from typing import Any, Dict, Optional, Set
from db import get_db, get_cursor
from data_layer.recovery_metrics import (
SLEEP_DEBT_ROLLING_WINDOW_DAYS,
SLEEP_DEBT_TARGET_HOURS_DEFAULT,
calculate_hrv_vs_baseline_pct,
calculate_recovery_score_v2,
calculate_rhr_vs_baseline_pct,
calculate_sleep_debt_hours,
get_sleep_duration_data,
get_sleep_quality_data,
sleep_debt_sum_hours_in_window,
)
from data_layer.utils import calculate_confidence, safe_float, serialize_dates
from data_layer.vital_signs_assessment import build_vital_items_from_rows
@@ -86,7 +89,7 @@ def build_recovery_score_chart_payload(profile_id: str, days: int) -> Dict[str,
"labels": labels,
"datasets": [
{
"label": "Recovery Score (proxy)",
"label": "HRV (ms, auf 0–100 begrenzt) — nicht der KPI Recovery-Score",
"data": values,
"borderColor": "#1D9E75",
"backgroundColor": "rgba(29, 158, 117, 0.1)",
@@ -101,7 +104,10 @@ def build_recovery_score_chart_payload(profile_id: str, days: int) -> Dict[str,
"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",
"chart_series_kind": "hrv_ms_clamped",
"kpi_score_source": "calculate_recovery_score_v2",
"note": "Kurve = HRV-Rohwert (ms) begrenzt auf 0–100, nur Verlaufsorientierung. "
"KPI-Kachel «Recovery-Score» = gewichteter Score (HRV, RHR, Schlaf, …).",
}
),
}
@@ -293,7 +299,9 @@ def build_sleep_debt_chart_payload(profile_id: str, days: int) -> Dict[str, Any]
},
}
cutoff = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
chart_cutoff = (datetime.now() - timedelta(days=days)).date()
# Historie vor dem Chart-Fenster, damit das rollierende 14-Tage-Fenster früh korrekt gefüllt ist
ext_cutoff = (datetime.now() - timedelta(days=days + SLEEP_DEBT_ROLLING_WINDOW_DAYS + 3)).strftime("%Y-%m-%d")
with get_db() as conn:
cur = get_cursor(conn)
@@ -301,12 +309,20 @@ def build_sleep_debt_chart_payload(profile_id: str, days: int) -> Dict[str, Any]
"""SELECT date, duration_minutes
FROM sleep_log
WHERE profile_id=%s AND date >= %s
ORDER BY date""",
(profile_id, cutoff),
AND duration_minutes IS NOT NULL
ORDER BY date ASC""",
(profile_id, ext_cutoff),
)
rows = cur.fetchall()
all_rows = [dict(r) for r in cur.fetchall()]
if not rows:
visible = []
for r in all_rows:
rd = r.get("date")
d = rd.date() if isinstance(rd, datetime) else rd
if d >= chart_cutoff:
visible.append(r)
if not visible:
return {
"chart_type": "line",
"data": {"labels": [], "datasets": []},
@@ -317,17 +333,13 @@ def build_sleep_debt_chart_payload(profile_id: str, days: int) -> Dict[str, Any]
},
}
labels = [row["date"].isoformat() for row in rows]
target_hours = 8.0
cumulative_debt = 0.0
labels = []
debt_values = []
for row in rows:
actual_hours = safe_float(row["duration_minutes"]) / 60 if row["duration_minutes"] else 0
daily_deficit = target_hours - actual_hours
cumulative_debt += daily_deficit
debt_values.append(cumulative_debt)
for r in visible:
rd = r.get("date")
end_d = rd.date() if isinstance(rd, datetime) else rd
labels.append(end_d.isoformat() if hasattr(end_d, "isoformat") else str(end_d))
debt_values.append(sleep_debt_sum_hours_in_window(all_rows, end_d))
return {
"chart_type": "line",
@@ -335,7 +347,7 @@ def build_sleep_debt_chart_payload(profile_id: str, days: int) -> Dict[str, Any]
"labels": labels,
"datasets": [
{
"label": "Schlafschuld (Stunden)",
"label": f"Schlafschuld (h), rollierend {SLEEP_DEBT_ROLLING_WINDOW_DAYS} Tage — wie KPI",
"data": debt_values,
"borderColor": "#EF4444",
"backgroundColor": "rgba(239, 68, 68, 0.1)",
@@ -347,10 +359,14 @@ def build_sleep_debt_chart_payload(profile_id: str, days: int) -> Dict[str, Any]
},
"metadata": serialize_dates(
{
"confidence": calculate_confidence(len(rows), days, "general"),
"data_points": len(rows),
"confidence": calculate_confidence(len(visible), days, "general"),
"data_points": len(visible),
"current_debt_hours": round(float(current_debt), 1),
"final_debt_hours": round(float(cumulative_debt), 1),
"sleep_debt_target_hours_per_night": SLEEP_DEBT_TARGET_HOURS_DEFAULT,
"rolling_window_days": SLEEP_DEBT_ROLLING_WINDOW_DAYS,
"note": "Gleiche Formel wie KPI: Summe der nächtlichen Defizite vs. "
f"{SLEEP_DEBT_TARGET_HOURS_DEFAULT} h/Nacht im rollierenden {SLEEP_DEBT_ROLLING_WINDOW_DAYS}-Tage-Fenster "
"(jeder Punkt = Fensterende an dem Datum). Ziel aktuell nicht in den Profileinstellungen änderbar.",
}
),
}