fix: Zuordnungen zuverlässig speichern und Mengen-Varianten zusammenfassen
Mapping bleibt erhalten, auch wenn der Nährwert-Rebuild länger dauert. Offene Liste führt 1 ml/2 ml Olivenöl als ein Lebensmittel. Dazu JSON-Sicherung, eigener Katalogeintrag und Gramm-pro-Einheit. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
86f15e6957
commit
c1873a47b1
17 files changed
+875
-54
No files matched your search
+56
-14
@@ -1,14 +1,16 @@
|
||||
"""Authenticated catalog search and user-owned foods / mappings."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from auth import require_auth
|
||||
from data_layer.food_mapping import (
|
||||
apply_mapping_to_items,
|
||||
apply_quantities_to_items,
|
||||
clear_mapping_from_items,
|
||||
normalize_food_name,
|
||||
suggest_catalog_foods,
|
||||
@@ -18,6 +20,8 @@ from data_layer.nutrition_items import dates_for_normalized_name, rebuild_daily_
|
||||
from db import get_cursor, get_db, r2d
|
||||
from routers.profiles import get_pid
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/bls", tags=["bls"])
|
||||
|
||||
|
||||
@@ -31,6 +35,17 @@ class MappingUpsert(BaseModel):
|
||||
source_name: str
|
||||
food_id: str
|
||||
source_system: str = "fddb"
|
||||
grams_per_unit: Optional[float] = None
|
||||
source_unit: Optional[str] = None
|
||||
|
||||
|
||||
def _pid(session: dict, x_profile_id: Optional[str] = None) -> str:
|
||||
return x_profile_id or session["profile_id"]
|
||||
|
||||
|
||||
def _rebuild_days(cur, profile_id: str, dates: list[str]) -> None:
|
||||
for d in dates:
|
||||
rebuild_daily_nutrients(cur, profile_id, d)
|
||||
|
||||
|
||||
@router.get("/foods")
|
||||
@@ -46,10 +61,15 @@ def search_foods(
|
||||
|
||||
|
||||
@router.post("/foods/manual")
|
||||
def create_user_food(body: UserFoodCreate, session: dict = Depends(require_auth)):
|
||||
def create_user_food(
|
||||
body: UserFoodCreate,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
from routers.admin_bls import _write_manual_macros
|
||||
import uuid
|
||||
|
||||
pid = session["profile_id"]
|
||||
pid = _pid(session, x_profile_id)
|
||||
name = (body.name_de or "").strip()
|
||||
if not name:
|
||||
raise HTTPException(400, "Name fehlt")
|
||||
@@ -62,7 +82,7 @@ def create_user_food(body: UserFoodCreate, session: dict = Depends(require_auth)
|
||||
VALUES (%s, %s, 'manual_user', %s, 'manual', %s)
|
||||
RETURNING *
|
||||
""",
|
||||
(name, body.name_en, pid, f"man-user-{normalize_food_name(name)[:40]}"),
|
||||
(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)
|
||||
@@ -70,13 +90,17 @@ def create_user_food(body: UserFoodCreate, session: dict = Depends(require_auth)
|
||||
|
||||
|
||||
@router.get("/mappings")
|
||||
def list_my_mappings(session: dict = Depends(require_auth)):
|
||||
pid = session["profile_id"]
|
||||
def list_my_mappings(
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
pid = _pid(session, x_profile_id)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT m.id, m.source_name_raw, m.source_name_normalized, m.food_id, m.source,
|
||||
m.grams_per_unit, m.source_unit,
|
||||
f.name_de AS food_name_de, f.bls_code, f.catalog_kind
|
||||
FROM food_name_mappings m
|
||||
JOIN food_catalog f ON f.id = m.food_id
|
||||
@@ -89,8 +113,12 @@ def list_my_mappings(session: dict = Depends(require_auth)):
|
||||
|
||||
|
||||
@router.post("/mappings")
|
||||
def upsert_my_mapping(body: MappingUpsert, session: dict = Depends(require_auth)):
|
||||
pid = session["profile_id"]
|
||||
def upsert_my_mapping(
|
||||
body: MappingUpsert,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
pid = _pid(session, x_profile_id)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
@@ -110,17 +138,28 @@ def upsert_my_mapping(body: MappingUpsert, session: dict = Depends(require_auth)
|
||||
profile_id=pid,
|
||||
source="bulk",
|
||||
source_system=body.source_system,
|
||||
grams_per_unit=body.grams_per_unit,
|
||||
source_unit=body.source_unit,
|
||||
)
|
||||
norm = normalize_food_name(body.source_name)
|
||||
n = apply_mapping_to_items(cur, pid, norm, body.food_id, mid)
|
||||
for d in dates_for_normalized_name(cur, pid, norm):
|
||||
rebuild_daily_nutrients(cur, pid, d)
|
||||
apply_quantities_to_items(cur, pid, norm, body.grams_per_unit)
|
||||
dates = dates_for_normalized_name(cur, pid, norm)
|
||||
try:
|
||||
with get_db() as conn:
|
||||
_rebuild_days(get_cursor(conn), pid, dates)
|
||||
except Exception:
|
||||
logger.exception("Nährwert-Rebuild nach Mapping %s fehlgeschlagen", norm)
|
||||
return {"mapping_id": mid, "items_updated": n, "source_name_normalized": norm}
|
||||
|
||||
|
||||
@router.delete("/mappings/{mapping_id}")
|
||||
def delete_my_mapping(mapping_id: int, session: dict = Depends(require_auth)):
|
||||
pid = session["profile_id"]
|
||||
def delete_my_mapping(
|
||||
mapping_id: int,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
pid = _pid(session, x_profile_id)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
@@ -137,8 +176,11 @@ def delete_my_mapping(mapping_id: int, session: dict = Depends(require_auth)):
|
||||
dates = dates_for_normalized_name(cur, pid, norm)
|
||||
clear_mapping_from_items(cur, pid, norm)
|
||||
cur.execute("DELETE FROM food_name_mappings WHERE id = %s AND profile_id = %s", (mapping_id, pid))
|
||||
for d in dates:
|
||||
rebuild_daily_nutrients(cur, pid, d)
|
||||
try:
|
||||
with get_db() as conn:
|
||||
_rebuild_days(get_cursor(conn), pid, dates)
|
||||
except Exception:
|
||||
logger.exception("Nährwert-Rebuild nach Mapping-Löschen fehlgeschlagen")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ from typing import Optional
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, HTTPException, UploadFile, File, Header, Depends
|
||||
from fastapi.responses import Response
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth, check_feature_access, increment_feature_usage
|
||||
@@ -349,14 +350,26 @@ def list_unmapped_foods(
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
pid = get_pid(x_profile_id)
|
||||
from data_layer.food_mapping import merge_unmapped_rows, normalize_food_name
|
||||
|
||||
pid = x_profile_id or session["profile_id"]
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT source_name_normalized
|
||||
FROM food_name_mappings
|
||||
WHERE profile_id = %s
|
||||
""",
|
||||
(pid,),
|
||||
)
|
||||
mapped = {r["source_name_normalized"] for r in cur.fetchall()}
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT i.source_name_raw, i.source_name_normalized,
|
||||
COUNT(*) AS count, MIN(i.date) AS first_date, MAX(i.date) AS last_date,
|
||||
MIN(r.id::text) AS matching_recipe_id
|
||||
MIN(r.id::text) AS matching_recipe_id,
|
||||
MIN(i.quantity_raw) AS sample_quantity_raw
|
||||
FROM nutrition_items i
|
||||
LEFT JOIN food_recipes r
|
||||
ON r.profile_id = i.profile_id AND r.name_normalized = i.source_name_normalized
|
||||
@@ -370,7 +383,8 @@ def list_unmapped_foods(
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT i.source_name_raw, i.source_name_normalized,
|
||||
COUNT(*) AS count, NULL::date AS first_date, NULL::date AS last_date
|
||||
COUNT(*) AS count, NULL::date AS first_date, NULL::date AS last_date,
|
||||
MIN(i.quantity_raw) AS sample_quantity_raw
|
||||
FROM food_recipe_ingredients i
|
||||
JOIN food_recipes r ON r.id = i.recipe_id
|
||||
LEFT JOIN food_name_mappings m
|
||||
@@ -383,13 +397,15 @@ def list_unmapped_foods(
|
||||
(pid,),
|
||||
)
|
||||
ings = [r2d(r) | {"kind": "recipe_ingredient"} for r in cur.fetchall()]
|
||||
seen = {d["source_name_normalized"] for d in diary}
|
||||
for ing in ings:
|
||||
if ing["source_name_normalized"] not in seen:
|
||||
diary.append(ing)
|
||||
seen.add(ing["source_name_normalized"])
|
||||
diary.sort(key=lambda x: (-int(x.get("count") or 0), x.get("source_name_normalized") or ""))
|
||||
return diary
|
||||
merged = merge_unmapped_rows(diary + ings)
|
||||
out = []
|
||||
for row in merged:
|
||||
key = row.get("source_name_normalized") or normalize_food_name(row.get("source_name_raw"))
|
||||
if key in mapped:
|
||||
continue
|
||||
out.append(row)
|
||||
out.sort(key=lambda x: (-int(x.get("count") or 0), x.get("source_name_normalized") or ""))
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/recipes")
|
||||
@@ -459,6 +475,50 @@ def apply_recipe_name(
|
||||
return {"ok": True, "items_updated": n}
|
||||
|
||||
|
||||
@router.get("/food-knowledge")
|
||||
def export_food_knowledge_file(
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
import json
|
||||
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)
|
||||
stamp = datetime.now().strftime("%Y-%m-%d")
|
||||
return Response(
|
||||
content=body.encode("utf-8"),
|
||||
media_type="application/json; charset=utf-8",
|
||||
headers={"Content-Disposition": f'attachment; filename="mitai-food-knowledge-{stamp}.json"'},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/food-knowledge")
|
||||
async def import_food_knowledge_file(
|
||||
file: UploadFile = File(...),
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
import json
|
||||
from data_layer.food_knowledge import import_food_knowledge, parse_food_knowledge_bundle
|
||||
|
||||
pid = get_pid(x_profile_id)
|
||||
raw = await file.read()
|
||||
if not raw:
|
||||
raise HTTPException(400, "Leere Datei")
|
||||
try:
|
||||
data = json.loads(raw.decode("utf-8-sig"))
|
||||
parse_food_knowledge_bundle(data)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
except Exception as e:
|
||||
raise HTTPException(400, f"Ungültiges JSON: {e}") from e
|
||||
with get_db() as conn:
|
||||
return import_food_knowledge(get_cursor(conn), pid, data)
|
||||
|
||||
|
||||
@router.post("/import-conflicts/resolve")
|
||||
def resolve_import_conflicts(
|
||||
body: dict,
|
||||
|
||||
Reference in new issue
Block a user