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
@@ -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