Compare commits
51
Commits
8be87bfdfb
..
V0.9g
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d22e7e8af | ||
|
|
0a1da37197 | ||
|
|
495f218f9a | ||
|
|
fac8820208 | ||
|
|
217990d417 | ||
|
|
1960ae4924 | ||
|
|
bcb867da69 | ||
|
|
398c645a98 | ||
|
|
7db98a4fa6 | ||
|
|
ce37afb2bb | ||
|
|
db90f397e8 | ||
|
|
498ad7a47f | ||
|
|
9e95fd8416 | ||
|
|
ca4f722b47 | ||
|
|
1c00238414 | ||
|
|
448d19b840 | ||
|
|
caebc37da0 | ||
|
|
6a3a782bff | ||
|
|
2f51b26418 | ||
|
|
92cc309489 | ||
|
|
1fdf91cb50 | ||
|
|
80d57918ae | ||
|
|
d97925d5a1 | ||
|
|
4a11d20c4d | ||
|
|
2303c04123 | ||
|
|
2c978bf948 | ||
|
|
210671059a | ||
|
|
1f4ee5021e | ||
|
|
1e758696fd | ||
|
|
a039a0fad3 | ||
|
|
b3cc588293 | ||
|
|
c9e4b6aa02 | ||
|
|
f46c367c27 | ||
|
|
ac4c6760d7 | ||
|
|
5a6a140dfd | ||
|
|
931012c16b | ||
|
|
03f4b871a9 | ||
|
|
601fc80178 | ||
|
|
3ff2a1bf45 | ||
|
|
51aa57f304 | ||
|
|
ca4411f30f | ||
|
|
b551365fb5 | ||
|
|
272c123952 | ||
|
|
9387670a7b | ||
|
|
d4a8401a6a | ||
|
|
aaf88a6f12 | ||
|
|
b789c1bd44 | ||
|
|
5062aa8068 | ||
|
|
8a042589e7 | ||
|
|
3898b5ad45 | ||
|
|
9d15336144 |
No files matched your search
@@ -78,7 +78,22 @@ frontend/src/
|
||||
|
||||
## Aktuelle Version: v9e+ (Phase 1 Goal System Fixes) 🎯 Ready for Phase 0b - 27.03.2026
|
||||
|
||||
### Letzte Updates (27.03.2026 - Phase 1 Fixes) 🆕
|
||||
### Letzte Updates (27.03.2026 - Phase 1 Complete) 🆕
|
||||
- ✅ **Custom Goals Page (Capture/Eigene Ziele):**
|
||||
- Neue Seite für tägliche Werterfassung individueller Ziele
|
||||
- Dedizierte UI für custom goals (ohne automatische Datenquelle)
|
||||
- Verhindert Verwechslung mit automatischem Tracking (Gewicht, Aktivität, etc.)
|
||||
- Clean UX: Zielauswahl → Schnellerfassung → Verlauf (letzte 5 Einträge)
|
||||
- Navigation: Capture Hub + direkter Link
|
||||
- ✅ **UX-Improvements Progress Modal:**
|
||||
- Volle Breite Eingabefelder, Labels als Überschriften, linksbündiger Text
|
||||
- Progress-Button nur bei custom goals sichtbar (source_table IS NULL)
|
||||
- ✅ **Architektur-Klarstellung:**
|
||||
- Analysis/Goals → Strategisch (Ziele definieren, Prioritäten setzen)
|
||||
- Capture/Custom Goals → Taktisch (tägliche Ist-Wert-Erfassung)
|
||||
- History → Auswertung (Zielerreichungs-Analysen)
|
||||
|
||||
### Updates (27.03.2026 - Phase 1 Fixes)
|
||||
- ✅ **Abstraction Layer:** goal_utils.py für zukunftssichere Phase 0b Platzhalter
|
||||
- ✅ **Primary Goal Toggle Fix:** is_primary Update funktioniert korrekt
|
||||
- ✅ **Lean Mass Berechnung:** Magermasse current_value wird berechnet
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Quick diagnostic: Check Migration 024 state
|
||||
|
||||
Run this inside the backend container:
|
||||
docker exec bodytrack-dev-backend-1 python check_migration_024.py
|
||||
"""
|
||||
|
||||
import psycopg2
|
||||
import os
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
# Database connection
|
||||
DB_HOST = os.getenv('DB_HOST', 'db')
|
||||
DB_PORT = os.getenv('DB_PORT', '5432')
|
||||
DB_NAME = os.getenv('DB_NAME', 'bodytrack')
|
||||
DB_USER = os.getenv('DB_USER', 'bodytrack')
|
||||
DB_PASS = os.getenv('DB_PASSWORD', '')
|
||||
|
||||
def main():
|
||||
print("=" * 70)
|
||||
print("Migration 024 Diagnostic")
|
||||
print("=" * 70)
|
||||
|
||||
# Connect to database
|
||||
conn = psycopg2.connect(
|
||||
host=DB_HOST,
|
||||
port=DB_PORT,
|
||||
dbname=DB_NAME,
|
||||
user=DB_USER,
|
||||
password=DB_PASS
|
||||
)
|
||||
cur = conn.cursor(cursor_factory=RealDictCursor)
|
||||
|
||||
# 1. Check if table exists
|
||||
print("\n1. Checking if goal_type_definitions table exists...")
|
||||
cur.execute("""
|
||||
SELECT EXISTS (
|
||||
SELECT FROM information_schema.tables
|
||||
WHERE table_name = 'goal_type_definitions'
|
||||
)
|
||||
""")
|
||||
exists = cur.fetchone()['exists']
|
||||
print(f" ✓ Table exists: {exists}")
|
||||
|
||||
if not exists:
|
||||
print("\n❌ TABLE DOES NOT EXIST - Migration 024 did not run!")
|
||||
print("\nRECOMMENDED ACTION:")
|
||||
print(" 1. Restart backend container: docker restart bodytrack-dev-backend-1")
|
||||
print(" 2. Check logs: docker logs bodytrack-dev-backend-1 | grep 'Migration'")
|
||||
cur.close()
|
||||
conn.close()
|
||||
return
|
||||
|
||||
# 2. Check row count
|
||||
print("\n2. Checking row count...")
|
||||
cur.execute("SELECT COUNT(*) as count FROM goal_type_definitions")
|
||||
count = cur.fetchone()['count']
|
||||
print(f" Row count: {count}")
|
||||
|
||||
if count == 0:
|
||||
print("\n❌ TABLE IS EMPTY - Seed data was not inserted!")
|
||||
print("\nPOSSIBLE CAUSES:")
|
||||
print(" - INSERT statements failed (constraint violation?)")
|
||||
print(" - Migration ran partially")
|
||||
print("\nRECOMMENDED ACTION:")
|
||||
print(" Run the seed statements manually (see below)")
|
||||
else:
|
||||
print(f" ✓ Table has {count} entries")
|
||||
|
||||
# 3. Show all entries
|
||||
print("\n3. Current goal type definitions:")
|
||||
cur.execute("""
|
||||
SELECT type_key, label_de, unit, is_system, is_active, created_at
|
||||
FROM goal_type_definitions
|
||||
ORDER BY is_system DESC, type_key
|
||||
""")
|
||||
|
||||
entries = cur.fetchall()
|
||||
if entries:
|
||||
print(f"\n {'Type Key':<20} {'Label':<20} {'Unit':<10} {'System':<8} {'Active':<8}")
|
||||
print(" " + "-" * 70)
|
||||
for row in entries:
|
||||
status = "SYSTEM" if row['is_system'] else "CUSTOM"
|
||||
active = "YES" if row['is_active'] else "NO"
|
||||
print(f" {row['type_key']:<20} {row['label_de']:<20} {row['unit']:<10} {status:<8} {active:<8}")
|
||||
else:
|
||||
print(" (empty)")
|
||||
|
||||
# 4. Check schema_migrations
|
||||
print("\n4. Checking schema_migrations tracking...")
|
||||
cur.execute("""
|
||||
SELECT EXISTS (
|
||||
SELECT FROM information_schema.tables
|
||||
WHERE table_name = 'schema_migrations'
|
||||
)
|
||||
""")
|
||||
sm_exists = cur.fetchone()['exists']
|
||||
|
||||
if sm_exists:
|
||||
cur.execute("""
|
||||
SELECT filename, executed_at
|
||||
FROM schema_migrations
|
||||
WHERE filename = '024_goal_type_registry.sql'
|
||||
""")
|
||||
tracked = cur.fetchone()
|
||||
if tracked:
|
||||
print(f" ✓ Migration 024 is tracked (executed: {tracked['executed_at']})")
|
||||
else:
|
||||
print(" ❌ Migration 024 is NOT tracked in schema_migrations")
|
||||
else:
|
||||
print(" ⚠️ schema_migrations table does not exist")
|
||||
|
||||
# 5. Check for errors
|
||||
print("\n5. Potential issues:")
|
||||
issues = []
|
||||
|
||||
if count == 0:
|
||||
issues.append("No seed data - INSERTs failed")
|
||||
|
||||
if count > 0 and count < 6:
|
||||
issues.append(f"Only {count} types (expected 8) - partial seed")
|
||||
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as inactive_count
|
||||
FROM goal_type_definitions
|
||||
WHERE is_active = false
|
||||
""")
|
||||
inactive = cur.fetchone()['inactive_count']
|
||||
if inactive > 2:
|
||||
issues.append(f"{inactive} inactive types (expected 2)")
|
||||
|
||||
if not issues:
|
||||
print(" ✓ No issues detected")
|
||||
else:
|
||||
for issue in issues:
|
||||
print(f" ❌ {issue}")
|
||||
|
||||
# 6. Test query that frontend uses
|
||||
print("\n6. Testing frontend query (WHERE is_active = true)...")
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as active_count
|
||||
FROM goal_type_definitions
|
||||
WHERE is_active = true
|
||||
""")
|
||||
active_count = cur.fetchone()['active_count']
|
||||
print(f" Active types returned: {active_count}")
|
||||
|
||||
if active_count == 0:
|
||||
print(" ❌ This is why frontend shows empty list!")
|
||||
|
||||
print("\n" + "=" * 70)
|
||||
print("SUMMARY")
|
||||
print("=" * 70)
|
||||
|
||||
if count == 0:
|
||||
print("\n🔴 PROBLEM: Table exists but has no data")
|
||||
print("\nQUICK FIX: Run these SQL commands manually:")
|
||||
print("\n```sql")
|
||||
print("-- Connect to database:")
|
||||
print("docker exec -it bodytrack-dev-db-1 psql -U bodytrack -d bodytrack")
|
||||
print("\n-- Then paste migration content:")
|
||||
print("-- (copy from backend/migrations/024_goal_type_registry.sql)")
|
||||
print("-- Skip CREATE TABLE (already exists), run INSERT statements only")
|
||||
print("```")
|
||||
elif active_count >= 6:
|
||||
print("\n🟢 EVERYTHING LOOKS GOOD")
|
||||
print(f" {active_count} active goal types available")
|
||||
print("\nIf frontend still shows error, check:")
|
||||
print(" 1. Backend logs: docker logs bodytrack-dev-backend-1 -f")
|
||||
print(" 2. Network tab in browser DevTools")
|
||||
print(" 3. API endpoint: curl -H 'X-Auth-Token: YOUR_TOKEN' http://localhost:8099/api/goals/goal-types")
|
||||
else:
|
||||
print(f"\n🟡 PARTIAL DATA: {active_count} active types (expected 6)")
|
||||
print(" Some INSERTs might have failed")
|
||||
|
||||
cur.close()
|
||||
conn.close()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,215 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Quick Fix: Insert seed data for goal_type_definitions
|
||||
|
||||
This script ONLY inserts the 8 standard goal types.
|
||||
Safe to run multiple times (uses ON CONFLICT DO NOTHING).
|
||||
|
||||
Run inside backend container:
|
||||
docker exec bodytrack-dev-backend-1 python fix_seed_goal_types.py
|
||||
"""
|
||||
|
||||
import psycopg2
|
||||
import os
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
# Database connection
|
||||
DB_HOST = os.getenv('DB_HOST', 'db')
|
||||
DB_PORT = os.getenv('DB_PORT', '5432')
|
||||
DB_NAME = os.getenv('DB_NAME', 'bodytrack')
|
||||
DB_USER = os.getenv('DB_USER', 'bodytrack')
|
||||
DB_PASS = os.getenv('DB_PASSWORD', '')
|
||||
|
||||
SEED_DATA = [
|
||||
{
|
||||
'type_key': 'weight',
|
||||
'label_de': 'Gewicht',
|
||||
'label_en': 'Weight',
|
||||
'unit': 'kg',
|
||||
'icon': '⚖️',
|
||||
'category': 'body',
|
||||
'source_table': 'weight_log',
|
||||
'source_column': 'weight',
|
||||
'aggregation_method': 'latest',
|
||||
'description': 'Aktuelles Körpergewicht',
|
||||
'is_system': True
|
||||
},
|
||||
{
|
||||
'type_key': 'body_fat',
|
||||
'label_de': 'Körperfett',
|
||||
'label_en': 'Body Fat',
|
||||
'unit': '%',
|
||||
'icon': '📊',
|
||||
'category': 'body',
|
||||
'source_table': 'caliper_log',
|
||||
'source_column': 'body_fat_pct',
|
||||
'aggregation_method': 'latest',
|
||||
'description': 'Körperfettanteil aus Caliper-Messung',
|
||||
'is_system': True
|
||||
},
|
||||
{
|
||||
'type_key': 'lean_mass',
|
||||
'label_de': 'Muskelmasse',
|
||||
'label_en': 'Lean Mass',
|
||||
'unit': 'kg',
|
||||
'icon': '💪',
|
||||
'category': 'body',
|
||||
'calculation_formula': '{"type": "lean_mass", "dependencies": ["weight_log.weight", "caliper_log.body_fat_pct"], "formula": "weight - (weight * body_fat_pct / 100)"}',
|
||||
'description': 'Fettfreie Körpermasse (berechnet aus Gewicht und Körperfett)',
|
||||
'is_system': True
|
||||
},
|
||||
{
|
||||
'type_key': 'vo2max',
|
||||
'label_de': 'VO2Max',
|
||||
'label_en': 'VO2Max',
|
||||
'unit': 'ml/kg/min',
|
||||
'icon': '🫁',
|
||||
'category': 'recovery',
|
||||
'source_table': 'vitals_baseline',
|
||||
'source_column': 'vo2_max',
|
||||
'aggregation_method': 'latest',
|
||||
'description': 'Maximale Sauerstoffaufnahme (geschätzt oder gemessen)',
|
||||
'is_system': True
|
||||
},
|
||||
{
|
||||
'type_key': 'rhr',
|
||||
'label_de': 'Ruhepuls',
|
||||
'label_en': 'Resting Heart Rate',
|
||||
'unit': 'bpm',
|
||||
'icon': '💓',
|
||||
'category': 'recovery',
|
||||
'source_table': 'vitals_baseline',
|
||||
'source_column': 'resting_hr',
|
||||
'aggregation_method': 'latest',
|
||||
'description': 'Ruhepuls morgens vor dem Aufstehen',
|
||||
'is_system': True
|
||||
},
|
||||
{
|
||||
'type_key': 'bp',
|
||||
'label_de': 'Blutdruck',
|
||||
'label_en': 'Blood Pressure',
|
||||
'unit': 'mmHg',
|
||||
'icon': '❤️',
|
||||
'category': 'recovery',
|
||||
'source_table': 'blood_pressure_log',
|
||||
'source_column': 'systolic',
|
||||
'aggregation_method': 'latest',
|
||||
'description': 'Blutdruck (aktuell nur systolisch, v2.0: beide Werte)',
|
||||
'is_system': True
|
||||
},
|
||||
{
|
||||
'type_key': 'strength',
|
||||
'label_de': 'Kraft',
|
||||
'label_en': 'Strength',
|
||||
'unit': 'kg',
|
||||
'icon': '🏋️',
|
||||
'category': 'activity',
|
||||
'description': 'Maximalkraft (Platzhalter, Datenquelle in v2.0)',
|
||||
'is_system': True,
|
||||
'is_active': False
|
||||
},
|
||||
{
|
||||
'type_key': 'flexibility',
|
||||
'label_de': 'Beweglichkeit',
|
||||
'label_en': 'Flexibility',
|
||||
'unit': 'cm',
|
||||
'icon': '🤸',
|
||||
'category': 'activity',
|
||||
'description': 'Beweglichkeit (Platzhalter, Datenquelle in v2.0)',
|
||||
'is_system': True,
|
||||
'is_active': False
|
||||
}
|
||||
]
|
||||
|
||||
def main():
|
||||
print("=" * 70)
|
||||
print("Goal Type Definitions - Seed Data Fix")
|
||||
print("=" * 70)
|
||||
|
||||
# Connect to database
|
||||
conn = psycopg2.connect(
|
||||
host=DB_HOST,
|
||||
port=DB_PORT,
|
||||
dbname=DB_NAME,
|
||||
user=DB_USER,
|
||||
password=DB_PASS
|
||||
)
|
||||
conn.autocommit = False
|
||||
cur = conn.cursor(cursor_factory=RealDictCursor)
|
||||
|
||||
try:
|
||||
# Check current state
|
||||
cur.execute("SELECT COUNT(*) as count FROM goal_type_definitions")
|
||||
before_count = cur.fetchone()['count']
|
||||
print(f"\nBefore: {before_count} goal types in database")
|
||||
|
||||
# Insert seed data
|
||||
print(f"\nInserting {len(SEED_DATA)} standard goal types...")
|
||||
inserted = 0
|
||||
skipped = 0
|
||||
|
||||
for data in SEED_DATA:
|
||||
columns = list(data.keys())
|
||||
values = [data[col] for col in columns]
|
||||
placeholders = ', '.join(['%s'] * len(values))
|
||||
cols_str = ', '.join(columns)
|
||||
|
||||
sql = f"""
|
||||
INSERT INTO goal_type_definitions ({cols_str})
|
||||
VALUES ({placeholders})
|
||||
ON CONFLICT (type_key) DO NOTHING
|
||||
RETURNING id
|
||||
"""
|
||||
|
||||
cur.execute(sql, values)
|
||||
result = cur.fetchone()
|
||||
|
||||
if result:
|
||||
inserted += 1
|
||||
print(f" ✓ {data['type_key']}: {data['label_de']}")
|
||||
else:
|
||||
skipped += 1
|
||||
print(f" - {data['type_key']}: already exists (skipped)")
|
||||
|
||||
conn.commit()
|
||||
|
||||
# Check final state
|
||||
cur.execute("SELECT COUNT(*) as count FROM goal_type_definitions")
|
||||
after_count = cur.fetchone()['count']
|
||||
|
||||
print(f"\nAfter: {after_count} goal types in database")
|
||||
print(f" Inserted: {inserted}")
|
||||
print(f" Skipped: {skipped}")
|
||||
|
||||
# Show summary
|
||||
cur.execute("""
|
||||
SELECT type_key, label_de, is_active, is_system
|
||||
FROM goal_type_definitions
|
||||
ORDER BY is_system DESC, type_key
|
||||
""")
|
||||
|
||||
print("\n" + "=" * 70)
|
||||
print("Current Goal Types:")
|
||||
print("=" * 70)
|
||||
print(f"\n{'Type Key':<20} {'Label':<20} {'System':<8} {'Active':<8}")
|
||||
print("-" * 70)
|
||||
|
||||
for row in cur.fetchall():
|
||||
status = "YES" if row['is_system'] else "NO"
|
||||
active = "YES" if row['is_active'] else "NO"
|
||||
print(f"{row['type_key']:<20} {row['label_de']:<20} {status:<8} {active:<8}")
|
||||
|
||||
print("\n✅ DONE! Goal types seeded successfully.")
|
||||
print("\nNext step: Reload frontend to see the changes.")
|
||||
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
print(f"\n❌ Error: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
finally:
|
||||
cur.close()
|
||||
conn.close()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+196
-104
@@ -24,9 +24,8 @@ def get_focus_weights(conn, profile_id: str) -> Dict[str, float]:
|
||||
"""
|
||||
Get focus area weights for a profile.
|
||||
|
||||
This is an abstraction layer that will evolve:
|
||||
- V1 (now): Maps goal_mode → predefined weights
|
||||
- V2 (later): Reads from focus_areas table → custom user weights
|
||||
V2 (Goal System v2.0): Reads from focus_areas table with custom user weights.
|
||||
Falls back to goal_mode mapping if focus_areas not set.
|
||||
|
||||
Args:
|
||||
conn: Database connection
|
||||
@@ -55,7 +54,29 @@ def get_focus_weights(conn, profile_id: str) -> Dict[str, float]:
|
||||
"""
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Fetch current goal_mode
|
||||
# V2: Try to fetch from focus_areas table
|
||||
cur.execute("""
|
||||
SELECT weight_loss_pct, muscle_gain_pct, strength_pct,
|
||||
endurance_pct, flexibility_pct, health_pct
|
||||
FROM focus_areas
|
||||
WHERE profile_id = %s AND active = true
|
||||
LIMIT 1
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
|
||||
if row:
|
||||
# Convert percentages to weights (0-1 range)
|
||||
return {
|
||||
'weight_loss': row['weight_loss_pct'] / 100.0,
|
||||
'muscle_gain': row['muscle_gain_pct'] / 100.0,
|
||||
'strength': row['strength_pct'] / 100.0,
|
||||
'endurance': row['endurance_pct'] / 100.0,
|
||||
'flexibility': row['flexibility_pct'] / 100.0,
|
||||
'health': row['health_pct'] / 100.0
|
||||
}
|
||||
|
||||
# V1 Fallback: Use goal_mode if focus_areas not set
|
||||
cur.execute(
|
||||
"SELECT goal_mode FROM profiles WHERE id = %s",
|
||||
(profile_id,)
|
||||
@@ -63,59 +84,68 @@ def get_focus_weights(conn, profile_id: str) -> Dict[str, float]:
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row:
|
||||
# Fallback: balanced health focus
|
||||
# Ultimate fallback: balanced health focus
|
||||
return {
|
||||
'weight_loss': 0.0,
|
||||
'muscle_gain': 0.0,
|
||||
'strength': 0.0,
|
||||
'endurance': 0.0,
|
||||
'flexibility': 0.0,
|
||||
'health': 1.0
|
||||
'strength': 0.10,
|
||||
'endurance': 0.20,
|
||||
'flexibility': 0.15,
|
||||
'health': 0.55
|
||||
}
|
||||
|
||||
goal_mode = row['goal_mode'] or 'health'
|
||||
goal_mode = row['goal_mode']
|
||||
|
||||
# V1: Predefined weight mappings per goal_mode
|
||||
# These represent "typical" focus distributions for each mode
|
||||
if not goal_mode:
|
||||
return {
|
||||
'weight_loss': 0.0,
|
||||
'muscle_gain': 0.0,
|
||||
'strength': 0.10,
|
||||
'endurance': 0.20,
|
||||
'flexibility': 0.15,
|
||||
'health': 0.55
|
||||
}
|
||||
|
||||
# V1: Predefined weight mappings per goal_mode (fallback)
|
||||
WEIGHT_MAPPINGS = {
|
||||
'weight_loss': {
|
||||
'weight_loss': 0.60, # Primary: fat loss
|
||||
'endurance': 0.20, # Support: cardio for calorie burn
|
||||
'muscle_gain': 0.0, # Not compatible
|
||||
'strength': 0.10, # Maintain muscle during deficit
|
||||
'flexibility': 0.05, # Minor: mobility work
|
||||
'health': 0.05 # Minor: general wellness
|
||||
'weight_loss': 0.60,
|
||||
'endurance': 0.20,
|
||||
'muscle_gain': 0.0,
|
||||
'strength': 0.10,
|
||||
'flexibility': 0.05,
|
||||
'health': 0.05
|
||||
},
|
||||
'strength': {
|
||||
'strength': 0.50, # Primary: strength gains
|
||||
'muscle_gain': 0.40, # Support: hypertrophy
|
||||
'endurance': 0.10, # Minor: work capacity
|
||||
'weight_loss': 0.0, # Not compatible with strength focus
|
||||
'strength': 0.50,
|
||||
'muscle_gain': 0.40,
|
||||
'endurance': 0.10,
|
||||
'weight_loss': 0.0,
|
||||
'flexibility': 0.0,
|
||||
'health': 0.0
|
||||
},
|
||||
'endurance': {
|
||||
'endurance': 0.70, # Primary: aerobic capacity
|
||||
'health': 0.20, # Support: cardiovascular health
|
||||
'flexibility': 0.10, # Support: mobility for running
|
||||
'endurance': 0.70,
|
||||
'health': 0.20,
|
||||
'flexibility': 0.10,
|
||||
'weight_loss': 0.0,
|
||||
'muscle_gain': 0.0,
|
||||
'strength': 0.0
|
||||
},
|
||||
'recomposition': {
|
||||
'weight_loss': 0.30, # Equal: lose fat
|
||||
'muscle_gain': 0.30, # Equal: gain muscle
|
||||
'strength': 0.25, # Support: progressive overload
|
||||
'endurance': 0.10, # Minor: conditioning
|
||||
'flexibility': 0.05, # Minor: mobility
|
||||
'weight_loss': 0.30,
|
||||
'muscle_gain': 0.30,
|
||||
'strength': 0.25,
|
||||
'endurance': 0.10,
|
||||
'flexibility': 0.05,
|
||||
'health': 0.0
|
||||
},
|
||||
'health': {
|
||||
'health': 0.50, # Primary: general wellness
|
||||
'endurance': 0.20, # Support: cardio health
|
||||
'flexibility': 0.15, # Support: mobility
|
||||
'strength': 0.10, # Support: functional strength
|
||||
'weight_loss': 0.05, # Minor: maintain healthy weight
|
||||
'health': 0.50,
|
||||
'endurance': 0.20,
|
||||
'flexibility': 0.15,
|
||||
'strength': 0.10,
|
||||
'weight_loss': 0.05,
|
||||
'muscle_gain': 0.0
|
||||
}
|
||||
}
|
||||
@@ -181,7 +211,7 @@ def get_goal_type_config(conn, type_key: str) -> Optional[Dict[str, Any]]:
|
||||
|
||||
cur.execute("""
|
||||
SELECT type_key, source_table, source_column, aggregation_method,
|
||||
calculation_formula, label_de, unit, icon, category
|
||||
calculation_formula, filter_conditions, label_de, unit, icon, category
|
||||
FROM goal_type_definitions
|
||||
WHERE type_key = %s AND is_active = true
|
||||
LIMIT 1
|
||||
@@ -221,7 +251,8 @@ def get_current_value_for_goal(conn, profile_id: str, goal_type: str) -> Optiona
|
||||
profile_id,
|
||||
config['source_table'],
|
||||
config['source_column'],
|
||||
config['aggregation_method']
|
||||
config['aggregation_method'],
|
||||
config.get('filter_conditions')
|
||||
)
|
||||
|
||||
|
||||
@@ -230,7 +261,8 @@ def _fetch_by_aggregation_method(
|
||||
profile_id: str,
|
||||
table: str,
|
||||
column: str,
|
||||
method: str
|
||||
method: str,
|
||||
filter_conditions: Optional[Any] = None
|
||||
) -> Optional[float]:
|
||||
"""
|
||||
Fetch value using specified aggregation method.
|
||||
@@ -244,83 +276,143 @@ def _fetch_by_aggregation_method(
|
||||
- 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
|
||||
|
||||
Args:
|
||||
filter_conditions: Optional JSON filters (e.g., {"training_type": "strength"})
|
||||
"""
|
||||
# Guard: source_table/column required for simple aggregation
|
||||
if not table or not column:
|
||||
print(f"[WARNING] Missing source_table or source_column for aggregation")
|
||||
return None
|
||||
|
||||
# Table-specific date column mapping (some tables use different column names)
|
||||
DATE_COLUMN_MAP = {
|
||||
'blood_pressure_log': 'measured_at',
|
||||
'activity_log': 'date',
|
||||
'weight_log': 'date',
|
||||
'circumference_log': 'date',
|
||||
'caliper_log': 'date',
|
||||
'nutrition_log': 'date',
|
||||
'sleep_log': 'date',
|
||||
'vitals_baseline': 'date',
|
||||
'rest_days': 'date',
|
||||
'fitness_tests': 'test_date'
|
||||
}
|
||||
date_col = DATE_COLUMN_MAP.get(table, 'date')
|
||||
|
||||
# Build filter SQL from JSON conditions
|
||||
filter_sql = ""
|
||||
filter_params = []
|
||||
|
||||
if filter_conditions:
|
||||
try:
|
||||
if isinstance(filter_conditions, str):
|
||||
filters = json.loads(filter_conditions)
|
||||
else:
|
||||
filters = filter_conditions
|
||||
|
||||
for filter_col, filter_val in filters.items():
|
||||
if isinstance(filter_val, list):
|
||||
# IN clause for multiple values
|
||||
placeholders = ', '.join(['%s'] * len(filter_val))
|
||||
filter_sql += f" AND {filter_col} IN ({placeholders})"
|
||||
filter_params.extend(filter_val)
|
||||
else:
|
||||
# Single value equality
|
||||
filter_sql += f" AND {filter_col} = %s"
|
||||
filter_params.append(filter_val)
|
||||
except (json.JSONDecodeError, TypeError, AttributeError) as e:
|
||||
print(f"[WARNING] Invalid filter_conditions: {e}, ignoring filters")
|
||||
|
||||
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
|
||||
try:
|
||||
if method == 'latest':
|
||||
params = [profile_id] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT {column} FROM {table}
|
||||
WHERE profile_id = %s AND {column} IS NOT NULL{filter_sql}
|
||||
ORDER BY {date_col} DESC LIMIT 1
|
||||
""", params)
|
||||
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_7d':
|
||||
days_ago = date.today() - timedelta(days=7)
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT AVG({column}) as avg_value FROM {table}
|
||||
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
""", params)
|
||||
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 == 'avg_30d':
|
||||
days_ago = date.today() - timedelta(days=30)
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT AVG({column}) as avg_value FROM {table}
|
||||
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
""", params)
|
||||
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 == 'sum_30d':
|
||||
days_ago = date.today() - timedelta(days=30)
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT SUM({column}) as sum_value FROM {table}
|
||||
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
""", params)
|
||||
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_7d':
|
||||
days_ago = date.today() - timedelta(days=7)
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT COUNT(*) as count_value FROM {table}
|
||||
WHERE profile_id = %s AND {date_col} >= %s{filter_sql}
|
||||
""", params)
|
||||
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 == 'count_30d':
|
||||
days_ago = date.today() - timedelta(days=30)
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT COUNT(*) as count_value FROM {table}
|
||||
WHERE profile_id = %s AND {date_col} >= %s{filter_sql}
|
||||
""", params)
|
||||
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 == 'min_30d':
|
||||
days_ago = date.today() - timedelta(days=30)
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT MIN({column}) as min_value FROM {table}
|
||||
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
""", params)
|
||||
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
|
||||
elif method == 'max_30d':
|
||||
days_ago = date.today() - timedelta(days=30)
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT MAX({column}) as max_value FROM {table}
|
||||
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
""", params)
|
||||
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}")
|
||||
else:
|
||||
print(f"[WARNING] Unknown aggregation method: {method}")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
print(f"[ERROR] Failed to fetch value from {table}.{column} using {method}: {e}")
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -36,9 +36,7 @@ CREATE TABLE IF NOT EXISTS goal_type_definitions (
|
||||
|
||||
-- Audit
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW(),
|
||||
created_by UUID REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
updated_by UUID REFERENCES profiles(id) ON DELETE SET NULL
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_goal_type_definitions_active ON goal_type_definitions(is_active) WHERE is_active = true;
|
||||
@@ -63,7 +61,8 @@ INSERT INTO goal_type_definitions (
|
||||
'weight', 'Gewicht', 'Weight', 'kg', '⚖️', 'body',
|
||||
'weight_log', 'weight', 'latest',
|
||||
'Aktuelles Körpergewicht', true
|
||||
);
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 2. Body Fat (simple - latest value)
|
||||
INSERT INTO goal_type_definitions (
|
||||
@@ -74,7 +73,8 @@ INSERT INTO goal_type_definitions (
|
||||
'body_fat', 'Körperfett', 'Body Fat', '%', '📊', 'body',
|
||||
'caliper_log', 'body_fat_pct', 'latest',
|
||||
'Körperfettanteil aus Caliper-Messung', true
|
||||
);
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 3. Lean Mass (complex - calculation formula)
|
||||
INSERT INTO goal_type_definitions (
|
||||
@@ -85,7 +85,8 @@ INSERT INTO goal_type_definitions (
|
||||
'lean_mass', 'Muskelmasse', 'Lean Mass', 'kg', '💪', 'body',
|
||||
'{"type": "lean_mass", "dependencies": ["weight_log.weight", "caliper_log.body_fat_pct"], "formula": "weight - (weight * body_fat_pct / 100)"}',
|
||||
'Fettfreie Körpermasse (berechnet aus Gewicht und Körperfett)', true
|
||||
);
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 4. VO2 Max (simple - latest value)
|
||||
INSERT INTO goal_type_definitions (
|
||||
@@ -96,7 +97,8 @@ INSERT INTO goal_type_definitions (
|
||||
'vo2max', 'VO2Max', 'VO2Max', 'ml/kg/min', '🫁', 'recovery',
|
||||
'vitals_baseline', 'vo2_max', 'latest',
|
||||
'Maximale Sauerstoffaufnahme (geschätzt oder gemessen)', true
|
||||
);
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 5. Resting Heart Rate (simple - latest value)
|
||||
INSERT INTO goal_type_definitions (
|
||||
@@ -107,7 +109,8 @@ INSERT INTO goal_type_definitions (
|
||||
'rhr', 'Ruhepuls', 'Resting Heart Rate', 'bpm', '💓', 'recovery',
|
||||
'vitals_baseline', 'resting_hr', 'latest',
|
||||
'Ruhepuls morgens vor dem Aufstehen', true
|
||||
);
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 6. Blood Pressure (placeholder - compound goal for v2.0)
|
||||
-- Currently limited to single value, v2.0 will support systolic/diastolic
|
||||
@@ -119,7 +122,8 @@ INSERT INTO goal_type_definitions (
|
||||
'bp', 'Blutdruck', 'Blood Pressure', 'mmHg', '❤️', 'recovery',
|
||||
'blood_pressure_log', 'systolic', 'latest',
|
||||
'Blutdruck (aktuell nur systolisch, v2.0: beide Werte)', true
|
||||
);
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 7. Strength (placeholder - no data source yet)
|
||||
INSERT INTO goal_type_definitions (
|
||||
@@ -128,7 +132,8 @@ INSERT INTO goal_type_definitions (
|
||||
) VALUES (
|
||||
'strength', 'Kraft', 'Strength', 'kg', '🏋️', 'activity',
|
||||
'Maximalkraft (Platzhalter, Datenquelle in v2.0)', true, false
|
||||
);
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 8. Flexibility (placeholder - no data source yet)
|
||||
INSERT INTO goal_type_definitions (
|
||||
@@ -137,7 +142,8 @@ INSERT INTO goal_type_definitions (
|
||||
) VALUES (
|
||||
'flexibility', 'Beweglichkeit', 'Flexibility', 'cm', '🤸', 'activity',
|
||||
'Beweglichkeit (Platzhalter, Datenquelle in v2.0)', true, false
|
||||
);
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- ============================================================================
|
||||
-- Example: Future custom goal types (commented out, for reference)
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
-- Migration 025: Cleanup goal_type_definitions
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Remove problematic FK columns and ensure seed data
|
||||
|
||||
-- Remove created_by/updated_by columns if they exist
|
||||
-- (May have been created by failed Migration 024)
|
||||
ALTER TABLE goal_type_definitions DROP COLUMN IF EXISTS created_by;
|
||||
ALTER TABLE goal_type_definitions DROP COLUMN IF EXISTS updated_by;
|
||||
|
||||
-- Re-insert seed data (ON CONFLICT ensures idempotency)
|
||||
-- This fixes cases where Migration 024 created table but failed to seed
|
||||
|
||||
-- 1. Weight
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'weight', 'Gewicht', 'Weight', 'kg', '⚖️', 'body',
|
||||
'weight_log', 'weight', 'latest',
|
||||
'Aktuelles Körpergewicht', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 2. Body Fat
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'body_fat', 'Körperfett', 'Body Fat', '%', '📊', 'body',
|
||||
'caliper_log', 'body_fat_pct', 'latest',
|
||||
'Körperfettanteil aus Caliper-Messung', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 3. Lean Mass
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
calculation_formula,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'lean_mass', 'Muskelmasse', 'Lean Mass', 'kg', '💪', 'body',
|
||||
'{"type": "lean_mass", "dependencies": ["weight_log.weight", "caliper_log.body_fat_pct"], "formula": "weight - (weight * body_fat_pct / 100)"}',
|
||||
'Fettfreie Körpermasse (berechnet aus Gewicht und Körperfett)', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 4. VO2 Max
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'vo2max', 'VO2Max', 'VO2Max', 'ml/kg/min', '🫁', 'recovery',
|
||||
'vitals_baseline', 'vo2_max', 'latest',
|
||||
'Maximale Sauerstoffaufnahme (geschätzt oder gemessen)', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 5. Resting Heart Rate
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'rhr', 'Ruhepuls', 'Resting Heart Rate', 'bpm', '💓', 'recovery',
|
||||
'vitals_baseline', 'resting_hr', 'latest',
|
||||
'Ruhepuls morgens vor dem Aufstehen', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 6. Blood Pressure
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'bp', 'Blutdruck', 'Blood Pressure', 'mmHg', '❤️', 'recovery',
|
||||
'blood_pressure_log', 'systolic', 'latest',
|
||||
'Blutdruck (aktuell nur systolisch, v2.0: beide Werte)', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 7. Strength (inactive placeholder)
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
description, is_system, is_active
|
||||
) VALUES (
|
||||
'strength', 'Kraft', 'Strength', 'kg', '🏋️', 'activity',
|
||||
'Maximalkraft (Platzhalter, Datenquelle in v2.0)', true, false
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 8. Flexibility (inactive placeholder)
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
description, is_system, is_active
|
||||
) VALUES (
|
||||
'flexibility', 'Beweglichkeit', 'Flexibility', 'cm', '🤸', 'activity',
|
||||
'Beweglichkeit (Platzhalter, Datenquelle in v2.0)', true, false
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
@@ -0,0 +1,40 @@
|
||||
-- Migration 026: Goal Type Filters
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Enable filtered counting/aggregation (e.g., count only strength training)
|
||||
|
||||
-- Add filter_conditions column for flexible filtering
|
||||
ALTER TABLE goal_type_definitions
|
||||
ADD COLUMN IF NOT EXISTS filter_conditions JSONB;
|
||||
|
||||
COMMENT ON COLUMN goal_type_definitions.filter_conditions IS
|
||||
'Optional filter conditions as JSON. Example: {"training_type": "strength"} to count only strength training sessions.
|
||||
Supports any column in the source table. Format: {"column_name": "value"} or {"column_name": ["value1", "value2"]} for IN clause.';
|
||||
|
||||
-- Example usage (commented out):
|
||||
/*
|
||||
-- Count only strength training sessions per week
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
filter_conditions,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'strength_frequency', 'Krafttraining Häufigkeit', 'x/Woche', '🏋️', 'activity',
|
||||
'activity_log', 'id', 'count_7d',
|
||||
'{"training_type": "strength"}',
|
||||
'Anzahl Krafttraining-Einheiten pro Woche', false
|
||||
) ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- Count only cardio sessions per week
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
filter_conditions,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'cardio_frequency', 'Cardio Häufigkeit', 'x/Woche', '🏃', 'activity',
|
||||
'activity_log', 'id', 'count_7d',
|
||||
'{"training_type": "cardio"}',
|
||||
'Anzahl Cardio-Einheiten pro Woche', false
|
||||
) ON CONFLICT (type_key) DO NOTHING;
|
||||
*/
|
||||
@@ -0,0 +1,125 @@
|
||||
-- Migration 027: Focus Areas System (Goal System v2.0)
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Replace single primary goal with weighted multi-goal system
|
||||
|
||||
-- ============================================================================
|
||||
-- Focus Areas Table
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS focus_areas (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
|
||||
-- Six focus dimensions (percentages, sum = 100)
|
||||
weight_loss_pct INTEGER DEFAULT 0 CHECK (weight_loss_pct >= 0 AND weight_loss_pct <= 100),
|
||||
muscle_gain_pct INTEGER DEFAULT 0 CHECK (muscle_gain_pct >= 0 AND muscle_gain_pct <= 100),
|
||||
strength_pct INTEGER DEFAULT 0 CHECK (strength_pct >= 0 AND strength_pct <= 100),
|
||||
endurance_pct INTEGER DEFAULT 0 CHECK (endurance_pct >= 0 AND endurance_pct <= 100),
|
||||
flexibility_pct INTEGER DEFAULT 0 CHECK (flexibility_pct >= 0 AND flexibility_pct <= 100),
|
||||
health_pct INTEGER DEFAULT 0 CHECK (health_pct >= 0 AND health_pct <= 100),
|
||||
|
||||
-- Status
|
||||
active BOOLEAN DEFAULT true,
|
||||
|
||||
-- Audit
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW(),
|
||||
|
||||
-- Constraints
|
||||
CONSTRAINT sum_equals_100 CHECK (
|
||||
weight_loss_pct + muscle_gain_pct + strength_pct +
|
||||
endurance_pct + flexibility_pct + health_pct = 100
|
||||
)
|
||||
);
|
||||
|
||||
-- Only one active focus_areas per profile
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_focus_areas_profile_active
|
||||
ON focus_areas(profile_id) WHERE active = true;
|
||||
|
||||
COMMENT ON TABLE focus_areas IS 'User-defined focus area weights (replaces simple goal_mode). Enables multi-goal prioritization with custom percentages.';
|
||||
COMMENT ON COLUMN focus_areas.weight_loss_pct IS 'Focus on fat loss (0-100%)';
|
||||
COMMENT ON COLUMN focus_areas.muscle_gain_pct IS 'Focus on muscle growth (0-100%)';
|
||||
COMMENT ON COLUMN focus_areas.strength_pct IS 'Focus on strength gains (0-100%)';
|
||||
COMMENT ON COLUMN focus_areas.endurance_pct IS 'Focus on aerobic capacity (0-100%)';
|
||||
COMMENT ON COLUMN focus_areas.flexibility_pct IS 'Focus on mobility/flexibility (0-100%)';
|
||||
COMMENT ON COLUMN focus_areas.health_pct IS 'Focus on general health (0-100%)';
|
||||
|
||||
-- ============================================================================
|
||||
-- Migrate existing goal_mode to focus_areas
|
||||
-- ============================================================================
|
||||
|
||||
-- For each profile with a goal_mode, create initial focus_areas
|
||||
INSERT INTO focus_areas (
|
||||
profile_id,
|
||||
weight_loss_pct, muscle_gain_pct, strength_pct,
|
||||
endurance_pct, flexibility_pct, health_pct
|
||||
)
|
||||
SELECT
|
||||
id AS profile_id,
|
||||
CASE goal_mode
|
||||
WHEN 'weight_loss' THEN 60
|
||||
WHEN 'recomposition' THEN 30
|
||||
WHEN 'health' THEN 5
|
||||
ELSE 0
|
||||
END AS weight_loss_pct,
|
||||
|
||||
CASE goal_mode
|
||||
WHEN 'strength' THEN 40 ELSE 0
|
||||
END +
|
||||
CASE goal_mode
|
||||
WHEN 'recomposition' THEN 30 ELSE 0
|
||||
END AS muscle_gain_pct,
|
||||
|
||||
CASE goal_mode
|
||||
WHEN 'strength' THEN 50
|
||||
WHEN 'recomposition' THEN 25
|
||||
WHEN 'weight_loss' THEN 10
|
||||
WHEN 'health' THEN 10
|
||||
ELSE 0
|
||||
END AS strength_pct,
|
||||
|
||||
CASE goal_mode
|
||||
WHEN 'endurance' THEN 70
|
||||
WHEN 'recomposition' THEN 10
|
||||
WHEN 'weight_loss' THEN 20
|
||||
WHEN 'health' THEN 20
|
||||
ELSE 0
|
||||
END AS endurance_pct,
|
||||
|
||||
CASE goal_mode
|
||||
WHEN 'endurance' THEN 10 ELSE 0
|
||||
END +
|
||||
CASE goal_mode
|
||||
WHEN 'health' THEN 15 ELSE 0
|
||||
END +
|
||||
CASE goal_mode
|
||||
WHEN 'recomposition' THEN 5 ELSE 0
|
||||
END +
|
||||
CASE goal_mode
|
||||
WHEN 'weight_loss' THEN 5 ELSE 0
|
||||
END AS flexibility_pct,
|
||||
|
||||
CASE goal_mode
|
||||
WHEN 'health' THEN 50
|
||||
WHEN 'endurance' THEN 20
|
||||
WHEN 'strength' THEN 10
|
||||
WHEN 'weight_loss' THEN 5
|
||||
ELSE 0
|
||||
END AS health_pct
|
||||
FROM profiles
|
||||
WHERE goal_mode IS NOT NULL
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- For profiles without goal_mode, use balanced health focus
|
||||
INSERT INTO focus_areas (
|
||||
profile_id,
|
||||
weight_loss_pct, muscle_gain_pct, strength_pct,
|
||||
endurance_pct, flexibility_pct, health_pct
|
||||
)
|
||||
SELECT
|
||||
id AS profile_id,
|
||||
0, 0, 10, 20, 15, 55
|
||||
FROM profiles
|
||||
WHERE goal_mode IS NULL
|
||||
AND id NOT IN (SELECT profile_id FROM focus_areas WHERE active = true)
|
||||
ON CONFLICT DO NOTHING;
|
||||
@@ -0,0 +1,57 @@
|
||||
-- Migration 028: Goal Categories and Priorities
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Multi-dimensional goal priorities (one primary goal per category)
|
||||
|
||||
-- ============================================================================
|
||||
-- Add category and priority columns
|
||||
-- ============================================================================
|
||||
|
||||
ALTER TABLE goals
|
||||
ADD COLUMN category VARCHAR(50),
|
||||
ADD COLUMN priority INTEGER DEFAULT 2 CHECK (priority >= 1 AND priority <= 3);
|
||||
|
||||
COMMENT ON COLUMN goals.category IS 'Goal category: body, training, nutrition, recovery, health, other';
|
||||
COMMENT ON COLUMN goals.priority IS 'Priority level: 1=high, 2=medium, 3=low';
|
||||
|
||||
-- ============================================================================
|
||||
-- Migrate existing goals to categories based on goal_type
|
||||
-- ============================================================================
|
||||
|
||||
UPDATE goals SET category = CASE
|
||||
-- Body composition goals
|
||||
WHEN goal_type IN ('weight', 'body_fat', 'lean_mass') THEN 'body'
|
||||
|
||||
-- Training goals
|
||||
WHEN goal_type IN ('strength', 'flexibility', 'training_frequency') THEN 'training'
|
||||
|
||||
-- Health/cardio goals
|
||||
WHEN goal_type IN ('vo2max', 'rhr', 'bp', 'hrv') THEN 'health'
|
||||
|
||||
-- Recovery goals
|
||||
WHEN goal_type IN ('sleep_quality', 'sleep_duration', 'rest_days') THEN 'recovery'
|
||||
|
||||
-- Nutrition goals
|
||||
WHEN goal_type IN ('calories', 'protein', 'healthy_eating') THEN 'nutrition'
|
||||
|
||||
-- Default
|
||||
ELSE 'other'
|
||||
END
|
||||
WHERE category IS NULL;
|
||||
|
||||
-- ============================================================================
|
||||
-- Set priority based on is_primary
|
||||
-- ============================================================================
|
||||
|
||||
UPDATE goals SET priority = CASE
|
||||
WHEN is_primary = true THEN 1 -- Primary goals get priority 1
|
||||
ELSE 2 -- Others get priority 2 (medium)
|
||||
END;
|
||||
|
||||
-- ============================================================================
|
||||
-- Create index for category-based queries
|
||||
-- ============================================================================
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_goals_category_priority
|
||||
ON goals(profile_id, category, priority);
|
||||
|
||||
COMMENT ON INDEX idx_goals_category_priority IS 'Fast lookup for category-grouped goals sorted by priority';
|
||||
@@ -0,0 +1,74 @@
|
||||
-- Migration 029: Fix Missing Goal Types (flexibility, strength)
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Ensure flexibility and strength goal types are active and properly configured
|
||||
|
||||
-- These types were created earlier but are inactive or misconfigured
|
||||
-- This migration fixes them without breaking if they don't exist
|
||||
|
||||
-- ============================================================================
|
||||
-- Upsert flexibility goal type
|
||||
-- ============================================================================
|
||||
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
calculation_formula, filter_conditions, description, is_active
|
||||
) VALUES (
|
||||
'flexibility',
|
||||
'Beweglichkeit',
|
||||
'Flexibility',
|
||||
'cm',
|
||||
'🤸',
|
||||
'training',
|
||||
NULL, -- No automatic data source
|
||||
NULL,
|
||||
'latest',
|
||||
NULL,
|
||||
NULL,
|
||||
'Beweglichkeit und Mobilität - manuelle Erfassung',
|
||||
true
|
||||
)
|
||||
ON CONFLICT (type_key)
|
||||
DO UPDATE SET
|
||||
label_de = 'Beweglichkeit',
|
||||
label_en = 'Flexibility',
|
||||
unit = 'cm',
|
||||
icon = '🤸',
|
||||
category = 'training',
|
||||
is_active = true,
|
||||
description = 'Beweglichkeit und Mobilität - manuelle Erfassung';
|
||||
|
||||
-- ============================================================================
|
||||
-- Upsert strength goal type
|
||||
-- ============================================================================
|
||||
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
calculation_formula, filter_conditions, description, is_active
|
||||
) VALUES (
|
||||
'strength',
|
||||
'Kraftniveau',
|
||||
'Strength',
|
||||
'Punkte',
|
||||
'💪',
|
||||
'training',
|
||||
NULL, -- No automatic data source
|
||||
NULL,
|
||||
'latest',
|
||||
NULL,
|
||||
NULL,
|
||||
'Allgemeines Kraftniveau - manuelle Erfassung',
|
||||
true
|
||||
)
|
||||
ON CONFLICT (type_key)
|
||||
DO UPDATE SET
|
||||
label_de = 'Kraftniveau',
|
||||
label_en = 'Strength',
|
||||
unit = 'Punkte',
|
||||
icon = '💪',
|
||||
category = 'training',
|
||||
is_active = true,
|
||||
description = 'Allgemeines Kraftniveau - manuelle Erfassung';
|
||||
|
||||
COMMENT ON TABLE goal_type_definitions IS 'Goal type registry - defines all available goal types (v1.5: DB-driven, flexible system)';
|
||||
@@ -0,0 +1,64 @@
|
||||
-- Migration 030: Goal Progress Log
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Track progress history for all goals (especially custom goals without data source)
|
||||
|
||||
-- ============================================================================
|
||||
-- Goal Progress Log Table
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS goal_progress_log (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
goal_id UUID NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
|
||||
-- Progress data
|
||||
date DATE NOT NULL,
|
||||
value DECIMAL(10,2) NOT NULL,
|
||||
note TEXT,
|
||||
|
||||
-- Metadata
|
||||
source VARCHAR(20) DEFAULT 'manual' CHECK (source IN ('manual', 'automatic', 'import')),
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW(),
|
||||
|
||||
-- Constraints
|
||||
CONSTRAINT unique_progress_per_day UNIQUE(goal_id, date)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_goal_progress_goal_date ON goal_progress_log(goal_id, date DESC);
|
||||
CREATE INDEX idx_goal_progress_profile ON goal_progress_log(profile_id);
|
||||
|
||||
COMMENT ON TABLE goal_progress_log IS 'Progress history for goals - enables manual tracking for custom goals and charts';
|
||||
COMMENT ON COLUMN goal_progress_log.value IS 'Progress value in goal unit (e.g., kg, cm, points)';
|
||||
COMMENT ON COLUMN goal_progress_log.source IS 'manual: user entered, automatic: computed from data source, import: CSV/API';
|
||||
|
||||
-- ============================================================================
|
||||
-- Function: Update goal current_value from latest progress
|
||||
-- ============================================================================
|
||||
|
||||
CREATE OR REPLACE FUNCTION update_goal_current_value()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
-- Update current_value in goals table with latest progress entry
|
||||
UPDATE goals
|
||||
SET current_value = (
|
||||
SELECT value
|
||||
FROM goal_progress_log
|
||||
WHERE goal_id = NEW.goal_id
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
),
|
||||
updated_at = NOW()
|
||||
WHERE id = NEW.goal_id;
|
||||
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- Trigger: Auto-update current_value when progress is added/updated
|
||||
CREATE TRIGGER trigger_update_goal_current_value
|
||||
AFTER INSERT OR UPDATE ON goal_progress_log
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_goal_current_value();
|
||||
|
||||
COMMENT ON FUNCTION update_goal_current_value IS 'Auto-update goal.current_value when new progress is logged';
|
||||
+527
-32
@@ -27,16 +27,27 @@ router = APIRouter(prefix="/api/goals", tags=["goals"])
|
||||
# ============================================================================
|
||||
|
||||
class GoalModeUpdate(BaseModel):
|
||||
"""Update strategic goal mode"""
|
||||
"""Update strategic goal mode (deprecated - use FocusAreasUpdate)"""
|
||||
goal_mode: str # weight_loss, strength, endurance, recomposition, health
|
||||
|
||||
class FocusAreasUpdate(BaseModel):
|
||||
"""Update focus area weights (v2.0)"""
|
||||
weight_loss_pct: int
|
||||
muscle_gain_pct: int
|
||||
strength_pct: int
|
||||
endurance_pct: int
|
||||
flexibility_pct: int
|
||||
health_pct: int
|
||||
|
||||
class GoalCreate(BaseModel):
|
||||
"""Create or update a concrete goal"""
|
||||
goal_type: str # weight, body_fat, lean_mass, vo2max, strength, flexibility, bp, rhr
|
||||
is_primary: bool = False
|
||||
is_primary: bool = False # Kept for backward compatibility
|
||||
target_value: float
|
||||
unit: str # kg, %, ml/kg/min, bpm, mmHg, cm, reps
|
||||
target_date: Optional[date] = None
|
||||
category: Optional[str] = 'other' # body, training, nutrition, recovery, health, other
|
||||
priority: Optional[int] = 2 # 1=high, 2=medium, 3=low
|
||||
name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
@@ -45,7 +56,9 @@ class GoalUpdate(BaseModel):
|
||||
target_value: Optional[float] = None
|
||||
target_date: Optional[date] = None
|
||||
status: Optional[str] = None # active, reached, abandoned, expired
|
||||
is_primary: Optional[bool] = None
|
||||
is_primary: Optional[bool] = None # Kept for backward compatibility
|
||||
category: Optional[str] = None # body, training, nutrition, recovery, health, other
|
||||
priority: Optional[int] = None # 1=high, 2=medium, 3=low
|
||||
name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
@@ -64,6 +77,17 @@ class FitnessTestCreate(BaseModel):
|
||||
test_date: date
|
||||
test_conditions: Optional[str] = None
|
||||
|
||||
class GoalProgressCreate(BaseModel):
|
||||
"""Log progress for a goal"""
|
||||
date: date
|
||||
value: float
|
||||
note: Optional[str] = None
|
||||
|
||||
class GoalProgressUpdate(BaseModel):
|
||||
"""Update progress entry"""
|
||||
value: Optional[float] = None
|
||||
note: Optional[str] = None
|
||||
|
||||
class GoalTypeCreate(BaseModel):
|
||||
"""Create custom goal type definition"""
|
||||
type_key: str
|
||||
@@ -76,6 +100,7 @@ class GoalTypeCreate(BaseModel):
|
||||
source_column: Optional[str] = None
|
||||
aggregation_method: Optional[str] = 'latest'
|
||||
calculation_formula: Optional[str] = None
|
||||
filter_conditions: Optional[dict] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
class GoalTypeUpdate(BaseModel):
|
||||
@@ -89,6 +114,7 @@ class GoalTypeUpdate(BaseModel):
|
||||
source_column: Optional[str] = None
|
||||
aggregation_method: Optional[str] = None
|
||||
calculation_formula: Optional[str] = None
|
||||
filter_conditions: Optional[dict] = None
|
||||
description: Optional[str] = None
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
@@ -152,6 +178,177 @@ def _get_goal_mode_description(mode: str) -> str:
|
||||
}
|
||||
return descriptions.get(mode, 'Unbekannt')
|
||||
|
||||
# ============================================================================
|
||||
# Focus Areas (v2.0): Weighted Multi-Goal System
|
||||
# ============================================================================
|
||||
|
||||
@router.get("/focus-areas")
|
||||
def get_focus_areas(session: dict = Depends(require_auth)):
|
||||
"""
|
||||
Get current focus area weights.
|
||||
|
||||
Returns custom weights if set, otherwise derives from goal_mode.
|
||||
"""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Try to get custom focus areas
|
||||
cur.execute("""
|
||||
SELECT weight_loss_pct, muscle_gain_pct, strength_pct,
|
||||
endurance_pct, flexibility_pct, health_pct,
|
||||
created_at, updated_at
|
||||
FROM focus_areas
|
||||
WHERE profile_id = %s AND active = true
|
||||
LIMIT 1
|
||||
""", (pid,))
|
||||
|
||||
row = cur.fetchone()
|
||||
|
||||
if row:
|
||||
return {
|
||||
"custom": True,
|
||||
"weight_loss_pct": row['weight_loss_pct'],
|
||||
"muscle_gain_pct": row['muscle_gain_pct'],
|
||||
"strength_pct": row['strength_pct'],
|
||||
"endurance_pct": row['endurance_pct'],
|
||||
"flexibility_pct": row['flexibility_pct'],
|
||||
"health_pct": row['health_pct'],
|
||||
"updated_at": row['updated_at']
|
||||
}
|
||||
|
||||
# Fallback: Derive from goal_mode
|
||||
cur.execute("SELECT goal_mode FROM profiles WHERE id = %s", (pid,))
|
||||
profile = cur.fetchone()
|
||||
|
||||
if not profile or not profile['goal_mode']:
|
||||
# Default balanced health
|
||||
return {
|
||||
"custom": False,
|
||||
"weight_loss_pct": 0,
|
||||
"muscle_gain_pct": 0,
|
||||
"strength_pct": 10,
|
||||
"endurance_pct": 20,
|
||||
"flexibility_pct": 15,
|
||||
"health_pct": 55,
|
||||
"source": "default"
|
||||
}
|
||||
|
||||
# Derive from goal_mode (using same logic as migration)
|
||||
mode = profile['goal_mode']
|
||||
mode_mappings = {
|
||||
'weight_loss': {
|
||||
'weight_loss_pct': 60,
|
||||
'muscle_gain_pct': 0,
|
||||
'strength_pct': 10,
|
||||
'endurance_pct': 20,
|
||||
'flexibility_pct': 5,
|
||||
'health_pct': 5
|
||||
},
|
||||
'strength': {
|
||||
'weight_loss_pct': 0,
|
||||
'muscle_gain_pct': 40,
|
||||
'strength_pct': 50,
|
||||
'endurance_pct': 10,
|
||||
'flexibility_pct': 0,
|
||||
'health_pct': 0
|
||||
},
|
||||
'endurance': {
|
||||
'weight_loss_pct': 0,
|
||||
'muscle_gain_pct': 0,
|
||||
'strength_pct': 0,
|
||||
'endurance_pct': 70,
|
||||
'flexibility_pct': 10,
|
||||
'health_pct': 20
|
||||
},
|
||||
'recomposition': {
|
||||
'weight_loss_pct': 30,
|
||||
'muscle_gain_pct': 30,
|
||||
'strength_pct': 25,
|
||||
'endurance_pct': 10,
|
||||
'flexibility_pct': 5,
|
||||
'health_pct': 0
|
||||
},
|
||||
'health': {
|
||||
'weight_loss_pct': 0,
|
||||
'muscle_gain_pct': 0,
|
||||
'strength_pct': 10,
|
||||
'endurance_pct': 20,
|
||||
'flexibility_pct': 15,
|
||||
'health_pct': 55
|
||||
}
|
||||
}
|
||||
|
||||
mapping = mode_mappings.get(mode, mode_mappings['health'])
|
||||
mapping['custom'] = False
|
||||
mapping['source'] = f"goal_mode:{mode}"
|
||||
return mapping
|
||||
|
||||
@router.put("/focus-areas")
|
||||
def update_focus_areas(data: FocusAreasUpdate, session: dict = Depends(require_auth)):
|
||||
"""
|
||||
Update focus area weights (upsert).
|
||||
|
||||
Validates that sum = 100 and all values are 0-100.
|
||||
"""
|
||||
pid = session['profile_id']
|
||||
|
||||
# Validate sum = 100
|
||||
total = (
|
||||
data.weight_loss_pct + data.muscle_gain_pct + data.strength_pct +
|
||||
data.endurance_pct + data.flexibility_pct + data.health_pct
|
||||
)
|
||||
|
||||
if total != 100:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Summe muss 100% sein (aktuell: {total}%)"
|
||||
)
|
||||
|
||||
# Validate range 0-100
|
||||
values = [
|
||||
data.weight_loss_pct, data.muscle_gain_pct, data.strength_pct,
|
||||
data.endurance_pct, data.flexibility_pct, data.health_pct
|
||||
]
|
||||
|
||||
if any(v < 0 or v > 100 for v in values):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Alle Werte müssen zwischen 0 und 100 liegen"
|
||||
)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Deactivate old focus_areas
|
||||
cur.execute(
|
||||
"UPDATE focus_areas SET active = false WHERE profile_id = %s",
|
||||
(pid,)
|
||||
)
|
||||
|
||||
# Insert new focus_areas
|
||||
cur.execute("""
|
||||
INSERT INTO focus_areas (
|
||||
profile_id, weight_loss_pct, muscle_gain_pct, strength_pct,
|
||||
endurance_pct, flexibility_pct, health_pct
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""", (
|
||||
pid, data.weight_loss_pct, data.muscle_gain_pct, data.strength_pct,
|
||||
data.endurance_pct, data.flexibility_pct, data.health_pct
|
||||
))
|
||||
|
||||
return {
|
||||
"message": "Fokus-Bereiche aktualisiert",
|
||||
"weight_loss_pct": data.weight_loss_pct,
|
||||
"muscle_gain_pct": data.muscle_gain_pct,
|
||||
"strength_pct": data.strength_pct,
|
||||
"endurance_pct": data.endurance_pct,
|
||||
"flexibility_pct": data.flexibility_pct,
|
||||
"health_pct": data.health_pct
|
||||
}
|
||||
|
||||
# ============================================================================
|
||||
# Tactical Layer: Concrete Goals
|
||||
# ============================================================================
|
||||
@@ -161,27 +358,42 @@ def list_goals(session: dict = Depends(require_auth)):
|
||||
"""List all goals for current user"""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT id, goal_type, is_primary, status,
|
||||
target_value, current_value, start_value, unit,
|
||||
start_date, target_date, reached_date,
|
||||
name, description,
|
||||
progress_pct, projection_date, on_track,
|
||||
created_at, updated_at
|
||||
FROM goals
|
||||
WHERE profile_id = %s
|
||||
ORDER BY is_primary DESC, created_at DESC
|
||||
""", (pid,))
|
||||
try:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT id, goal_type, is_primary, status,
|
||||
target_value, current_value, start_value, unit,
|
||||
start_date, target_date, reached_date,
|
||||
name, description,
|
||||
progress_pct, projection_date, on_track,
|
||||
created_at, updated_at
|
||||
FROM goals
|
||||
WHERE profile_id = %s
|
||||
ORDER BY is_primary DESC, created_at DESC
|
||||
""", (pid,))
|
||||
|
||||
goals = [r2d(row) for row in cur.fetchall()]
|
||||
goals = [r2d(row) for row in cur.fetchall()]
|
||||
print(f"[DEBUG] Loaded {len(goals)} goals for profile {pid}")
|
||||
|
||||
# Update current values for each goal
|
||||
for goal in goals:
|
||||
_update_goal_progress(conn, pid, goal)
|
||||
# Update current values for each goal
|
||||
for goal in goals:
|
||||
try:
|
||||
_update_goal_progress(conn, pid, goal)
|
||||
except Exception as e:
|
||||
print(f"[ERROR] Failed to update progress for goal {goal.get('id')}: {e}")
|
||||
# Continue with other goals even if one fails
|
||||
|
||||
return goals
|
||||
return goals
|
||||
|
||||
except Exception as e:
|
||||
print(f"[ERROR] list_goals failed: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Fehler beim Laden der Ziele: {str(e)}"
|
||||
)
|
||||
|
||||
@router.post("/create")
|
||||
def create_goal(data: GoalCreate, session: dict = Depends(require_auth)):
|
||||
@@ -206,13 +418,13 @@ def create_goal(data: GoalCreate, session: dict = Depends(require_auth)):
|
||||
INSERT INTO goals (
|
||||
profile_id, goal_type, is_primary,
|
||||
target_value, current_value, start_value, unit,
|
||||
target_date, name, description
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
target_date, category, priority, name, description
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""", (
|
||||
pid, data.goal_type, data.is_primary,
|
||||
data.target_value, current_value, current_value, data.unit,
|
||||
data.target_date, data.name, data.description
|
||||
data.target_date, data.category, data.priority, data.name, data.description
|
||||
))
|
||||
|
||||
goal_id = cur.fetchone()['id']
|
||||
@@ -264,6 +476,14 @@ def update_goal(goal_id: str, data: GoalUpdate, session: dict = Depends(require_
|
||||
updates.append("is_primary = %s")
|
||||
params.append(data.is_primary)
|
||||
|
||||
if data.category is not None:
|
||||
updates.append("category = %s")
|
||||
params.append(data.category)
|
||||
|
||||
if data.priority is not None:
|
||||
updates.append("priority = %s")
|
||||
params.append(data.priority)
|
||||
|
||||
if data.name is not None:
|
||||
updates.append("name = %s")
|
||||
params.append(data.name)
|
||||
@@ -302,6 +522,174 @@ def delete_goal(goal_id: str, session: dict = Depends(require_auth)):
|
||||
|
||||
return {"message": "Ziel gelöscht"}
|
||||
|
||||
# ============================================================================
|
||||
# Goal Progress Endpoints
|
||||
# ============================================================================
|
||||
|
||||
@router.get("/{goal_id}/progress")
|
||||
def get_goal_progress(goal_id: str, session: dict = Depends(require_auth)):
|
||||
"""Get progress history for a goal"""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Verify ownership
|
||||
cur.execute(
|
||||
"SELECT id FROM goals WHERE id = %s AND profile_id = %s",
|
||||
(goal_id, pid)
|
||||
)
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(status_code=404, detail="Ziel nicht gefunden")
|
||||
|
||||
# Get progress entries
|
||||
cur.execute("""
|
||||
SELECT id, date, value, note, source, created_at
|
||||
FROM goal_progress_log
|
||||
WHERE goal_id = %s
|
||||
ORDER BY date DESC
|
||||
""", (goal_id,))
|
||||
|
||||
entries = cur.fetchall()
|
||||
return [r2d(e) for e in entries]
|
||||
|
||||
@router.post("/{goal_id}/progress")
|
||||
def create_goal_progress(goal_id: str, data: GoalProgressCreate, session: dict = Depends(require_auth)):
|
||||
"""Log new progress for a goal"""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Verify ownership and check if manual entry is allowed
|
||||
cur.execute("""
|
||||
SELECT g.id, g.unit, gt.source_table
|
||||
FROM goals g
|
||||
LEFT JOIN goal_type_definitions gt ON g.goal_type = gt.type_key
|
||||
WHERE g.id = %s AND g.profile_id = %s
|
||||
""", (goal_id, pid))
|
||||
goal = cur.fetchone()
|
||||
if not goal:
|
||||
raise HTTPException(status_code=404, detail="Ziel nicht gefunden")
|
||||
|
||||
# Prevent manual entries for goals with automatic data sources
|
||||
if goal['source_table']:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Manuelle Einträge nicht erlaubt für automatisch erfasste Ziele. "
|
||||
f"Bitte nutze die entsprechende Erfassungsseite (z.B. Gewicht, Aktivität)."
|
||||
)
|
||||
|
||||
# Insert progress entry
|
||||
try:
|
||||
cur.execute("""
|
||||
INSERT INTO goal_progress_log (goal_id, profile_id, date, value, note, source)
|
||||
VALUES (%s, %s, %s, %s, %s, 'manual')
|
||||
RETURNING id
|
||||
""", (goal_id, pid, data.date, data.value, data.note))
|
||||
|
||||
progress_id = cur.fetchone()['id']
|
||||
|
||||
# Trigger will auto-update goals.current_value
|
||||
return {
|
||||
"id": progress_id,
|
||||
"message": f"Fortschritt erfasst: {data.value} {goal['unit']}"
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
if "unique_progress_per_day" in str(e):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Für {data.date} existiert bereits ein Eintrag. Bitte bearbeite den existierenden Eintrag."
|
||||
)
|
||||
raise HTTPException(status_code=500, detail=f"Fehler beim Speichern: {str(e)}")
|
||||
|
||||
@router.delete("/{goal_id}/progress/{progress_id}")
|
||||
def delete_goal_progress(goal_id: str, progress_id: str, session: dict = Depends(require_auth)):
|
||||
"""Delete progress entry"""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Verify ownership
|
||||
cur.execute(
|
||||
"SELECT id FROM goals WHERE id = %s AND profile_id = %s",
|
||||
(goal_id, pid)
|
||||
)
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(status_code=404, detail="Ziel nicht gefunden")
|
||||
|
||||
# Delete progress entry
|
||||
cur.execute(
|
||||
"DELETE FROM goal_progress_log WHERE id = %s AND goal_id = %s AND profile_id = %s",
|
||||
(progress_id, goal_id, pid)
|
||||
)
|
||||
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(status_code=404, detail="Progress-Eintrag nicht gefunden")
|
||||
|
||||
# After deletion, recalculate current_value from remaining entries
|
||||
cur.execute("""
|
||||
UPDATE goals
|
||||
SET current_value = (
|
||||
SELECT value FROM goal_progress_log
|
||||
WHERE goal_id = %s
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
)
|
||||
WHERE id = %s
|
||||
""", (goal_id, goal_id))
|
||||
|
||||
return {"message": "Progress-Eintrag gelöscht"}
|
||||
|
||||
@router.get("/grouped")
|
||||
def get_goals_grouped(session: dict = Depends(require_auth)):
|
||||
"""
|
||||
Get goals grouped by category, sorted by priority.
|
||||
|
||||
Returns structure:
|
||||
{
|
||||
"body": [{"id": "...", "goal_type": "weight", "priority": 1, ...}, ...],
|
||||
"training": [...],
|
||||
"nutrition": [...],
|
||||
"recovery": [...],
|
||||
"health": [...],
|
||||
"other": [...]
|
||||
}
|
||||
"""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get all active goals with type definitions
|
||||
cur.execute("""
|
||||
SELECT
|
||||
g.id, g.goal_type, g.target_value, g.current_value, g.start_value,
|
||||
g.unit, g.target_date, g.status, g.is_primary, g.category, g.priority,
|
||||
g.name, g.description, g.progress_pct, g.on_track, g.projection_date,
|
||||
g.created_at, g.updated_at,
|
||||
gt.label_de, gt.icon, gt.category as type_category,
|
||||
gt.source_table, gt.source_column
|
||||
FROM goals g
|
||||
LEFT JOIN goal_type_definitions gt ON g.goal_type = gt.type_key
|
||||
WHERE g.profile_id = %s
|
||||
ORDER BY g.category, g.priority ASC, g.created_at DESC
|
||||
""", (pid,))
|
||||
|
||||
goals = cur.fetchall()
|
||||
|
||||
# Group by category
|
||||
grouped = {}
|
||||
for goal in goals:
|
||||
cat = goal['category'] or 'other'
|
||||
if cat not in grouped:
|
||||
grouped[cat] = []
|
||||
grouped[cat].append(r2d(goal))
|
||||
|
||||
return grouped
|
||||
|
||||
# ============================================================================
|
||||
# Training Phases
|
||||
# ============================================================================
|
||||
@@ -493,6 +881,108 @@ def _calculate_norm_category(test_type: str, value: float, unit: str) -> Optiona
|
||||
# Goal Type Definitions (Phase 1.5 - Flexible Goal System)
|
||||
# ============================================================================
|
||||
|
||||
@router.get("/schema-info")
|
||||
def get_schema_info(session: dict = Depends(require_auth)):
|
||||
"""
|
||||
Get available tables and columns for goal type creation.
|
||||
|
||||
Admin-only endpoint for building custom goal types.
|
||||
Returns structure with descriptions for UX guidance.
|
||||
"""
|
||||
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")
|
||||
|
||||
# Define relevant tables with descriptions
|
||||
# Only include tables that make sense for goal tracking
|
||||
schema = {
|
||||
"weight_log": {
|
||||
"description": "Gewichtsverlauf",
|
||||
"columns": {
|
||||
"weight": {"type": "DECIMAL", "description": "Körpergewicht in kg"}
|
||||
}
|
||||
},
|
||||
"caliper_log": {
|
||||
"description": "Caliper-Messungen (Hautfalten)",
|
||||
"columns": {
|
||||
"body_fat_pct": {"type": "DECIMAL", "description": "Körperfettanteil in %"},
|
||||
"sum_mm": {"type": "DECIMAL", "description": "Summe Hautfalten in mm"}
|
||||
}
|
||||
},
|
||||
"circumference_log": {
|
||||
"description": "Umfangsmessungen",
|
||||
"columns": {
|
||||
"c_neck": {"type": "DECIMAL", "description": "Nackenumfang in cm"},
|
||||
"c_chest": {"type": "DECIMAL", "description": "Brustumfang in cm"},
|
||||
"c_waist": {"type": "DECIMAL", "description": "Taillenumfang in cm"},
|
||||
"c_hips": {"type": "DECIMAL", "description": "Hüftumfang in cm"},
|
||||
"c_thigh_l": {"type": "DECIMAL", "description": "Oberschenkel links in cm"},
|
||||
"c_thigh_r": {"type": "DECIMAL", "description": "Oberschenkel rechts in cm"},
|
||||
"c_calf_l": {"type": "DECIMAL", "description": "Wade links in cm"},
|
||||
"c_calf_r": {"type": "DECIMAL", "description": "Wade rechts in cm"},
|
||||
"c_bicep_l": {"type": "DECIMAL", "description": "Bizeps links in cm"},
|
||||
"c_bicep_r": {"type": "DECIMAL", "description": "Bizeps rechts in cm"}
|
||||
}
|
||||
},
|
||||
"activity_log": {
|
||||
"description": "Trainingseinheiten",
|
||||
"columns": {
|
||||
"id": {"type": "UUID", "description": "ID (für Zählung von Einheiten)"},
|
||||
"duration_minutes": {"type": "INTEGER", "description": "Trainingsdauer in Minuten"},
|
||||
"perceived_exertion": {"type": "INTEGER", "description": "Belastungsempfinden (1-10)"},
|
||||
"quality_rating": {"type": "INTEGER", "description": "Qualitätsbewertung (1-10)"}
|
||||
}
|
||||
},
|
||||
"nutrition_log": {
|
||||
"description": "Ernährungstagebuch",
|
||||
"columns": {
|
||||
"calories": {"type": "INTEGER", "description": "Kalorien in kcal"},
|
||||
"protein_g": {"type": "DECIMAL", "description": "Protein in g"},
|
||||
"carbs_g": {"type": "DECIMAL", "description": "Kohlenhydrate in g"},
|
||||
"fat_g": {"type": "DECIMAL", "description": "Fett in g"}
|
||||
}
|
||||
},
|
||||
"sleep_log": {
|
||||
"description": "Schlafprotokoll",
|
||||
"columns": {
|
||||
"total_minutes": {"type": "INTEGER", "description": "Gesamtschlafdauer in Minuten"}
|
||||
}
|
||||
},
|
||||
"vitals_baseline": {
|
||||
"description": "Vitalwerte (morgens)",
|
||||
"columns": {
|
||||
"resting_hr": {"type": "INTEGER", "description": "Ruhepuls in bpm"},
|
||||
"hrv_rmssd": {"type": "INTEGER", "description": "Herzratenvariabilität (RMSSD) in ms"},
|
||||
"vo2_max": {"type": "DECIMAL", "description": "VO2 Max in ml/kg/min"},
|
||||
"spo2": {"type": "INTEGER", "description": "Sauerstoffsättigung in %"},
|
||||
"respiratory_rate": {"type": "INTEGER", "description": "Atemfrequenz pro Minute"}
|
||||
}
|
||||
},
|
||||
"blood_pressure_log": {
|
||||
"description": "Blutdruckmessungen",
|
||||
"columns": {
|
||||
"systolic": {"type": "INTEGER", "description": "Systolischer Blutdruck in mmHg"},
|
||||
"diastolic": {"type": "INTEGER", "description": "Diastolischer Blutdruck in mmHg"},
|
||||
"pulse": {"type": "INTEGER", "description": "Puls in bpm"}
|
||||
}
|
||||
},
|
||||
"rest_days": {
|
||||
"description": "Ruhetage",
|
||||
"columns": {
|
||||
"id": {"type": "UUID", "description": "ID (für Zählung von Ruhetagen)"}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return schema
|
||||
|
||||
@router.get("/goal-types")
|
||||
def list_goal_type_definitions(session: dict = Depends(require_auth)):
|
||||
"""
|
||||
@@ -568,20 +1058,21 @@ def create_goal_type_definition(
|
||||
)
|
||||
|
||||
# Insert new goal type
|
||||
import json as json_lib
|
||||
filter_json = json_lib.dumps(data.filter_conditions) if data.filter_conditions else None
|
||||
|
||||
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)
|
||||
calculation_formula, filter_conditions, description, is_active, is_system
|
||||
) VALUES (%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
|
||||
data.aggregation_method, data.calculation_formula, filter_json, data.description,
|
||||
True, False # is_active=True, is_system=False
|
||||
))
|
||||
|
||||
goal_type_id = cur.fetchone()['id']
|
||||
@@ -665,6 +1156,12 @@ def update_goal_type_definition(
|
||||
updates.append("calculation_formula = %s")
|
||||
params.append(data.calculation_formula)
|
||||
|
||||
if data.filter_conditions is not None:
|
||||
import json as json_lib
|
||||
filter_json = json_lib.dumps(data.filter_conditions) if data.filter_conditions else None
|
||||
updates.append("filter_conditions = %s")
|
||||
params.append(filter_json)
|
||||
|
||||
if data.description is not None:
|
||||
updates.append("description = %s")
|
||||
params.append(data.description)
|
||||
@@ -677,8 +1174,6 @@ def update_goal_type_definition(
|
||||
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(
|
||||
|
||||
@@ -37,6 +37,7 @@ import SleepPage from './pages/SleepPage'
|
||||
import RestDaysPage from './pages/RestDaysPage'
|
||||
import VitalsPage from './pages/VitalsPage'
|
||||
import GoalsPage from './pages/GoalsPage'
|
||||
import CustomGoalsPage from './pages/CustomGoalsPage'
|
||||
import './app.css'
|
||||
|
||||
function Nav() {
|
||||
@@ -175,6 +176,7 @@ function AppShell() {
|
||||
<Route path="/rest-days" element={<RestDaysPage/>}/>
|
||||
<Route path="/vitals" element={<VitalsPage/>}/>
|
||||
<Route path="/goals" element={<GoalsPage/>}/>
|
||||
<Route path="/custom-goals" element={<CustomGoalsPage/>}/>
|
||||
<Route path="/nutrition" element={<NutritionPage/>}/>
|
||||
<Route path="/activity" element={<ActivityPage/>}/>
|
||||
<Route path="/analysis" element={<Analysis/>}/>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { api } from '../utils/api'
|
||||
|
||||
export default function AdminGoalTypesPage() {
|
||||
const [goalTypes, setGoalTypes] = useState([])
|
||||
const [schemaInfo, setSchemaInfo] = useState(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState(null)
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
@@ -19,6 +20,7 @@ export default function AdminGoalTypesPage() {
|
||||
source_table: '',
|
||||
source_column: '',
|
||||
aggregation_method: 'latest',
|
||||
filter_conditions: '',
|
||||
description: ''
|
||||
})
|
||||
|
||||
@@ -42,9 +44,14 @@ export default function AdminGoalTypesPage() {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const data = await api.listGoalTypeDefinitions()
|
||||
console.log('[DEBUG] Loaded goal types:', data)
|
||||
setGoalTypes(data || [])
|
||||
const [typesData, schema] = await Promise.all([
|
||||
api.listGoalTypeDefinitions(),
|
||||
api.getSchemaInfo()
|
||||
])
|
||||
console.log('[DEBUG] Loaded goal types:', typesData)
|
||||
console.log('[DEBUG] Loaded schema info:', schema)
|
||||
setGoalTypes(typesData || [])
|
||||
setSchemaInfo(schema || {})
|
||||
} catch (err) {
|
||||
console.error('[ERROR] Failed to load goal types:', err)
|
||||
setError(`Fehler beim Laden der Goal Types: ${err.message || err.toString()}`)
|
||||
@@ -69,6 +76,7 @@ export default function AdminGoalTypesPage() {
|
||||
source_table: '',
|
||||
source_column: '',
|
||||
aggregation_method: 'latest',
|
||||
filter_conditions: '',
|
||||
description: ''
|
||||
})
|
||||
setShowForm(true)
|
||||
@@ -85,6 +93,7 @@ export default function AdminGoalTypesPage() {
|
||||
source_table: type.source_table || '',
|
||||
source_column: type.source_column || '',
|
||||
aggregation_method: type.aggregation_method || 'latest',
|
||||
filter_conditions: type.filter_conditions ? JSON.stringify(type.filter_conditions, null, 2) : '',
|
||||
description: type.description || ''
|
||||
})
|
||||
setShowForm(true)
|
||||
@@ -96,16 +105,29 @@ export default function AdminGoalTypesPage() {
|
||||
return
|
||||
}
|
||||
|
||||
// Parse filter_conditions from string to JSON
|
||||
let payload = { ...formData }
|
||||
if (formData.filter_conditions && formData.filter_conditions.trim()) {
|
||||
try {
|
||||
payload.filter_conditions = JSON.parse(formData.filter_conditions)
|
||||
} catch (e) {
|
||||
setError('Ungültiges JSON in Filter-Bedingungen')
|
||||
return
|
||||
}
|
||||
} else {
|
||||
payload.filter_conditions = null
|
||||
}
|
||||
|
||||
try {
|
||||
if (editingType) {
|
||||
await api.updateGoalType(editingType, formData)
|
||||
await api.updateGoalType(editingType, payload)
|
||||
showToast('✓ Goal Type aktualisiert')
|
||||
} else {
|
||||
if (!formData.type_key) {
|
||||
setError('Bitte eindeutigen Key angeben (z.B. meditation_minutes)')
|
||||
return
|
||||
}
|
||||
await api.createGoalType(formData)
|
||||
await api.createGoalType(payload)
|
||||
showToast('✓ Goal Type erstellt')
|
||||
}
|
||||
|
||||
@@ -375,25 +397,59 @@ export default function AdminGoalTypesPage() {
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
|
||||
<div>
|
||||
<label className="form-label">Tabelle</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
style={{ width: '100%' }}
|
||||
value={formData.source_table}
|
||||
onChange={e => setFormData(f => ({ ...f, source_table: e.target.value }))}
|
||||
placeholder="z.B. meditation_log"
|
||||
/>
|
||||
{schemaInfo ? (
|
||||
<select
|
||||
className="form-input"
|
||||
style={{ width: '100%' }}
|
||||
value={formData.source_table}
|
||||
onChange={e => setFormData(f => ({ ...f, source_table: e.target.value, source_column: '' }))}
|
||||
>
|
||||
<option value="">-- Optional --</option>
|
||||
{Object.entries(schemaInfo).map(([table, info]) => (
|
||||
<option key={table} value={table} title={info.description}>
|
||||
{table} - {info.description}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
style={{ width: '100%' }}
|
||||
value={formData.source_table}
|
||||
onChange={e => setFormData(f => ({ ...f, source_table: e.target.value }))}
|
||||
placeholder="Lade Schema..."
|
||||
disabled
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<label className="form-label">Spalte</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
style={{ width: '100%' }}
|
||||
value={formData.source_column}
|
||||
onChange={e => setFormData(f => ({ ...f, source_column: e.target.value }))}
|
||||
placeholder="z.B. duration_minutes"
|
||||
/>
|
||||
{schemaInfo && formData.source_table && schemaInfo[formData.source_table] ? (
|
||||
<select
|
||||
className="form-input"
|
||||
style={{ width: '100%' }}
|
||||
value={formData.source_column}
|
||||
onChange={e => setFormData(f => ({ ...f, source_column: e.target.value }))}
|
||||
>
|
||||
<option value="">-- Wählen --</option>
|
||||
{Object.entries(schemaInfo[formData.source_table].columns).map(([col, info]) => (
|
||||
<option key={col} value={col} title={info.description}>
|
||||
{col} - {info.description}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
style={{ width: '100%' }}
|
||||
value={formData.source_column}
|
||||
onChange={e => setFormData(f => ({ ...f, source_column: e.target.value }))}
|
||||
placeholder={formData.source_table ? "Spalte wählen..." : "Erst Tabelle wählen"}
|
||||
disabled={!formData.source_table}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -412,6 +468,21 @@ export default function AdminGoalTypesPage() {
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Filter Conditions */}
|
||||
<div>
|
||||
<label className="form-label">Filter (optional, JSON)</label>
|
||||
<textarea
|
||||
className="form-input"
|
||||
style={{ width: '100%', minHeight: 80, fontFamily: 'monospace', fontSize: 13 }}
|
||||
value={formData.filter_conditions}
|
||||
onChange={e => setFormData(f => ({ ...f, filter_conditions: e.target.value }))}
|
||||
placeholder={'Beispiel:\n{\n "training_type": "strength"\n}\n\nOder mehrere Werte:\n{\n "training_type": ["strength", "hiit"]\n}'}
|
||||
/>
|
||||
<div style={{ fontSize: 12, color: 'var(--text2)', marginTop: 4 }}>
|
||||
💡 Filtert Einträge nach Spalten. Beispiel: <code>{`{"training_type": "strength"}`}</code> zählt nur Krafttraining
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div>
|
||||
<label className="form-label">Beschreibung (optional)</label>
|
||||
|
||||
@@ -453,7 +453,7 @@ export default function AdminPanel() {
|
||||
</div>
|
||||
|
||||
{/* KI-Prompts Section */}
|
||||
<div className="card">
|
||||
<div className="card section-gap" style={{marginTop:16}}>
|
||||
<div style={{fontWeight:700,fontSize:14,marginBottom:12,display:'flex',alignItems:'center',gap:6}}>
|
||||
<Settings size={16} color="var(--accent)"/> KI-Prompts (v9f)
|
||||
</div>
|
||||
@@ -468,6 +468,23 @@ export default function AdminPanel() {
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Goal Types Section */}
|
||||
<div className="card section-gap" style={{marginTop:16}}>
|
||||
<div style={{fontWeight:700,fontSize:14,marginBottom:12,display:'flex',alignItems:'center',gap:6}}>
|
||||
<Settings size={16} color="var(--accent)"/> Ziel-Typen (v9e)
|
||||
</div>
|
||||
<div style={{fontSize:12,color:'var(--text3)',marginBottom:12,lineHeight:1.5}}>
|
||||
Verwalte Goal-Type-Definitionen: Erstelle custom goal types mit oder ohne automatische Datenquelle.
|
||||
</div>
|
||||
<div style={{display:'grid',gap:8}}>
|
||||
<Link to="/admin/goal-types">
|
||||
<button className="btn btn-secondary btn-full">
|
||||
🎯 Ziel-Typen verwalten
|
||||
</button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -66,6 +66,13 @@ const ENTRIES = [
|
||||
to: '/vitals',
|
||||
color: '#E74C3C',
|
||||
},
|
||||
{
|
||||
icon: '🎯',
|
||||
label: 'Eigene Ziele',
|
||||
sub: 'Fortschritte für individuelle Ziele erfassen',
|
||||
to: '/custom-goals',
|
||||
color: '#1D9E75',
|
||||
},
|
||||
{
|
||||
icon: '📖',
|
||||
label: 'Messanleitung',
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { api } from '../utils/api'
|
||||
import { Target, TrendingUp, Calendar, CheckCircle2, AlertCircle } from 'lucide-react'
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
export default function CustomGoalsPage() {
|
||||
const [customGoals, setCustomGoals] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState(null)
|
||||
const [selectedGoal, setSelectedGoal] = useState(null)
|
||||
const [formData, setFormData] = useState({
|
||||
date: new Date().toISOString().split('T')[0],
|
||||
value: '',
|
||||
note: ''
|
||||
})
|
||||
const [recentProgress, setRecentProgress] = useState([])
|
||||
|
||||
useEffect(() => {
|
||||
loadCustomGoals()
|
||||
}, [])
|
||||
|
||||
const loadCustomGoals = async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
const grouped = await api.listGoalsGrouped()
|
||||
|
||||
// Extract all goals and filter for custom only (no source_table)
|
||||
const allGoals = Object.values(grouped).flat()
|
||||
const custom = allGoals.filter(g => !g.source_table)
|
||||
|
||||
setCustomGoals(custom)
|
||||
setError(null)
|
||||
} catch (err) {
|
||||
console.error('Failed to load custom goals:', err)
|
||||
setError(err.message || 'Fehler beim Laden')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const loadRecentProgress = async (goalId) => {
|
||||
try {
|
||||
const entries = await api.listGoalProgress(goalId)
|
||||
setRecentProgress(entries.slice(0, 5)) // Last 5 entries
|
||||
} catch (err) {
|
||||
console.error('Failed to load progress:', err)
|
||||
setRecentProgress([])
|
||||
}
|
||||
}
|
||||
|
||||
const handleSelectGoal = async (goal) => {
|
||||
setSelectedGoal(goal)
|
||||
setFormData({
|
||||
date: new Date().toISOString().split('T')[0],
|
||||
value: goal.current_value || '',
|
||||
note: ''
|
||||
})
|
||||
await loadRecentProgress(goal.id)
|
||||
}
|
||||
|
||||
const handleSaveProgress = async () => {
|
||||
if (!formData.value || !formData.date) {
|
||||
setError('Bitte Datum und Wert eingeben')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const data = {
|
||||
date: formData.date,
|
||||
value: parseFloat(formData.value),
|
||||
note: formData.note || null
|
||||
}
|
||||
|
||||
await api.createGoalProgress(selectedGoal.id, data)
|
||||
|
||||
// Reset form and reload
|
||||
setFormData({
|
||||
date: new Date().toISOString().split('T')[0],
|
||||
value: '',
|
||||
note: ''
|
||||
})
|
||||
|
||||
await loadCustomGoals()
|
||||
await loadRecentProgress(selectedGoal.id)
|
||||
|
||||
// Update selected goal with new current_value
|
||||
const updated = customGoals.find(g => g.id === selectedGoal.id)
|
||||
if (updated) setSelectedGoal(updated)
|
||||
|
||||
setError(null)
|
||||
} catch (err) {
|
||||
console.error('Failed to save progress:', err)
|
||||
setError(err.message || 'Fehler beim Speichern')
|
||||
}
|
||||
}
|
||||
|
||||
const getProgressPercentage = (goal) => {
|
||||
if (!goal.current_value || !goal.target_value) return 0
|
||||
|
||||
const current = parseFloat(goal.current_value)
|
||||
const target = parseFloat(goal.target_value)
|
||||
const start = parseFloat(goal.start_value) || 0
|
||||
|
||||
if (goal.direction === 'decrease') {
|
||||
return Math.min(100, Math.max(0, ((start - current) / (start - target)) * 100))
|
||||
} else {
|
||||
return Math.min(100, Math.max(0, ((current - start) / (target - start)) * 100))
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{ padding: 20, textAlign: 'center' }}>
|
||||
<div className="spinner" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ paddingBottom: 80 }}>
|
||||
{/* Header */}
|
||||
<div style={{
|
||||
background: 'linear-gradient(135deg, var(--accent) 0%, var(--accent-dark) 100%)',
|
||||
color: 'white',
|
||||
padding: '24px 16px',
|
||||
marginBottom: 16
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
|
||||
<Target size={28} />
|
||||
<h1 style={{ fontSize: 24, fontWeight: 700, margin: 0 }}>Eigene Ziele</h1>
|
||||
</div>
|
||||
<div style={{ fontSize: 14, opacity: 0.9 }}>
|
||||
Erfasse Fortschritte für deine individuellen Ziele
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div style={{
|
||||
margin: '0 16px 16px',
|
||||
padding: 12,
|
||||
background: '#FEE2E2',
|
||||
color: '#991B1B',
|
||||
borderRadius: 8,
|
||||
fontSize: 14
|
||||
}}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{customGoals.length === 0 ? (
|
||||
<div className="card" style={{ margin: 16, textAlign: 'center', padding: 40 }}>
|
||||
<Target size={48} style={{ color: 'var(--text3)', margin: '0 auto 16px' }} />
|
||||
<div style={{ fontSize: 16, color: 'var(--text2)', marginBottom: 8 }}>
|
||||
Keine eigenen Ziele vorhanden
|
||||
</div>
|
||||
<div style={{ fontSize: 14, color: 'var(--text3)' }}>
|
||||
Erstelle eigene Ziele über die Ziele-Seite in der Analyse
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, padding: 16 }}>
|
||||
{/* Goal Selection */}
|
||||
<div className="card">
|
||||
<h2 style={{ fontSize: 16, marginBottom: 12, fontWeight: 600 }}>
|
||||
Ziel auswählen ({customGoals.length})
|
||||
</h2>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{customGoals.map(goal => {
|
||||
const progress = getProgressPercentage(goal)
|
||||
const isSelected = selectedGoal?.id === goal.id
|
||||
|
||||
return (
|
||||
<button
|
||||
key={goal.id}
|
||||
onClick={() => handleSelectGoal(goal)}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: 12,
|
||||
background: isSelected ? 'var(--accent)' : 'var(--surface2)',
|
||||
color: isSelected ? 'white' : 'var(--text1)',
|
||||
border: 'none',
|
||||
borderRadius: 8,
|
||||
cursor: 'pointer',
|
||||
textAlign: 'left',
|
||||
transition: 'all 0.2s'
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
|
||||
<span style={{ fontWeight: 600 }}>
|
||||
{goal.name || goal.label_de || goal.goal_type}
|
||||
</span>
|
||||
{goal.current_value && (
|
||||
<span style={{
|
||||
fontSize: 18,
|
||||
fontWeight: 700,
|
||||
opacity: isSelected ? 1 : 0.8
|
||||
}}>
|
||||
{goal.current_value} {goal.unit}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{goal.target_value && (
|
||||
<>
|
||||
<div style={{ fontSize: 13, opacity: isSelected ? 0.9 : 0.7, marginBottom: 6 }}>
|
||||
Ziel: {goal.target_value} {goal.unit}
|
||||
</div>
|
||||
|
||||
<div style={{
|
||||
width: '100%',
|
||||
height: 6,
|
||||
background: isSelected ? 'rgba(255,255,255,0.2)' : 'var(--surface)',
|
||||
borderRadius: 3,
|
||||
overflow: 'hidden'
|
||||
}}>
|
||||
<div style={{
|
||||
width: `${progress}%`,
|
||||
height: '100%',
|
||||
background: isSelected ? 'white' : 'var(--accent)',
|
||||
transition: 'width 0.3s'
|
||||
}} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Progress Entry Form */}
|
||||
{selectedGoal && (
|
||||
<div className="card">
|
||||
<h2 style={{ fontSize: 16, marginBottom: 16, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<TrendingUp size={20} style={{ color: 'var(--accent)' }} />
|
||||
Fortschritt erfassen
|
||||
</h2>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
|
||||
<div>
|
||||
<div style={{
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
marginBottom: 8,
|
||||
color: 'var(--text1)'
|
||||
}}>
|
||||
Datum
|
||||
</div>
|
||||
<input
|
||||
type="date"
|
||||
className="form-input"
|
||||
value={formData.date}
|
||||
onChange={(e) => setFormData({ ...formData, date: e.target.value })}
|
||||
max={new Date().toISOString().split('T')[0]}
|
||||
style={{ width: '100%', textAlign: 'left' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div style={{
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
marginBottom: 8,
|
||||
color: 'var(--text1)'
|
||||
}}>
|
||||
Wert ({selectedGoal.unit})
|
||||
</div>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
className="form-input"
|
||||
value={formData.value}
|
||||
onChange={(e) => setFormData({ ...formData, value: e.target.value })}
|
||||
placeholder={`Aktueller Wert in ${selectedGoal.unit}`}
|
||||
style={{ width: '100%', textAlign: 'left' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div style={{
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
marginBottom: 8,
|
||||
color: 'var(--text1)'
|
||||
}}>
|
||||
Notiz (optional)
|
||||
</div>
|
||||
<textarea
|
||||
className="form-input"
|
||||
value={formData.note}
|
||||
onChange={(e) => setFormData({ ...formData, note: e.target.value })}
|
||||
placeholder="Optionale Notiz zu dieser Messung..."
|
||||
rows={2}
|
||||
style={{ width: '100%', textAlign: 'left' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
className="btn-primary"
|
||||
onClick={handleSaveProgress}
|
||||
disabled={!formData.value}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
<CheckCircle2 size={18} style={{ marginRight: 8 }} />
|
||||
Wert speichern
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Recent Progress */}
|
||||
{selectedGoal && recentProgress.length > 0 && (
|
||||
<div className="card">
|
||||
<h2 style={{ fontSize: 16, marginBottom: 12, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<Calendar size={20} style={{ color: 'var(--accent)' }} />
|
||||
Letzte Einträge
|
||||
</h2>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{recentProgress.map(entry => (
|
||||
<div key={entry.id} style={{
|
||||
padding: 12,
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: 8
|
||||
}}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
|
||||
<span style={{ fontSize: 14, color: 'var(--text2)' }}>
|
||||
{dayjs(entry.date).format('DD.MM.YYYY')}
|
||||
</span>
|
||||
<span style={{ fontSize: 18, fontWeight: 600, color: 'var(--accent)' }}>
|
||||
{entry.value} {selectedGoal.unit}
|
||||
</span>
|
||||
</div>
|
||||
{entry.note && (
|
||||
<div style={{ fontSize: 13, color: 'var(--text3)' }}>
|
||||
{entry.note}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Help Card */}
|
||||
{!selectedGoal && (
|
||||
<div style={{
|
||||
padding: 16,
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: 8,
|
||||
border: '1px solid var(--border)'
|
||||
}}>
|
||||
<div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
|
||||
<AlertCircle size={20} style={{ color: 'var(--accent)', flexShrink: 0, marginTop: 2 }} />
|
||||
<div style={{ fontSize: 14, color: 'var(--text2)' }}>
|
||||
<div style={{ fontWeight: 600, marginBottom: 4, color: 'var(--text1)' }}>
|
||||
Eigene Ziele erfassen
|
||||
</div>
|
||||
Wähle ein Ziel aus und erfasse regelmäßig deine Fortschritte.
|
||||
Die Werte werden automatisch in deine Zielverfolgung übernommen.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+758
-216
File diff suppressed because it is too large.
Load diff
@@ -334,16 +334,28 @@ export const api = {
|
||||
// v9e: Goals System (Strategic + Tactical)
|
||||
getGoalMode: () => req('/goals/mode'),
|
||||
updateGoalMode: (mode) => req('/goals/mode', jput({goal_mode: mode})),
|
||||
|
||||
// Focus Areas (v2.0)
|
||||
getFocusAreas: () => req('/goals/focus-areas'),
|
||||
updateFocusAreas: (d) => req('/goals/focus-areas', jput(d)),
|
||||
|
||||
listGoals: () => req('/goals/list'),
|
||||
listGoalsGrouped: () => req('/goals/grouped'),
|
||||
createGoal: (d) => req('/goals/create', json(d)),
|
||||
updateGoal: (id,d) => req(`/goals/${id}`, jput(d)),
|
||||
deleteGoal: (id) => req(`/goals/${id}`, {method:'DELETE'}),
|
||||
|
||||
// Goal Progress (v2.1)
|
||||
listGoalProgress: (id) => req(`/goals/${id}/progress`),
|
||||
createGoalProgress: (id,d) => req(`/goals/${id}/progress`, json(d)),
|
||||
deleteGoalProgress: (gid,pid) => req(`/goals/${gid}/progress/${pid}`, {method:'DELETE'}),
|
||||
|
||||
// Goal Type Definitions (Phase 1.5)
|
||||
listGoalTypeDefinitions: () => req('/goals/goal-types'),
|
||||
createGoalType: (d) => req('/goals/goal-types', json(d)),
|
||||
updateGoalType: (id,d) => req(`/goals/goal-types/${id}`, jput(d)),
|
||||
deleteGoalType: (id) => req(`/goals/goal-types/${id}`, {method:'DELETE'}),
|
||||
getSchemaInfo: () => req('/goals/schema-info'),
|
||||
|
||||
// Training Phases
|
||||
listTrainingPhases: () => req('/goals/phases'),
|
||||
|
||||
Reference in new issue
Block a user