feat: implement nutrition history visualization bundle and related API endpoint
Deploy Development / deploy (push) Successful in 57s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s

- Added a new `nutrition_interpretation.py` file to handle KPI tile generation for nutrition history.
- Introduced `nutrition_viz.py` to create a visualization bundle for nutrition data, integrating metrics and historical analysis.
- Implemented `get_nutrition_history_viz` endpoint in `charts.py` to serve the new visualization data.
- Updated frontend components to fetch and display nutrition history data, enhancing user experience with detailed insights.
- Refactored existing logic to streamline data handling and improve overall performance.
This commit is contained in:
Lars committed 2026-04-19 17:20:24 +02:00
1 parent a8eafa8ba4
commit b96b1931db
6 files changed
+774 -292

No files matched your search

+145 -7
View File
@@ -20,6 +20,7 @@ Phase 0c: Multi-Layer Architecture
Version: 1.0
"""
import statistics
from typing import Dict, List, Optional
from datetime import datetime, timedelta, date
from db import get_db, get_cursor, r2d
@@ -110,7 +111,9 @@ def _get_profile_goal_mode(profile_id: str) -> str:
def get_nutrition_average_data(
profile_id: str,
days: int = 30
days: int = 30,
*,
all_history: bool = False,
) -> Dict:
"""
Get average nutrition values for all macros.
@@ -136,11 +139,18 @@ def get_nutrition_average_data(
"""
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cutoff = None if all_history else (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
# Mean over calendar days (per-day sums), not over raw log rows.
if cutoff:
inner_where = "WHERE profile_id=%s AND date >= %s"
params = (profile_id, cutoff)
else:
inner_where = "WHERE profile_id=%s"
params = (profile_id,)
cur.execute(
"""SELECT
f"""SELECT
AVG(daily_kcal) AS kcal_avg,
AVG(daily_protein) AS protein_avg,
AVG(daily_carbs) AS carbs_avg,
@@ -153,10 +163,10 @@ def get_nutrition_average_data(
COALESCE(SUM(carbs_g), 0)::float AS daily_carbs,
COALESCE(SUM(fat_g), 0)::float AS daily_fat
FROM nutrition_log
WHERE profile_id=%s AND date >= %s
{inner_where}
GROUP BY date
) AS daily""",
(profile_id, cutoff),
params,
)
row = cur.fetchone()
@@ -494,8 +504,6 @@ def get_macro_consistency_data(
"data_points": len(rows)
}
import statistics
protein_pcts = []
carbs_pcts = []
fat_pcts = []
@@ -561,6 +569,136 @@ def get_macro_consistency_data(
}
def get_weekly_macro_distribution_chart_data(profile_id: str, weeks: int) -> Dict:
"""
Chart E3: gestapelte Wochenbalken (Makro-%), gleiche Logik wie /charts/weekly-macro-distribution.
"""
cutoff = (datetime.now() - timedelta(weeks=weeks)).strftime("%Y-%m-%d")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""SELECT date, protein_g, carbs_g, fat_g, kcal
FROM nutrition_log
WHERE profile_id=%s AND date >= %s
AND protein_g IS NOT NULL AND carbs_g IS NOT NULL
AND fat_g IS NOT NULL AND kcal > 0
ORDER BY date""",
(profile_id, cutoff),
)
rows = cur.fetchall()
if not rows or len(rows) < 7:
return {
"chart_type": "bar",
"data": {
"labels": [],
"datasets": [],
},
"metadata": {
"confidence": "insufficient",
"data_points": len(rows) if rows else 0,
"message": "Nicht genug Daten für Wochen-Analyse (min. 7 Tage)",
},
}
weekly_data: Dict[str, Dict[str, List[float]]] = {}
for row in rows:
date_obj = row["date"] if isinstance(row["date"], datetime) else datetime.fromisoformat(str(row["date"]))
iso_week = date_obj.strftime("%Y-W%V")
if iso_week not in weekly_data:
weekly_data[iso_week] = {
"protein": [],
"carbs": [],
"fat": [],
"kcal": [],
}
weekly_data[iso_week]["protein"].append(safe_float(row["protein_g"]))
weekly_data[iso_week]["carbs"].append(safe_float(row["carbs_g"]))
weekly_data[iso_week]["fat"].append(safe_float(row["fat_g"]))
weekly_data[iso_week]["kcal"].append(safe_float(row["kcal"]))
labels: List[str] = []
protein_pcts: List[float] = []
carbs_pcts: List[float] = []
fat_pcts: List[float] = []
for iso_week in sorted(weekly_data.keys())[-weeks:]:
data = weekly_data[iso_week]
avg_protein = sum(data["protein"]) / len(data["protein"]) if data["protein"] else 0
avg_carbs = sum(data["carbs"]) / len(data["carbs"]) if data["carbs"] else 0
avg_fat = sum(data["fat"]) / len(data["fat"]) if data["fat"] else 0
protein_kcal = avg_protein * 4
carbs_kcal = avg_carbs * 4
fat_kcal = avg_fat * 9
total_kcal = protein_kcal + carbs_kcal + fat_kcal
if total_kcal > 0:
labels.append(f"KW {iso_week[-2:]}")
protein_pcts.append(round((protein_kcal / total_kcal) * 100, 1))
carbs_pcts.append(round((carbs_kcal / total_kcal) * 100, 1))
fat_pcts.append(round((fat_kcal / total_kcal) * 100, 1))
protein_cv = (
statistics.stdev(protein_pcts) / statistics.mean(protein_pcts) * 100
if len(protein_pcts) > 1 and statistics.mean(protein_pcts) > 0
else 0
)
carbs_cv = (
statistics.stdev(carbs_pcts) / statistics.mean(carbs_pcts) * 100
if len(carbs_pcts) > 1 and statistics.mean(carbs_pcts) > 0
else 0
)
fat_cv = (
statistics.stdev(fat_pcts) / statistics.mean(fat_pcts) * 100
if len(fat_pcts) > 1 and statistics.mean(fat_pcts) > 0
else 0
)
return {
"chart_type": "bar",
"data": {
"labels": labels,
"datasets": [
{
"label": "Protein (%)",
"data": protein_pcts,
"backgroundColor": "#1D9E75",
"stack": "macro",
},
{
"label": "Kohlenhydrate (%)",
"data": carbs_pcts,
"backgroundColor": "#F59E0B",
"stack": "macro",
},
{
"label": "Fett (%)",
"data": fat_pcts,
"backgroundColor": "#EF4444",
"stack": "macro",
},
],
},
"metadata": {
"confidence": calculate_confidence(len(rows), weeks * 7, "general"),
"data_points": len(rows),
"weeks_analyzed": len(labels),
"avg_protein_pct": round(statistics.mean(protein_pcts), 1) if protein_pcts else 0,
"avg_carbs_pct": round(statistics.mean(carbs_pcts), 1) if carbs_pcts else 0,
"avg_fat_pct": round(statistics.mean(fat_pcts), 1) if fat_pcts else 0,
"protein_cv": round(protein_cv, 1),
"carbs_cv": round(carbs_cv, 1),
"fat_cv": round(fat_cv, 1),
},
}
# ============================================================================
# Calculated Metrics (migrated from calculations/nutrition_metrics.py)
# ============================================================================