feat: Eigene Stoffe am Lebensmittel anlegen
EPA-Chips und mg/µg vom Etikett; fehlende Parameter ohne Admin. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
a5adff6196
commit
d35087ad84
9 files changed
+246
-29
No files matched your search
@@ -1,8 +1,12 @@
|
||||
"""Catalog attribute definitions and numeric values (BLS EAV + extensions)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
_ATTR_KEY_RE = re.compile(r"[^A-Z0-9]+")
|
||||
_ALLOWED_UNITS = {"g": "g", "mg": "mg", "µg": "µg", "ug": "µg", "mcg": "µg", "kcal": "kcal", "kj": "kJ"}
|
||||
|
||||
MACRO_TO_KEY = {
|
||||
"kcal": "ENERCC",
|
||||
"protein_g": "PROT625",
|
||||
@@ -17,9 +21,24 @@ def scale_to_per_100g(value: float, serving_g: float | None) -> float:
|
||||
return float(value) * (100.0 / float(serving_g))
|
||||
|
||||
|
||||
def list_numeric_attributes(cur, query: str = "", limit: int = 40) -> list[dict[str, Any]]:
|
||||
q = (query or "").strip()
|
||||
def list_numeric_attributes(
|
||||
cur, query: str = "", limit: int = 40, keys: list[str] | None = None
|
||||
) -> list[dict[str, Any]]:
|
||||
lim = min(max(int(limit or 40), 1), 80)
|
||||
wanted = [str(k).strip() for k in (keys or []) if str(k).strip()]
|
||||
if wanted:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, attr_key, name_de, name_en, unit, category, origin
|
||||
FROM food_attributes
|
||||
WHERE is_active = true AND data_type = 'num_per_100g'
|
||||
AND attr_key = ANY(%s)
|
||||
ORDER BY sort_order, attr_key
|
||||
""",
|
||||
(wanted,),
|
||||
)
|
||||
return [dict(r) for r in cur.fetchall()]
|
||||
q = (query or "").strip()
|
||||
if q:
|
||||
like = f"%{q}%"
|
||||
cur.execute(
|
||||
@@ -126,3 +145,43 @@ def extra_attributes_for_food(cur, food_id: str) -> dict[str, float]:
|
||||
(food_id, list(MACRO_TO_KEY.values())),
|
||||
)
|
||||
return {r["attr_key"]: float(r["value_num"]) for r in cur.fetchall()}
|
||||
|
||||
|
||||
def normalize_attr_key(raw: str | None) -> str:
|
||||
key = _ATTR_KEY_RE.sub("_", (raw or "").strip().upper()).strip("_")
|
||||
return key[:64]
|
||||
|
||||
|
||||
def normalize_attr_unit(raw: str | None) -> str:
|
||||
return _ALLOWED_UNITS.get((raw or "g").strip().lower(), "g")
|
||||
|
||||
|
||||
def create_extension_attribute(cur, name_de: str, unit: str = "g", attr_key: str | None = None) -> dict[str, Any]:
|
||||
name = (name_de or "").strip()
|
||||
if not name:
|
||||
raise ValueError("Name fehlt")
|
||||
key = normalize_attr_key(attr_key or name)
|
||||
if not key:
|
||||
raise ValueError("attr_key fehlt")
|
||||
unit_n = normalize_attr_unit(unit)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, attr_key, name_de, name_en, unit, category, origin
|
||||
FROM food_attributes
|
||||
WHERE attr_key = %s AND is_active = true
|
||||
""",
|
||||
(key,),
|
||||
)
|
||||
existing = cur.fetchone()
|
||||
if existing:
|
||||
return dict(existing)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO food_attributes
|
||||
(attr_key, name_de, name_en, unit, category, data_type, origin, sort_order)
|
||||
VALUES (%s, %s, %s, %s, 'extension', 'num_per_100g', 'extension', 9100)
|
||||
RETURNING id, attr_key, name_de, name_en, unit, category, origin
|
||||
""",
|
||||
(key, name, None, unit_n),
|
||||
)
|
||||
return dict(cur.fetchone())
|
||||
+21
-1
@@ -52,6 +52,12 @@ class SuggestBatchBody(BaseModel):
|
||||
limit: int = 3
|
||||
|
||||
|
||||
class UserAttributeCreate(BaseModel):
|
||||
name_de: str
|
||||
unit: str = "g"
|
||||
attr_key: Optional[str] = None
|
||||
|
||||
|
||||
def _pid(session: dict, x_profile_id: Optional[str] = None) -> str:
|
||||
return x_profile_id or session["profile_id"]
|
||||
|
||||
@@ -100,12 +106,26 @@ def search_foods(
|
||||
@router.get("/attributes")
|
||||
def list_food_attributes(
|
||||
q: str = "",
|
||||
keys: str = "",
|
||||
limit: int = 40,
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
from data_layer.food_attributes import list_numeric_attributes
|
||||
key_list = [p.strip() for p in (keys or "").split(",") if p.strip()]
|
||||
with get_db() as conn:
|
||||
return list_numeric_attributes(get_cursor(conn), q, limit=limit)
|
||||
return list_numeric_attributes(get_cursor(conn), q, limit=limit, keys=key_list or None)
|
||||
|
||||
|
||||
@router.post("/attributes")
|
||||
def create_food_attribute(body: UserAttributeCreate, session: dict = Depends(require_auth)):
|
||||
from data_layer.food_attributes import create_extension_attribute
|
||||
try:
|
||||
with get_db() as conn:
|
||||
return create_extension_attribute(
|
||||
get_cursor(conn), body.name_de, body.unit, body.attr_key
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
|
||||
|
||||
@router.post("/foods/suggest-batch")
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
from data_layer.food_attributes import macros_and_attributes_to_values, scale_to_per_100g
|
||||
from data_layer.food_attributes import (
|
||||
create_extension_attribute,
|
||||
macros_and_attributes_to_values,
|
||||
normalize_attr_key,
|
||||
normalize_attr_unit,
|
||||
scale_to_per_100g,
|
||||
)
|
||||
|
||||
|
||||
def test_scale_serving_to_per_100g():
|
||||
@@ -7,6 +13,28 @@ def test_scale_serving_to_per_100g():
|
||||
assert scale_to_per_100g(10, None) == 10
|
||||
|
||||
|
||||
def test_attr_key_and_unit_normalize():
|
||||
assert normalize_attr_key("Vitamin D3") == "VITAMIN_D3"
|
||||
assert normalize_attr_unit("ug") == "µg"
|
||||
assert normalize_attr_unit("mcg") == "µg"
|
||||
|
||||
|
||||
def test_create_extension_returns_existing():
|
||||
class _Cur:
|
||||
def __init__(self):
|
||||
self.calls = 0
|
||||
|
||||
def execute(self, sql, params=None):
|
||||
self.calls += 1
|
||||
self._row = {"id": 1, "attr_key": "VITAMIN_D3", "name_de": "Vitamin D3", "name_en": None, "unit": "µg", "category": "extension", "origin": "extension"} if self.calls == 1 else None
|
||||
|
||||
def fetchone(self):
|
||||
return self._row
|
||||
|
||||
row = create_extension_attribute(_Cur(), "Vitamin D3", "µg")
|
||||
assert row["attr_key"] == "VITAMIN_D3"
|
||||
|
||||
|
||||
def test_norsan_label_epa_converts():
|
||||
"""Etikett: 1100 mg EPA = 1.1 g in 8 g Portion → g/100 g."""
|
||||
vals = macros_and_attributes_to_values(
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ MODULE_VERSIONS = {
|
||||
"activity": "1.2.1", # Legacy CSV import: activity_entries feature enforcement
|
||||
"nutrition": "1.3.5", # Listen-Dialog: Mapping an der Zutat; Suche Listen/eigene vor BLS
|
||||
"tandoor": "1.0.1", # Router-Import ohne future-annotations (Backend startet)
|
||||
"bls": "1.0.5", # GET /bls/units
|
||||
"bls": "1.0.6", # Nutzer darf Extension-Stoffe anlegen; EPA-Chips; mg/µg am Etikett
|
||||
"photos": "1.0.0",
|
||||
"insights": "1.3.0",
|
||||
"prompts": "1.1.0",
|
||||
|
||||
Reference in new issue
Block a user