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
@@ -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),
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user