feat: enhance vital signs matrix chart payload and visualization
Deploy Development / deploy (push) Successful in 1m2s
Build Test / pytest-backend (push) Successful in 5s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 17s

- Introduced new functions to handle vital signs data retrieval and processing, including fallback mechanisms for missing values.
- Updated SQL queries in `build_vital_signs_matrix_chart_payload` to improve date filtering and data accuracy.
- Enhanced the frontend `RecoveryDashboardOverview` component to display vital signs with contextual coloring based on health tones.
- Adjusted the data structure for chart rendering, ensuring a more informative and visually appealing representation of vital metrics.
This commit is contained in:
Lars committed 2026-04-20 08:36:45 +02:00
1 parent d3cb9d4ad9
commit d4868b3797
5 files changed
+392 -77

No files matched your search

+108 -52
View File
@@ -19,6 +19,7 @@ from data_layer.recovery_metrics import (
get_sleep_quality_data,
)
from data_layer.utils import calculate_confidence, safe_float, serialize_dates
from data_layer.vital_signs_assessment import build_vital_items_from_rows
def build_recovery_score_chart_payload(profile_id: str, days: int) -> Dict[str, Any]:
@@ -355,17 +356,40 @@ def build_sleep_debt_chart_payload(profile_id: str, days: int) -> Dict[str, Any]
}
def _vitals_row_has_any_value(row: Any) -> bool:
if not row:
return False
for k in ("resting_hr", "hrv", "vo2_max", "spo2", "respiratory_rate"):
if row.get(k) is not None:
return True
return False
def _bp_row_complete(row: Any) -> bool:
return bool(row and row.get("systolic") is not None and row.get("diastolic") is not None)
def _tone_to_bar_value(tone: str) -> float:
return {"good": 88.0, "warn": 52.0, "bad": 22.0, "neutral": 62.0}.get(tone, 55.0)
def build_vital_signs_matrix_chart_payload(profile_id: str, days: int) -> Dict[str, Any]:
"""Letzte Messungen im Fenster; sonst Fallback auf jüngste Messung überhaupt (Issue 53 / Layer 1)."""
if days < 7:
days = 7
if days > 30:
days = 30
if days > 365:
days = 365
cutoff = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
vitals_row = None
bp_row = None
vitals_measured_at = None
bp_measured_at = None
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""SELECT resting_hr, hrv, vo2_max, spo2, respiratory_rate
"""SELECT date, resting_hr, hrv, vo2_max, spo2, respiratory_rate
FROM vitals_baseline
WHERE profile_id=%s AND date >= %s
ORDER BY date DESC
@@ -373,9 +397,26 @@ def build_vital_signs_matrix_chart_payload(profile_id: str, days: int) -> Dict[s
(profile_id, cutoff),
)
vitals_row = cur.fetchone()
if vitals_row and vitals_row.get("date") is not None:
d = vitals_row["date"]
vitals_measured_at = d.isoformat() if hasattr(d, "isoformat") else str(d)
if not _vitals_row_has_any_value(vitals_row):
cur.execute(
"""SELECT date, resting_hr, hrv, vo2_max, spo2, respiratory_rate
FROM vitals_baseline
WHERE profile_id=%s
ORDER BY date DESC
LIMIT 1""",
(profile_id,),
)
vitals_row = cur.fetchone()
if vitals_row and vitals_row.get("date") is not None:
d = vitals_row["date"]
vitals_measured_at = d.isoformat() if hasattr(d, "isoformat") else str(d)
cur.execute(
"""SELECT systolic, diastolic
"""SELECT measured_at, systolic, diastolic
FROM blood_pressure_log
WHERE profile_id=%s AND measured_at::date >= %s::date
ORDER BY measured_at DESC
@@ -383,74 +424,89 @@ def build_vital_signs_matrix_chart_payload(profile_id: str, days: int) -> Dict[s
(profile_id, cutoff),
)
bp_row = cur.fetchone()
if bp_row and bp_row.get("measured_at") is not None:
bp_measured_at = bp_row["measured_at"]
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"]:
labels.append("HRV (ms)")
values.append(safe_float(vitals_row["hrv"]))
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 not _bp_row_complete(bp_row):
cur.execute(
"""SELECT measured_at, systolic, diastolic
FROM blood_pressure_log
WHERE profile_id=%s
ORDER BY measured_at DESC
LIMIT 1""",
(profile_id,),
)
bp_row = cur.fetchone()
if bp_row and bp_row.get("measured_at") is not None:
bp_measured_at = bp_row["measured_at"]
# Dict-like rows for assessment (exclude date/measured_at from value checks)
vitals_for_items = dict(vitals_row) if vitals_row else None
if vitals_for_items and "date" in vitals_for_items:
vitals_for_items = {k: v for k, v in vitals_for_items.items() if k != "date"}
bp_for_items = None
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"]))
bp_for_items = {"systolic": bp_row.get("systolic"), "diastolic": bp_row.get("diastolic")}
if not labels:
items = build_vital_items_from_rows(vitals_for_items, bp_for_items)
if not items:
return {
"chart_type": "bar",
"data": {"labels": [], "datasets": []},
"metadata": {
"confidence": "insufficient",
"data_points": 0,
"message": "Keine Vitalwerte verfügbar",
"message": "Keine Vitalwerte mit Zahlenwerten — Baseline-Vitals und/oder Blutdruck erfassen.",
"vital_items": [],
"vitals_measured_at": vitals_measured_at,
"blood_pressure_measured_at": bp_measured_at.isoformat() if bp_measured_at and hasattr(bp_measured_at, "isoformat") else None,
},
}
for it in items:
it["bar_value"] = round(_tone_to_bar_value(it["tone"]), 1)
labels_short = [it["label_de"] for it in items]
bar_values = [it["bar_value"] for it in items]
colors = []
for it in items:
t = it["tone"]
if t == "good":
colors.append("#1D9E75")
elif t == "warn":
colors.append("#EF9F27")
elif t == "bad":
colors.append("#D85A30")
else:
colors.append("#6B7280")
return {
"chart_type": "bar",
"data": {
"labels": labels,
"labels": labels_short,
"datasets": [
{
"label": "Wert",
"data": values,
"backgroundColor": "#1D9E75",
"borderColor": "#085041",
"label": "Einschätzung (relativ)",
"data": bar_values,
"backgroundColor": colors,
"borderColor": colors,
"borderWidth": 1,
}
],
},
"metadata": {
"confidence": "medium",
"data_points": len(values),
"note": "Latest measurements within last " + str(days) + " days",
},
"metadata": serialize_dates(
{
"confidence": "medium",
"data_points": len(items),
"note": "Orientierende Zonen, keine Diagnose. Balken = relative Einordnung (nicht körperliche Einheit).",
"vital_items": items,
"bar_is_relative_score": True,
"vitals_measured_at": vitals_measured_at,
"blood_pressure_measured_at": bp_measured_at.isoformat()
if bp_measured_at and hasattr(bp_measured_at, "isoformat")
else (str(bp_measured_at) if bp_measured_at else None),
"disclaimer_de": "Hinweis: Nur Orientierung; bei Beschwerden oder auffälligen Werten ärztlich abklären.",
}
),
}