fix: Listen in der Tagesuebersicht und Katalog-Makros uebernehmen
Deploy Development / deploy (push) Successful in 1m13s
Build Test / pytest-backend (push) Successful in 6s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 22s

Tagebuchzeilen mit Liste gelten als zugeordnet. Berechnete Zutaten-Makros lassen sich am Tag in nutrition_log schreiben.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-09-14 13:31:30 +02:00
1 parent 44e3e216ab
commit 95453d548a
10 files changed
+221 -28

No files matched your search

+7 -1
View File
@@ -10,6 +10,10 @@ LEADING_QTY_RE = re.compile(
r"^\s*\d+(?:[.,]\d+)?\s*(?:g|kg|ml|l|stück|stk|st\.?|portion(?:en)?)\b[\s,.:\-–]*",
re.IGNORECASE,
)
TRAILING_QTY_RE = re.compile(
r"[\s,.:\-–]+\d+(?:[.,]\d+)?\s*(?:g|kg|ml|l)\s*$",
re.IGNORECASE,
)
MULTISPACE_RE = re.compile(r"\s+")
DECIMAL_IN_NAME_RE = re.compile(r"(\d),(\d)")
@@ -27,8 +31,10 @@ def normalize_food_name(raw: str | None) -> str:
s = strip_leading_quantity(raw)
if not s:
return ""
s = TRAILING_QTY_RE.sub("", s)
s = s.replace("-", " ")
s = DECIMAL_IN_NAME_RE.sub(r"\1.\2", s)
return s.lower()
return MULTISPACE_RE.sub(" ", s).strip().lower()
def item_name_keys(raw: str | None, stored_norm: str | None = None) -> set[str]:
+3 -1
View File
@@ -326,10 +326,12 @@ def save_recipe(cur, profile_id: str, rec: dict[str, Any], recipe_id: str | None
qty["quantity_raw"], qty["quantity_g"], qty["quantity_amount"], qty["source_unit"], i,
),
)
link_recipes_to_items(cur, profile_id)
linked, dates = link_recipes_to_items(cur, profile_id)
saved = get_recipe(cur, profile_id, rid)
if not saved:
raise ValueError("Rezept konnte nicht gelesen werden")
saved["items_linked"] = linked
saved["dates_linked"] = dates
return saved
+59
View File
@@ -446,6 +446,65 @@ def _touch_item_counts(cur, profile_id: str, day: str, sums: dict) -> None:
)
def day_macro_preview(cur, profile_id: str, day: date | str) -> dict[str, Any]:
sums = compute_day_macro_sums(cur, profile_id, day)
catalog = sums.get("catalog")
existing = sums.get("existing")
mapped = int(sums.get("mapped_item_count") or 0)
return {
"date": str(day)[:10],
"existing": existing,
"catalog": catalog,
"fddb": sums.get("fddb"),
"mapped_item_count": mapped,
"unmapped_item_count": int(sums.get("unmapped_item_count") or 0),
"catalog_origin": sums.get("catalog_origin"),
"can_apply": bool(catalog) and mapped > 0,
"differs": bool(existing and catalog and macros_differ(existing, catalog)),
}
def apply_day_catalog_macros(cur, profile_id: str, day: date | str) -> dict[str, Any]:
preview = day_macro_preview(cur, profile_id, day)
if not preview["can_apply"]:
raise ValueError("Keine aus Zuordnungen berechenbaren Tagesmakros")
cur.execute(
"SELECT source FROM nutrition_log WHERE profile_id = %s AND date = %s",
(profile_id, day),
)
row = cur.fetchone()
source = (row.get("source") if row else None) or "csv"
apply_nutrition_day_macros(
cur,
profile_id,
day,
preview["catalog"],
macro_origin=preview.get("catalog_origin") or "bls",
source=source,
confirm=True,
)
rebuild_daily_nutrients(cur, profile_id, day)
preview = day_macro_preview(cur, profile_id, day)
preview["applied"] = True
return preview
def annotate_nutrition_item(cur, profile_id: str, row: dict[str, Any]) -> dict[str, Any]:
item = dict(row)
item["id"] = str(item["id"])
if item.get("food_id"):
item["food_id"] = str(item["food_id"])
if item.get("recipe_id"):
item["recipe_id"] = str(item["recipe_id"])
from data_layer.food_recipes import catalog_macros_for_recipe
item["recipe_complete"] = catalog_macros_for_recipe(
cur, profile_id, item["recipe_id"], item.get("quantity_g")
) is not None
else:
item["recipe_complete"] = False
return item
def resolve_choice_macros(sums: dict[str, Any], choice: str) -> tuple[dict[str, float], str]:
if choice == "existing":
return sums["existing"], "user_confirmed"
+45 -5
View File
@@ -339,9 +339,11 @@ def list_nutrition_items(
if date:
cur.execute(
"""
SELECT i.*, f.name_de AS food_name_de, f.bls_code, f.catalog_kind
SELECT i.*, f.name_de AS food_name_de, f.bls_code, f.catalog_kind,
r.name_raw AS recipe_name_de
FROM nutrition_items i
LEFT JOIN food_catalog f ON f.id = i.food_id
LEFT JOIN food_recipes r ON r.id = i.recipe_id
WHERE i.profile_id=%s AND i.date=%s
ORDER BY i.logged_at NULLS LAST, i.source_name_raw
""",
@@ -350,16 +352,19 @@ def list_nutrition_items(
else:
cur.execute(
"""
SELECT i.*, f.name_de AS food_name_de, f.bls_code, f.catalog_kind
SELECT i.*, f.name_de AS food_name_de, f.bls_code, f.catalog_kind,
r.name_raw AS recipe_name_de
FROM nutrition_items i
LEFT JOIN food_catalog f ON f.id = i.food_id
LEFT JOIN food_recipes r ON r.id = i.recipe_id
WHERE i.profile_id=%s
ORDER BY i.date DESC, i.logged_at NULLS LAST
LIMIT %s
""",
(pid, min(limit, 500)),
)
return [r2d(r) for r in cur.fetchall()]
from data_layer.nutrition_items import annotate_nutrition_item
return [annotate_nutrition_item(cur, pid, r2d(r)) for r in cur.fetchall()]
@router.get("/unmapped")
@@ -422,10 +427,13 @@ def create_food_recipe(
session: dict = Depends(require_auth),
):
from data_layer.food_recipes import save_recipe
from data_layer.nutrition_items import schedule_daily_nutrient_rebuild
pid = get_pid(x_profile_id)
try:
with get_db() as conn:
return save_recipe(get_cursor(conn), pid, body.model_dump())
saved = save_recipe(get_cursor(conn), pid, body.model_dump())
schedule_daily_nutrient_rebuild(pid, saved.get("dates_linked") or [], "Liste angelegt")
return saved
except ValueError as e:
raise HTTPException(400, str(e)) from e
@@ -438,10 +446,13 @@ def update_food_recipe(
session: dict = Depends(require_auth),
):
from data_layer.food_recipes import save_recipe
from data_layer.nutrition_items import schedule_daily_nutrient_rebuild
pid = get_pid(x_profile_id)
try:
with get_db() as conn:
return save_recipe(get_cursor(conn), pid, body.model_dump(), recipe_id)
saved = save_recipe(get_cursor(conn), pid, body.model_dump(), recipe_id)
schedule_daily_nutrient_rebuild(pid, saved.get("dates_linked") or [], "Liste geändert")
return saved
except KeyError:
raise HTTPException(404, "Rezept nicht gefunden") from None
except ValueError as e:
@@ -612,6 +623,35 @@ def resolve_import_conflicts(
return {"applied": applied}
@router.get("/days/{day}/macros")
def get_day_macros(
day: str,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth),
):
from data_layer.nutrition_items import day_macro_preview
pid = get_pid(x_profile_id)
with get_db() as conn:
return day_macro_preview(get_cursor(conn), pid, day)
@router.post("/days/{day}/apply-catalog-macros")
def apply_catalog_macros_for_day(
day: str,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth),
):
from data_layer.nutrition_items import apply_day_catalog_macros
pid = get_pid(x_profile_id)
try:
with get_db() as conn:
return apply_day_catalog_macros(get_cursor(conn), pid, day)
except ValueError as e:
raise HTTPException(400, str(e)) from e
@router.put("/days/{day}/mark")
def upsert_day_mark(
day: str,
+5
View File
@@ -137,6 +137,11 @@ def test_list_name_matches_despite_quantity_prefix():
assert not names_match_list("Haferflocken", "haferflocken", "müsli mix")
def test_list_name_matches_hyphen_and_trailing_qty():
assert names_match_list("Quark-Skyr Blaubeeren", "quark-skyr blaubeeren", "quark skyr blaubeeren")
assert names_match_list("Quark skyr Blaubeeren 250 g", None, "Quark skyr Blaubeeren")
def test_unmapped_meta_includes_recent_ingredients():
batches = [
[],
+1 -1
View File
@@ -20,7 +20,7 @@ MODULE_VERSIONS = {
"circumference": "1.0.1",
"caliper": "1.0.1",
"activity": "1.2.1", # Legacy CSV import: activity_entries feature enforcement
"nutrition": "1.3.7", # Sichtbarkeit persönlich vs. zentral im Mapping
"nutrition": "1.3.8", # Listen in Tagesübersicht; Katalog-Makros auf den Tag übernehmen
"tandoor": "1.0.1", # Router-Import ohne future-annotations (Backend startet)
"bls": "1.0.13", # Stoffe gruppiert und sortiert (BLS-Nährstoffgruppen)