feat: Phase 1.5 - Flexible Goal System (DB-Registry) Part 1/2
KRITISCHE ARCHITEKTUR-ÄNDERUNG vor Phase 0b: Ermöglicht dynamische Goal Types ohne Code-Änderungen. Backend: - Migration 024: goal_type_definitions Tabelle → 8 existierende Typen als Seed-Data migriert → Flexible Schema: source_table, aggregation_method, calculation_formula → System vs. Custom Types (is_system flag) - goal_utils.py: Universal Value Fetcher → get_current_value_for_goal() ersetzt hardcoded if/elif chain → Unterstützt: latest, avg_7d, avg_30d, sum_30d, count_7d, etc. → Komplexe Formeln (lean_mass) via calculation_formula JSON - goals.py: CRUD API für Goal Type Definitions → GET /goals/goal-types (public) → POST/PUT/DELETE /goals/goal-types (admin-only) → Schutz für System-Types (nicht löschbar) - goals.py: _get_current_value_for_goal_type() delegiert zu Universal Fetcher Frontend: - api.js: 4 neue Funktionen (listGoalTypeDefinitions, create, update, delete) Dokumentation: - TODO_GOAL_SYSTEM.md: Phase 1.5 hinzugefügt, Roadmap aktualisiert Part 2/2 (nächster Commit): - Frontend: Dynamic Goal Types Dropdown - Admin UI: Goal Type Management Page - Testing Warum JETZT (vor Phase 0b)? - Phase 0b Platzhalter (120+) nutzen Goals für Score-Berechnungen - Flexible Goals → automatisch in Platzhaltern verfügbar - Später umbauen = Doppelarbeit (alle Platzhalter anpassen) Zukünftige Custom Goals möglich: - 🧘 Meditation (min/Tag) - 📅 Trainingshäufigkeit (x/Woche) - 📊 Planabweichung (%) - 🎯 Ritual-Adherence (%) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
27a8af7008
commit
65ee5f898f
5 files changed
+835
-81
No files matched your search
+297
-68
@@ -17,6 +17,7 @@ from decimal import Decimal
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth
|
||||
from goal_utils import get_current_value_for_goal
|
||||
|
||||
router = APIRouter(prefix="/api/goals", tags=["goals"])
|
||||
|
||||
@@ -62,6 +63,34 @@ class FitnessTestCreate(BaseModel):
|
||||
test_date: date
|
||||
test_conditions: Optional[str] = None
|
||||
|
||||
class GoalTypeCreate(BaseModel):
|
||||
"""Create custom goal type definition"""
|
||||
type_key: str
|
||||
label_de: str
|
||||
label_en: Optional[str] = None
|
||||
unit: str
|
||||
icon: Optional[str] = None
|
||||
category: Optional[str] = 'custom'
|
||||
source_table: Optional[str] = None
|
||||
source_column: Optional[str] = None
|
||||
aggregation_method: Optional[str] = 'latest'
|
||||
calculation_formula: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
class GoalTypeUpdate(BaseModel):
|
||||
"""Update goal type definition"""
|
||||
label_de: Optional[str] = None
|
||||
label_en: Optional[str] = None
|
||||
unit: Optional[str] = None
|
||||
icon: Optional[str] = None
|
||||
category: Optional[str] = None
|
||||
source_table: Optional[str] = None
|
||||
source_column: Optional[str] = None
|
||||
aggregation_method: Optional[str] = None
|
||||
calculation_formula: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
# ============================================================================
|
||||
# Strategic Layer: Goal Modes
|
||||
# ============================================================================
|
||||
@@ -405,77 +434,22 @@ def create_fitness_test(data: FitnessTestCreate, session: dict = Depends(require
|
||||
# ============================================================================
|
||||
|
||||
def _get_current_value_for_goal_type(conn, profile_id: str, goal_type: str) -> Optional[float]:
|
||||
"""Get current value for a goal type from latest data"""
|
||||
cur = get_cursor(conn)
|
||||
"""
|
||||
Get current value for a goal type.
|
||||
|
||||
if goal_type == 'weight':
|
||||
cur.execute("""
|
||||
SELECT weight FROM weight_log
|
||||
WHERE profile_id = %s
|
||||
ORDER BY date DESC LIMIT 1
|
||||
""", (profile_id,))
|
||||
row = cur.fetchone()
|
||||
return float(row['weight']) if row else None
|
||||
DEPRECATED: This function now delegates to the universal fetcher in goal_utils.py.
|
||||
Phase 1.5: All goal types are now defined in goal_type_definitions table.
|
||||
|
||||
elif goal_type == 'body_fat':
|
||||
cur.execute("""
|
||||
SELECT body_fat_pct FROM caliper_log
|
||||
WHERE profile_id = %s
|
||||
ORDER BY date DESC LIMIT 1
|
||||
""", (profile_id,))
|
||||
row = cur.fetchone()
|
||||
return float(row['body_fat_pct']) if row else None
|
||||
Args:
|
||||
conn: Database connection
|
||||
profile_id: User's profile ID
|
||||
goal_type: Goal type key (e.g., 'weight', 'meditation_minutes')
|
||||
|
||||
elif goal_type == 'lean_mass':
|
||||
# Calculate lean mass: weight - (weight * body_fat_pct / 100)
|
||||
# Need both latest weight and latest body fat percentage
|
||||
cur.execute("""
|
||||
SELECT weight FROM weight_log
|
||||
WHERE profile_id = %s
|
||||
ORDER BY date DESC LIMIT 1
|
||||
""", (profile_id,))
|
||||
weight_row = cur.fetchone()
|
||||
|
||||
cur.execute("""
|
||||
SELECT body_fat_pct FROM caliper_log
|
||||
WHERE profile_id = %s
|
||||
ORDER BY date DESC LIMIT 1
|
||||
""", (profile_id,))
|
||||
bf_row = cur.fetchone()
|
||||
|
||||
if weight_row and bf_row:
|
||||
try:
|
||||
weight = float(weight_row['weight'])
|
||||
bf_pct = float(bf_row['body_fat_pct'])
|
||||
lean_mass = weight - (weight * bf_pct / 100.0)
|
||||
return round(lean_mass, 2)
|
||||
except (ValueError, TypeError) as e:
|
||||
print(f"[DEBUG] lean_mass calculation error: {e}, weight={weight_row}, bf={bf_row}")
|
||||
return None
|
||||
|
||||
# Debug: Log why calculation failed
|
||||
print(f"[DEBUG] lean_mass calc failed - weight_row: {weight_row is not None}, bf_row: {bf_row is not None}")
|
||||
return None
|
||||
|
||||
elif goal_type == 'vo2max':
|
||||
cur.execute("""
|
||||
SELECT vo2_max FROM vitals_baseline
|
||||
WHERE profile_id = %s AND vo2_max IS NOT NULL
|
||||
ORDER BY date DESC LIMIT 1
|
||||
""", (profile_id,))
|
||||
row = cur.fetchone()
|
||||
return float(row['vo2_max']) if row else None
|
||||
|
||||
elif goal_type == 'rhr':
|
||||
cur.execute("""
|
||||
SELECT resting_hr FROM vitals_baseline
|
||||
WHERE profile_id = %s AND resting_hr IS NOT NULL
|
||||
ORDER BY date DESC LIMIT 1
|
||||
""", (profile_id,))
|
||||
row = cur.fetchone()
|
||||
return float(row['resting_hr']) if row else None
|
||||
|
||||
return None
|
||||
Returns:
|
||||
Current value or None
|
||||
"""
|
||||
# Delegate to universal fetcher (Phase 1.5)
|
||||
return get_current_value_for_goal(conn, profile_id, goal_type)
|
||||
|
||||
def _update_goal_progress(conn, profile_id: str, goal: dict):
|
||||
"""Update goal progress (modifies goal dict in-place)"""
|
||||
@@ -513,3 +487,258 @@ def _calculate_norm_category(test_type: str, value: float, unit: str) -> Optiona
|
||||
"""
|
||||
# Placeholder - should use proper norm tables
|
||||
return None
|
||||
|
||||
# ============================================================================
|
||||
# Goal Type Definitions (Phase 1.5 - Flexible Goal System)
|
||||
# ============================================================================
|
||||
|
||||
@router.get("/goal-types")
|
||||
def list_goal_type_definitions(session: dict = Depends(require_auth)):
|
||||
"""
|
||||
Get all active goal type definitions.
|
||||
|
||||
Public endpoint - returns all available goal types for dropdown.
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT id, type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
calculation_formula, description, is_system,
|
||||
created_at, updated_at
|
||||
FROM goal_type_definitions
|
||||
WHERE is_active = true
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN is_system = true THEN 0
|
||||
ELSE 1
|
||||
END,
|
||||
label_de
|
||||
""")
|
||||
|
||||
return [r2d(row) for row in cur.fetchall()]
|
||||
|
||||
@router.post("/goal-types")
|
||||
def create_goal_type_definition(
|
||||
data: GoalTypeCreate,
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Create custom goal type definition.
|
||||
|
||||
Admin-only endpoint for creating new goal types.
|
||||
Users with admin role can define custom metrics.
|
||||
"""
|
||||
pid = session['profile_id']
|
||||
|
||||
# Check admin role
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
|
||||
profile = cur.fetchone()
|
||||
|
||||
if not profile or profile['role'] != 'admin':
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Admin-Zugriff erforderlich"
|
||||
)
|
||||
|
||||
# Validate type_key is unique
|
||||
cur.execute(
|
||||
"SELECT id FROM goal_type_definitions WHERE type_key = %s",
|
||||
(data.type_key,)
|
||||
)
|
||||
if cur.fetchone():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Goal Type '{data.type_key}' existiert bereits"
|
||||
)
|
||||
|
||||
# Insert new goal type
|
||||
cur.execute("""
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
calculation_formula, description, is_active, is_system,
|
||||
created_by, updated_by
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""", (
|
||||
data.type_key, data.label_de, data.label_en, data.unit, data.icon,
|
||||
data.category, data.source_table, data.source_column,
|
||||
data.aggregation_method, data.calculation_formula, data.description,
|
||||
True, False, # is_active=True, is_system=False
|
||||
pid, pid
|
||||
))
|
||||
|
||||
goal_type_id = cur.fetchone()['id']
|
||||
|
||||
return {
|
||||
"id": goal_type_id,
|
||||
"message": f"Goal Type '{data.label_de}' erstellt"
|
||||
}
|
||||
|
||||
@router.put("/goal-types/{goal_type_id}")
|
||||
def update_goal_type_definition(
|
||||
goal_type_id: str,
|
||||
data: GoalTypeUpdate,
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Update goal type definition.
|
||||
|
||||
Admin-only. System goal types can be updated but not deleted.
|
||||
"""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check admin role
|
||||
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
|
||||
profile = cur.fetchone()
|
||||
|
||||
if not profile or profile['role'] != 'admin':
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Admin-Zugriff erforderlich"
|
||||
)
|
||||
|
||||
# Check goal type exists
|
||||
cur.execute(
|
||||
"SELECT id FROM goal_type_definitions WHERE id = %s",
|
||||
(goal_type_id,)
|
||||
)
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(status_code=404, detail="Goal Type nicht gefunden")
|
||||
|
||||
# Build update query
|
||||
updates = []
|
||||
params = []
|
||||
|
||||
if data.label_de is not None:
|
||||
updates.append("label_de = %s")
|
||||
params.append(data.label_de)
|
||||
|
||||
if data.label_en is not None:
|
||||
updates.append("label_en = %s")
|
||||
params.append(data.label_en)
|
||||
|
||||
if data.unit is not None:
|
||||
updates.append("unit = %s")
|
||||
params.append(data.unit)
|
||||
|
||||
if data.icon is not None:
|
||||
updates.append("icon = %s")
|
||||
params.append(data.icon)
|
||||
|
||||
if data.category is not None:
|
||||
updates.append("category = %s")
|
||||
params.append(data.category)
|
||||
|
||||
if data.source_table is not None:
|
||||
updates.append("source_table = %s")
|
||||
params.append(data.source_table)
|
||||
|
||||
if data.source_column is not None:
|
||||
updates.append("source_column = %s")
|
||||
params.append(data.source_column)
|
||||
|
||||
if data.aggregation_method is not None:
|
||||
updates.append("aggregation_method = %s")
|
||||
params.append(data.aggregation_method)
|
||||
|
||||
if data.calculation_formula is not None:
|
||||
updates.append("calculation_formula = %s")
|
||||
params.append(data.calculation_formula)
|
||||
|
||||
if data.description is not None:
|
||||
updates.append("description = %s")
|
||||
params.append(data.description)
|
||||
|
||||
if data.is_active is not None:
|
||||
updates.append("is_active = %s")
|
||||
params.append(data.is_active)
|
||||
|
||||
if not updates:
|
||||
raise HTTPException(status_code=400, detail="Keine Änderungen angegeben")
|
||||
|
||||
updates.append("updated_at = NOW()")
|
||||
updates.append("updated_by = %s")
|
||||
params.append(pid)
|
||||
params.append(goal_type_id)
|
||||
|
||||
cur.execute(
|
||||
f"UPDATE goal_type_definitions SET {', '.join(updates)} WHERE id = %s",
|
||||
tuple(params)
|
||||
)
|
||||
|
||||
return {"message": "Goal Type aktualisiert"}
|
||||
|
||||
@router.delete("/goal-types/{goal_type_id}")
|
||||
def delete_goal_type_definition(
|
||||
goal_type_id: str,
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Delete (deactivate) goal type definition.
|
||||
|
||||
Admin-only. System goal types cannot be deleted, only deactivated.
|
||||
Custom goal types can be fully deleted if no goals reference them.
|
||||
"""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check admin role
|
||||
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
|
||||
profile = cur.fetchone()
|
||||
|
||||
if not profile or profile['role'] != 'admin':
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Admin-Zugriff erforderlich"
|
||||
)
|
||||
|
||||
# Get goal type info
|
||||
cur.execute(
|
||||
"SELECT id, type_key, is_system FROM goal_type_definitions WHERE id = %s",
|
||||
(goal_type_id,)
|
||||
)
|
||||
goal_type = cur.fetchone()
|
||||
|
||||
if not goal_type:
|
||||
raise HTTPException(status_code=404, detail="Goal Type nicht gefunden")
|
||||
|
||||
# Check if any goals use this type
|
||||
cur.execute(
|
||||
"SELECT COUNT(*) as count FROM goals WHERE goal_type = %s",
|
||||
(goal_type['type_key'],)
|
||||
)
|
||||
count = cur.fetchone()['count']
|
||||
|
||||
if count > 0:
|
||||
# Deactivate instead of delete
|
||||
cur.execute(
|
||||
"UPDATE goal_type_definitions SET is_active = false WHERE id = %s",
|
||||
(goal_type_id,)
|
||||
)
|
||||
return {
|
||||
"message": f"Goal Type deaktiviert ({count} Ziele nutzen diesen Typ)"
|
||||
}
|
||||
else:
|
||||
if goal_type['is_system']:
|
||||
# System types: only deactivate
|
||||
cur.execute(
|
||||
"UPDATE goal_type_definitions SET is_active = false WHERE id = %s",
|
||||
(goal_type_id,)
|
||||
)
|
||||
return {"message": "System Goal Type deaktiviert"}
|
||||
else:
|
||||
# Custom types: delete
|
||||
cur.execute(
|
||||
"DELETE FROM goal_type_definitions WHERE id = %s",
|
||||
(goal_type_id,)
|
||||
)
|
||||
return {"message": "Goal Type gelöscht"}
|
||||
Reference in new issue
Block a user