feat: introduce fitness dashboard overview and enhance activity metrics
- Added new functions to build fitness dashboard visualizations, including weekly training volume and training type distribution charts. - Updated the `charts.py` router to include a new endpoint for the fitness dashboard, integrating data from activity metrics. - Refactored existing activity-related functions to improve modularity and maintainability. - Updated frontend components to reflect the new fitness terminology and integrate the fitness dashboard overview, enhancing user experience.
This commit is contained in:
1 parent
d7304c1a44
commit
b5c5f2f612
11 files changed
+739
-124
No files matched your search
@@ -330,24 +330,30 @@ def calculate_training_frequency_7d(profile_id: str) -> Optional[int]:
|
||||
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"""
|
||||
def calculate_quality_sessions_pct(profile_id: str, days: int = 28) -> Optional[int]:
|
||||
"""Anteil qualitativ guter Sessions (quality_label) im Zeitfenster ``days``."""
|
||||
if days < 1:
|
||||
days = 28
|
||||
cutoff = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
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,))
|
||||
AND date >= %s
|
||||
""",
|
||||
(profile_id, cutoff),
|
||||
)
|
||||
|
||||
row = cur.fetchone()
|
||||
if not row or row['total'] == 0:
|
||||
if not row or row["total"] == 0:
|
||||
return None
|
||||
|
||||
pct = (row['quality_count'] / row['total']) * 100
|
||||
pct = (row["quality_count"] / row["total"]) * 100
|
||||
return int(pct)
|
||||
|
||||
|
||||
@@ -1222,3 +1228,128 @@ def get_training_parameters_ki_glossary_data(profile_id: str) -> Dict[str, Any]:
|
||||
"parameters": rows,
|
||||
"meta": {"count": len(rows), "scope": "global_active_catalog"},
|
||||
}
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Chart payloads (Phase 0c / Layer 1) — gemeinsam mit charts-Router und Layer-2b-Bundles
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def build_training_volume_chart_payload(profile_id: str, weeks: int) -> Dict[str, Any]:
|
||||
"""
|
||||
Wöchentliches Trainingsvolumen (Minuten) — gleiche Logik wie GET /api/charts/training-volume.
|
||||
"""
|
||||
if weeks < 4:
|
||||
weeks = 4
|
||||
if weeks > 52:
|
||||
weeks = 52
|
||||
|
||||
cutoff = (datetime.now() - timedelta(weeks=weeks)).strftime("%Y-%m-%d")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""SELECT
|
||||
DATE_TRUNC('week', date) as week_start,
|
||||
SUM(duration_min) as total_minutes,
|
||||
COUNT(*) as session_count
|
||||
FROM activity_log
|
||||
WHERE profile_id=%s AND date >= %s
|
||||
GROUP BY week_start
|
||||
ORDER BY week_start""",
|
||||
(profile_id, cutoff),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
if not rows:
|
||||
return {
|
||||
"chart_type": "bar",
|
||||
"data": {"labels": [], "datasets": []},
|
||||
"metadata": {
|
||||
"confidence": "insufficient",
|
||||
"data_points": 0,
|
||||
"message": "Keine Aktivitätsdaten vorhanden",
|
||||
},
|
||||
}
|
||||
|
||||
labels = [row["week_start"].strftime("KW %V") for row in rows]
|
||||
values = [safe_float(row["total_minutes"]) for row in rows]
|
||||
|
||||
confidence = calculate_confidence(len(rows), weeks * 7, "general")
|
||||
|
||||
return {
|
||||
"chart_type": "bar",
|
||||
"data": {
|
||||
"labels": labels,
|
||||
"datasets": [
|
||||
{
|
||||
"label": "Trainingsminuten",
|
||||
"data": values,
|
||||
"backgroundColor": "#1D9E75",
|
||||
"borderColor": "#085041",
|
||||
"borderWidth": 1,
|
||||
}
|
||||
],
|
||||
},
|
||||
"metadata": serialize_dates(
|
||||
{
|
||||
"confidence": confidence,
|
||||
"data_points": len(rows),
|
||||
"avg_minutes_week": round(sum(values) / len(values), 1) if values else 0,
|
||||
"total_sessions": sum(row["session_count"] for row in rows),
|
||||
}
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def build_training_type_distribution_chart_payload(profile_id: str, days: int) -> Dict[str, Any]:
|
||||
"""
|
||||
Trainingstyp-Verteilung — gleiche Logik wie GET /api/charts/training-type-distribution.
|
||||
"""
|
||||
dist_data = get_training_type_distribution_data(profile_id, days)
|
||||
|
||||
if dist_data["confidence"] == "insufficient":
|
||||
return {
|
||||
"chart_type": "pie",
|
||||
"data": {"labels": [], "datasets": []},
|
||||
"metadata": {
|
||||
"confidence": "insufficient",
|
||||
"data_points": 0,
|
||||
"message": "Keine Trainingstypen-Daten",
|
||||
},
|
||||
}
|
||||
|
||||
labels = [item["category"] for item in dist_data["distribution"]]
|
||||
values = [item["count"] for item in dist_data["distribution"]]
|
||||
|
||||
colors = [
|
||||
"#1D9E75",
|
||||
"#3B82F6",
|
||||
"#F59E0B",
|
||||
"#EF4444",
|
||||
"#8B5CF6",
|
||||
"#10B981",
|
||||
"#F97316",
|
||||
"#06B6D4",
|
||||
]
|
||||
|
||||
return {
|
||||
"chart_type": "pie",
|
||||
"data": {
|
||||
"labels": labels,
|
||||
"datasets": [
|
||||
{
|
||||
"data": values,
|
||||
"backgroundColor": colors[: len(values)],
|
||||
"borderWidth": 2,
|
||||
"borderColor": "#fff",
|
||||
}
|
||||
],
|
||||
},
|
||||
"metadata": {
|
||||
"confidence": dist_data["confidence"],
|
||||
"total_sessions": dist_data["total_sessions"],
|
||||
"categorized_sessions": dist_data["categorized_sessions"],
|
||||
"uncategorized_sessions": dist_data["uncategorized_sessions"],
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
"""
|
||||
KPI-Kacheln für Layer-2b Fitness-Dashboard (Issue #53).
|
||||
|
||||
Ausgabe für KpiTilesOverview; ``keys`` = Platzhalter-Registry-Referenzen.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
def _verdict(status: str) -> str:
|
||||
if status == "good":
|
||||
return "Gut"
|
||||
if status == "warn":
|
||||
return "Hinweis"
|
||||
return "Achtung"
|
||||
|
||||
|
||||
def _minutes_status(minutes: Optional[int]) -> str:
|
||||
if minutes is None:
|
||||
return "warn"
|
||||
if 150 <= minutes <= 300:
|
||||
return "good"
|
||||
if minutes < 150:
|
||||
return "warn" if minutes >= 90 else "bad"
|
||||
return "warn"
|
||||
|
||||
|
||||
def _quality_status(pct: Optional[int]) -> str:
|
||||
if pct is None:
|
||||
return "warn"
|
||||
if pct >= 60:
|
||||
return "good"
|
||||
if pct >= 40:
|
||||
return "warn"
|
||||
return "bad"
|
||||
|
||||
|
||||
def _score_status(score: Optional[int]) -> str:
|
||||
if score is None:
|
||||
return "warn"
|
||||
if score >= 70:
|
||||
return "good"
|
||||
if score >= 50:
|
||||
return "warn"
|
||||
return "bad"
|
||||
|
||||
|
||||
def _vo2_status(trend: Optional[float]) -> str:
|
||||
if trend is None:
|
||||
return "warn"
|
||||
if trend > 0.5:
|
||||
return "good"
|
||||
if trend >= -0.5:
|
||||
return "warn"
|
||||
return "bad"
|
||||
|
||||
|
||||
def build_fitness_dashboard_kpi_tiles(
|
||||
summary: Dict[str, Any],
|
||||
minutes_7d: Optional[int],
|
||||
quality_pct: Optional[int],
|
||||
quality_window_days: int,
|
||||
activity_score: Optional[int],
|
||||
vo2_trend: Optional[float],
|
||||
top_focus: Optional[Dict[str, Any]],
|
||||
) -> List[Dict[str, Any]]:
|
||||
spw = summary.get("sessions_per_week")
|
||||
try:
|
||||
spw_f = float(spw) if spw is not None else None
|
||||
except (TypeError, ValueError):
|
||||
spw_f = None
|
||||
spw_s = f"{spw_f:.1f}".replace(".", ",") if spw_f is not None else "—"
|
||||
|
||||
m_status = _minutes_status(minutes_7d)
|
||||
q_status = _quality_status(quality_pct)
|
||||
s_status = _score_status(activity_score)
|
||||
v_status = _vo2_status(vo2_trend)
|
||||
|
||||
tiles: List[Dict[str, Any]] = [
|
||||
{
|
||||
"key": "minutes_week",
|
||||
"category": "Minuten (7 Tage)",
|
||||
"icon": "⏱",
|
||||
"value": f"{minutes_7d} min" if minutes_7d is not None else "—",
|
||||
"sublabel": "WHO: 150–300 min/Woche",
|
||||
"status": m_status,
|
||||
"verdict": _verdict(m_status),
|
||||
"hoverTop": "Summe Trainingsminuten (letzte 7 Tage)",
|
||||
"hoverBody": "Gleiche Quelle wie Platzhalter training_minutes_week.",
|
||||
"keys": ["training_minutes_week", "activity_score"],
|
||||
},
|
||||
{
|
||||
"key": "sessions_per_week",
|
||||
"category": "Sessions / Woche",
|
||||
"icon": "📅",
|
||||
"value": spw_s,
|
||||
"sublabel": f"Fenster: {summary.get('days_analyzed', '—')} Tage",
|
||||
"status": "good",
|
||||
"verdict": "Gut",
|
||||
"hoverTop": "Durchschnittliche Sessions pro Woche",
|
||||
"hoverBody": "Aus activity_summary (activity_log im gewählten Zeitraum).",
|
||||
"keys": ["activity_summary"],
|
||||
},
|
||||
{
|
||||
"key": "quality_pct",
|
||||
"category": "Qualitätssessions",
|
||||
"icon": "✓",
|
||||
"value": f"{quality_pct} %" if quality_pct is not None else "—",
|
||||
"sublabel": f"Anteil «gut+» · {quality_window_days} Tage",
|
||||
"status": q_status,
|
||||
"verdict": _verdict(q_status),
|
||||
"hoverTop": "Anteil Sessions mit guter Qualitätslabel-Klassifikation",
|
||||
"hoverBody": "Entspricht quality_sessions_pct (Fenster wie gewählt).",
|
||||
"keys": ["quality_sessions_pct"],
|
||||
},
|
||||
{
|
||||
"key": "activity_score",
|
||||
"category": "Activity-Score",
|
||||
"icon": "🎯",
|
||||
"value": str(activity_score) if activity_score is not None else "—",
|
||||
"sublabel": "Ausrichtung an gewichteten Fokusbereichen",
|
||||
"status": s_status,
|
||||
"verdict": _verdict(s_status) if activity_score is not None else "Hinweis",
|
||||
"hoverTop": "Gewichteter Score (0–100)",
|
||||
"hoverBody": "Ohne gewichtete Aktivitäts-Fokusbereiche kein Score.",
|
||||
"keys": ["activity_score"],
|
||||
},
|
||||
{
|
||||
"key": "vo2_trend",
|
||||
"category": "VO₂max-Trend",
|
||||
"icon": "🫁",
|
||||
"value": f"{vo2_trend:+.1f}" if vo2_trend is not None else "—",
|
||||
"sublabel": "28-Tage-Trend (geschätzt)",
|
||||
"status": v_status,
|
||||
"verdict": _verdict(v_status) if vo2_trend is not None else "Hinweis",
|
||||
"hoverTop": "Trend der VO₂max-Schätzung aus Aktivitätsdaten",
|
||||
"hoverBody": "Wie vo2max_trend_28d im Data Layer.",
|
||||
"keys": ["vo2max_trend_28d"],
|
||||
},
|
||||
]
|
||||
|
||||
if top_focus:
|
||||
prog = top_focus.get("progress")
|
||||
prog_s = f"{prog} %" if prog is not None else "—"
|
||||
w = top_focus.get("weight")
|
||||
try:
|
||||
w_s = f"{float(w):.0f} %" if w is not None else "—"
|
||||
except (TypeError, ValueError):
|
||||
w_s = "—"
|
||||
tiles.append(
|
||||
{
|
||||
"key": "top_focus",
|
||||
"category": "Schwerpunkt-Fokus",
|
||||
"icon": "🔭",
|
||||
"value": str(top_focus.get("label") or "—"),
|
||||
"sublabel": f"Fortschritt {prog_s} · Gewicht {w_s}",
|
||||
"status": "good",
|
||||
"verdict": "Gut",
|
||||
"hoverTop": "Höchstgewichteter Fokusbereich",
|
||||
"hoverBody": "Aus focus_area_definitions + Nutzer-Gewichtungen.",
|
||||
"keys": ["top_focus_area_name", "top_focus_area_progress"],
|
||||
}
|
||||
)
|
||||
|
||||
return tiles
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
Layer 2b: Fitness-Hub — ein Bundle für die Aktivitäts-/Fitness-UI (Issue #53).
|
||||
|
||||
Single Source: activity_metrics + dieselben Hilfsfunktionen wie Chart-Endpunkte A1/A2.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from db import get_db, get_cursor
|
||||
from data_layer.activity_metrics import (
|
||||
build_training_type_distribution_chart_payload,
|
||||
build_training_volume_chart_payload,
|
||||
calculate_activity_score,
|
||||
calculate_training_minutes_week,
|
||||
calculate_quality_sessions_pct,
|
||||
calculate_vo2max_trend_28d,
|
||||
get_activity_summary_data,
|
||||
)
|
||||
from data_layer.fitness_interpretation import build_fitness_dashboard_kpi_tiles
|
||||
from data_layer.scores import get_top_focus_area
|
||||
|
||||
|
||||
def _iso(d: Any) -> Optional[str]:
|
||||
if d is None:
|
||||
return None
|
||||
if hasattr(d, "isoformat"):
|
||||
return d.isoformat()[:10]
|
||||
return str(d)[:10]
|
||||
|
||||
|
||||
def _has_activity_entries(profile_id: str) -> bool:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT 1 FROM activity_log WHERE profile_id=%s LIMIT 1",
|
||||
(profile_id,),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
|
||||
|
||||
def _last_activity_date(profile_id: str) -> Optional[str]:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT MAX(date) AS d FROM activity_log WHERE profile_id=%s",
|
||||
(profile_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row or row["d"] is None:
|
||||
return None
|
||||
return _iso(row["d"])
|
||||
|
||||
|
||||
def get_fitness_dashboard_viz_bundle(profile_id: str, days: int) -> Dict[str, Any]:
|
||||
"""
|
||||
Bundle für Fitness-Übersicht: KPI-Kacheln + eingebettete Chart-Payloads (Chart.js-Format).
|
||||
|
||||
``days``: Analysefenster für Zusammenfassung; >=9999 = lange Historie (max. 3650 Tage).
|
||||
"""
|
||||
if not _has_activity_entries(profile_id):
|
||||
return {
|
||||
"confidence": "insufficient",
|
||||
"has_activity_entries": False,
|
||||
"message": "Noch keine Aktivitätsdaten",
|
||||
"kpi_tiles": [],
|
||||
"summary": {},
|
||||
"charts": {},
|
||||
"meta": {"layer_1": "activity_metrics", "layer_2b": "fitness_viz"},
|
||||
}
|
||||
|
||||
all_history = days >= 9999
|
||||
eff_days = 3650 if all_history else max(7, min(int(days), 3650))
|
||||
|
||||
summary = get_activity_summary_data(profile_id, eff_days)
|
||||
|
||||
weeks_vol = max(4, min(52, (min(eff_days, 365) + 6) // 7))
|
||||
dist_days = min(90, max(7, min(eff_days, 365)))
|
||||
|
||||
volume_chart = build_training_volume_chart_payload(profile_id, weeks_vol)
|
||||
type_chart = build_training_type_distribution_chart_payload(profile_id, dist_days)
|
||||
|
||||
quality_days = dist_days
|
||||
quality_pct = calculate_quality_sessions_pct(profile_id, quality_days)
|
||||
minutes_7d = calculate_training_minutes_week(profile_id)
|
||||
activity_score = calculate_activity_score(profile_id)
|
||||
vo2_trend = calculate_vo2max_trend_28d(profile_id)
|
||||
top_focus = get_top_focus_area(profile_id)
|
||||
|
||||
kpi_tiles = build_fitness_dashboard_kpi_tiles(
|
||||
summary,
|
||||
minutes_7d,
|
||||
quality_pct,
|
||||
quality_days,
|
||||
activity_score,
|
||||
vo2_trend,
|
||||
top_focus,
|
||||
)
|
||||
|
||||
conf = summary.get("confidence") or "medium"
|
||||
if summary.get("activity_count", 0) == 0:
|
||||
conf = "insufficient"
|
||||
|
||||
return {
|
||||
"confidence": conf,
|
||||
"has_activity_entries": True,
|
||||
"days_requested": days,
|
||||
"effective_window_days": eff_days,
|
||||
"training_volume_weeks_used": weeks_vol,
|
||||
"training_type_dist_days_used": dist_days,
|
||||
"last_updated": _last_activity_date(profile_id),
|
||||
"summary": summary,
|
||||
"kpi_tiles": kpi_tiles,
|
||||
"interpretation_tiles": [],
|
||||
"charts": {
|
||||
"training_volume": volume_chart,
|
||||
"training_type_distribution": type_chart,
|
||||
},
|
||||
"meta": {
|
||||
"layer_1": "activity_metrics",
|
||||
"layer_2b": "fitness_viz",
|
||||
"issue": "53-layer-2b-fitness",
|
||||
},
|
||||
}
|
||||
Reference in new issue
Block a user