feat: Zuordnen ohne Freeze und zuerst die letzten Wochen
Katalogsuche und Bestätigen blockieren die UI nicht mehr; offene Namen starten bei den aktuellen Tagebucheinträgen, alter Ballast bleibt unter Alle. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
c1873a47b1
commit
132a364a3a
17 files changed
+745
-163
No files matched your search
@@ -216,6 +216,8 @@ def admin_create_manual_food(body: ManualFoodCreate, session: dict = Depends(req
|
||||
)
|
||||
food = r2d(cur.fetchone())
|
||||
_write_manual_macros(cur, food["id"], body.macros_per_100g)
|
||||
from data_layer.food_suggest import invalidate_suggest_index
|
||||
invalidate_suggest_index()
|
||||
return food
|
||||
|
||||
|
||||
|
||||
+58
-15
@@ -2,6 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException
|
||||
@@ -13,9 +14,13 @@ from data_layer.food_mapping import (
|
||||
apply_quantities_to_items,
|
||||
clear_mapping_from_items,
|
||||
normalize_food_name,
|
||||
suggest_catalog_foods,
|
||||
upsert_food_mapping,
|
||||
)
|
||||
from data_layer.food_suggest import (
|
||||
invalidate_suggest_index,
|
||||
suggest_batch,
|
||||
suggest_catalog_foods_ranked,
|
||||
)
|
||||
from data_layer.nutrition_items import dates_for_normalized_name, rebuild_daily_nutrients
|
||||
from db import get_cursor, get_db, r2d
|
||||
from routers.profiles import get_pid
|
||||
@@ -39,6 +44,11 @@ class MappingUpsert(BaseModel):
|
||||
source_unit: Optional[str] = None
|
||||
|
||||
|
||||
class SuggestBatchBody(BaseModel):
|
||||
names: list[str]
|
||||
limit: int = 3
|
||||
|
||||
|
||||
def _pid(session: dict, x_profile_id: Optional[str] = None) -> str:
|
||||
return x_profile_id or session["profile_id"]
|
||||
|
||||
@@ -48,6 +58,25 @@ def _rebuild_days(cur, profile_id: str, dates: list[str]) -> None:
|
||||
rebuild_daily_nutrients(cur, profile_id, d)
|
||||
|
||||
|
||||
def _rebuild_days_bg(profile_id: str, dates: list[str], context: str) -> None:
|
||||
if not dates:
|
||||
return
|
||||
try:
|
||||
with get_db() as conn:
|
||||
_rebuild_days(get_cursor(conn), profile_id, dates)
|
||||
except Exception:
|
||||
logger.exception("Nährwert-Rebuild nach %s fehlgeschlagen", context)
|
||||
|
||||
|
||||
def _schedule_rebuild(profile_id: str, dates: list[str], context: str) -> None:
|
||||
threading.Thread(
|
||||
target=_rebuild_days_bg,
|
||||
args=(profile_id, list(dates), context),
|
||||
daemon=True,
|
||||
name="nutrition-rebuild",
|
||||
).start()
|
||||
|
||||
|
||||
@router.get("/foods")
|
||||
def search_foods(
|
||||
q: str = "",
|
||||
@@ -57,7 +86,19 @@ def search_foods(
|
||||
pid = session["profile_id"]
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
return suggest_catalog_foods(cur, q, pid, limit=min(max(limit, 1), 50))
|
||||
return suggest_catalog_foods_ranked(cur, q, pid, limit=min(max(limit, 1), 50))
|
||||
|
||||
|
||||
@router.post("/foods/suggest-batch")
|
||||
def suggest_foods_batch(
|
||||
body: SuggestBatchBody,
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
names = [n for n in (body.names or []) if isinstance(n, str)][:80]
|
||||
limit = min(max(body.limit or 3, 1), 5)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
return suggest_batch(cur, session["profile_id"], names, limit=limit)
|
||||
|
||||
|
||||
@router.post("/foods/manual")
|
||||
@@ -86,6 +127,7 @@ def create_user_food(
|
||||
)
|
||||
food = r2d(cur.fetchone())
|
||||
_write_manual_macros(cur, food["id"], body.macros_per_100g)
|
||||
invalidate_suggest_index(pid)
|
||||
return food
|
||||
|
||||
|
||||
@@ -123,13 +165,14 @@ def upsert_my_mapping(
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id FROM food_catalog
|
||||
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),
|
||||
)
|
||||
if not cur.fetchone():
|
||||
food = cur.fetchone()
|
||||
if not food:
|
||||
raise HTTPException(404, "Lebensmittel nicht gefunden")
|
||||
mid = upsert_food_mapping(
|
||||
cur,
|
||||
@@ -145,12 +188,16 @@ def upsert_my_mapping(
|
||||
n = apply_mapping_to_items(cur, pid, norm, body.food_id, mid)
|
||||
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}
|
||||
_schedule_rebuild(pid, dates, f"Mapping {norm}")
|
||||
return {
|
||||
"mapping_id": mid,
|
||||
"items_updated": n,
|
||||
"source_name_normalized": norm,
|
||||
"food_id": body.food_id,
|
||||
"food_name_de": food["name_de"],
|
||||
"bls_code": food.get("bls_code"),
|
||||
"catalog_kind": food.get("catalog_kind"),
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/mappings/{mapping_id}")
|
||||
@@ -176,11 +223,7 @@ def delete_my_mapping(
|
||||
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))
|
||||
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")
|
||||
_schedule_rebuild(pid, dates, "Mapping-Löschen")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
|
||||
@@ -347,10 +347,18 @@ def list_nutrition_items(
|
||||
|
||||
@router.get("/unmapped")
|
||||
def list_unmapped_foods(
|
||||
since_days: int = 0,
|
||||
count_only: bool = False,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
from data_layer.food_mapping import merge_unmapped_rows, normalize_food_name
|
||||
from data_layer.food_mapping import (
|
||||
as_iso_date,
|
||||
filter_unmapped_since,
|
||||
merge_unmapped_rows,
|
||||
normalize_food_name,
|
||||
sort_unmapped_rows,
|
||||
)
|
||||
|
||||
pid = x_profile_id or session["profile_id"]
|
||||
with get_db() as conn:
|
||||
@@ -383,18 +391,27 @@ 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, 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
|
||||
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, pid),
|
||||
)
|
||||
ings = [r2d(r) | {"kind": "recipe_ingredient"} for r in cur.fetchall()]
|
||||
merged = merge_unmapped_rows(diary + ings)
|
||||
@@ -403,9 +420,14 @@ def list_unmapped_foods(
|
||||
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)
|
||||
out.sort(key=lambda x: (-int(x.get("count") or 0), x.get("source_name_normalized") or ""))
|
||||
return out
|
||||
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)
|
||||
|
||||
|
||||
@router.get("/recipes")
|
||||
|
||||
Reference in new issue
Block a user