feat: Rezepte beim Zuordnen anlegen und offene Zutaten listen
Lebensmittel oder Rezept wählbar; gemappte Zutaten werden übernommen, offene erscheinen in der Liste. Dazu Fettgehalt-Suche, EPA-Stoffe, Rezept-CRUD und Wechsel bestehender Zuordnungen. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
132a364a3a
commit
a7e5511039
26 files changed
+1234
-147
No files matched your search
@@ -264,21 +264,5 @@ def admin_create_attribute(body: AttributeCreate, session: dict = Depends(requir
|
||||
|
||||
|
||||
def _write_manual_macros(cur, food_id: str, macros: dict | None) -> None:
|
||||
if not macros:
|
||||
return
|
||||
mapping = {"kcal": "ENERCC", "protein_g": "PROT625", "fat_g": "FAT", "carbs_g": "CHO"}
|
||||
for field, key in mapping.items():
|
||||
if field not in macros or macros[field] is None:
|
||||
continue
|
||||
cur.execute("SELECT id FROM food_attributes WHERE attr_key = %s", (key,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
continue
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO food_attribute_values (food_id, attribute_id, value_num, is_trace)
|
||||
VALUES (%s, %s, %s, false)
|
||||
ON CONFLICT (food_id, attribute_id) DO UPDATE SET value_num = EXCLUDED.value_num, updated_at = NOW()
|
||||
""",
|
||||
(food_id, row["id"], float(macros[field])),
|
||||
)
|
||||
from data_layer.food_attributes import macros_and_attributes_to_values, write_numeric_attributes
|
||||
write_numeric_attributes(cur, food_id, macros_and_attributes_to_values(macros, None))
|
||||
@@ -7,7 +7,8 @@ from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from auth import require_admin
|
||||
from data_layer.food_mapping import upsert_food_mapping
|
||||
from data_layer.food_mapping import apply_mapping_to_items, upsert_food_mapping
|
||||
from data_layer.nutrition_items import dates_for_normalized_name, rebuild_daily_nutrients
|
||||
from db import get_cursor, get_db, r2d
|
||||
|
||||
router = APIRouter(prefix="/api/admin/food-mappings", tags=["admin", "food-mappings"])
|
||||
@@ -20,6 +21,12 @@ class FoodMappingCreate(BaseModel):
|
||||
source_system: str = "fddb"
|
||||
|
||||
|
||||
class FoodMappingUpdate(BaseModel):
|
||||
food_id: str
|
||||
grams_per_unit: Optional[float] = None
|
||||
source_unit: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_food_mappings(
|
||||
profile_id: Optional[str] = None,
|
||||
@@ -93,6 +100,49 @@ def create_food_mapping(body: FoodMappingCreate, session: dict = Depends(require
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
@router.put("/{mapping_id}")
|
||||
def update_food_mapping(mapping_id: int, body: FoodMappingUpdate, session: dict = Depends(require_admin)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, source_name_raw, source_name_normalized, profile_id
|
||||
FROM food_name_mappings WHERE id = %s
|
||||
""",
|
||||
(mapping_id,),
|
||||
)
|
||||
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():
|
||||
raise HTTPException(404, "Lebensmittel nicht gefunden")
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE food_name_mappings
|
||||
SET food_id = %s, grams_per_unit = COALESCE(%s, grams_per_unit),
|
||||
source_unit = COALESCE(%s, source_unit), source = 'admin', updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(body.food_id, body.grams_per_unit, body.source_unit, mapping_id),
|
||||
)
|
||||
if row.get("profile_id"):
|
||||
apply_mapping_to_items(cur, str(row["profile_id"]), row["source_name_normalized"], body.food_id, mapping_id)
|
||||
dates = dates_for_normalized_name(cur, str(row["profile_id"]), row["source_name_normalized"])
|
||||
for d in dates:
|
||||
rebuild_daily_nutrients(cur, str(row["profile_id"]), d)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT m.*, f.name_de AS food_name_de, f.bls_code
|
||||
FROM food_name_mappings m
|
||||
JOIN food_catalog f ON f.id = m.food_id
|
||||
WHERE m.id = %s
|
||||
""",
|
||||
(mapping_id,),
|
||||
)
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
@router.delete("/{mapping_id}")
|
||||
def delete_food_mapping(mapping_id: int, session: dict = Depends(require_admin)):
|
||||
with get_db() as conn:
|
||||
|
||||
+17
-2
@@ -34,6 +34,8 @@ class UserFoodCreate(BaseModel):
|
||||
name_de: str
|
||||
name_en: Optional[str] = None
|
||||
macros_per_100g: Optional[dict] = None
|
||||
attributes: Optional[dict] = None
|
||||
serving_g: Optional[float] = None
|
||||
|
||||
|
||||
class MappingUpsert(BaseModel):
|
||||
@@ -89,6 +91,17 @@ def search_foods(
|
||||
return suggest_catalog_foods_ranked(cur, q, pid, limit=min(max(limit, 1), 50))
|
||||
|
||||
|
||||
@router.get("/attributes")
|
||||
def list_food_attributes(
|
||||
q: str = "",
|
||||
limit: int = 40,
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
from data_layer.food_attributes import list_numeric_attributes
|
||||
with get_db() as conn:
|
||||
return list_numeric_attributes(get_cursor(conn), q, limit=limit)
|
||||
|
||||
|
||||
@router.post("/foods/suggest-batch")
|
||||
def suggest_foods_batch(
|
||||
body: SuggestBatchBody,
|
||||
@@ -107,13 +120,15 @@ def create_user_food(
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
from routers.admin_bls import _write_manual_macros
|
||||
from data_layer.food_attributes import macros_and_attributes_to_values, write_numeric_attributes
|
||||
import uuid
|
||||
|
||||
pid = _pid(session, x_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(
|
||||
@@ -126,7 +141,7 @@ def create_user_food(
|
||||
(name, body.name_en, pid, f"man-user-{normalize_food_name(name)[:32]}-{uuid.uuid4().hex[:8]}"),
|
||||
)
|
||||
food = r2d(cur.fetchone())
|
||||
_write_manual_macros(cur, food["id"], body.macros_per_100g)
|
||||
write_numeric_attributes(cur, food["id"], values)
|
||||
invalidate_suggest_index(pid)
|
||||
return food
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, HTTPException, UploadFile, File, Header, Depends
|
||||
from fastapi.responses import Response
|
||||
from pydantic import BaseModel
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth, check_feature_access, increment_feature_usage
|
||||
@@ -23,6 +24,19 @@ router = APIRouter(prefix="/api/nutrition", tags=["nutrition"])
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RecipeIngredientIn(BaseModel):
|
||||
source_name_raw: str
|
||||
quantity_raw: Optional[str] = None
|
||||
quantity_g: Optional[float] = None
|
||||
|
||||
|
||||
class RecipeIn(BaseModel):
|
||||
name_raw: str
|
||||
portions: float = 1
|
||||
description: Optional[str] = None
|
||||
ingredients: list[RecipeIngredientIn] = []
|
||||
|
||||
|
||||
# ── Helper ────────────────────────────────────────────────────────────────────
|
||||
def _pf(s):
|
||||
"""Parse float from string (handles comma decimal separator)."""
|
||||
@@ -441,6 +455,55 @@ def list_food_recipes(
|
||||
return list_recipes(get_cursor(conn), pid)
|
||||
|
||||
|
||||
@router.post("/recipes")
|
||||
def create_food_recipe(
|
||||
body: RecipeIn,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
from data_layer.food_recipes import save_recipe
|
||||
pid = get_pid(x_profile_id)
|
||||
try:
|
||||
with get_db() as conn:
|
||||
return save_recipe(get_cursor(conn), pid, body.model_dump())
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
|
||||
|
||||
@router.put("/recipes/{recipe_id}")
|
||||
def update_food_recipe(
|
||||
recipe_id: str,
|
||||
body: RecipeIn,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
from data_layer.food_recipes import save_recipe
|
||||
pid = get_pid(x_profile_id)
|
||||
try:
|
||||
with get_db() as conn:
|
||||
return save_recipe(get_cursor(conn), pid, body.model_dump(), recipe_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "Rezept nicht gefunden") from None
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
|
||||
|
||||
@router.delete("/recipes/{recipe_id}")
|
||||
def delete_food_recipe(
|
||||
recipe_id: str,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
from data_layer.food_recipes import delete_recipe
|
||||
pid = get_pid(x_profile_id)
|
||||
try:
|
||||
with get_db() as conn:
|
||||
delete_recipe(get_cursor(conn), pid, recipe_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "Rezept nicht gefunden") from None
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/recipes/import-fddb-lists")
|
||||
async def import_fddb_lists(
|
||||
file: UploadFile = File(...),
|
||||
@@ -506,9 +569,13 @@ def export_food_knowledge_file(
|
||||
from data_layer.food_knowledge import export_food_knowledge
|
||||
|
||||
pid = get_pid(x_profile_id)
|
||||
with get_db() as conn:
|
||||
bundle = export_food_knowledge(get_cursor(conn), pid)
|
||||
body = json.dumps(bundle, ensure_ascii=False, indent=2, default=str)
|
||||
try:
|
||||
with get_db() as conn:
|
||||
bundle = export_food_knowledge(get_cursor(conn), pid)
|
||||
body = json.dumps(bundle, ensure_ascii=False, indent=2, default=str)
|
||||
except Exception:
|
||||
logger.exception("Export food-knowledge fehlgeschlagen")
|
||||
raise HTTPException(500, "Export fehlgeschlagen") from None
|
||||
stamp = datetime.now().strftime("%Y-%m-%d")
|
||||
return Response(
|
||||
content=body.encode("utf-8"),
|
||||
|
||||
Reference in new issue
Block a user