feat: FDDB-Listen auflösen und Katalog nach Name suchen
Tagebuchzeilen eigener Rezepte werden über den Listen-Import in Zutaten zerlegt. Zuordnen erfolgt im Namens-Popup statt per BLS-Code. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
4b1be3019d
commit
86f15e6957
17 files changed
+866
-86
No files matched your search
@@ -17,6 +17,7 @@ def normalize_food_name(raw: str | None) -> str:
|
||||
if not raw:
|
||||
return ""
|
||||
s = unicodedata.normalize("NFKC", str(raw)).strip().strip('"').strip("'")
|
||||
s = s.lstrip("!")
|
||||
s = LEADING_QTY_RE.sub("", s)
|
||||
s = DECIMAL_IN_NAME_RE.sub(r"\1.\2", s)
|
||||
s = MULTISPACE_RE.sub(" ", s).strip().lower()
|
||||
@@ -133,6 +134,7 @@ def apply_mapping_to_items(cur, profile_id: str, source_name_normalized: str, fo
|
||||
UPDATE nutrition_items
|
||||
SET food_id = %s, mapping_id = %s, value_origin = %s, updated_at = NOW()
|
||||
WHERE profile_id = %s AND source_name_normalized = %s
|
||||
AND recipe_id IS NULL
|
||||
""",
|
||||
(food_id, mapping_id, origin, profile_id, source_name_normalized),
|
||||
)
|
||||
@@ -166,8 +168,11 @@ def suggest_catalog_foods(cur, query: str, profile_id: str | None, limit: int =
|
||||
q = (query or "").strip()
|
||||
if not q:
|
||||
return []
|
||||
like = f"%{q}%"
|
||||
norm = normalize_food_name(q)
|
||||
primary = q.split(",")[0].strip() or q
|
||||
like_full = f"%{q}%"
|
||||
like_primary = f"%{primary}%"
|
||||
prefix = f"{primary}%"
|
||||
norm = normalize_food_name(primary)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, bls_code, name_de, name_en, catalog_kind, food_group
|
||||
@@ -178,17 +183,24 @@ def suggest_catalog_foods(cur, query: str, profile_id: str | None, limit: int =
|
||||
OR owner_profile_id = %s
|
||||
)
|
||||
AND (
|
||||
name_de ILIKE %s OR COALESCE(name_en, '') ILIKE %s
|
||||
name_de ILIKE %s OR name_de ILIKE %s
|
||||
OR COALESCE(name_en, '') ILIKE %s OR COALESCE(name_en, '') ILIKE %s
|
||||
OR COALESCE(bls_code, '') ILIKE %s
|
||||
OR lower(name_de) = %s
|
||||
)
|
||||
ORDER BY
|
||||
CASE WHEN lower(name_de) = %s THEN 0
|
||||
WHEN COALESCE(bls_code, '') ILIKE %s THEN 1
|
||||
ELSE 2 END,
|
||||
CASE
|
||||
WHEN lower(name_de) = %s THEN 0
|
||||
WHEN name_de ILIKE %s THEN 1
|
||||
WHEN COALESCE(bls_code, '') ILIKE %s THEN 2
|
||||
ELSE 3 END,
|
||||
name_de
|
||||
LIMIT %s
|
||||
""",
|
||||
(profile_id, like, like, like, norm, norm, q, limit),
|
||||
(
|
||||
profile_id,
|
||||
like_full, like_primary, like_full, like_primary, like_full, norm,
|
||||
norm, prefix, q, limit,
|
||||
),
|
||||
)
|
||||
return [dict(r) for r in cur.fetchall()]
|
||||
@@ -0,0 +1,192 @@
|
||||
"""FDDB recipe lists: upsert, link to diary items, catalog macros via ingredients."""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from data_layer.food_mapping import get_food_mapping_with_cursor, normalize_food_name
|
||||
from data_layer.nutrition_items import catalog_macros_for_item, _f
|
||||
|
||||
|
||||
def upsert_recipes(cur, profile_id: str, recipes: list[dict[str, Any]]) -> dict[str, int]:
|
||||
inserted = updated = ingredients = 0
|
||||
for rec in recipes:
|
||||
norm = rec.get("name_normalized") or normalize_food_name(rec.get("name_raw"))
|
||||
if not norm:
|
||||
continue
|
||||
cur.execute(
|
||||
"SELECT id FROM food_recipes WHERE profile_id = %s AND name_normalized = %s",
|
||||
(profile_id, norm),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
rid = row["id"]
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE food_recipes
|
||||
SET name_raw=%s, portions=%s, description=%s, updated_at=NOW()
|
||||
WHERE id=%s
|
||||
""",
|
||||
(rec["name_raw"], rec.get("portions") or 1, rec.get("description"), rid),
|
||||
)
|
||||
cur.execute("DELETE FROM food_recipe_ingredients WHERE recipe_id = %s", (rid,))
|
||||
updated += 1
|
||||
else:
|
||||
rid = str(uuid.uuid4())
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO food_recipes
|
||||
(id, profile_id, name_raw, name_normalized, portions, description, source)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,'fddb_list')
|
||||
""",
|
||||
(rid, profile_id, rec["name_raw"], norm, rec.get("portions") or 1, rec.get("description")),
|
||||
)
|
||||
inserted += 1
|
||||
for ing in rec.get("ingredients") or []:
|
||||
inorm = ing.get("source_name_normalized") or normalize_food_name(ing.get("source_name_raw"))
|
||||
if not inorm:
|
||||
continue
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO food_recipe_ingredients
|
||||
(id, recipe_id, source_name_raw, source_name_normalized,
|
||||
quantity_raw, quantity_g, sort_order)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s)
|
||||
""",
|
||||
(
|
||||
str(uuid.uuid4()), rid, ing["source_name_raw"], inorm,
|
||||
ing.get("quantity_raw"), ing.get("quantity_g"), ing.get("sort_order") or 0,
|
||||
),
|
||||
)
|
||||
ingredients += 1
|
||||
linked, dates = link_recipes_to_items(cur, profile_id)
|
||||
return {
|
||||
"inserted": inserted,
|
||||
"updated": updated,
|
||||
"ingredients": ingredients,
|
||||
"items_linked": linked,
|
||||
"dates_linked": dates,
|
||||
}
|
||||
|
||||
|
||||
def link_recipes_to_items(cur, profile_id: str) -> tuple[int, list[str]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT DISTINCT i.date::text AS date
|
||||
FROM nutrition_items i
|
||||
JOIN food_recipes r ON r.profile_id = i.profile_id
|
||||
AND i.source_name_normalized = r.name_normalized
|
||||
WHERE i.profile_id = %s AND i.food_id IS NULL
|
||||
""",
|
||||
(profile_id,),
|
||||
)
|
||||
dates = [r["date"] for r in cur.fetchall()]
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE nutrition_items i
|
||||
SET recipe_id = r.id, updated_at = NOW()
|
||||
FROM food_recipes r
|
||||
WHERE i.profile_id = %s AND r.profile_id = %s
|
||||
AND i.source_name_normalized = r.name_normalized
|
||||
AND i.food_id IS NULL
|
||||
""",
|
||||
(profile_id, profile_id),
|
||||
)
|
||||
return cur.rowcount or 0, dates
|
||||
|
||||
|
||||
def list_recipes(cur, profile_id: str) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, name_raw, name_normalized, portions, description, source
|
||||
FROM food_recipes
|
||||
WHERE profile_id = %s
|
||||
ORDER BY name_normalized
|
||||
""",
|
||||
(profile_id,),
|
||||
)
|
||||
recipes = [dict(r) for r in cur.fetchall()]
|
||||
if not recipes:
|
||||
return []
|
||||
ids = [r["id"] for r in recipes]
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT recipe_id, source_name_raw, source_name_normalized, quantity_raw, quantity_g, sort_order
|
||||
FROM food_recipe_ingredients
|
||||
WHERE recipe_id = ANY(%s)
|
||||
ORDER BY sort_order, source_name_raw
|
||||
""",
|
||||
(ids,),
|
||||
)
|
||||
by_r: dict[str, list] = {str(i): [] for i in ids}
|
||||
for row in cur.fetchall():
|
||||
by_r.setdefault(str(row["recipe_id"]), []).append(dict(row))
|
||||
for rec in recipes:
|
||||
rec["ingredients"] = by_r.get(str(rec["id"]), [])
|
||||
return recipes
|
||||
|
||||
|
||||
def apply_recipe_to_items(cur, profile_id: str, source_name_normalized: str, recipe_id: str) -> int:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE nutrition_items
|
||||
SET recipe_id = %s, food_id = NULL, mapping_id = NULL, value_origin = 'fddb', updated_at = NOW()
|
||||
WHERE profile_id = %s AND source_name_normalized = %s
|
||||
""",
|
||||
(recipe_id, profile_id, source_name_normalized),
|
||||
)
|
||||
return cur.rowcount or 0
|
||||
|
||||
|
||||
def mapped_ingredient_quantities(
|
||||
cur, profile_id: str, recipe_id: str, eaten_qty_g: float | None
|
||||
) -> list[dict[str, Any]] | None:
|
||||
cur.execute(
|
||||
"SELECT portions FROM food_recipes WHERE id = %s AND profile_id = %s",
|
||||
(recipe_id, profile_id),
|
||||
)
|
||||
rec = cur.fetchone()
|
||||
if not rec:
|
||||
return None
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT source_name_raw, quantity_g
|
||||
FROM food_recipe_ingredients
|
||||
WHERE recipe_id = %s
|
||||
ORDER BY sort_order
|
||||
""",
|
||||
(recipe_id,),
|
||||
)
|
||||
ings = cur.fetchall()
|
||||
if not ings:
|
||||
return None
|
||||
total_g = sum(_f(i.get("quantity_g")) for i in ings)
|
||||
if eaten_qty_g and eaten_qty_g > 0 and total_g > 0:
|
||||
scale = float(eaten_qty_g) / total_g
|
||||
else:
|
||||
portions = float(rec.get("portions") or 1) or 1.0
|
||||
scale = 1.0 / portions
|
||||
out = []
|
||||
for ing in ings:
|
||||
mapping = get_food_mapping_with_cursor(cur, ing["source_name_raw"], profile_id)
|
||||
if not mapping:
|
||||
return None
|
||||
out.append({
|
||||
"food_id": mapping["food_id"],
|
||||
"quantity_g": _f(ing.get("quantity_g")) * scale,
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def catalog_macros_for_recipe(cur, profile_id: str, recipe_id: str, eaten_qty_g: float | None) -> dict[str, float] | None:
|
||||
parts = mapped_ingredient_quantities(cur, profile_id, recipe_id, eaten_qty_g)
|
||||
if not parts:
|
||||
return None
|
||||
acc = {"kcal": 0.0, "protein_g": 0.0, "fat_g": 0.0, "carbs_g": 0.0}
|
||||
for part in parts:
|
||||
cat = catalog_macros_for_item(cur, part["food_id"], part["quantity_g"])
|
||||
if not cat:
|
||||
return None
|
||||
for k in acc:
|
||||
acc[k] += cat[k]
|
||||
return acc
|
||||
@@ -99,7 +99,7 @@ def compute_day_macro_sums(cur, profile_id: str, day: date | str) -> dict[str, A
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT food_id, quantity_g, fddb_kcal, fddb_protein_g, fddb_fat_g, fddb_carbs_g, value_origin
|
||||
SELECT food_id, recipe_id, quantity_g, fddb_kcal, fddb_protein_g, fddb_fat_g, fddb_carbs_g, value_origin
|
||||
FROM nutrition_items
|
||||
WHERE profile_id = %s AND date = %s
|
||||
""",
|
||||
@@ -115,7 +115,11 @@ def compute_day_macro_sums(cur, profile_id: str, day: date | str) -> dict[str, A
|
||||
fddb["protein_g"] += _f(it.get("fddb_protein_g"))
|
||||
fddb["fat_g"] += _f(it.get("fddb_fat_g"))
|
||||
fddb["carbs_g"] += _f(it.get("fddb_carbs_g"))
|
||||
cat = catalog_macros_for_item(cur, it.get("food_id"), it.get("quantity_g"))
|
||||
if it.get("recipe_id") and not it.get("food_id"):
|
||||
from data_layer.food_recipes import catalog_macros_for_recipe
|
||||
cat = catalog_macros_for_recipe(cur, profile_id, it["recipe_id"], it.get("quantity_g"))
|
||||
else:
|
||||
cat = catalog_macros_for_item(cur, it.get("food_id"), it.get("quantity_g"))
|
||||
if cat:
|
||||
mapped += 1
|
||||
used_bls = True
|
||||
@@ -200,6 +204,24 @@ def apply_nutrition_day_macros(
|
||||
return "created"
|
||||
|
||||
|
||||
def _accumulate_food_qty(cur, acc: dict[int, list[float]], food_id: str, quantity_g: float) -> None:
|
||||
if not food_id or not quantity_g or quantity_g <= 0:
|
||||
return
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT v.attribute_id, v.value_num, v.is_trace, a.data_type
|
||||
FROM food_attribute_values v
|
||||
JOIN food_attributes a ON a.id = v.attribute_id
|
||||
WHERE v.food_id = %s AND a.data_type = 'num_per_100g'
|
||||
AND v.value_num IS NOT NULL AND v.is_trace = false
|
||||
""",
|
||||
(food_id,),
|
||||
)
|
||||
factor = float(quantity_g) / 100.0
|
||||
for row in cur.fetchall():
|
||||
acc.setdefault(row["attribute_id"], []).append(float(row["value_num"]) * factor)
|
||||
|
||||
|
||||
def rebuild_daily_nutrients(cur, profile_id: str, day: date | str) -> None:
|
||||
cur.execute(
|
||||
"DELETE FROM nutrition_daily_nutrients WHERE profile_id = %s AND date = %s",
|
||||
@@ -207,28 +229,24 @@ def rebuild_daily_nutrients(cur, profile_id: str, day: date | str) -> None:
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT i.food_id, i.quantity_g
|
||||
FROM nutrition_items i
|
||||
WHERE i.profile_id = %s AND i.date = %s
|
||||
AND i.food_id IS NOT NULL AND i.quantity_g IS NOT NULL AND i.quantity_g > 0
|
||||
SELECT food_id, recipe_id, quantity_g
|
||||
FROM nutrition_items
|
||||
WHERE profile_id = %s AND date = %s
|
||||
""",
|
||||
(profile_id, day),
|
||||
)
|
||||
acc: dict[int, list[float]] = {}
|
||||
from data_layer.food_recipes import mapped_ingredient_quantities
|
||||
for it in cur.fetchall():
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT v.attribute_id, v.value_num, v.is_trace, a.data_type
|
||||
FROM food_attribute_values v
|
||||
JOIN food_attributes a ON a.id = v.attribute_id
|
||||
WHERE v.food_id = %s AND a.data_type = 'num_per_100g'
|
||||
AND v.value_num IS NOT NULL AND v.is_trace = false
|
||||
""",
|
||||
(it["food_id"],),
|
||||
)
|
||||
factor = float(it["quantity_g"]) / 100.0
|
||||
for row in cur.fetchall():
|
||||
acc.setdefault(row["attribute_id"], []).append(float(row["value_num"]) * factor)
|
||||
if it.get("food_id"):
|
||||
_accumulate_food_qty(cur, acc, it["food_id"], _f(it.get("quantity_g")))
|
||||
continue
|
||||
if it.get("recipe_id"):
|
||||
parts = mapped_ingredient_quantities(cur, profile_id, it["recipe_id"], it.get("quantity_g"))
|
||||
if not parts:
|
||||
continue
|
||||
for part in parts:
|
||||
_accumulate_food_qty(cur, acc, part["food_id"], part["quantity_g"])
|
||||
for attr_id, vals in acc.items():
|
||||
cur.execute(
|
||||
"""
|
||||
@@ -302,9 +320,9 @@ def replace_csv_items_for_dates(
|
||||
id, profile_id, date, logged_at, source_name_raw, source_name_normalized,
|
||||
source_system, quantity_raw, quantity_g,
|
||||
fddb_kcal, fddb_protein_g, fddb_fat_g, fddb_carbs_g,
|
||||
food_id, mapping_id, value_origin, source
|
||||
food_id, mapping_id, value_origin, source, recipe_id
|
||||
) VALUES (
|
||||
%s,%s,%s,%s,%s,%s,'fddb',%s,%s,%s,%s,%s,%s,%s,%s,%s,'csv'
|
||||
%s,%s,%s,%s,%s,%s,'fddb',%s,%s,%s,%s,%s,%s,%s,%s,%s,'csv',%s
|
||||
)
|
||||
""",
|
||||
(
|
||||
@@ -323,9 +341,12 @@ def replace_csv_items_for_dates(
|
||||
mapping["food_id"] if mapping else None,
|
||||
mapping["mapping_id"] if mapping else None,
|
||||
_item_value_origin(mapping),
|
||||
None,
|
||||
),
|
||||
)
|
||||
items_written += 1
|
||||
from data_layer.food_recipes import link_recipes_to_items
|
||||
link_recipes_to_items(cur, profile_id)
|
||||
days_written += 1
|
||||
sums = compute_day_macro_sums(cur, profile_id, iso)
|
||||
rebuild_daily_nutrients(cur, profile_id, iso)
|
||||
@@ -431,7 +452,12 @@ def dates_for_normalized_name(cur, profile_id: str, source_name_normalized: str)
|
||||
SELECT DISTINCT date::text AS date
|
||||
FROM nutrition_items
|
||||
WHERE profile_id = %s AND source_name_normalized = %s
|
||||
UNION
|
||||
SELECT DISTINCT i.date::text AS date
|
||||
FROM nutrition_items i
|
||||
JOIN food_recipe_ingredients ri ON ri.recipe_id = i.recipe_id
|
||||
WHERE i.profile_id = %s AND ri.source_name_normalized = %s
|
||||
""",
|
||||
(profile_id, source_name_normalized),
|
||||
(profile_id, source_name_normalized, profile_id, source_name_normalized),
|
||||
)
|
||||
return [r["date"] for r in cur.fetchall()]
|
||||
Reference in new issue
Block a user