feat: enhance recovery metrics and dashboard with sleep debt calculations and improved visualizations
- 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:
1 parent
61738cecb7
commit
6c962bf6e5
3 files changed
+129
-46
No files matched your search
@@ -21,6 +21,11 @@ from datetime import datetime, timedelta, date
|
||||
from db import get_db, get_cursor
|
||||
from data_layer.utils import calculate_confidence, safe_float, safe_int
|
||||
|
||||
# ── Schlafschuld (KPI + Charts): eine Zielschlafdauer, bis ein Profil-Feld existiert
|
||||
SLEEP_DEBT_TARGET_HOURS_DEFAULT = 7.5
|
||||
SLEEP_DEBT_ROLLING_WINDOW_DAYS = 14
|
||||
SLEEP_DEBT_MIN_NIGHTS_FOR_KPI = 10
|
||||
|
||||
|
||||
def _parse_sleep_segments(raw: Any) -> Optional[List[dict]]:
|
||||
"""JSONB kann dict/list/str sein; ungültig → None."""
|
||||
@@ -744,34 +749,70 @@ def calculate_sleep_avg_duration_7d(profile_id: str) -> Optional[float]:
|
||||
return round(avg_hours, 1)
|
||||
|
||||
|
||||
def _row_date_as_date(d: Any) -> Optional[date]:
|
||||
if d is None:
|
||||
return None
|
||||
if isinstance(d, datetime):
|
||||
return d.date()
|
||||
if isinstance(d, date):
|
||||
return d
|
||||
return None
|
||||
|
||||
|
||||
def sleep_debt_sum_hours_in_window(
|
||||
night_rows: List[Dict[str, Any]],
|
||||
window_end: date,
|
||||
*,
|
||||
target_hours: float = SLEEP_DEBT_TARGET_HOURS_DEFAULT,
|
||||
window_days: int = SLEEP_DEBT_ROLLING_WINDOW_DAYS,
|
||||
min_nights: int = SLEEP_DEBT_MIN_NIGHTS_FOR_KPI,
|
||||
) -> Optional[float]:
|
||||
"""
|
||||
Summe der nächtlichen Defizite (nur Unter-Ziel, kein „Überschuss-Guthaben“) im Fenster
|
||||
(window_end − window_days … window_end], Kalendertage).
|
||||
Gleiche Logik wie KPI calculate_sleep_debt_hours für window_end = heute.
|
||||
"""
|
||||
start = window_end - timedelta(days=window_days)
|
||||
tmin = target_hours * 60.0
|
||||
total_min = 0.0
|
||||
nights = 0
|
||||
for row in night_rows:
|
||||
rd = _row_date_as_date(row.get("date"))
|
||||
if rd is None or rd < start or rd > window_end:
|
||||
continue
|
||||
dm = row.get("duration_minutes")
|
||||
if dm is None:
|
||||
continue
|
||||
nights += 1
|
||||
total_min += max(0.0, tmin - float(dm))
|
||||
if nights < min_nights:
|
||||
return None
|
||||
return round(total_min / 60.0, 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
|
||||
Aufsummierte Schlafschuld (h) der letzten 14 Kalendertage bis heute —
|
||||
Ziel pro Nacht: SLEEP_DEBT_TARGET_HOURS_DEFAULT (aktuell nicht profilkonfigurierbar).
|
||||
"""
|
||||
target_hours = 7.5
|
||||
|
||||
today = datetime.now().date()
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT duration_minutes
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT date, duration_minutes
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '14 days'
|
||||
AND date >= %s::date - INTERVAL '14 days'
|
||||
AND date <= %s::date
|
||||
AND duration_minutes IS NOT NULL
|
||||
ORDER BY date DESC
|
||||
""", (profile_id,))
|
||||
""",
|
||||
(profile_id, today, today),
|
||||
)
|
||||
rows = [dict(r) for r in cur.fetchall()]
|
||||
|
||||
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)
|
||||
return sleep_debt_sum_hours_in_window(rows, today)
|
||||
|
||||
|
||||
def calculate_sleep_regularity_proxy(profile_id: str) -> Optional[float]:
|
||||
|
||||
Reference in new issue
Block a user