fix: Offene Lebensmittel nach Listen-Import wieder anzeigen
Unmapped ohne Kreuzjoin, Listen-GET kurz, Rebuild im Hintergrund. Tandoor-Zugang (URL/Token) in den Einstellungen mit ausliefern. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
fa542e0fb9
commit
d6838abda7
23 files changed
+786
-114
No files matched your search
@@ -366,96 +366,42 @@ def list_nutrition_items(
|
||||
def list_unmapped_foods(
|
||||
since_days: int = 0,
|
||||
count_only: bool = False,
|
||||
meta: bool = False,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
from data_layer.food_mapping import (
|
||||
as_iso_date,
|
||||
filter_unmapped_since,
|
||||
merge_unmapped_rows,
|
||||
normalize_food_name,
|
||||
sort_unmapped_rows,
|
||||
)
|
||||
from data_layer.food_mapping import list_unmapped_payload
|
||||
|
||||
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(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
|
||||
WHERE i.profile_id=%s AND i.food_id IS NULL AND i.recipe_id IS NULL
|
||||
GROUP BY i.source_name_raw, i.source_name_normalized
|
||||
ORDER BY count DESC, i.source_name_normalized
|
||||
""",
|
||||
(pid,),
|
||||
)
|
||||
diary = [r2d(r) | {"kind": "diary"} for r in cur.fetchall()]
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT i.source_name_raw, i.source_name_normalized,
|
||||
COUNT(*) AS count, u.first_used AS first_date, u.last_used 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
|
||||
ON m.profile_id = r.profile_id
|
||||
AND m.source_name_normalized = i.source_name_normalized
|
||||
LEFT JOIN (
|
||||
SELECT r2.id AS recipe_id, MIN(ni.date) AS first_used, MAX(ni.date) AS last_used
|
||||
FROM food_recipes r2
|
||||
JOIN nutrition_items ni
|
||||
ON ni.profile_id = r2.profile_id
|
||||
AND (ni.recipe_id = r2.id OR ni.source_name_normalized = r2.name_normalized)
|
||||
WHERE r2.profile_id = %s
|
||||
GROUP BY r2.id
|
||||
) u ON u.recipe_id = r.id
|
||||
WHERE r.profile_id = %s AND m.id IS NULL
|
||||
GROUP BY i.source_name_raw, i.source_name_normalized, u.first_used, u.last_used
|
||||
ORDER BY count DESC, i.source_name_normalized
|
||||
""",
|
||||
(pid, pid),
|
||||
)
|
||||
ings = [r2d(r) | {"kind": "recipe_ingredient"} for r in cur.fetchall()]
|
||||
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
|
||||
row["last_date"] = as_iso_date(row.get("last_date"))
|
||||
row["first_date"] = as_iso_date(row.get("first_date"))
|
||||
out.append(row)
|
||||
days = max(0, min(int(since_days or 0), 3650))
|
||||
recent = sort_unmapped_rows(filter_unmapped_since(out, days), days)
|
||||
if count_only:
|
||||
return {"count": len(recent), "total": len(out), "since_days": days}
|
||||
return recent if days else sort_unmapped_rows(out, 0)
|
||||
return list_unmapped_payload(get_cursor(conn), pid, since_days, count_only, meta)
|
||||
|
||||
|
||||
@router.get("/recipes")
|
||||
def list_food_recipes(
|
||||
brief: bool = False,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
from data_layer.food_recipes import list_recipes
|
||||
pid = get_pid(x_profile_id)
|
||||
with get_db() as conn:
|
||||
return list_recipes(get_cursor(conn), pid)
|
||||
return list_recipes(get_cursor(conn), pid, with_ingredients=not brief)
|
||||
|
||||
|
||||
@router.get("/recipes/{recipe_id}")
|
||||
def get_food_recipe(
|
||||
recipe_id: str,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
from data_layer.food_recipes import get_recipe
|
||||
pid = get_pid(x_profile_id)
|
||||
with get_db() as conn:
|
||||
rec = get_recipe(get_cursor(conn), pid, recipe_id)
|
||||
if not rec:
|
||||
raise HTTPException(404, "Rezept nicht gefunden")
|
||||
return rec
|
||||
|
||||
|
||||
@router.post("/recipes")
|
||||
@@ -530,10 +476,10 @@ async def import_fddb_lists(
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
stats = upsert_recipes(cur, pid, recipes)
|
||||
from data_layer.nutrition_items import rebuild_daily_nutrients
|
||||
for d in stats.pop("dates_linked", []) or []:
|
||||
rebuild_daily_nutrients(cur, pid, d)
|
||||
return {"ok": True, "recipes": len(recipes), **stats}
|
||||
dates = stats.pop("dates_linked", []) or []
|
||||
from data_layer.nutrition_items import schedule_daily_nutrient_rebuild
|
||||
schedule_daily_nutrient_rebuild(pid, dates, "FDDB-Listenimport")
|
||||
return {"ok": True, "recipes": len(recipes), "rebuild_pending": len(dates), **stats}
|
||||
|
||||
|
||||
@router.post("/recipes/{recipe_id}/apply")
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Per-user Tandoor connection. No recipe import yet."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from starlette.requests import Request
|
||||
from slowapi import Limiter
|
||||
from slowapi.util import get_remote_address
|
||||
|
||||
from auth import require_auth
|
||||
from data_layer.tandoor_client import TandoorError, normalize_base_url, probe_connection
|
||||
from data_layer.tandoor_settings import (
|
||||
get_public_settings,
|
||||
get_settings,
|
||||
record_probe,
|
||||
upsert_settings,
|
||||
)
|
||||
from db import get_cursor, get_db
|
||||
|
||||
router = APIRouter(prefix="/api/tandoor", tags=["tandoor"])
|
||||
limiter = Limiter(key_func=get_remote_address)
|
||||
|
||||
|
||||
class TandoorSettingsIn(BaseModel):
|
||||
base_url: str = ""
|
||||
token: Optional[str] = None
|
||||
clear_token: bool = False
|
||||
|
||||
|
||||
class TandoorProbeIn(BaseModel):
|
||||
base_url: Optional[str] = None
|
||||
token: Optional[str] = Field(default=None, description="Nur zum Testen; leer = gespeichertes Token")
|
||||
|
||||
|
||||
@router.get("/settings")
|
||||
def read_settings(session: dict = Depends(require_auth)):
|
||||
pid = session["profile_id"]
|
||||
with get_db() as conn:
|
||||
return get_public_settings(get_cursor(conn), pid)
|
||||
|
||||
|
||||
@router.put("/settings")
|
||||
def write_settings(body: TandoorSettingsIn, session: dict = Depends(require_auth)):
|
||||
pid = session["profile_id"]
|
||||
try:
|
||||
if body.clear_token:
|
||||
url = ""
|
||||
else:
|
||||
url = normalize_base_url(body.base_url)
|
||||
with get_db() as conn:
|
||||
return upsert_settings(
|
||||
get_cursor(conn), pid, url, body.token, clear_token=body.clear_token
|
||||
)
|
||||
except (TandoorError, ValueError) as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
|
||||
|
||||
@router.post("/test")
|
||||
@limiter.limit("10/minute")
|
||||
def test_connection(request: Request, body: TandoorProbeIn | None = None, session: dict = Depends(require_auth)):
|
||||
pid = session["profile_id"]
|
||||
body = body or TandoorProbeIn()
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
stored = get_settings(cur, pid)
|
||||
url = (body.base_url or "").strip() or ((stored or {}).get("base_url") or "")
|
||||
token = (body.token or "").strip() or ((stored or {}).get("api_token") or "")
|
||||
try:
|
||||
result = probe_connection(url, token)
|
||||
if stored:
|
||||
record_probe(cur, pid, True)
|
||||
return result
|
||||
except TandoorError as e:
|
||||
if stored:
|
||||
record_probe(cur, pid, False, str(e))
|
||||
raise HTTPException(400, str(e)) from e
|
||||
Reference in new issue
Block a user