feat: BLS-Stammdaten, FDDB-Mapping und Item-Tagebuch (#106)
Katalog, lernendes Mapping ohne KI, optionale Items und Import-Policy. Playwright-Smoke und Issue-Audit um Ernährung/Zuordnen/API ergänzt. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
72d101415f
commit
919c77fcf8
39 files changed
+2648
-47
No files matched your search
@@ -0,0 +1,234 @@
|
||||
"""Admin BLS catalog import and attribute/food maintenance."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
|
||||
from pydantic import BaseModel
|
||||
|
||||
from auth import require_admin
|
||||
from bls.import_service import upsert_attributes, upsert_foods
|
||||
from bls.parser import parse_components_xlsx, parse_foods_xlsx
|
||||
from db import get_cursor, get_db, r2d
|
||||
|
||||
router = APIRouter(prefix="/api/admin/bls", tags=["admin", "bls"])
|
||||
|
||||
|
||||
class AttributeCreate(BaseModel):
|
||||
attr_key: str
|
||||
name_de: str
|
||||
name_en: Optional[str] = None
|
||||
unit: Optional[str] = None
|
||||
category: Optional[str] = None
|
||||
data_type: str = "num_per_100g"
|
||||
enum_values: Optional[list] = None
|
||||
|
||||
|
||||
class ManualFoodCreate(BaseModel):
|
||||
name_de: str
|
||||
name_en: Optional[str] = None
|
||||
macros_per_100g: Optional[dict] = None
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
def bls_status(session: dict = Depends(require_admin)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT COUNT(*) AS n FROM food_catalog WHERE catalog_kind = 'official_bls'")
|
||||
foods = cur.fetchone()["n"]
|
||||
cur.execute("SELECT COUNT(*) AS n FROM food_attributes WHERE origin = 'official_bls'")
|
||||
attrs = cur.fetchone()["n"]
|
||||
cur.execute("SELECT COUNT(*) AS n FROM food_catalog WHERE catalog_kind <> 'official_bls'")
|
||||
manual = cur.fetchone()["n"]
|
||||
cur.execute("SELECT MAX(updated_at) AS last_updated FROM food_catalog WHERE catalog_kind = 'official_bls'")
|
||||
last = cur.fetchone()["last_updated"]
|
||||
return {
|
||||
"official_foods": foods,
|
||||
"official_attributes": attrs,
|
||||
"manual_foods": manual,
|
||||
"last_updated": last,
|
||||
"source": "Max Rubner-Institut, BLS 4.0 (frei verfügbar)",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/import/components")
|
||||
async def import_components(
|
||||
file: UploadFile = File(...),
|
||||
dry_run: bool = True,
|
||||
session: dict = Depends(require_admin),
|
||||
):
|
||||
raw = await file.read()
|
||||
if not raw:
|
||||
raise HTTPException(400, "Leere Datei")
|
||||
try:
|
||||
attrs = parse_components_xlsx(raw)
|
||||
except Exception as e:
|
||||
raise HTTPException(400, f"Components-Datei unlesbar: {e}") from e
|
||||
if dry_run:
|
||||
return {"dry_run": True, "attributes": len(attrs), "sample": attrs[:8]}
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
stats = upsert_attributes(cur, attrs)
|
||||
return {"dry_run": False, **stats}
|
||||
|
||||
|
||||
@router.post("/import/foods")
|
||||
async def import_foods(
|
||||
file: UploadFile = File(...),
|
||||
dry_run: bool = True,
|
||||
session: dict = Depends(require_admin),
|
||||
):
|
||||
raw = await file.read()
|
||||
if not raw:
|
||||
raise HTTPException(400, "Leere Datei")
|
||||
try:
|
||||
parsed = parse_foods_xlsx(raw)
|
||||
except Exception as e:
|
||||
raise HTTPException(400, f"Datendatei unlesbar: {e}") from e
|
||||
foods = parsed["foods"]
|
||||
if dry_run:
|
||||
return {
|
||||
"dry_run": True,
|
||||
"foods": len(foods),
|
||||
"attribute_columns": len(parsed["attribute_headers"]),
|
||||
"sample": [
|
||||
{"bls_code": f["bls_code"], "name_de": f["name_de"]}
|
||||
for f in foods[:8]
|
||||
],
|
||||
}
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
stats = upsert_foods(cur, foods)
|
||||
return {"dry_run": False, **stats}
|
||||
|
||||
|
||||
@router.get("/foods")
|
||||
def admin_list_foods(
|
||||
q: Optional[str] = None,
|
||||
kind: Optional[str] = None,
|
||||
limit: int = 50,
|
||||
session: dict = Depends(require_admin),
|
||||
):
|
||||
limit = min(max(limit, 1), 200)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
conds = ["is_active = true"]
|
||||
params: list = []
|
||||
if kind:
|
||||
conds.append("catalog_kind = %s")
|
||||
params.append(kind)
|
||||
if q:
|
||||
conds.append("(name_de ILIKE %s OR COALESCE(name_en,'') ILIKE %s OR COALESCE(bls_code,'') ILIKE %s)")
|
||||
like = f"%{q}%"
|
||||
params.extend([like, like, like])
|
||||
params.append(limit)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT id, bls_code, name_de, name_en, catalog_kind, food_group, bls_version
|
||||
FROM food_catalog
|
||||
WHERE {' AND '.join(conds)}
|
||||
ORDER BY name_de
|
||||
LIMIT %s
|
||||
""",
|
||||
params,
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.get("/foods/{food_id}")
|
||||
def admin_food_detail(food_id: str, session: dict = Depends(require_admin)):
|
||||
from data_layer.nutrition_items import resolve_food_attributes
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT * FROM food_catalog WHERE id = %s", (food_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Lebensmittel nicht gefunden")
|
||||
attrs = resolve_food_attributes(cur, food_id)
|
||||
return {**r2d(row), "attributes": attrs}
|
||||
|
||||
|
||||
@router.post("/foods/manual")
|
||||
def admin_create_manual_food(body: ManualFoodCreate, session: dict = Depends(require_admin)):
|
||||
from data_layer.food_mapping import normalize_food_name
|
||||
|
||||
name = (body.name_de or "").strip()
|
||||
if not name:
|
||||
raise HTTPException(400, "Name fehlt")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO food_catalog (name_de, name_en, catalog_kind, source, external_key)
|
||||
VALUES (%s, %s, 'manual_admin', 'manual', %s)
|
||||
RETURNING *
|
||||
""",
|
||||
(name, body.name_en, f"man-admin-{normalize_food_name(name)[:40]}"),
|
||||
)
|
||||
food = r2d(cur.fetchone())
|
||||
_write_manual_macros(cur, food["id"], body.macros_per_100g)
|
||||
return food
|
||||
|
||||
|
||||
@router.get("/attributes")
|
||||
def admin_list_attributes(session: dict = Depends(require_admin)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, attr_key, name_de, name_en, unit, category, data_type, origin, sort_order
|
||||
FROM food_attributes
|
||||
WHERE is_active = true
|
||||
ORDER BY origin, sort_order, attr_key
|
||||
"""
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.post("/attributes")
|
||||
def admin_create_attribute(body: AttributeCreate, session: dict = Depends(require_admin)):
|
||||
key = body.attr_key.strip().upper().replace(" ", "_")
|
||||
if not key:
|
||||
raise HTTPException(400, "attr_key fehlt")
|
||||
if body.data_type not in ("num_per_100g", "boolean", "text", "enum"):
|
||||
raise HTTPException(400, "Ungültiger data_type")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO food_attributes
|
||||
(attr_key, name_de, name_en, unit, category, data_type, enum_values, origin, sort_order)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, 'extension', 9000)
|
||||
RETURNING *
|
||||
""",
|
||||
(
|
||||
key, body.name_de, body.name_en, body.unit, body.category,
|
||||
body.data_type, None if not body.enum_values else body.enum_values,
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(409, f"Attribut existiert bereits oder ist ungültig: {e}") from e
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
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])),
|
||||
)
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Admin CRUD for food_name_mappings."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
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 db import get_cursor, get_db, r2d
|
||||
|
||||
router = APIRouter(prefix="/api/admin/food-mappings", tags=["admin", "food-mappings"])
|
||||
|
||||
|
||||
class FoodMappingCreate(BaseModel):
|
||||
source_name: str
|
||||
food_id: str
|
||||
profile_id: Optional[str] = None
|
||||
source_system: str = "fddb"
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_food_mappings(
|
||||
profile_id: Optional[str] = None,
|
||||
global_only: bool = False,
|
||||
session: dict = Depends(require_admin),
|
||||
):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
q = """
|
||||
SELECT m.id, m.source_name_raw, m.source_name_normalized, m.food_id,
|
||||
m.profile_id, m.source, m.created_at, m.updated_at,
|
||||
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
|
||||
"""
|
||||
conds, params = [], []
|
||||
if global_only:
|
||||
conds.append("m.profile_id IS NULL")
|
||||
elif profile_id:
|
||||
conds.append("m.profile_id = %s")
|
||||
params.append(profile_id)
|
||||
if conds:
|
||||
q += " WHERE " + " AND ".join(conds)
|
||||
q += " ORDER BY m.source_name_normalized"
|
||||
cur.execute(q, params)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.get("/stats/coverage")
|
||||
def mapping_coverage(session: dict = Depends(require_admin)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
COUNT(*) AS total_items,
|
||||
COUNT(food_id) AS mapped_items,
|
||||
COUNT(*) - COUNT(food_id) AS unmapped_items,
|
||||
COUNT(DISTINCT source_name_normalized) AS unique_names,
|
||||
COUNT(DISTINCT CASE WHEN food_id IS NULL THEN source_name_normalized END) AS unmapped_names
|
||||
FROM nutrition_items
|
||||
"""
|
||||
)
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_food_mapping(body: FoodMappingCreate, session: dict = Depends(require_admin)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT id FROM food_catalog WHERE id = %s", (body.food_id,))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Lebensmittel nicht gefunden")
|
||||
mid = upsert_food_mapping(
|
||||
cur,
|
||||
source_name_raw=body.source_name,
|
||||
food_id=body.food_id,
|
||||
profile_id=body.profile_id or None,
|
||||
source="admin",
|
||||
source_system=body.source_system,
|
||||
)
|
||||
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
|
||||
""",
|
||||
(mid,),
|
||||
)
|
||||
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:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("DELETE FROM food_name_mappings WHERE id = %s RETURNING id", (mapping_id,))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Mapping nicht gefunden")
|
||||
return {"ok": True}
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Authenticated catalog search and user-owned foods / mappings."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from auth import require_auth
|
||||
from data_layer.food_mapping import (
|
||||
apply_mapping_to_items,
|
||||
clear_mapping_from_items,
|
||||
normalize_food_name,
|
||||
suggest_catalog_foods,
|
||||
upsert_food_mapping,
|
||||
)
|
||||
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
|
||||
|
||||
router = APIRouter(prefix="/api/bls", tags=["bls"])
|
||||
|
||||
|
||||
class UserFoodCreate(BaseModel):
|
||||
name_de: str
|
||||
name_en: Optional[str] = None
|
||||
macros_per_100g: Optional[dict] = None
|
||||
|
||||
|
||||
class MappingUpsert(BaseModel):
|
||||
source_name: str
|
||||
food_id: str
|
||||
source_system: str = "fddb"
|
||||
|
||||
|
||||
@router.get("/foods")
|
||||
def search_foods(
|
||||
q: str = "",
|
||||
limit: int = 20,
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
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))
|
||||
|
||||
|
||||
@router.post("/foods/manual")
|
||||
def create_user_food(body: UserFoodCreate, session: dict = Depends(require_auth)):
|
||||
from routers.admin_bls import _write_manual_macros
|
||||
|
||||
pid = session["profile_id"]
|
||||
name = (body.name_de or "").strip()
|
||||
if not name:
|
||||
raise HTTPException(400, "Name fehlt")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO food_catalog
|
||||
(name_de, name_en, catalog_kind, owner_profile_id, source, external_key)
|
||||
VALUES (%s, %s, 'manual_user', %s, 'manual', %s)
|
||||
RETURNING *
|
||||
""",
|
||||
(name, body.name_en, pid, f"man-user-{normalize_food_name(name)[:40]}"),
|
||||
)
|
||||
food = r2d(cur.fetchone())
|
||||
_write_manual_macros(cur, food["id"], body.macros_per_100g)
|
||||
return food
|
||||
|
||||
|
||||
@router.get("/mappings")
|
||||
def list_my_mappings(session: dict = Depends(require_auth)):
|
||||
pid = session["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,
|
||||
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
|
||||
WHERE m.profile_id = %s
|
||||
ORDER BY m.source_name_normalized
|
||||
""",
|
||||
(pid,),
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.post("/mappings")
|
||||
def upsert_my_mapping(body: MappingUpsert, session: dict = Depends(require_auth)):
|
||||
pid = session["profile_id"]
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id 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():
|
||||
raise HTTPException(404, "Lebensmittel nicht gefunden")
|
||||
mid = upsert_food_mapping(
|
||||
cur,
|
||||
source_name_raw=body.source_name,
|
||||
food_id=body.food_id,
|
||||
profile_id=pid,
|
||||
source="bulk",
|
||||
source_system=body.source_system,
|
||||
)
|
||||
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)
|
||||
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"]
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT source_name_normalized FROM food_name_mappings
|
||||
WHERE id = %s AND profile_id = %s
|
||||
""",
|
||||
(mapping_id, pid),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Mapping nicht gefunden")
|
||||
norm = row["source_name_normalized"]
|
||||
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)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# keep get_pid imported for consistency with other routers
|
||||
_ = get_pid
|
||||
+248
-35
@@ -31,8 +31,13 @@ def _pf(s):
|
||||
|
||||
# ── Endpoints ─────────────────────────────────────────────────────────────────
|
||||
@router.post("/import-csv")
|
||||
async def import_nutrition_csv(file: UploadFile=File(...), x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||
"""Import FDDB nutrition CSV."""
|
||||
async def import_nutrition_csv(
|
||||
file: UploadFile = File(...),
|
||||
overwrite_existing: bool = False,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
"""Import FDDB nutrition CSV (optional item persist + conflict policy)."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
# Phase 4: Check feature access and ENFORCE
|
||||
@@ -56,48 +61,97 @@ async def import_nutrition_csv(file: UploadFile=File(...), x_profile_id: Optiona
|
||||
except: text = raw.decode('latin-1')
|
||||
if text.startswith('\ufeff'): text = text[1:]
|
||||
if not text.strip(): raise HTTPException(400,"Leere Datei")
|
||||
from data_layer.nutrition_items import get_import_policy, replace_csv_items_for_dates
|
||||
|
||||
overwrite = bool(overwrite_existing)
|
||||
reader = csv.DictReader(io.StringIO(text), delimiter=';')
|
||||
item_rows = []
|
||||
days: dict = {}
|
||||
count = 0
|
||||
for row in reader:
|
||||
rd = row.get('datum_tag_monat_jahr_stunde_minute','').strip().strip('"')
|
||||
if not rd: continue
|
||||
try:
|
||||
p = rd.split(' ')[0].split('.')
|
||||
parts = rd.split(' ')
|
||||
p = parts[0].split('.')
|
||||
iso = f"{p[2]}-{p[1]}-{p[0]}"
|
||||
except: continue
|
||||
days.setdefault(iso,{'kcal':0,'fat_g':0,'carbs_g':0,'protein_g':0})
|
||||
days[iso]['kcal'] += _pf(row.get('kj',0))/4.184
|
||||
days[iso]['fat_g'] += _pf(row.get('fett_g',0))
|
||||
days[iso]['carbs_g'] += _pf(row.get('kh_g',0))
|
||||
days[iso]['protein_g'] += _pf(row.get('protein_g',0))
|
||||
count+=1
|
||||
inserted=0
|
||||
new_entries=0
|
||||
logged_at = None
|
||||
if len(parts) > 1:
|
||||
try:
|
||||
logged_at = datetime.strptime(rd.strip(), '%d.%m.%Y %H:%M')
|
||||
except ValueError:
|
||||
logged_at = None
|
||||
except Exception:
|
||||
continue
|
||||
kcal = _pf(row.get('kj', 0)) / 4.184
|
||||
fat = _pf(row.get('fett_g', 0))
|
||||
carbs = _pf(row.get('kh_g', 0))
|
||||
prot = _pf(row.get('protein_g', 0))
|
||||
days.setdefault(iso, {'kcal': 0, 'fat_g': 0, 'carbs_g': 0, 'protein_g': 0})
|
||||
days[iso]['kcal'] += kcal
|
||||
days[iso]['fat_g'] += fat
|
||||
days[iso]['carbs_g'] += carbs
|
||||
days[iso]['protein_g'] += prot
|
||||
name = (row.get('bezeichnung') or '').strip().strip('"')
|
||||
if name:
|
||||
item_rows.append({
|
||||
"date": iso,
|
||||
"logged_at": logged_at,
|
||||
"food_name": name,
|
||||
"quantity_raw": (row.get('menge') or '').strip() or None,
|
||||
"kcal": kcal,
|
||||
"protein_g": prot,
|
||||
"fat_g": fat,
|
||||
"carbs_g": carbs,
|
||||
})
|
||||
count += 1
|
||||
inserted = 0
|
||||
new_entries = 0
|
||||
ingest_result = {"conflicts": [], "items_written": 0, "policy": "prompt"}
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
for iso,vals in days.items():
|
||||
kcal=round(vals['kcal'],1); fat=round(vals['fat_g'],1)
|
||||
carbs=round(vals['carbs_g'],1); prot=round(vals['protein_g'],1)
|
||||
cur.execute("SELECT id FROM nutrition_log WHERE profile_id=%s AND date=%s",(pid,iso))
|
||||
is_new = not cur.fetchone()
|
||||
if not is_new:
|
||||
# UPDATE existing
|
||||
cur.execute("UPDATE nutrition_log SET kcal=%s,protein_g=%s,fat_g=%s,carbs_g=%s WHERE profile_id=%s AND date=%s",
|
||||
(kcal,prot,fat,carbs,pid,iso))
|
||||
else:
|
||||
# INSERT new
|
||||
cur.execute("INSERT INTO nutrition_log (id,profile_id,date,kcal,protein_g,fat_g,carbs_g,source,created) VALUES (%s,%s,%s,%s,%s,%s,%s,'csv',CURRENT_TIMESTAMP)",
|
||||
(str(uuid.uuid4()),pid,iso,kcal,prot,fat,carbs))
|
||||
new_entries += 1
|
||||
inserted+=1
|
||||
policy = get_import_policy(cur, pid)
|
||||
override = "overwrite_catalog" if overwrite else None
|
||||
if item_rows:
|
||||
ingest_result = replace_csv_items_for_dates(
|
||||
cur, pid, item_rows, policy=policy, policy_override=override,
|
||||
)
|
||||
new_entries = ingest_result.get("new_log_days") or 0
|
||||
inserted = ingest_result.get("days_written") or 0
|
||||
else:
|
||||
for iso, vals in days.items():
|
||||
kcal = round(vals['kcal'], 1)
|
||||
fat = round(vals['fat_g'], 1)
|
||||
carbs = round(vals['carbs_g'], 1)
|
||||
prot = round(vals['protein_g'], 1)
|
||||
cur.execute("SELECT id FROM nutrition_log WHERE profile_id=%s AND date=%s", (pid, iso))
|
||||
is_new = not cur.fetchone()
|
||||
if not is_new:
|
||||
if policy in ("overwrite_catalog", "overwrite_fddb") or overwrite:
|
||||
cur.execute(
|
||||
"UPDATE nutrition_log SET kcal=%s,protein_g=%s,fat_g=%s,carbs_g=%s,source='csv',macro_origin='fddb' WHERE profile_id=%s AND date=%s",
|
||||
(kcal, prot, fat, carbs, pid, iso),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"INSERT INTO nutrition_log (id,profile_id,date,kcal,protein_g,fat_g,carbs_g,source,macro_origin,created) VALUES (%s,%s,%s,%s,%s,%s,%s,'csv','fddb',CURRENT_TIMESTAMP)",
|
||||
(str(uuid.uuid4()), pid, iso, kcal, prot, fat, carbs),
|
||||
)
|
||||
new_entries += 1
|
||||
inserted += 1
|
||||
|
||||
# Phase 2: Increment usage counter for each new entry created
|
||||
for _ in range(new_entries):
|
||||
increment_feature_usage(pid, 'nutrition_entries')
|
||||
|
||||
return {"rows_parsed":count,"days_imported":inserted,"new_entries":new_entries,
|
||||
"date_range":{"from":min(days) if days else None,"to":max(days) if days else None}}
|
||||
return {
|
||||
"rows_parsed": count,
|
||||
"days_imported": inserted,
|
||||
"new_entries": new_entries,
|
||||
"items_written": ingest_result.get("items_written", 0),
|
||||
"conflicts": ingest_result.get("conflicts") or [],
|
||||
"policy": ingest_result.get("policy", "prompt"),
|
||||
"date_range": {"from": min(days) if days else None, "to": max(days) if days else None},
|
||||
}
|
||||
|
||||
|
||||
@router.post("")
|
||||
@@ -122,7 +176,7 @@ def create_nutrition(date: str, kcal: float, protein_g: float, fat_g: float, car
|
||||
# UPDATE existing entry
|
||||
cur.execute("""
|
||||
UPDATE nutrition_log
|
||||
SET kcal=%s, protein_g=%s, fat_g=%s, carbs_g=%s, source='manual'
|
||||
SET kcal=%s, protein_g=%s, fat_g=%s, carbs_g=%s, source='manual', macro_origin='manual'
|
||||
WHERE id=%s AND profile_id=%s
|
||||
""", (round(kcal,1), round(protein_g,1), round(fat_g,1), round(carbs_g,1), existing['id'], pid))
|
||||
return {"success": True, "mode": "updated", "id": existing['id']}
|
||||
@@ -145,8 +199,8 @@ def create_nutrition(date: str, kcal: float, protein_g: float, fat_g: float, car
|
||||
# INSERT new entry
|
||||
new_id = str(uuid.uuid4())
|
||||
cur.execute("""
|
||||
INSERT INTO nutrition_log (id, profile_id, date, kcal, protein_g, fat_g, carbs_g, source, created)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, 'manual', CURRENT_TIMESTAMP)
|
||||
INSERT INTO nutrition_log (id, profile_id, date, kcal, protein_g, fat_g, carbs_g, source, macro_origin, created)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, 'manual', 'manual', CURRENT_TIMESTAMP)
|
||||
""", (new_id, pid, date, round(kcal,1), round(protein_g,1), round(fat_g,1), round(carbs_g,1)))
|
||||
|
||||
# Phase 2: Increment usage counter
|
||||
@@ -162,7 +216,17 @@ def list_nutrition(limit: int=365, x_profile_id: Optional[str]=Header(default=No
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT * FROM nutrition_log WHERE profile_id=%s ORDER BY date DESC LIMIT %s", (pid,limit))
|
||||
"""
|
||||
SELECT n.*, m.mark_type, m.note AS mark_note
|
||||
FROM nutrition_log n
|
||||
LEFT JOIN nutrition_day_marks m
|
||||
ON m.profile_id = n.profile_id AND m.date = n.date
|
||||
WHERE n.profile_id=%s
|
||||
ORDER BY n.date DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(pid, limit),
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@@ -228,6 +292,155 @@ def import_history(x_profile_id: Optional[str]=Header(default=None), session: di
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.get("/items")
|
||||
def list_nutrition_items(
|
||||
date: Optional[str] = None,
|
||||
limit: int = 200,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
pid = get_pid(x_profile_id)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if date:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT i.*, f.name_de AS food_name_de, f.bls_code, f.catalog_kind
|
||||
FROM nutrition_items i
|
||||
LEFT JOIN food_catalog f ON f.id = i.food_id
|
||||
WHERE i.profile_id=%s AND i.date=%s
|
||||
ORDER BY i.logged_at NULLS LAST, i.source_name_raw
|
||||
""",
|
||||
(pid, date),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT i.*, f.name_de AS food_name_de, f.bls_code, f.catalog_kind
|
||||
FROM nutrition_items i
|
||||
LEFT JOIN food_catalog f ON f.id = i.food_id
|
||||
WHERE i.profile_id=%s
|
||||
ORDER BY i.date DESC, i.logged_at NULLS LAST
|
||||
LIMIT %s
|
||||
""",
|
||||
(pid, min(limit, 500)),
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.get("/unmapped")
|
||||
def list_unmapped_foods(
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
pid = get_pid(x_profile_id)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT source_name_raw, source_name_normalized,
|
||||
COUNT(*) AS count, MIN(date) AS first_date, MAX(date) AS last_date
|
||||
FROM nutrition_items
|
||||
WHERE profile_id=%s AND food_id IS NULL
|
||||
GROUP BY source_name_raw, source_name_normalized
|
||||
ORDER BY count DESC, source_name_normalized
|
||||
""",
|
||||
(pid,),
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.post("/import-conflicts/resolve")
|
||||
def resolve_import_conflicts(
|
||||
body: dict,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
from data_layer.nutrition_items import (
|
||||
apply_nutrition_day_macros,
|
||||
compute_day_macro_sums,
|
||||
resolve_choice_macros,
|
||||
)
|
||||
|
||||
pid = get_pid(x_profile_id)
|
||||
decisions = body.get("decisions") or []
|
||||
applied = 0
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
for dec in decisions:
|
||||
day = dec.get("date")
|
||||
choice = dec.get("choice")
|
||||
if not day or not choice:
|
||||
continue
|
||||
sums = compute_day_macro_sums(cur, pid, day)
|
||||
if not sums.get("existing") and choice == "existing":
|
||||
continue
|
||||
macros, origin = resolve_choice_macros(sums, choice)
|
||||
apply_nutrition_day_macros(
|
||||
cur, pid, day, macros, macro_origin=origin, source="csv", confirm=True,
|
||||
)
|
||||
applied += 1
|
||||
return {"applied": applied}
|
||||
|
||||
|
||||
@router.put("/days/{day}/mark")
|
||||
def upsert_day_mark(
|
||||
day: str,
|
||||
body: dict,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
pid = get_pid(x_profile_id)
|
||||
mark_type = (body or {}).get("mark_type")
|
||||
note = (body or {}).get("note")
|
||||
if mark_type not in ("fasting", "incomplete"):
|
||||
raise HTTPException(400, "mark_type muss fasting oder incomplete sein")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO nutrition_day_marks (profile_id, date, mark_type, note, source, updated_at)
|
||||
VALUES (%s, %s, %s, %s, 'manual', NOW())
|
||||
ON CONFLICT (profile_id, date)
|
||||
DO UPDATE SET mark_type = EXCLUDED.mark_type, note = EXCLUDED.note, updated_at = NOW()
|
||||
RETURNING *
|
||||
""",
|
||||
(pid, day, mark_type, note),
|
||||
)
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
@router.delete("/days/{day}/mark")
|
||||
def delete_day_mark(
|
||||
day: str,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
pid = get_pid(x_profile_id)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"DELETE FROM nutrition_day_marks WHERE profile_id=%s AND date=%s",
|
||||
(pid, day),
|
||||
)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/marks")
|
||||
def list_day_marks(
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
pid = get_pid(x_profile_id)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT * FROM nutrition_day_marks WHERE profile_id=%s ORDER BY date DESC",
|
||||
(pid,),
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.put("/{entry_id}")
|
||||
def update_nutrition(entry_id: str, kcal: float, protein_g: float, fat_g: float, carbs_g: float,
|
||||
x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||
@@ -242,7 +455,7 @@ def update_nutrition(entry_id: str, kcal: float, protein_g: float, fat_g: float,
|
||||
|
||||
cur.execute("""
|
||||
UPDATE nutrition_log
|
||||
SET kcal=%s, protein_g=%s, fat_g=%s, carbs_g=%s
|
||||
SET kcal=%s, protein_g=%s, fat_g=%s, carbs_g=%s, source='manual', macro_origin='manual'
|
||||
WHERE id=%s AND profile_id=%s
|
||||
""", (round(kcal,1), round(protein_g,1), round(fat_g,1), round(carbs_g,1), entry_id, pid))
|
||||
|
||||
|
||||
@@ -109,9 +109,17 @@ def update_profile(pid: str, p: ProfileUpdate, session=Depends(require_auth)):
|
||||
data["verification_expires"] = None
|
||||
|
||||
nullable_keys = {"goal_weight", "goal_bf_pct", "dob"}
|
||||
allowed_nutrition_policy = {
|
||||
"prompt", "overwrite_catalog", "overwrite_fddb", "keep_existing",
|
||||
}
|
||||
for k, v in patch.items():
|
||||
if k == "email":
|
||||
continue
|
||||
if k == "nutrition_import_conflict_policy":
|
||||
if v not in allowed_nutrition_policy:
|
||||
raise HTTPException(400, "Ungültige Import-Policy")
|
||||
data[k] = v
|
||||
continue
|
||||
if v is None and k in nullable_keys:
|
||||
data[k] = None
|
||||
elif v is not None:
|
||||
|
||||
Reference in new issue
Block a user