Author SHA1 Message Date
Lars 8d56c352fc Merge pull request 'Bug Fixes' (#63) from develop into main
Deploy Production / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
Reviewed-on: #63
2026-04-05 17:54:00 +02:00
Lars ebea9946a7 Merge pull request 'feat: Add admin access denial alert to Dashboard with timeout handling' (#62) from develop into main
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Deploy Production / deploy (push) Successful in 55s
Reviewed-on: #62
2026-04-05 11:29:03 +02:00
Lars 9fb04af7df Merge pull request 'Responsive Gui - partially Workflow' (#61) from develop into main
Deploy Production / deploy (push) Failing after 1s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Reviewed-on: #61
2026-04-05 11:27:43 +02:00
Lars 3f5b9b8b58 Merge pull request 'Platzhaltersystem für Ernährung, Körper und Aktivity' (#60) from develop into main
Deploy Production / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
Reviewed-on: #60
2026-04-03 09:28:13 +02:00
Lars 5bbea036c2 Merge pull request 'develop' (#59) from develop into main
Deploy Production / deploy (push) Successful in 53s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Reviewed-on: #59
2026-04-03 08:23:48 +02:00
Lars c762495b6f Merge pull request 'Goals -System refactored - Platzhaltersystem enhanced (als draft)' (#53) from develop into main
Deploy Production / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Reviewed-on: #53
2026-03-31 11:46:47 +02:00
Lars 979e734bd9 Merge pull request 'Bug Fix' (#52) from develop into main
Deploy Production / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
Reviewed-on: #52
2026-03-27 22:16:18 +01:00
Lars 79cb3e0100 Merge pull request 'V 0.9h dynamic focus area system' (#51) from develop into main
Deploy Production / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Reviewed-on: #51
2026-03-27 21:14:40 +01:00
Lars 9d22e7e8af Merge pull request 'Goalsystem V1' (#50) from develop into main
Deploy Production / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Reviewed-on: #50
2026-03-27 17:40:50 +01:00
Lars f46c367c27 Merge pull request 'Flexibles KI Prompt System' (#48) from develop into main
Deploy Production / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Reviewed-on: #48
2026-03-26 14:49:47 +01:00
Lars ac4c6760d7 Merge pull request 'globaler Filter für Qualitätsgates von Trainings' (#41) from develop into main
Deploy Production / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 13s
Reviewed-on: #41
2026-03-24 08:44:22 +01:00
Lars 5a6a140dfd Merge pull request 'Bugfixes: Vitals Import (German columns + decimal values)' (#23) from develop into main
Deploy Production / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
2026-03-23 16:52:27 +01:00
Lars 931012c16b Merge pull request 'v9d Phase 2d: Vitals Module Refactoring (Baseline + Blood Pressure)' (#22) from develop into main
Deploy Production / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
2026-03-23 16:27:03 +01:00
Lars 03f4b871a9 Merge pull request 'Production Release: RestDays Widget + Trainingstyp Fix' (#16) from develop into main
Deploy Production / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Merge pull request #16: Production Release
2026-03-23 09:24:17 +01:00
Lars 601fc80178 Merge pull request 'WP 9c Phase 1' (#12) from develop into main
Deploy Production / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Reviewed-on: #12
2026-03-22 14:14:34 +01:00
Lars 3ff2a1bf45 Merge pull request 'Abschluss 9c' (#11) from develop into main
Deploy Production / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Reviewed-on: #11
2026-03-21 21:20:10 +01:00
Lars 51aa57f304 Merge pull request 'Final Feature 9c' (#10) from develop into main
Deploy Production / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Reviewed-on: #10
2026-03-21 12:41:41 +01:00
Lars ca4411f30f Merge pull request 'fix: update version string to v9c' (#9) from develop into main
Deploy Production / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Reviewed-on: #9
2026-03-21 09:00:55 +01:00
Lars b551365fb5 Merge pull request 'Membership-System und Bug Fixing (inkl. Nutrition)' (#8) from develop into main
Deploy Production / deploy (push) Failing after 1s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Reviewed-on: #8
2026-03-21 08:48:56 +01:00
Lars 272c123952 Merge pull request '9c Phase 2' (#6) from develop into main
Deploy Production / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Reviewed-on: #6
2026-03-19 14:59:25 +01:00
Lars 9387670a7b Merge pull request '9c datatables' (#5) from develop into main
Deploy Production / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Reviewed-on: #5
2026-03-19 13:00:31 +01:00
Lars d4a8401a6a Merge pull request 'Refactored Main.py' (#4) from develop into main
Deploy Production / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Reviewed-on: #4
2026-03-19 11:44:32 +01:00
Lars aaf88a6f12 Merge pull request 'fix: Migration-Fehler - meas_id Spalte in ai_insights' (#3) from develop into main
Deploy Production / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Reviewed-on: #3
2026-03-19 08:41:13 +01:00
Lars b789c1bd44 Merge pull request 'bug Fix Login' (#2) from develop into main
Deploy Production / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 13s
Reviewed-on: #2
2026-03-19 08:29:48 +01:00
Lars 5062aa8068 docker-compose.yml aktualisiert
Deploy Production / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
2026-03-19 08:21:12 +01:00
Lars 8a042589e7 docker-compose.yml aktualisiert
Deploy Production / deploy (push) Failing after 1s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 12s
2026-03-19 08:19:19 +01:00
Lars 3898b5ad45 docker-compose.yml aktualisiert
Deploy Production / deploy (push) Failing after 38s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
2026-03-19 08:06:02 +01:00
Lars 9d15336144 Merge pull request 'Version 9b' (#1) from develop into main
Deploy Production / deploy (push) Failing after 42s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Reviewed-on: #1
2026-03-19 08:04:01 +01:00
12 changed files with 35 additions and 613 deletions

No files matched your search

-111
View File
@@ -1,111 +0,0 @@
"""Derive lean_mass and fat_mass from weight_log + body_fat_pct for caliper entries."""
from datetime import date, datetime
from decimal import Decimal
from typing import Any, Dict, List, Optional, Tuple
from db import get_cursor, r2d
def as_date(d: Any) -> Optional[date]:
if d is None:
return None
if isinstance(d, datetime):
return d.date()
if isinstance(d, date):
return d
if isinstance(d, str) and len(d) >= 10:
return datetime.strptime(d[:10], "%Y-%m-%d").date()
return None
def _floaty(x: Any) -> float:
if isinstance(x, Decimal):
return float(x)
return float(x)
def load_weight_rows(conn: Any, profile_id: str) -> List[Dict[str, Any]]:
cur = get_cursor(conn)
cur.execute(
"SELECT date, weight FROM weight_log WHERE profile_id=%s ORDER BY date",
(profile_id,),
)
return [r2d(r) for r in cur.fetchall()]
def nearest_weight_kg(weight_rows: List[Dict[str, Any]], caliper_date: Any) -> Optional[float]:
td = as_date(caliper_date)
if td is None or not weight_rows:
return None
best: Optional[float] = None
best_delta: Optional[int] = None
for row in weight_rows:
wd = as_date(row.get("date"))
if wd is None:
continue
wraw = row.get("weight")
if wraw is None:
continue
delta = abs((wd - td).days)
if best_delta is None or delta < best_delta:
best_delta = delta
best = _floaty(wraw)
return best
def nearest_weight_kg_from_map(wlog: Dict[Any, Any], target_date: Any) -> Optional[float]:
if not wlog:
return None
td = as_date(target_date)
if td is None:
return None
best_w: Optional[float] = None
best_delta: Optional[int] = None
for wd, wval in wlog.items():
if wval is None:
continue
wdate = as_date(wd)
if wdate is None:
continue
delta = abs((wdate - td).days)
if best_delta is None or delta < best_delta:
best_delta = delta
best_w = _floaty(wval)
return best_w
def compute_lean_fat_kg(weight_kg: float, body_fat_pct: float) -> Tuple[float, float]:
lean = round(weight_kg - (weight_kg * body_fat_pct / 100.0), 2)
fat = round(weight_kg * body_fat_pct / 100.0, 2)
return lean, fat
def fill_caliper_body_comp(d: Dict[str, Any], conn: Any, profile_id: str) -> None:
"""Mutate caliper API payload (model_dump) before INSERT/UPDATE."""
bf = d.get("body_fat_pct")
if bf is None:
return
if d.get("lean_mass") is not None and d.get("fat_mass") is not None:
return
rows = load_weight_rows(conn, profile_id)
w = nearest_weight_kg(rows, d.get("date"))
if w is None:
return
lean, fat = compute_lean_fat_kg(w, _floaty(bf))
d["lean_mass"] = lean
d["fat_mass"] = fat
def enrich_caliper_row_for_response(row: Dict[str, Any], weight_rows: List[Dict[str, Any]]) -> None:
"""Fill missing lean_mass / fat_mass for API responses (read path)."""
bf = row.get("body_fat_pct")
if bf is None:
return
if row.get("lean_mass") is not None and row.get("fat_mass") is not None:
return
w = nearest_weight_kg(weight_rows, row.get("date"))
if w is None:
return
lean, fat = compute_lean_fat_kg(w, _floaty(bf))
row["lean_mass"] = lean
row["fat_mass"] = fat
-20
View File
@@ -1,20 +0,0 @@
"""Kleine Helfer für Focus-Area-Nutzungstypen (ohne Router-/Auth-Abhängigkeiten)."""
from __future__ import annotations
import json
from typing import Any, List
def coerce_usage_type_keys(raw: Any) -> List[str]:
"""json_agg / JSON-Spalte zu list[str] normalisieren."""
if raw is None:
return []
if isinstance(raw, list):
return [str(x) for x in raw]
if isinstance(raw, str):
try:
data = json.loads(raw)
return [str(x) for x in data] if isinstance(data, list) else []
except json.JSONDecodeError:
return []
return []
@@ -1,24 +0,0 @@
-- Migration 035: Backfill caliper lean_mass / fat_mass from nearest weight_log row
-- Date: 2026-04-06
UPDATE caliper_log c
SET
lean_mass = sub.lean_mass,
fat_mass = sub.fat_mass
FROM (
SELECT
c2.id,
round((wl.weight::numeric - (wl.weight::numeric * c2.body_fat_pct::numeric / 100.0))::numeric, 2) AS lean_mass,
round((wl.weight::numeric * c2.body_fat_pct::numeric / 100.0)::numeric, 2) AS fat_mass
FROM caliper_log c2
CROSS JOIN LATERAL (
SELECT w.weight
FROM weight_log w
WHERE w.profile_id = c2.profile_id
ORDER BY abs(w.date - c2.date) ASC
LIMIT 1
) wl
WHERE c2.body_fat_pct IS NOT NULL
AND (c2.lean_mass IS NULL OR c2.fat_mass IS NULL)
) sub
WHERE c.id = sub.id;
@@ -1,36 +0,0 @@
-- Migration 036: Focus Area — erlaubte Nutzungstypen (Referenz + M:N)
-- Date: 2026-04-06
-- Purpose: System-seeded usage types; optional Zuordnung pro Focus Area (kein Auto-Backfill)
-- Referenztabelle: feste, systemdefinierte Nutzungstypen
CREATE TABLE IF NOT EXISTS focus_area_usage_types (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
key VARCHAR(64) UNIQUE NOT NULL,
label_de VARCHAR(160),
sort_order INT NOT NULL DEFAULT 0,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
COMMENT ON TABLE focus_area_usage_types IS
'Systemdefinierte Nutzungsarten für Focus Areas (kein Admin-CRUD in v1)';
-- M:N: welche Nutzungstypen für eine Focus Area erlaubt sind (leer = noch nicht klassifiziert)
CREATE TABLE IF NOT EXISTS focus_area_definition_usage_types (
focus_area_id UUID NOT NULL REFERENCES focus_area_definitions(id) ON DELETE CASCADE,
usage_type_id UUID NOT NULL REFERENCES focus_area_usage_types(id) ON DELETE CASCADE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
PRIMARY KEY (focus_area_id, usage_type_id)
);
CREATE INDEX IF NOT EXISTS idx_fadut_focus_area ON focus_area_definition_usage_types(focus_area_id);
CREATE INDEX IF NOT EXISTS idx_fadut_usage_type ON focus_area_definition_usage_types(usage_type_id);
COMMENT ON TABLE focus_area_definition_usage_types IS
'Zuordnung Focus Area → erlaubte Nutzungstypen (kein automatisches Befüllen bestehender Areas)';
-- Seed: nur die drei Typen — keine Zeilen in der Junction-Tabelle
INSERT INTO focus_area_usage_types (key, label_de, sort_order) VALUES
('goal_priority', 'Ziele / Prioritäten', 1),
('expected_training_effect', 'Erwartetes Trainingseffekt-Profil', 2),
('concrete_training_contribution', 'Konkrete Trainings-Beiträge / Belastungsausprägung', 3)
ON CONFLICT (key) DO NOTHING;
+1 -8
View File
@@ -14,7 +14,6 @@ from auth import require_auth, check_feature_access, increment_feature_usage
from models import CaliperEntry
from routers.profiles import get_pid
from feature_logger import log_feature_usage
from caliper_composition import enrich_caliper_row_for_response, fill_caliper_body_comp, load_weight_rows
router = APIRouter(prefix="/api/caliper", tags=["caliper"])
logger = logging.getLogger(__name__)
@@ -28,11 +27,7 @@ def list_caliper(limit: int=100, x_profile_id: Optional[str]=Header(default=None
cur = get_cursor(conn)
cur.execute(
"SELECT * FROM caliper_log WHERE profile_id=%s ORDER BY date DESC LIMIT %s", (pid,limit))
rows = [r2d(r) for r in cur.fetchall()]
weight_rows = load_weight_rows(conn, pid)
for row in rows:
enrich_caliper_row_for_response(row, weight_rows)
return rows
return [r2d(r) for r in cur.fetchall()]
@router.post("")
@@ -60,7 +55,6 @@ def upsert_caliper(e: CaliperEntry, x_profile_id: Optional[str]=Header(default=N
cur.execute("SELECT id FROM caliper_log WHERE profile_id=%s AND date=%s", (pid,e.date))
ex = cur.fetchone()
d = e.model_dump()
fill_caliper_body_comp(d, conn, pid)
is_new_entry = not ex
if ex:
@@ -92,7 +86,6 @@ def update_caliper(eid: str, e: CaliperEntry, x_profile_id: Optional[str]=Header
pid = get_pid(x_profile_id)
with get_db() as conn:
d = e.model_dump()
fill_caliper_body_comp(d, conn, pid)
cur = get_cursor(conn)
cur.execute(f"UPDATE caliper_log SET {', '.join(f'{k}=%s' for k in d)} WHERE id=%s AND profile_id=%s",
list(d.values())+[eid,pid])
+4 -20
View File
@@ -21,7 +21,6 @@ from db import get_db, get_cursor, r2d
from auth import require_auth, check_feature_access, increment_feature_usage
from routers.profiles import get_pid
from feature_logger import log_feature_usage
from caliper_composition import enrich_caliper_row_for_response, load_weight_rows
router = APIRouter(prefix="/api/export", tags=["export"])
logger = logging.getLogger(__name__)
@@ -69,21 +68,10 @@ def export_csv(x_profile_id: Optional[str]=Header(default=None), session: dict=D
details = f"Taille:{float(r['c_waist'])}cm Bauch:{float(r['c_belly'])}cm Hüfte:{float(r['c_hip'])}cm"
writer.writerow(["Umfänge", r['date'], "", details])
# Caliper (Magermasse aus Gewicht + KF% nachziehen wenn in DB leer)
cur.execute(
"SELECT date, body_fat_pct, lean_mass, fat_mass FROM caliper_log WHERE profile_id=%s ORDER BY date",
(pid,),
)
cal_rows = [r2d(r) for r in cur.fetchall()]
weight_rows = load_weight_rows(conn, pid)
for r in cal_rows:
enrich_caliper_row_for_response(r, weight_rows)
if r.get("body_fat_pct") is None:
continue
bf = float(r["body_fat_pct"])
lm = r.get("lean_mass")
details = f"Magermasse:{float(lm)}kg" if lm is not None else ""
writer.writerow(["Caliper", r["date"], f"{bf}%", details])
# Caliper
cur.execute("SELECT date, body_fat_pct, lean_mass FROM caliper_log WHERE profile_id=%s ORDER BY date", (pid,))
for r in cur.fetchall():
writer.writerow(["Caliper", r['date'], f"{float(r['body_fat_pct'])}%", f"Magermasse:{float(r['lean_mass'])}kg"])
# Nutrition
cur.execute("SELECT date, kcal, protein_g FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,))
@@ -153,10 +141,6 @@ def export_json(x_profile_id: Optional[str]=Header(default=None), session: dict=
cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,))
data['insights'] = [r2d(r) for r in cur.fetchall()]
w_rows = [{'date': x['date'], 'weight': x['weight']} for x in data.get('weight', [])]
for row in data.get('caliper', []):
enrich_caliper_row_for_response(row, w_rows)
def decimal_handler(obj):
if isinstance(obj, Decimal):
return float(obj)
+3 -112
View File
@@ -3,11 +3,10 @@ Focus Areas Router
Manages dynamic focus area definitions and user preferences
"""
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel, Field
from pydantic import BaseModel
from typing import Optional, List
from db import get_db, get_cursor, r2d
from auth import require_auth
from focus_area_usage_helpers import coerce_usage_type_keys
router = APIRouter(prefix="/api/focus-areas", tags=["focus-areas"])
@@ -37,11 +36,6 @@ class UserFocusPreferences(BaseModel):
"""User's focus area weightings (dynamic)"""
preferences: dict # {focus_area_id: weight_pct}
class FocusAreaUsageTypesUpdate(BaseModel):
"""Replace all usage-type assignments for one focus area (admin)."""
usage_type_keys: List[str] = Field(default_factory=list)
# ============================================================================
# Focus Area Definitions (Admin)
# ============================================================================
@@ -64,27 +58,14 @@ def list_focus_area_definitions(
query = """
SELECT id, key, name_de, name_en, icon, description, category, is_active,
created_at, updated_at,
COALESCE(
(
SELECT json_agg(faut.key ORDER BY faut.sort_order, faut.key)
FROM focus_area_definition_usage_types fadut
JOIN focus_area_usage_types faut ON faut.id = fadut.usage_type_id
WHERE fadut.focus_area_id = focus_area_definitions.id
),
'[]'::json
) AS allowed_usage_type_keys
created_at, updated_at
FROM focus_area_definitions
WHERE is_active = true OR %s
ORDER BY category, name_de
"""
cur.execute(query, (include_inactive,))
areas = []
for row in cur.fetchall():
d = r2d(row)
d['allowed_usage_type_keys'] = coerce_usage_type_keys(d.get('allowed_usage_type_keys'))
areas.append(d)
areas = [r2d(row) for row in cur.fetchall()]
# Group by category
grouped = {}
@@ -94,10 +75,6 @@ def list_focus_area_definitions(
grouped[cat] = []
grouped[cat].append(area)
if session.get('role') != 'admin':
for area in areas:
area.pop('allowed_usage_type_keys', None)
return {
"areas": areas,
"grouped": grouped,
@@ -249,92 +226,6 @@ def delete_focus_area_definition(
return {"message": "Focus Area gelöscht"}
@router.get("/usage-types")
def list_focus_area_usage_types(session: dict = Depends(require_auth)):
"""
Liste aller systemdefinierten Nutzungstypen (Admin, Konfigurations-UI).
Keine freie Anlage neuer Typen über die API.
"""
if session.get('role') != 'admin':
raise HTTPException(status_code=403, detail="Admin-Rechte erforderlich")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT id, key, label_de, sort_order
FROM focus_area_usage_types
ORDER BY sort_order, key
""")
rows = [r2d(r) for r in cur.fetchall()]
return {"usage_types": rows, "total": len(rows)}
@router.put("/definitions/{area_id}/usage-types")
def replace_focus_area_usage_types(
area_id: str,
data: FocusAreaUsageTypesUpdate,
session: dict = Depends(require_auth),
):
"""
Ersetzt die Nutzungstyp-Zuweisungen einer Focus Area (Admin).
Leere Liste entfernt alle Zuordnungen. Unbekannte Keys → 400.
"""
if session.get('role') != 'admin':
raise HTTPException(status_code=403, detail="Admin-Rechte erforderlich")
keys = list(dict.fromkeys(data.usage_type_keys)) # dedupe, preserve order
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT id FROM focus_area_definitions WHERE id = %s",
(area_id,),
)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Focus Area nicht gefunden")
if not keys:
cur.execute(
"DELETE FROM focus_area_definition_usage_types WHERE focus_area_id = %s",
(area_id,),
)
return {"message": "Nutzungstyp-Zuweisungen entfernt", "usage_type_keys": []}
placeholders = ','.join(['%s'] * len(keys))
cur.execute(
f"""
SELECT id, key FROM focus_area_usage_types
WHERE key IN ({placeholders})
""",
keys,
)
found = {row['key']: row['id'] for row in cur.fetchall()}
missing = [k for k in keys if k not in found]
if missing:
raise HTTPException(
status_code=400,
detail=f"Unbekannte Nutzungstyp-Keys: {', '.join(missing)}",
)
cur.execute(
"DELETE FROM focus_area_definition_usage_types WHERE focus_area_id = %s",
(area_id,),
)
for k in keys:
ut_id = found[k]
cur.execute(
"""
INSERT INTO focus_area_definition_usage_types (focus_area_id, usage_type_id)
VALUES (%s, %s)
ON CONFLICT (focus_area_id, usage_type_id) DO NOTHING
""",
(area_id, ut_id),
)
return {"message": "Nutzungstyp-Zuweisungen aktualisiert", "usage_type_keys": keys}
# ============================================================================
# User Focus Preferences
# ============================================================================
+2 -7
View File
@@ -16,7 +16,6 @@ from db import get_db, get_cursor, r2d
from auth import require_auth, check_feature_access, increment_feature_usage
from routers.profiles import get_pid
from feature_logger import log_feature_usage
from caliper_composition import compute_lean_fat_kg, nearest_weight_kg_from_map
router = APIRouter(prefix="/api/nutrition", tags=["nutrition"])
logger = logging.getLogger(__name__)
@@ -203,12 +202,8 @@ def nutrition_correlations(x_profile_id: Optional[str]=Header(default=None), ses
if d in cal_by_date:
lm = cal_by_date[d].get('lean_mass')
bf = cal_by_date[d].get('body_fat_pct')
if bf is not None and lm is None:
wkg = nearest_weight_kg_from_map(wlog, d)
if wkg is not None:
lm, _fat = compute_lean_fat_kg(wkg, float(bf))
row['lean_mass'] = float(lm) if lm is not None else None
row['body_fat_pct'] = float(bf) if bf is not None else None
row['lean_mass']=float(lm) if lm is not None else None
row['body_fat_pct']=float(bf) if bf is not None else None
result.append(row)
return result
@@ -1,127 +0,0 @@
"""
Tests: Focus Area Nutzungstypen (Migration 036, Router-Helfer).
Ohne MITAI_INTEGRATION_DB=1 werden nur SQL-Datei und reine Python-Helfer geprüft.
Mit gesetztem Flag optional Verifikation gegen eine PostgreSQL-Instanz (Migration 036 angewendet).
"""
from __future__ import annotations
import os
import sys
import uuid
from pathlib import Path
import pytest
BACKEND_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(BACKEND_ROOT))
def test_migration_036_defines_schema_and_seeds_keys():
p = BACKEND_ROOT / "migrations" / "036_focus_area_usage_types.sql"
assert p.is_file(), f"expected {p}"
text = p.read_text(encoding="utf-8")
assert "CREATE TABLE IF NOT EXISTS focus_area_usage_types" in text
assert "CREATE TABLE IF NOT EXISTS focus_area_definition_usage_types" in text
for key in (
"goal_priority",
"expected_training_effect",
"concrete_training_contribution",
):
assert key in text
assert "ON CONFLICT (key) DO NOTHING" in text
# Explizit: kein automatisches Befüllen der M:N-Tabelle
assert "INSERT INTO focus_area_definition_usage_types" not in text
def test_coerce_usage_type_keys_normalizes_values():
from focus_area_usage_helpers import coerce_usage_type_keys
assert coerce_usage_type_keys(None) == []
assert coerce_usage_type_keys([]) == []
assert coerce_usage_type_keys(["goal_priority", "expected_training_effect"]) == [
"goal_priority",
"expected_training_effect",
]
assert coerce_usage_type_keys('["concrete_training_contribution"]') == [
"concrete_training_contribution"
]
@pytest.mark.skipif(
os.getenv("MITAI_INTEGRATION_DB") != "1",
reason="Set MITAI_INTEGRATION_DB=1 plus DB_* env to run DB checks (nur Dev/CI!)",
)
def test_integration_focus_area_usage_types_seeded_and_junction_writable():
"""Nur gegen Dev-DB ausführen. Nutzt temporäre focus_area_definitions-Zeile, keine bestehenden Daten."""
from db import get_db, get_cursor
from focus_area_usage_helpers import coerce_usage_type_keys
tmp_id = str(uuid.uuid4())
tmp_key = f"tmp_usage_{tmp_id[:8]}"
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT key FROM focus_area_usage_types
ORDER BY sort_order, key
"""
)
keys = [row["key"] for row in cur.fetchall()]
assert keys == [
"goal_priority",
"expected_training_effect",
"concrete_training_contribution",
]
cur.execute(
"""
INSERT INTO focus_area_definitions
(id, key, name_de, category, is_active)
VALUES (%s, %s, 'tmp_test_usage', 'custom', false)
""",
(tmp_id, tmp_key),
)
cur.execute(
"""
SELECT COALESCE(
(
SELECT json_agg(faut.key ORDER BY faut.sort_order, faut.key)
FROM focus_area_definition_usage_types fadut
JOIN focus_area_usage_types faut ON faut.id = fadut.usage_type_id
WHERE fadut.focus_area_id = %s
),
'[]'::json
) AS allowed_usage_type_keys
""",
(tmp_id,),
)
assert coerce_usage_type_keys(cur.fetchone()["allowed_usage_type_keys"]) == []
cur.execute(
"""
INSERT INTO focus_area_definition_usage_types (focus_area_id, usage_type_id)
SELECT %s, u.id FROM focus_area_usage_types u WHERE u.key = %s
""",
(tmp_id, "goal_priority"),
)
cur.execute(
"""
INSERT INTO focus_area_definition_usage_types (focus_area_id, usage_type_id)
SELECT %s, u.id FROM focus_area_usage_types u WHERE u.key = %s
""",
(tmp_id, "expected_training_effect"),
)
cur.execute(
"""
SELECT COUNT(*) AS n
FROM focus_area_definition_usage_types
WHERE focus_area_id = %s
""",
(tmp_id,),
)
assert cur.fetchone()["n"] == 2
cur.execute("DELETE FROM focus_area_definitions WHERE id = %s", (tmp_id,))
+13 -137
View File
@@ -14,19 +14,8 @@ const CATEGORIES = [
{ value: 'custom', label: 'Eigene' }
]
function groupAreasByCategory(areas) {
const grouped = {}
for (const area of areas) {
const cat = area.category || 'other'
if (!grouped[cat]) grouped[cat] = []
grouped[cat].push(area)
}
return grouped
}
export default function AdminFocusAreasPage() {
const [data, setData] = useState({ areas: [], grouped: {}, total: 0 })
const [usageTypesCatalog, setUsageTypesCatalog] = useState([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [showInactive, setShowInactive] = useState(false)
@@ -45,35 +34,11 @@ export default function AdminFocusAreasPage() {
loadData()
}, [showInactive])
useEffect(() => {
let cancelled = false
;(async () => {
try {
const r = await api.listFocusAreaUsageTypes()
if (!cancelled) setUsageTypesCatalog(r.usage_types || [])
} catch (e) {
console.error('usage-types catalog:', e)
if (!cancelled) setUsageTypesCatalog([])
}
})()
return () => { cancelled = true }
}, [])
const loadData = async () => {
try {
setLoading(true)
const result = await api.listFocusAreaDefinitions(showInactive)
const areas = (result.areas || []).map(a => ({
...a,
allowed_usage_type_keys: Array.isArray(a.allowed_usage_type_keys)
? a.allowed_usage_type_keys
: []
}))
setData({
areas,
grouped: groupAreasByCategory(areas),
total: result.total ?? areas.length
})
setData(result)
setError(null)
} catch (err) {
console.error('Failed to load focus areas:', err)
@@ -109,20 +74,14 @@ export default function AdminFocusAreasPage() {
const handleUpdate = async (id) => {
try {
const area = data.areas.find(a => a.id === id)
const usageKeys = Array.isArray(area.allowed_usage_type_keys)
? area.allowed_usage_type_keys
: []
await Promise.all([
api.updateFocusAreaDefinition(id, {
name_de: area.name_de,
name_en: area.name_en,
icon: area.icon,
description: area.description,
category: area.category,
is_active: area.is_active
}),
api.setFocusAreaUsageTypes(id, usageKeys)
])
await api.updateFocusAreaDefinition(id, {
name_de: area.name_de,
name_en: area.name_en,
icon: area.icon,
description: area.description,
category: area.category,
is_active: area.is_active
})
setEditingId(null)
await loadData()
} catch (err) {
@@ -154,25 +113,12 @@ export default function AdminFocusAreasPage() {
}
const updateField = (id, field, value) => {
setData(prev => {
const areas = prev.areas.map(a =>
setData(prev => ({
...prev,
areas: prev.areas.map(a =>
a.id === id ? { ...a, [field]: value } : a
)
return { ...prev, areas, grouped: groupAreasByCategory(areas), total: areas.length }
})
}
const toggleUsageTypeKey = (areaId, key, checked) => {
setData(prev => {
const areas = prev.areas.map(a => {
if (a.id !== areaId) return a
const cur = new Set(Array.isArray(a.allowed_usage_type_keys) ? a.allowed_usage_type_keys : [])
if (checked) cur.add(key)
else cur.delete(key)
return { ...a, allowed_usage_type_keys: [...cur] }
})
return { ...prev, areas, grouped: groupAreasByCategory(areas), total: areas.length }
})
}))
}
if (loading) {
@@ -418,45 +364,6 @@ export default function AdminFocusAreasPage() {
/>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 6 }}>
Erlaubte Nutzungstypen
</label>
{usageTypesCatalog.length === 0 ? (
<span style={{ fontSize: 12, color: 'var(--text3)' }}>
Kein Katalog geladen (Backend / Migration prüfen).
</span>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{usageTypesCatalog.map(ut => (
<label
key={ut.id}
style={{
fontSize: 13,
display: 'flex',
alignItems: 'flex-start',
gap: 8,
cursor: 'pointer'
}}
>
<input
type="checkbox"
style={{ marginTop: 3 }}
checked={(area.allowed_usage_type_keys || []).includes(ut.key)}
onChange={(e) =>
toggleUsageTypeKey(area.id, ut.key, e.target.checked)
}
/>
<span>
<span style={{ display: 'block' }}>{ut.label_de}</span>
<code style={{ fontSize: 11, color: 'var(--text3)' }}>{ut.key}</code>
</span>
</label>
))}
</div>
)}
</div>
<div style={{ display: 'flex', gap: 8 }}>
<button
className="btn-primary"
@@ -523,37 +430,6 @@ export default function AdminFocusAreasPage() {
{area.description}
</div>
)}
{(area.allowed_usage_type_keys || []).length > 0 && (
<div
style={{
fontSize: 12,
marginTop: 8,
display: 'flex',
flexWrap: 'wrap',
gap: 6
}}
>
{(area.allowed_usage_type_keys || []).map(k => {
const ut = usageTypesCatalog.find(x => x.key === k)
return (
<span
key={k}
style={{
padding: '2px 8px',
borderRadius: 6,
background: 'var(--surface2)',
border: '1px solid var(--border)',
color: 'var(--text2)'
}}
title={k}
>
{ut?.label_de || k}
</span>
)
})}
</div>
)}
</div>
<div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
+12 -8
View File
@@ -19,6 +19,7 @@ function emptyForm() {
function CaliperForm({ form, setForm, profile, onSave, onCancel, saveLabel='Speichern', saving=false, error=null, usage=null }) {
const sex = profile?.sex||'m'
const age = profile?.dob ? Math.floor((Date.now()-new Date(profile.dob))/(365.25*24*3600*1000)) : 30
const weight = form.weight || 80
const sfPoints = METHOD_POINTS[form.sf_method]?.[sex] || []
const sfVals = {}
sfPoints.forEach(k=>{ const v=form[`sf_${k}`]; if(v!==''&&v!=null) sfVals[k]=parseFloat(v) })
@@ -78,7 +79,7 @@ function CaliperForm({ form, setForm, profile, onSave, onCancel, saveLabel='Spei
<button
className="btn btn-primary"
style={{width:'100%', cursor: (usage && !usage.allowed) ? 'not-allowed' : 'pointer'}}
onClick={()=>onSave(bfPct)}
onClick={()=>onSave(bfPct, sex)}
disabled={saving || (usage && !usage.allowed)}
>
{(usage && !usage.allowed) ? '🔒 Limit erreicht' : saveLabel}
@@ -116,19 +117,22 @@ export default function CaliperScreen() {
loadUsage()
},[])
const buildPayload = (f, bfPct) => {
const buildPayload = (f, bfPct, sex) => {
const weight = profile?.weight || null
const payload = { date: f.date, sf_method: f.sf_method, notes: f.notes }
Object.entries(f).forEach(([k,v])=>{ if(k.startsWith('sf_')&&v!==''&&v!=null) payload[k]=parseFloat(v) })
if (bfPct != null) payload.body_fat_pct = bfPct
// lean_mass / fat_mass: Backend leitet aus nächstem weight_log zum Messdatum ab
if(bfPct!=null) {
payload.body_fat_pct = bfPct
// get latest weight from profile or skip lean/fat
}
return payload
}
const handleSave = async (bfPct) => {
const handleSave = async (bfPct, sex) => {
setSaving(true)
setError(null)
try {
const payload = buildPayload(form, bfPct)
const payload = buildPayload(form, bfPct, sex)
await api.upsertCaliper(payload)
setSaved(true)
await load()
@@ -144,8 +148,8 @@ export default function CaliperScreen() {
}
}
const handleUpdate = async (bfPct) => {
const payload = buildPayload(editing, bfPct)
const handleUpdate = async (bfPct, sex) => {
const payload = buildPayload(editing, bfPct, sex)
await api.updateCaliper(editing.id, payload)
setEditing(null); await load()
}
-3
View File
@@ -375,9 +375,6 @@ export const api = {
getUserFocusPreferences: () => req('/focus-areas/user-preferences'),
updateUserFocusPreferences: (d) => req('/focus-areas/user-preferences', jput(d)),
getFocusAreaStats: () => req('/focus-areas/stats'),
listFocusAreaUsageTypes: () => req('/focus-areas/usage-types'),
setFocusAreaUsageTypes: (id, usageTypeKeys) =>
req(`/focus-areas/definitions/${id}/usage-types`, jput({ usage_type_keys: usageTypeKeys })),
// Chart Endpoints (Phase 0c - Phase 1: Nutrition + Recovery)
// Nutrition Charts (E1-E5)