feat: Add update functionality for training category and type parameters
Deploy Development / deploy (push) Successful in 50s
Build Test / pytest-backend (push) Successful in 8s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s

- Introduced new endpoints for updating training category and type parameters in the backend.
- Added corresponding update functions in the frontend API utility.
- Enhanced the Admin Activity Attribute Profiles page to support editing and saving changes for category and type parameters.
- Implemented state management for editing parameters and improved error handling during updates.
This commit is contained in:
Lars committed 2026-04-14 12:26:52 +02:00
1 parent cf7379b2f6
commit 196b6c5cf1
5 files changed
+971 -344

No files matched your search

+16 -6
View File
@@ -35,18 +35,18 @@ logger = logging.getLogger(__name__)
def list_activity(
limit: int = Query(200, ge=1, le=50_000),
days: Optional[int] = Query(None, ge=1, le=4000, description="Nur Einträge mit date >= HEUTE − days (Kalendertage)"),
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth),
):
"""Get activity entries for current profile. Optional *days* filter by calendar window (not the same as *limit*)."""
pid = get_pid(x_profile_id)
# Immer das Profil der gültigen Session (X-Profile-Id wird hier nicht verwendet).
pid = str(session["profile_id"])
with get_db() as conn:
cur = get_cursor(conn)
# Issue #31: Apply global quality filter (profile from DB = saved level)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
profile = r2d(cur.fetchone())
quality_filter = get_quality_filter_sql(profile)
quality_filter = get_quality_filter_sql(profile or {})
if days is not None:
cur.execute(
@@ -229,13 +229,23 @@ def get_activity_session(
@router.get("/stats")
def activity_stats(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
def activity_stats(session: dict = Depends(require_auth)):
"""Get activity statistics (last 30 entries)."""
pid = get_pid(x_profile_id)
pid = str(session["profile_id"])
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
profile = r2d(cur.fetchone())
quality_filter = get_quality_filter_sql(profile or {})
cur.execute(
"SELECT * FROM activity_log WHERE profile_id=%s ORDER BY date DESC LIMIT 30", (pid,))
f"""
SELECT * FROM activity_log
WHERE profile_id=%s {quality_filter}
ORDER BY date DESC
LIMIT 30
""",
(pid,),
)
rows = [r2d(r) for r in cur.fetchall()]
if not rows: return {"count":0,"total_kcal":0,"total_min":0,"by_type":{}}
total_kcal=sum(float(r.get('kcal_active') or 0) for r in rows)
@@ -30,6 +30,18 @@ class TypeParameterCreate(BaseModel):
ui_group: Optional[str] = Field(None, max_length=50)
class CategoryParameterUpdate(BaseModel):
sort_order: Optional[int] = None
required: Optional[bool] = None
ui_group: Optional[str] = Field(None, max_length=50)
class TypeParameterUpdate(BaseModel):
sort_order: Optional[int] = None
required: Optional[bool] = None
ui_group: Optional[str] = Field(None, max_length=50)
@router.get("/training-category-parameters")
def admin_list_category_parameters(
category: Optional[str] = Query(None, description="Filter: training_types.category"),
@@ -91,6 +103,41 @@ def admin_add_category_parameter(
return {"id": new_id}
@router.put("/training-category-parameters/{link_id}")
def admin_update_category_parameter(
link_id: int,
body: CategoryParameterUpdate,
session: dict = Depends(require_admin),
):
patch = body.model_dump(exclude_unset=True)
if not patch:
raise HTTPException(400, "Keine Felder zum Aktualisieren")
cols: list[str] = []
vals: list = []
if "sort_order" in patch:
cols.append("sort_order = %s")
vals.append(patch["sort_order"])
if "required" in patch:
cols.append("required = %s")
vals.append(patch["required"])
if "ui_group" in patch:
cols.append("ui_group = %s")
vals.append(patch["ui_group"].strip() if patch["ui_group"] else None)
if not cols:
raise HTTPException(400, "Keine Felder zum Aktualisieren")
vals.append(link_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
f"UPDATE training_category_parameter SET {', '.join(cols)} WHERE id = %s RETURNING id",
vals,
)
if not cur.fetchone():
raise HTTPException(404, "Eintrag nicht gefunden")
conn.commit()
return {"ok": True, "id": link_id}
@router.delete("/training-category-parameters/{link_id}")
def admin_delete_category_parameter(
link_id: int,
@@ -167,6 +214,41 @@ def admin_add_type_parameter(
return {"id": new_id}
@router.put("/training-type-parameters/{link_id}")
def admin_update_type_parameter(
link_id: int,
body: TypeParameterUpdate,
session: dict = Depends(require_admin),
):
patch = body.model_dump(exclude_unset=True)
if not patch:
raise HTTPException(400, "Keine Felder zum Aktualisieren")
cols: list[str] = []
vals: list = []
if "sort_order" in patch:
cols.append("sort_order = %s")
vals.append(patch["sort_order"])
if "required" in patch:
cols.append("required = %s")
vals.append(patch["required"])
if "ui_group" in patch:
cols.append("ui_group = %s")
vals.append(patch["ui_group"].strip() if patch["ui_group"] else None)
if not cols:
raise HTTPException(400, "Keine Felder zum Aktualisieren")
vals.append(link_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
f"UPDATE training_type_parameter SET {', '.join(cols)} WHERE id = %s RETURNING id",
vals,
)
if not cur.fetchone():
raise HTTPException(404, "Eintrag nicht gefunden")
conn.commit()
return {"ok": True, "id": link_id}
@router.delete("/training-type-parameters/{link_id}")
def admin_delete_type_parameter(
link_id: int,