feat: Enhance Dashboard widget configuration and layout management
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s

- Added validation for widget configuration in the DashboardWidgetEntry model to ensure proper data structure.
- Updated the DashboardLayoutPayload to include widget configuration in the serialized output.
- Improved the PilotBodySection and DashboardLabPage components to support dynamic chart days configuration for the body overview widget.
- Refactored layout editor functions to normalize widget configurations for better handling.
- Bumped app_dashboard version to 1.2.0 to reflect the new features and improvements.
This commit is contained in:
Lars committed 2026-04-07 11:58:07 +02:00
1 parent f6c5f96768
commit 87c4cbc4b4
11 files changed
+298 -62

No files matched your search

+24 -5
View File
@@ -7,8 +7,9 @@ from __future__ import annotations
from typing import Any, Literal
from pydantic import BaseModel, Field, model_validator
from pydantic import BaseModel, Field, field_validator, model_validator
from dashboard_widget_config import validate_widget_entry_config
from widget_catalog import ALLOWED_WIDGET_IDS, WIDGET_CATALOG
# Abwärtskompatibel (Tests importieren weiterhin aus diesem Modul)
@@ -31,6 +32,21 @@ def default_layout_dict() -> dict[str, Any]:
class DashboardWidgetEntry(BaseModel):
id: str = Field(min_length=1, max_length=64)
enabled: bool = True
config: dict[str, Any] = Field(default_factory=dict)
@field_validator("config", mode="before")
@classmethod
def _config_coerce(cls, v: Any) -> dict[str, Any]:
if v is None:
return {}
if not isinstance(v, dict):
raise ValueError("config muss Objekt sein")
return v
@model_validator(mode="after")
def _normalize_widget_config(self) -> DashboardWidgetEntry:
normalized = validate_widget_entry_config(self.id, self.config)
return self.model_copy(update={"config": normalized})
class DashboardLayoutPayload(BaseModel):
@@ -50,10 +66,13 @@ class DashboardLayoutPayload(BaseModel):
return self
def to_stored_dict(self) -> dict[str, Any]:
return {
"version": self.version,
"widgets": [{"id": w.id, "enabled": w.enabled} for w in self.widgets],
}
out_widgets: list[dict[str, Any]] = []
for w in self.widgets:
d: dict[str, Any] = {"id": w.id, "enabled": w.enabled}
if w.config:
d["config"] = dict(w.config)
out_widgets.append(d)
return {"version": self.version, "widgets": out_widgets}
def coalesce_effective_layout(raw: Any) -> tuple[bool, dict[str, Any]]:
+64
View File
@@ -0,0 +1,64 @@
"""
Pro-Widget-Konfiguration im Dashboard-Layout (v1).
Nur ausgewählte Widget-IDs dürfen nicht-leere config haben; bekannte Keys werden validiert.
"""
from __future__ import annotations
import json
import math
from typing import Any
MAX_WIDGET_CONFIG_JSON_BYTES = 1024
WIDGETS_ALLOWING_CONFIG: frozenset[str] = frozenset({"body_overview"})
def _config_json_size_bytes(config: dict[str, Any]) -> int:
return len(json.dumps(config, sort_keys=True, ensure_ascii=False).encode("utf-8"))
def validate_widget_entry_config(widget_id: str, raw: Any) -> dict[str, Any]:
if raw is None:
return {}
if not isinstance(raw, dict):
raise ValueError(f"Widget {widget_id}: config muss ein Objekt sein")
if _config_json_size_bytes(raw) > MAX_WIDGET_CONFIG_JSON_BYTES:
raise ValueError(f"Widget {widget_id}: config zu groß (max. {MAX_WIDGET_CONFIG_JSON_BYTES} Byte JSON)")
if not raw:
return {}
if widget_id not in WIDGETS_ALLOWING_CONFIG:
raise ValueError(f"Widget {widget_id}: keine Konfiguration unterstützt")
if widget_id == "body_overview":
return _validate_body_overview_config(raw)
raise ValueError(f"Widget {widget_id}: keine Konfiguration unterstützt")
def _validate_body_overview_config(raw: dict[str, Any]) -> dict[str, Any]:
allowed = frozenset({"chart_days"})
unknown = set(raw) - allowed
if unknown:
raise ValueError(f"body_overview: unbekannte config-Felder: {sorted(unknown)}")
out: dict[str, Any] = {}
if "chart_days" not in raw:
return out
v = raw["chart_days"]
if isinstance(v, bool):
raise ValueError("body_overview: chart_days muss ganze Zahl sein")
if isinstance(v, float):
if not math.isfinite(v):
raise ValueError("body_overview: chart_days muss ganze Zahl sein")
if abs(v - round(v)) > 1e-9:
raise ValueError("body_overview: chart_days muss ganze Zahl sein")
v = int(round(v))
elif isinstance(v, int):
pass
else:
raise ValueError("body_overview: chart_days muss ganze Zahl sein")
if v < 7 or v > 90:
raise ValueError("body_overview: chart_days muss zwischen 7 und 90 liegen")
out["chart_days"] = v
return out
@@ -0,0 +1,54 @@
import pytest
from dashboard_layout_schema import DashboardLayoutPayload, coalesce_effective_layout, default_layout_dict
from dashboard_widget_config import validate_widget_entry_config
def test_body_chart_days_bounds():
assert validate_widget_entry_config("body_overview", {"chart_days": 7}) == {"chart_days": 7}
assert validate_widget_entry_config("body_overview", {"chart_days": 90}) == {"chart_days": 90}
assert validate_widget_entry_config("body_overview", {"chart_days": 42.0}) == {"chart_days": 42}
with pytest.raises(ValueError):
validate_widget_entry_config("body_overview", {"chart_days": 6})
with pytest.raises(ValueError):
validate_widget_entry_config("body_overview", {"chart_days": 91})
def test_welcome_config_rejected():
with pytest.raises(ValueError):
validate_widget_entry_config("welcome", {"x": 1})
def test_body_unknown_key():
with pytest.raises(ValueError):
validate_widget_entry_config("body_overview", {"chart_days": 30, "extra": 1})
def test_layout_payload_with_chart_days_roundtrip():
p = DashboardLayoutPayload.model_validate(
{
"version": 1,
"widgets": [
{"id": "welcome", "enabled": True},
{
"id": "body_overview",
"enabled": True,
"config": {"chart_days": 42},
},
],
}
)
d = p.to_stored_dict()
assert d["widgets"][1]["config"]["chart_days"] == 42
def test_coalesce_rejects_invalid_widget_config():
raw = {
"version": 1,
"widgets": [
{"id": "welcome", "enabled": True, "config": {"evil": True}},
],
}
custom, eff = coalesce_effective_layout(raw)
assert custom is False
assert eff == default_layout_dict()
+1 -1
View File
@@ -30,7 +30,7 @@ MODULE_VERSIONS = {
"importdata": "1.0.0",
"membership": "2.1.0",
"workflow": "0.6.0", # Phase 4: End Node Template Engine
"app_dashboard": "1.1.0", # Dashboard-Lab + GET /widgets/catalog (Widget-System Iteration 1)
"app_dashboard": "1.2.0", # Widget-Config (body_overview.chart_days) + Validierung
}
CHANGELOG = [
+1 -1
View File
@@ -35,7 +35,7 @@ WIDGET_CATALOG: list[WidgetCatalogEntry] = [
{
"id": "body_overview",
"title": "Körper (Chart)",
"description": "Gewicht & Kennzahlen",
"description": "Gewicht & Kennzahlen (optional: config chart_days 7–90)",
},
{
"id": "activity_overview",