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
+229
-7
@@ -1,18 +1,22 @@
|
||||
"""
|
||||
Goal Utilities - Abstraction Layer for Focus Weights
|
||||
Goal Utilities - Abstraction Layer for Focus Weights & Universal Value Fetcher
|
||||
|
||||
This module provides an abstraction layer between goal modes and focus weights.
|
||||
This allows Phase 0b placeholders to work with the current simple goal_mode system,
|
||||
while enabling future v2.0 redesign (focus_areas table) without rewriting 120+ placeholders.
|
||||
This module provides:
|
||||
1. Abstraction layer between goal modes and focus weights (Phase 1)
|
||||
2. Universal value fetcher for dynamic goal types (Phase 1.5)
|
||||
|
||||
Version History:
|
||||
- V1 (current): Maps goal_mode to predefined weights
|
||||
- V1 (Phase 1): Maps goal_mode to predefined weights
|
||||
- V1.5 (Phase 1.5): Universal value fetcher for DB-registry goal types
|
||||
- V2 (future): Reads from focus_areas table with custom user weights
|
||||
|
||||
Part of Phase 1: Quick Fixes + Abstraction Layer
|
||||
Part of Phase 1 + Phase 1.5: Flexible Goal System
|
||||
"""
|
||||
|
||||
from typing import Dict
|
||||
from typing import Dict, Optional, Any
|
||||
from datetime import date, timedelta
|
||||
from decimal import Decimal
|
||||
import json
|
||||
from db import get_cursor
|
||||
|
||||
|
||||
@@ -158,6 +162,224 @@ def get_focus_description(focus_area: str) -> str:
|
||||
return descriptions.get(focus_area, focus_area)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Phase 1.5: Universal Value Fetcher for Dynamic Goal Types
|
||||
# ============================================================================
|
||||
|
||||
def get_goal_type_config(conn, type_key: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Get goal type configuration from database registry.
|
||||
|
||||
Args:
|
||||
conn: Database connection
|
||||
type_key: Goal type key (e.g., 'weight', 'meditation_minutes')
|
||||
|
||||
Returns:
|
||||
Dict with config or None if not found/inactive
|
||||
"""
|
||||
cur = get_cursor(conn)
|
||||
|
||||
cur.execute("""
|
||||
SELECT type_key, source_table, source_column, aggregation_method,
|
||||
calculation_formula, label_de, unit, icon, category
|
||||
FROM goal_type_definitions
|
||||
WHERE type_key = %s AND is_active = true
|
||||
LIMIT 1
|
||||
""", (type_key,))
|
||||
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def get_current_value_for_goal(conn, profile_id: str, goal_type: str) -> Optional[float]:
|
||||
"""
|
||||
Universal value fetcher for any goal type.
|
||||
|
||||
Reads configuration from goal_type_definitions table and executes
|
||||
appropriate query based on aggregation_method or calculation_formula.
|
||||
|
||||
Args:
|
||||
conn: Database connection
|
||||
profile_id: User's profile ID
|
||||
goal_type: Goal type key (e.g., 'weight', 'meditation_minutes')
|
||||
|
||||
Returns:
|
||||
Current value as float or None if not available
|
||||
"""
|
||||
config = get_goal_type_config(conn, goal_type)
|
||||
|
||||
if not config:
|
||||
print(f"[WARNING] Goal type '{goal_type}' not found or inactive")
|
||||
return None
|
||||
|
||||
# Complex calculation (e.g., lean_mass)
|
||||
if config['calculation_formula']:
|
||||
return _execute_calculation_formula(conn, profile_id, config['calculation_formula'])
|
||||
|
||||
# Simple aggregation
|
||||
return _fetch_by_aggregation_method(
|
||||
conn,
|
||||
profile_id,
|
||||
config['source_table'],
|
||||
config['source_column'],
|
||||
config['aggregation_method']
|
||||
)
|
||||
|
||||
|
||||
def _fetch_by_aggregation_method(
|
||||
conn,
|
||||
profile_id: str,
|
||||
table: str,
|
||||
column: str,
|
||||
method: str
|
||||
) -> Optional[float]:
|
||||
"""
|
||||
Fetch value using specified aggregation method.
|
||||
|
||||
Supported methods:
|
||||
- latest: Most recent value
|
||||
- avg_7d: 7-day average
|
||||
- avg_30d: 30-day average
|
||||
- sum_30d: 30-day sum
|
||||
- count_7d: Count of entries in last 7 days
|
||||
- count_30d: Count of entries in last 30 days
|
||||
- min_30d: Minimum value in last 30 days
|
||||
- max_30d: Maximum value in last 30 days
|
||||
"""
|
||||
cur = get_cursor(conn)
|
||||
|
||||
if method == 'latest':
|
||||
cur.execute(f"""
|
||||
SELECT {column} FROM {table}
|
||||
WHERE profile_id = %s AND {column} IS NOT NULL
|
||||
ORDER BY date DESC LIMIT 1
|
||||
""", (profile_id,))
|
||||
row = cur.fetchone()
|
||||
return float(row[column]) if row else None
|
||||
|
||||
elif method == 'avg_7d':
|
||||
days_ago = date.today() - timedelta(days=7)
|
||||
cur.execute(f"""
|
||||
SELECT AVG({column}) as avg_value FROM {table}
|
||||
WHERE profile_id = %s AND date >= %s AND {column} IS NOT NULL
|
||||
""", (profile_id, days_ago))
|
||||
row = cur.fetchone()
|
||||
return float(row['avg_value']) if row and row['avg_value'] is not None else None
|
||||
|
||||
elif method == 'avg_30d':
|
||||
days_ago = date.today() - timedelta(days=30)
|
||||
cur.execute(f"""
|
||||
SELECT AVG({column}) as avg_value FROM {table}
|
||||
WHERE profile_id = %s AND date >= %s AND {column} IS NOT NULL
|
||||
""", (profile_id, days_ago))
|
||||
row = cur.fetchone()
|
||||
return float(row['avg_value']) if row and row['avg_value'] is not None else None
|
||||
|
||||
elif method == 'sum_30d':
|
||||
days_ago = date.today() - timedelta(days=30)
|
||||
cur.execute(f"""
|
||||
SELECT SUM({column}) as sum_value FROM {table}
|
||||
WHERE profile_id = %s AND date >= %s AND {column} IS NOT NULL
|
||||
""", (profile_id, days_ago))
|
||||
row = cur.fetchone()
|
||||
return float(row['sum_value']) if row and row['sum_value'] is not None else None
|
||||
|
||||
elif method == 'count_7d':
|
||||
days_ago = date.today() - timedelta(days=7)
|
||||
cur.execute(f"""
|
||||
SELECT COUNT(*) as count_value FROM {table}
|
||||
WHERE profile_id = %s AND date >= %s
|
||||
""", (profile_id, days_ago))
|
||||
row = cur.fetchone()
|
||||
return float(row['count_value']) if row else 0.0
|
||||
|
||||
elif method == 'count_30d':
|
||||
days_ago = date.today() - timedelta(days=30)
|
||||
cur.execute(f"""
|
||||
SELECT COUNT(*) as count_value FROM {table}
|
||||
WHERE profile_id = %s AND date >= %s
|
||||
""", (profile_id, days_ago))
|
||||
row = cur.fetchone()
|
||||
return float(row['count_value']) if row else 0.0
|
||||
|
||||
elif method == 'min_30d':
|
||||
days_ago = date.today() - timedelta(days=30)
|
||||
cur.execute(f"""
|
||||
SELECT MIN({column}) as min_value FROM {table}
|
||||
WHERE profile_id = %s AND date >= %s AND {column} IS NOT NULL
|
||||
""", (profile_id, days_ago))
|
||||
row = cur.fetchone()
|
||||
return float(row['min_value']) if row and row['min_value'] is not None else None
|
||||
|
||||
elif method == 'max_30d':
|
||||
days_ago = date.today() - timedelta(days=30)
|
||||
cur.execute(f"""
|
||||
SELECT MAX({column}) as max_value FROM {table}
|
||||
WHERE profile_id = %s AND date >= %s AND {column} IS NOT NULL
|
||||
""", (profile_id, days_ago))
|
||||
row = cur.fetchone()
|
||||
return float(row['max_value']) if row and row['max_value'] is not None else None
|
||||
|
||||
else:
|
||||
print(f"[WARNING] Unknown aggregation method: {method}")
|
||||
return None
|
||||
|
||||
|
||||
def _execute_calculation_formula(conn, profile_id: str, formula_json: str) -> Optional[float]:
|
||||
"""
|
||||
Execute complex calculation formula.
|
||||
|
||||
Currently supports:
|
||||
- lean_mass: weight - (weight * body_fat_pct / 100)
|
||||
|
||||
Future: Parse JSON formula and execute dynamically.
|
||||
|
||||
Args:
|
||||
conn: Database connection
|
||||
profile_id: User's profile ID
|
||||
formula_json: JSON string with calculation config
|
||||
|
||||
Returns:
|
||||
Calculated value or None
|
||||
"""
|
||||
try:
|
||||
formula = json.loads(formula_json)
|
||||
calc_type = formula.get('type')
|
||||
|
||||
if calc_type == 'lean_mass':
|
||||
# Get dependencies
|
||||
cur = get_cursor(conn)
|
||||
|
||||
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:
|
||||
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)
|
||||
|
||||
return None
|
||||
|
||||
else:
|
||||
print(f"[WARNING] Unknown calculation type: {calc_type}")
|
||||
return None
|
||||
|
||||
except (json.JSONDecodeError, KeyError, ValueError, TypeError) as e:
|
||||
print(f"[ERROR] Formula execution failed: {e}, formula={formula_json}")
|
||||
return None
|
||||
|
||||
|
||||
# Future V2 Implementation (commented out for reference):
|
||||
"""
|
||||
def get_focus_weights_v2(conn, profile_id: str) -> Dict[str, float]:
|
||||
|
||||
Reference in new issue
Block a user