feat: Eigene und zentrale Lebensmittel bearbeiten, mit Sichtbarkeit im Mapping
Nutzer können persönliche Foods anlegen und ändern; der Admin legt zentrale Einträge für alle an. Suche und Namens-Mapping berücksichtigen persönlich, zentral und BLS. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
d35087ad84
commit
8b1e1da5d8
30 files changed
+1195
-120
No files matched your search
@@ -108,6 +108,57 @@ def write_numeric_attributes(cur, food_id: str, values: dict[str, Any] | None) -
|
||||
return written
|
||||
|
||||
|
||||
def replace_numeric_attributes(cur, food_id: str, values: dict[str, Any] | None) -> int:
|
||||
cur.execute("DELETE FROM food_attribute_values WHERE food_id = %s", (food_id,))
|
||||
return write_numeric_attributes(cur, food_id, values)
|
||||
|
||||
|
||||
KEY_TO_MACRO = {v: k for k, v in MACRO_TO_KEY.items()}
|
||||
|
||||
|
||||
def editor_payload_for_food(cur, food: dict[str, Any], *, editable: bool) -> dict[str, Any]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT a.attr_key, a.name_de, a.name_en, a.unit, a.category, a.origin, v.value_num
|
||||
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
|
||||
ORDER BY a.sort_order, a.attr_key
|
||||
""",
|
||||
(food["id"],),
|
||||
)
|
||||
macros = {"kcal": 0, "protein_g": 0, "fat_g": 0, "carbs_g": 0}
|
||||
extras = []
|
||||
for row in cur.fetchall():
|
||||
rec = dict(row)
|
||||
field = KEY_TO_MACRO.get(rec["attr_key"])
|
||||
if field:
|
||||
macros[field] = float(rec["value_num"])
|
||||
else:
|
||||
extras.append({
|
||||
"attr": {
|
||||
"attr_key": rec["attr_key"],
|
||||
"name_de": rec["name_de"],
|
||||
"name_en": rec["name_en"],
|
||||
"unit": rec["unit"],
|
||||
"category": rec["category"],
|
||||
"origin": rec["origin"],
|
||||
},
|
||||
"value": float(rec["value_num"]),
|
||||
})
|
||||
return {
|
||||
"id": str(food["id"]),
|
||||
"name_de": food.get("name_de") or "",
|
||||
"name_en": food.get("name_en"),
|
||||
"catalog_kind": food.get("catalog_kind"),
|
||||
"editable": editable,
|
||||
"macros_per_100g": macros,
|
||||
"attributes": extras,
|
||||
"serving_g": 100,
|
||||
}
|
||||
|
||||
|
||||
def macros_and_attributes_to_values(
|
||||
macros: dict[str, Any] | None,
|
||||
attributes: dict[str, Any] | None,
|
||||
|
||||
@@ -408,14 +408,16 @@ def get_food_mapping_with_cursor(
|
||||
"""
|
||||
SELECT m.id AS mapping_id, m.food_id, m.profile_id, m.source,
|
||||
m.grams_per_unit, m.source_unit,
|
||||
f.bls_code, f.name_de, f.catalog_kind
|
||||
f.bls_code, f.name_de, f.catalog_kind, f.owner_profile_id
|
||||
FROM food_name_mappings m
|
||||
JOIN food_catalog f ON f.id = m.food_id
|
||||
WHERE m.source_system = %s AND m.source_name_normalized = %s
|
||||
AND m.profile_id = %s
|
||||
AND f.is_active = true
|
||||
AND (f.owner_profile_id IS NULL OR f.owner_profile_id = %s)
|
||||
LIMIT 1
|
||||
""",
|
||||
(source_system, norm, profile_id),
|
||||
(source_system, norm, profile_id, profile_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
@@ -424,11 +426,13 @@ def get_food_mapping_with_cursor(
|
||||
"""
|
||||
SELECT m.id AS mapping_id, m.food_id, m.profile_id, m.source,
|
||||
m.grams_per_unit, m.source_unit,
|
||||
f.bls_code, f.name_de, f.catalog_kind
|
||||
f.bls_code, f.name_de, f.catalog_kind, f.owner_profile_id
|
||||
FROM food_name_mappings m
|
||||
JOIN food_catalog f ON f.id = m.food_id
|
||||
WHERE m.source_system = %s AND m.source_name_normalized = %s
|
||||
AND m.profile_id IS NULL
|
||||
AND f.is_active = true
|
||||
AND f.owner_profile_id IS NULL
|
||||
LIMIT 1
|
||||
""",
|
||||
(source_system, norm),
|
||||
@@ -448,6 +452,9 @@ def upsert_food_mapping(
|
||||
grams_per_unit: float | None = None,
|
||||
source_unit: str | None = None,
|
||||
) -> int:
|
||||
from data_layer.food_visibility import require_mapping_target
|
||||
|
||||
require_mapping_target(cur, food_id, profile_id)
|
||||
norm = normalize_food_name(source_name_raw)
|
||||
if not norm:
|
||||
raise ValueError("Leerer Lebensmittelname")
|
||||
@@ -622,7 +629,7 @@ def suggest_catalog_foods(cur, query: str, profile_id: str | None, limit: int =
|
||||
extra_sql = " OR (" + " AND ".join(parts) + ")"
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT id, bls_code, name_de, name_en, catalog_kind, food_group
|
||||
SELECT id, bls_code, name_de, name_en, catalog_kind, food_group, owner_profile_id
|
||||
FROM food_catalog
|
||||
WHERE is_active = true
|
||||
AND (
|
||||
@@ -642,6 +649,10 @@ def suggest_catalog_foods(cur, query: str, profile_id: str | None, limit: int =
|
||||
WHEN name_de ILIKE %s THEN 1
|
||||
WHEN COALESCE(bls_code, '') ILIKE %s THEN 2
|
||||
ELSE 3 END,
|
||||
CASE catalog_kind
|
||||
WHEN 'manual_user' THEN 0
|
||||
WHEN 'manual_admin' THEN 1
|
||||
ELSE 2 END,
|
||||
name_de
|
||||
LIMIT %s
|
||||
""",
|
||||
|
||||
@@ -131,6 +131,8 @@ def score_name_match(query: str, name_de: str, name_en: str | None = None) -> in
|
||||
|
||||
|
||||
def _public(food: dict[str, Any], score: int) -> dict[str, Any]:
|
||||
from data_layer.food_visibility import visibility_of
|
||||
|
||||
return {
|
||||
"id": str(food["id"]),
|
||||
"bls_code": food.get("bls_code"),
|
||||
@@ -138,6 +140,7 @@ def _public(food: dict[str, Any], score: int) -> dict[str, Any]:
|
||||
"name_en": food.get("name_en"),
|
||||
"catalog_kind": food.get("catalog_kind"),
|
||||
"food_group": food.get("food_group"),
|
||||
"visibility": visibility_of(food),
|
||||
"score": score,
|
||||
}
|
||||
|
||||
@@ -163,7 +166,7 @@ def get_suggest_index(cur, profile_id: str | None) -> dict[str, Any]:
|
||||
def load_suggest_index(cur, profile_id: str | None) -> dict[str, Any]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, bls_code, name_de, name_en, catalog_kind, food_group
|
||||
SELECT id, bls_code, name_de, name_en, catalog_kind, food_group, owner_profile_id
|
||||
FROM food_catalog
|
||||
WHERE is_active = true
|
||||
AND (owner_profile_id IS NULL OR owner_profile_id = %s)
|
||||
@@ -245,6 +248,11 @@ def _candidate_foods(index: dict[str, Any], query: str) -> list[dict[str, Any]]:
|
||||
return out[:MAX_CANDIDATES] if not number_tokens(query) else out
|
||||
|
||||
|
||||
def _vis_rank(food: dict[str, Any]) -> int:
|
||||
from data_layer.food_visibility import visibility_rank
|
||||
return visibility_rank(food)
|
||||
|
||||
|
||||
def suggest_for_name(index: dict[str, Any], query: str, limit: int = 3) -> dict[str, Any]:
|
||||
q = (query or "").strip()
|
||||
scored: list[tuple[int, int, dict]] = []
|
||||
@@ -253,7 +261,7 @@ def suggest_for_name(index: dict[str, Any], query: str, limit: int = 3) -> dict[
|
||||
if score < MIN_SCORE:
|
||||
continue
|
||||
scored.append((score, len(food.get("name_de") or ""), food))
|
||||
scored.sort(key=lambda x: (-x[0], x[1], x[2].get("name_de") or ""))
|
||||
scored.sort(key=lambda x: (-x[0], _vis_rank(x[2]), x[1], x[2].get("name_de") or ""))
|
||||
top = [_public(food, score) for score, _nlen, food in scored[: max(limit, 3)]]
|
||||
ambiguous = False
|
||||
if len(top) >= 2 and top[0]["score"] - top[1]["score"] <= 8 and top[1]["score"] >= 60:
|
||||
@@ -296,7 +304,7 @@ def suggest_catalog_foods_ranked(cur, query: str, profile_id: str | None, limit:
|
||||
if score < MIN_SCORE and not number_tokens(q):
|
||||
continue
|
||||
hits.append(_public(row, score or 40))
|
||||
hits.sort(key=lambda h: (-int(h.get("score") or 0), h.get("name_de") or ""))
|
||||
hits.sort(key=lambda h: (-int(h.get("score") or 0), _vis_rank(h), h.get("name_de") or ""))
|
||||
return hits[:limit]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Who may see and map a catalog food.
|
||||
|
||||
Scopes:
|
||||
- personal — ``manual_user`` with ``owner_profile_id`` (only that profile)
|
||||
- global — ``manual_admin`` (all users; no owner)
|
||||
- bls — official BLS (all users; no owner)
|
||||
|
||||
Name-mappings: a *user* mapping may target any food visible to that user.
|
||||
A *global* mapping (``profile_id IS NULL``) may only target global/BLS foods,
|
||||
never another user's private entry.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
VIS_PERSONAL = "personal"
|
||||
VIS_GLOBAL = "global"
|
||||
VIS_BLS = "bls"
|
||||
|
||||
SQL_VISIBLE_TO_PROFILE = "(owner_profile_id IS NULL OR owner_profile_id = %s)"
|
||||
SQL_GLOBAL_ONLY = "owner_profile_id IS NULL"
|
||||
|
||||
_KIND_VIS = {
|
||||
"official_bls": VIS_BLS,
|
||||
"manual_admin": VIS_GLOBAL,
|
||||
"manual_user": VIS_PERSONAL,
|
||||
}
|
||||
|
||||
_VIS_RANK = {VIS_PERSONAL: 0, VIS_GLOBAL: 1, VIS_BLS: 2}
|
||||
|
||||
|
||||
def visibility_of(food: dict[str, Any] | None) -> str:
|
||||
if not food:
|
||||
return VIS_BLS
|
||||
kind = food.get("catalog_kind")
|
||||
if kind in _KIND_VIS:
|
||||
return _KIND_VIS[kind]
|
||||
if food.get("owner_profile_id"):
|
||||
return VIS_PERSONAL
|
||||
return VIS_GLOBAL
|
||||
|
||||
|
||||
def visibility_rank(food: dict[str, Any] | None) -> int:
|
||||
return _VIS_RANK.get(visibility_of(food), 3)
|
||||
|
||||
|
||||
def is_active(food: dict[str, Any] | None) -> bool:
|
||||
if not food:
|
||||
return False
|
||||
if "is_active" not in food:
|
||||
return True
|
||||
return bool(food.get("is_active"))
|
||||
|
||||
|
||||
def is_visible_to(food: dict[str, Any] | None, profile_id: str | None) -> bool:
|
||||
if not is_active(food):
|
||||
return False
|
||||
owner = food.get("owner_profile_id")
|
||||
if owner is None:
|
||||
return True
|
||||
return profile_id is not None and str(owner) == str(profile_id)
|
||||
|
||||
|
||||
def is_global_mapping_target(food: dict[str, Any] | None) -> bool:
|
||||
return is_active(food) and food.get("owner_profile_id") is None
|
||||
|
||||
|
||||
def load_catalog_food(cur, food_id: str) -> dict[str, Any] | None:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, name_de, catalog_kind, owner_profile_id, is_active, bls_code
|
||||
FROM food_catalog
|
||||
WHERE id = %s
|
||||
""",
|
||||
(food_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def require_visible_food(cur, food_id: str, profile_id: str) -> dict[str, Any]:
|
||||
food = load_catalog_food(cur, food_id)
|
||||
if not is_visible_to(food, profile_id):
|
||||
raise LookupError("Lebensmittel nicht gefunden")
|
||||
return food
|
||||
|
||||
|
||||
def require_global_mapping_target(cur, food_id: str) -> dict[str, Any]:
|
||||
food = load_catalog_food(cur, food_id)
|
||||
if not food or not is_active(food):
|
||||
raise LookupError("Lebensmittel nicht gefunden")
|
||||
if not is_global_mapping_target(food):
|
||||
raise PermissionError("Globales Mapping darf nur auf zentrale oder BLS-Lebensmittel zeigen")
|
||||
return food
|
||||
|
||||
|
||||
def require_mapping_target(cur, food_id: str, mapping_profile_id: str | None) -> dict[str, Any]:
|
||||
if mapping_profile_id:
|
||||
return require_visible_food(cur, food_id, mapping_profile_id)
|
||||
return require_global_mapping_target(cur, food_id)
|
||||
|
||||
|
||||
def attach_visibility(row: dict[str, Any]) -> dict[str, Any]:
|
||||
row["visibility"] = visibility_of(row)
|
||||
return row
|
||||
@@ -487,3 +487,45 @@ def dates_for_normalized_name(cur, profile_id: str, source_name_normalized: str)
|
||||
(profile_id, source_name_normalized, profile_id, source_name_normalized),
|
||||
)
|
||||
return [r["date"] for r in cur.fetchall()]
|
||||
|
||||
|
||||
def dates_using_food(cur, profile_id: str, food_id: str) -> list[str]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT DISTINCT date::text AS date
|
||||
FROM nutrition_items
|
||||
WHERE profile_id = %s AND food_id = %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
|
||||
JOIN food_name_mappings m
|
||||
ON m.profile_id = i.profile_id
|
||||
AND m.source_name_normalized = ri.source_name_normalized
|
||||
AND m.food_id = %s
|
||||
WHERE i.profile_id = %s AND i.recipe_id IS NOT NULL
|
||||
""",
|
||||
(profile_id, food_id, food_id, profile_id),
|
||||
)
|
||||
return [r["date"] for r in cur.fetchall() if r.get("date")]
|
||||
|
||||
|
||||
def profiles_dates_using_food(cur, food_id: str) -> list[tuple[str, str]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT DISTINCT profile_id::text AS profile_id, date::text AS date
|
||||
FROM nutrition_items
|
||||
WHERE food_id = %s
|
||||
UNION
|
||||
SELECT DISTINCT i.profile_id::text AS profile_id, i.date::text AS date
|
||||
FROM nutrition_items i
|
||||
JOIN food_recipe_ingredients ri ON ri.recipe_id = i.recipe_id
|
||||
JOIN food_name_mappings m
|
||||
ON m.profile_id = i.profile_id
|
||||
AND m.source_name_normalized = ri.source_name_normalized
|
||||
AND m.food_id = %s
|
||||
WHERE i.recipe_id IS NOT NULL
|
||||
""",
|
||||
(food_id, food_id),
|
||||
)
|
||||
return [(r["profile_id"], r["date"]) for r in cur.fetchall() if r.get("profile_id") and r.get("date")]
|
||||
@@ -0,0 +1,18 @@
|
||||
-- Visibility invariant: personal foods have an owner; BLS and central admin foods do not.
|
||||
|
||||
UPDATE food_catalog
|
||||
SET owner_profile_id = NULL
|
||||
WHERE catalog_kind IN ('official_bls', 'manual_admin')
|
||||
AND owner_profile_id IS NOT NULL;
|
||||
|
||||
UPDATE food_catalog
|
||||
SET is_active = false
|
||||
WHERE catalog_kind = 'manual_user'
|
||||
AND owner_profile_id IS NULL;
|
||||
|
||||
ALTER TABLE food_catalog DROP CONSTRAINT IF EXISTS chk_food_catalog_owner;
|
||||
|
||||
ALTER TABLE food_catalog ADD CONSTRAINT chk_food_catalog_owner CHECK (
|
||||
(catalog_kind = 'manual_user' AND owner_profile_id IS NOT NULL)
|
||||
OR (catalog_kind IN ('official_bls', 'manual_admin') AND owner_profile_id IS NULL)
|
||||
);
|
||||
@@ -32,6 +32,8 @@ class ManualFoodCreate(BaseModel):
|
||||
name_de: str
|
||||
name_en: Optional[str] = None
|
||||
macros_per_100g: Optional[dict] = None
|
||||
attributes: Optional[dict] = None
|
||||
serving_g: Optional[float] = None
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
@@ -162,7 +164,9 @@ def admin_list_foods(
|
||||
cur = get_cursor(conn)
|
||||
conds = ["is_active = true"]
|
||||
params: list = []
|
||||
if kind:
|
||||
if kind == "manual":
|
||||
conds.append("catalog_kind IN ('manual_user', 'manual_admin')")
|
||||
elif kind:
|
||||
conds.append("catalog_kind = %s")
|
||||
params.append(kind)
|
||||
if q:
|
||||
@@ -172,7 +176,7 @@ def admin_list_foods(
|
||||
params.append(limit)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT id, bls_code, name_de, name_en, catalog_kind, food_group, bls_version
|
||||
SELECT id, bls_code, name_de, name_en, catalog_kind, food_group, bls_version, owner_profile_id
|
||||
FROM food_catalog
|
||||
WHERE {' AND '.join(conds)}
|
||||
ORDER BY name_de
|
||||
@@ -199,11 +203,15 @@ def admin_food_detail(food_id: str, session: dict = Depends(require_admin)):
|
||||
|
||||
@router.post("/foods/manual")
|
||||
def admin_create_manual_food(body: ManualFoodCreate, session: dict = Depends(require_admin)):
|
||||
from data_layer.food_attributes import macros_and_attributes_to_values, write_numeric_attributes
|
||||
from data_layer.food_mapping import normalize_food_name
|
||||
from data_layer.food_visibility import attach_visibility
|
||||
|
||||
name = (body.name_de or "").strip()
|
||||
if not name:
|
||||
raise HTTPException(400, "Name fehlt")
|
||||
serving = body.serving_g if body.serving_g and body.serving_g > 0 else None
|
||||
values = macros_and_attributes_to_values(body.macros_per_100g, body.attributes, serving)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
@@ -215,10 +223,64 @@ def admin_create_manual_food(body: ManualFoodCreate, session: dict = Depends(req
|
||||
(name, body.name_en, f"man-admin-{normalize_food_name(name)[:40]}"),
|
||||
)
|
||||
food = r2d(cur.fetchone())
|
||||
_write_manual_macros(cur, food["id"], body.macros_per_100g)
|
||||
write_numeric_attributes(cur, food["id"], values)
|
||||
from data_layer.food_suggest import invalidate_suggest_index
|
||||
invalidate_suggest_index()
|
||||
return food
|
||||
return attach_visibility(food)
|
||||
|
||||
|
||||
@router.put("/foods/manual/{food_id}")
|
||||
def admin_update_manual_food(food_id: str, body: ManualFoodCreate, session: dict = Depends(require_admin)):
|
||||
from collections import defaultdict
|
||||
|
||||
from data_layer.food_attributes import (
|
||||
editor_payload_for_food,
|
||||
macros_and_attributes_to_values,
|
||||
replace_numeric_attributes,
|
||||
)
|
||||
from data_layer.food_visibility import attach_visibility
|
||||
from data_layer.nutrition_items import profiles_dates_using_food, schedule_daily_nutrient_rebuild
|
||||
|
||||
name = (body.name_de or "").strip()
|
||||
if not name:
|
||||
raise HTTPException(400, "Name fehlt")
|
||||
serving = body.serving_g if body.serving_g and body.serving_g > 0 else None
|
||||
values = macros_and_attributes_to_values(body.macros_per_100g, body.attributes, serving)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, name_de, name_en, catalog_kind, owner_profile_id
|
||||
FROM food_catalog
|
||||
WHERE id = %s AND catalog_kind = 'manual_admin' AND is_active = true
|
||||
""",
|
||||
(food_id,),
|
||||
)
|
||||
food = cur.fetchone()
|
||||
if not food:
|
||||
raise HTTPException(404, "Zentrales Lebensmittel nicht gefunden")
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE food_catalog
|
||||
SET name_de = %s, name_en = %s, updated_at = NOW()
|
||||
WHERE id = %s
|
||||
RETURNING id, name_de, name_en, catalog_kind, owner_profile_id
|
||||
""",
|
||||
(name, body.name_en, food_id),
|
||||
)
|
||||
updated = dict(cur.fetchone())
|
||||
replace_numeric_attributes(cur, food_id, values)
|
||||
pairs = profiles_dates_using_food(cur, food_id)
|
||||
payload = attach_visibility(editor_payload_for_food(cur, updated, editable=True))
|
||||
from data_layer.food_suggest import invalidate_suggest_index
|
||||
invalidate_suggest_index()
|
||||
by_profile = defaultdict(list)
|
||||
for pid, day in pairs:
|
||||
by_profile[pid].append(day)
|
||||
for pid, dates in by_profile.items():
|
||||
schedule_daily_nutrient_rebuild(pid, dates, f"Zentrales Lebensmittel {name}")
|
||||
payload["rebuild_pending"] = len(pairs)
|
||||
return payload
|
||||
|
||||
|
||||
@router.get("/attributes")
|
||||
|
||||
@@ -52,7 +52,8 @@ def list_food_mappings(
|
||||
q += " WHERE " + " AND ".join(conds)
|
||||
q += " ORDER BY m.source_name_normalized"
|
||||
cur.execute(q, params)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
from data_layer.food_visibility import attach_visibility
|
||||
return [attach_visibility(r2d(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.get("/stats/coverage")
|
||||
@@ -77,9 +78,13 @@ def mapping_coverage(session: dict = Depends(require_admin)):
|
||||
def create_food_mapping(body: FoodMappingCreate, session: dict = Depends(require_admin)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT id FROM food_catalog WHERE id = %s", (body.food_id,))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Lebensmittel nicht gefunden")
|
||||
from data_layer.food_visibility import require_mapping_target
|
||||
try:
|
||||
require_mapping_target(cur, body.food_id, body.profile_id or None)
|
||||
except LookupError as e:
|
||||
raise HTTPException(404, str(e)) from e
|
||||
except PermissionError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
mid = upsert_food_mapping(
|
||||
cur,
|
||||
source_name_raw=body.source_name,
|
||||
@@ -114,9 +119,17 @@ def update_food_mapping(mapping_id: int, body: FoodMappingUpdate, session: dict
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Mapping nicht gefunden")
|
||||
cur.execute("SELECT id FROM food_catalog WHERE id = %s AND is_active = true", (body.food_id,))
|
||||
if not cur.fetchone():
|
||||
cur.execute("SELECT id, catalog_kind, owner_profile_id, is_active FROM food_catalog WHERE id = %s AND is_active = true", (body.food_id,))
|
||||
food = cur.fetchone()
|
||||
if not food:
|
||||
raise HTTPException(404, "Lebensmittel nicht gefunden")
|
||||
from data_layer.food_visibility import require_mapping_target
|
||||
try:
|
||||
require_mapping_target(cur, body.food_id, row.get("profile_id"))
|
||||
except LookupError as e:
|
||||
raise HTTPException(404, str(e)) from e
|
||||
except PermissionError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE food_name_mappings
|
||||
|
||||
+144
-23
@@ -95,12 +95,16 @@ def list_food_units(session: dict = Depends(require_auth)):
|
||||
def search_foods(
|
||||
q: str = "",
|
||||
limit: int = 20,
|
||||
scope: str = "visible",
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
pid = session["profile_id"]
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
return suggest_catalog_foods_ranked(cur, q, pid, limit=min(max(limit, 1), 50))
|
||||
hits = suggest_catalog_foods_ranked(cur, q, pid, limit=min(max(limit, 1), 50))
|
||||
if scope == "global":
|
||||
hits = [h for h in hits if h.get("visibility") != "personal"]
|
||||
return hits
|
||||
|
||||
|
||||
@router.get("/attributes")
|
||||
@@ -172,6 +176,122 @@ def create_user_food(
|
||||
return food
|
||||
|
||||
|
||||
@router.get("/foods/mine")
|
||||
def list_my_manual_foods(session: dict = Depends(require_auth)):
|
||||
pid = session["profile_id"]
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, name_de, catalog_kind, updated_at
|
||||
FROM food_catalog
|
||||
WHERE owner_profile_id = %s AND catalog_kind = 'manual_user' AND is_active = true
|
||||
ORDER BY name_de
|
||||
""",
|
||||
(pid,),
|
||||
)
|
||||
rows = [r2d(r) for r in cur.fetchall()]
|
||||
from data_layer.food_visibility import attach_visibility
|
||||
for row in rows:
|
||||
row["id"] = str(row["id"])
|
||||
attach_visibility(row)
|
||||
return rows
|
||||
|
||||
|
||||
@router.get("/foods/shared")
|
||||
def list_shared_manual_foods(session: dict = Depends(require_auth)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, name_de, catalog_kind, updated_at
|
||||
FROM food_catalog
|
||||
WHERE catalog_kind = 'manual_admin' AND owner_profile_id IS NULL AND is_active = true
|
||||
ORDER BY name_de
|
||||
"""
|
||||
)
|
||||
from data_layer.food_visibility import attach_visibility
|
||||
rows = [r2d(r) for r in cur.fetchall()]
|
||||
for row in rows:
|
||||
row["id"] = str(row["id"])
|
||||
attach_visibility(row)
|
||||
return rows
|
||||
|
||||
|
||||
@router.get("/foods/{food_id}")
|
||||
def get_food_detail(food_id: str, session: dict = Depends(require_auth)):
|
||||
from data_layer.food_attributes import editor_payload_for_food
|
||||
|
||||
pid = session["profile_id"]
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, name_de, name_en, catalog_kind, owner_profile_id
|
||||
FROM food_catalog
|
||||
WHERE id = %s AND is_active = true
|
||||
AND (owner_profile_id IS NULL OR owner_profile_id = %s)
|
||||
""",
|
||||
(food_id, pid),
|
||||
)
|
||||
food = cur.fetchone()
|
||||
if not food:
|
||||
raise HTTPException(404, "Lebensmittel nicht gefunden")
|
||||
food = dict(food)
|
||||
editable = food.get("catalog_kind") == "manual_user" and str(food.get("owner_profile_id") or "") == str(pid)
|
||||
from data_layer.food_visibility import attach_visibility
|
||||
return attach_visibility(editor_payload_for_food(cur, food, editable=editable))
|
||||
|
||||
|
||||
@router.put("/foods/manual/{food_id}")
|
||||
def update_user_food(food_id: str, body: UserFoodCreate, session: dict = Depends(require_auth)):
|
||||
from data_layer.food_attributes import (
|
||||
editor_payload_for_food,
|
||||
macros_and_attributes_to_values,
|
||||
replace_numeric_attributes,
|
||||
)
|
||||
from data_layer.nutrition_items import dates_using_food
|
||||
|
||||
pid = session["profile_id"]
|
||||
name = (body.name_de or "").strip()
|
||||
if not name:
|
||||
raise HTTPException(400, "Name fehlt")
|
||||
serving = body.serving_g if body.serving_g and body.serving_g > 0 else None
|
||||
values = macros_and_attributes_to_values(body.macros_per_100g, body.attributes, serving)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, name_de, name_en, catalog_kind, owner_profile_id
|
||||
FROM food_catalog
|
||||
WHERE id = %s AND catalog_kind = 'manual_user' AND owner_profile_id = %s AND is_active = true
|
||||
""",
|
||||
(food_id, pid),
|
||||
)
|
||||
food = cur.fetchone()
|
||||
if not food:
|
||||
raise HTTPException(404, "Eigenes Lebensmittel nicht gefunden")
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE food_catalog
|
||||
SET name_de = %s, name_en = %s, updated_at = NOW()
|
||||
WHERE id = %s
|
||||
RETURNING id, name_de, name_en, catalog_kind, owner_profile_id
|
||||
""",
|
||||
(name, body.name_en, food_id),
|
||||
)
|
||||
updated = dict(cur.fetchone())
|
||||
replace_numeric_attributes(cur, food_id, values)
|
||||
dates = dates_using_food(cur, pid, food_id)
|
||||
payload = editor_payload_for_food(cur, updated, editable=True)
|
||||
from data_layer.food_visibility import attach_visibility
|
||||
payload = attach_visibility(payload)
|
||||
invalidate_suggest_index(pid)
|
||||
_schedule_rebuild(pid, dates, f"Lebensmittel {name}")
|
||||
payload["rebuild_pending"] = len(dates)
|
||||
return payload
|
||||
|
||||
|
||||
@router.get("/mappings")
|
||||
def list_my_mappings(
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
@@ -192,7 +312,8 @@ def list_my_mappings(
|
||||
""",
|
||||
(pid,),
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
from data_layer.food_visibility import attach_visibility
|
||||
return [attach_visibility(r2d(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.post("/mappings")
|
||||
@@ -204,27 +325,26 @@ def upsert_my_mapping(
|
||||
pid = _pid(session, x_profile_id)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, name_de, bls_code, catalog_kind FROM food_catalog
|
||||
WHERE id = %s AND is_active = true
|
||||
AND (owner_profile_id IS NULL OR owner_profile_id = %s)
|
||||
""",
|
||||
(body.food_id, pid),
|
||||
)
|
||||
food = cur.fetchone()
|
||||
if not food:
|
||||
raise HTTPException(404, "Lebensmittel nicht gefunden")
|
||||
mid = upsert_food_mapping(
|
||||
cur,
|
||||
source_name_raw=body.source_name,
|
||||
food_id=body.food_id,
|
||||
profile_id=pid,
|
||||
source="bulk",
|
||||
source_system=body.source_system,
|
||||
grams_per_unit=body.grams_per_unit,
|
||||
source_unit=body.source_unit,
|
||||
)
|
||||
from data_layer.food_visibility import require_visible_food, visibility_of
|
||||
try:
|
||||
food = require_visible_food(cur, body.food_id, pid)
|
||||
except LookupError as e:
|
||||
raise HTTPException(404, str(e)) from e
|
||||
try:
|
||||
mid = upsert_food_mapping(
|
||||
cur,
|
||||
source_name_raw=body.source_name,
|
||||
food_id=body.food_id,
|
||||
profile_id=pid,
|
||||
source="bulk",
|
||||
source_system=body.source_system,
|
||||
grams_per_unit=body.grams_per_unit,
|
||||
source_unit=body.source_unit,
|
||||
)
|
||||
except PermissionError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
except LookupError as e:
|
||||
raise HTTPException(404, str(e)) from e
|
||||
norm = normalize_food_name(body.source_name)
|
||||
n = apply_mapping_to_items(cur, pid, norm, body.food_id, mid)
|
||||
apply_quantities_to_items(cur, pid, norm, body.grams_per_unit)
|
||||
@@ -238,6 +358,7 @@ def upsert_my_mapping(
|
||||
"food_name_de": food["name_de"],
|
||||
"bls_code": food.get("bls_code"),
|
||||
"catalog_kind": food.get("catalog_kind"),
|
||||
"visibility": visibility_of(food),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from data_layer.food_attributes import (
|
||||
create_extension_attribute,
|
||||
editor_payload_for_food,
|
||||
macros_and_attributes_to_values,
|
||||
normalize_attr_key,
|
||||
normalize_attr_unit,
|
||||
@@ -45,3 +46,41 @@ def test_norsan_label_epa_converts():
|
||||
assert abs(vals["FAT"] - 100) < 0.01
|
||||
assert abs(vals["EPA"] - 13.75) < 0.01
|
||||
assert abs(vals["ENERCC"] - 900) < 0.01
|
||||
|
||||
|
||||
def test_edit_payload_does_not_rescale_at_100g():
|
||||
vals = macros_and_attributes_to_values(
|
||||
{"kcal": 900, "protein_g": 0, "fat_g": 100, "carbs_g": 0},
|
||||
{"EPA": 13.75},
|
||||
serving_g=100,
|
||||
)
|
||||
assert vals["FAT"] == 100
|
||||
assert vals["EPA"] == 13.75
|
||||
assert vals["ENERCC"] == 900
|
||||
|
||||
|
||||
def test_editor_payload_splits_macros_and_extras():
|
||||
class _Cur:
|
||||
def execute(self, sql, params=None):
|
||||
pass
|
||||
|
||||
def fetchall(self):
|
||||
return [
|
||||
{"attr_key": "ENERCC", "name_de": "Energie", "name_en": None, "unit": "kcal", "category": "energy", "origin": "bls", "value_num": 900},
|
||||
{"attr_key": "FAT", "name_de": "Fett", "name_en": None, "unit": "g", "category": "macro", "origin": "bls", "value_num": 100},
|
||||
{"attr_key": "PROT625", "name_de": "Protein", "name_en": None, "unit": "g", "category": "macro", "origin": "bls", "value_num": 0},
|
||||
{"attr_key": "CHO", "name_de": "KH", "name_en": None, "unit": "g", "category": "macro", "origin": "bls", "value_num": 0},
|
||||
{"attr_key": "EPA", "name_de": "EPA", "name_en": None, "unit": "g", "category": "extension", "origin": "extension", "value_num": 13.75},
|
||||
]
|
||||
|
||||
payload = editor_payload_for_food(
|
||||
_Cur(),
|
||||
{"id": "abc", "name_de": "Omega-3", "name_en": None, "catalog_kind": "manual_user"},
|
||||
editable=True,
|
||||
)
|
||||
assert payload["editable"] is True
|
||||
assert payload["serving_g"] == 100
|
||||
assert payload["macros_per_100g"]["kcal"] == 900
|
||||
assert payload["macros_per_100g"]["fat_g"] == 100
|
||||
assert payload["attributes"][0]["attr"]["attr_key"] == "EPA"
|
||||
assert payload["attributes"][0]["value"] == 13.75
|
||||
@@ -105,3 +105,11 @@ def test_joghurt_10_ranks_above_35():
|
||||
packed = suggest_for_name(index, query, limit=3)
|
||||
assert packed["suggestions"][0]["name_de"] == full["name_de"], query
|
||||
assert packed["suggestions"][0]["score"] > score_name_match(query, light["name_de"])
|
||||
|
||||
|
||||
def test_personal_food_ranks_above_bls_on_tie():
|
||||
bls = {"id": "bls", "name_de": "Omega-3 Öl", "name_en": "", "bls_code": "X", "catalog_kind": "official_bls"}
|
||||
mine = {"id": "me", "name_de": "Omega-3 Öl", "name_en": "", "bls_code": None, "catalog_kind": "manual_user", "owner_profile_id": "u1"}
|
||||
packed = suggest_for_name(_index(bls, mine), "Omega-3 Öl", limit=2)
|
||||
assert packed["suggestions"][0]["id"] == "me"
|
||||
assert packed["suggestions"][0]["visibility"] == "personal"
|
||||
@@ -0,0 +1,90 @@
|
||||
from data_layer.food_visibility import (
|
||||
attach_visibility,
|
||||
is_global_mapping_target,
|
||||
is_visible_to,
|
||||
require_mapping_target,
|
||||
visibility_of,
|
||||
visibility_rank,
|
||||
)
|
||||
|
||||
|
||||
def test_visibility_scopes():
|
||||
assert visibility_of({"catalog_kind": "official_bls"}) == "bls"
|
||||
assert visibility_of({"catalog_kind": "manual_admin", "owner_profile_id": None}) == "global"
|
||||
assert visibility_of({"catalog_kind": "manual_user", "owner_profile_id": "u1"}) == "personal"
|
||||
assert visibility_rank({"catalog_kind": "manual_user"}) < visibility_rank({"catalog_kind": "manual_admin"})
|
||||
assert visibility_rank({"catalog_kind": "manual_admin"}) < visibility_rank({"catalog_kind": "official_bls"})
|
||||
|
||||
|
||||
def test_personal_food_not_visible_to_others():
|
||||
food = {"catalog_kind": "manual_user", "owner_profile_id": "alice", "is_active": True}
|
||||
assert is_visible_to(food, "alice") is True
|
||||
assert is_visible_to(food, "bob") is False
|
||||
assert is_global_mapping_target(food) is False
|
||||
|
||||
|
||||
def test_admin_and_bls_visible_to_everyone():
|
||||
admin = {"catalog_kind": "manual_admin", "owner_profile_id": None, "is_active": True}
|
||||
bls = {"catalog_kind": "official_bls", "owner_profile_id": None, "is_active": True}
|
||||
assert is_visible_to(admin, "bob") is True
|
||||
assert is_visible_to(bls, None) is True
|
||||
assert is_global_mapping_target(admin) is True
|
||||
assert is_global_mapping_target(bls) is True
|
||||
|
||||
|
||||
def test_attach_visibility():
|
||||
row = attach_visibility({"catalog_kind": "manual_admin"})
|
||||
assert row["visibility"] == "global"
|
||||
|
||||
|
||||
def test_require_global_mapping_rejects_personal():
|
||||
class _Cur:
|
||||
def execute(self, sql, params=None):
|
||||
self._row = {
|
||||
"id": params[0],
|
||||
"name_de": "Öl",
|
||||
"catalog_kind": "manual_user",
|
||||
"owner_profile_id": "alice",
|
||||
"is_active": True,
|
||||
"bls_code": None,
|
||||
}
|
||||
|
||||
def fetchone(self):
|
||||
return self._row
|
||||
|
||||
try:
|
||||
require_mapping_target(_Cur(), "fid", None)
|
||||
assert False, "expected PermissionError"
|
||||
except PermissionError:
|
||||
pass
|
||||
|
||||
|
||||
def test_require_user_mapping_allows_own_and_global():
|
||||
class _Cur:
|
||||
def __init__(self, food):
|
||||
self.food = food
|
||||
|
||||
def execute(self, sql, params=None):
|
||||
pass
|
||||
|
||||
def fetchone(self):
|
||||
return self.food
|
||||
|
||||
own = require_mapping_target(
|
||||
_Cur({
|
||||
"id": "1", "name_de": "X", "catalog_kind": "manual_user",
|
||||
"owner_profile_id": "alice", "is_active": True, "bls_code": None,
|
||||
}),
|
||||
"1",
|
||||
"alice",
|
||||
)
|
||||
assert own["catalog_kind"] == "manual_user"
|
||||
shared = require_mapping_target(
|
||||
_Cur({
|
||||
"id": "2", "name_de": "Y", "catalog_kind": "manual_admin",
|
||||
"owner_profile_id": None, "is_active": True, "bls_code": None,
|
||||
}),
|
||||
"2",
|
||||
"alice",
|
||||
)
|
||||
assert shared["catalog_kind"] == "manual_admin"
|
||||
+8
-4
@@ -8,8 +8,8 @@ Semantic Versioning: MAJOR.MINOR.PATCH
|
||||
"""
|
||||
|
||||
APP_VERSION = "0.9v"
|
||||
BUILD_DATE = "2026-09-12"
|
||||
DB_SCHEMA_VERSION = "20260912e" # 068 nutrition unmapped/recipe indexes
|
||||
BUILD_DATE = "2026-09-14"
|
||||
DB_SCHEMA_VERSION = "20260914a" # 069 food catalog visibility owner check
|
||||
|
||||
MODULE_VERSIONS = {
|
||||
"auth": "1.2.0",
|
||||
@@ -20,9 +20,10 @@ MODULE_VERSIONS = {
|
||||
"circumference": "1.0.1",
|
||||
"caliper": "1.0.1",
|
||||
"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
|
||||
"nutrition": "1.3.7", # Sichtbarkeit persönlich vs. zentral im Mapping
|
||||
"tandoor": "1.0.1", # Router-Import ohne future-annotations (Backend startet)
|
||||
"bls": "1.0.6", # Nutzer darf Extension-Stoffe anlegen; EPA-Chips; mg/µg am Etikett
|
||||
"bls": "1.0.9", # Nutzer-Foods privat, Admin-Foods zentral; Mapping achtet Sichtbarkeit
|
||||
|
||||
"photos": "1.0.0",
|
||||
"insights": "1.3.0",
|
||||
"prompts": "1.1.0",
|
||||
@@ -55,6 +56,9 @@ CHANGELOG = [
|
||||
"Zuordnen: Zeitraum 14 Tage / 4 Wochen / 90 Tage / Alle — zuerst aktuelle Tagebuchnamen",
|
||||
"Katalogsuche: Fettgehalt (9,5 / 10 %) bleibt erhalten, Joghurt 10% vor >3,5%",
|
||||
"Eigenes Lebensmittel: beliebige Katalog-Stoffe (EPA/DHA/…) plus Portionsumrechnung auf 100 g",
|
||||
"Eigene Lebensmittel nachträglich bearbeiten (Name, Makros, Stoffe); BLS bleibt fest",
|
||||
"Reiter Lebensmittel (Nutzer) und Admin-Katalog Manuell: Liste + Suche",
|
||||
"Sichtbarkeit: persönliche Foods nur Owner, zentrale Admin-Foods für alle; Mapping trennt global vs. Nutzer",
|
||||
"Zuordnen: Mapping-Export robust; Rezepte anlegen/bearbeiten; Admin-Mapping direkt ändern",
|
||||
"Rezept-Dialog: Zutaten aus Zuordnungen und Katalog suchen; Tandoor später",
|
||||
"Rezeptzutaten: Menge + Einheit (EL/TL/Prise/Stück); Umrechnung auf Gramm",
|
||||
|
||||
Reference in new issue
Block a user