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")]
|
||||
Reference in new issue
Block a user