Compare commits
49
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
12d516c881 | ||
|
|
448f6ad4f4 | ||
|
|
e4a2b63a48 | ||
|
|
ce4cd7daf1 | ||
|
|
9ab36145e5 | ||
|
|
eb5c099eca | ||
|
|
37ea1f8537 | ||
|
|
378bf434fc | ||
|
|
3116fbbc91 | ||
|
|
dfcdfbe335 | ||
|
|
029530e078 | ||
|
|
ba5d460e92 | ||
|
|
34ea51b8bd | ||
|
|
6ab0a8b631 | ||
|
|
6a961ce88f | ||
|
|
d14157f7ad | ||
|
|
f312dd0dbb | ||
|
|
2f64656d4d | ||
|
|
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 |
No files matched your search
@@ -76,9 +76,55 @@ frontend/src/
|
|||||||
└── technical/ # MEMBERSHIP_SYSTEM.md
|
└── technical/ # MEMBERSHIP_SYSTEM.md
|
||||||
```
|
```
|
||||||
|
|
||||||
## Aktuelle Version: v9e+ (Phase 1 Goal System Fixes) 🎯 Ready for Phase 0b - 27.03.2026
|
## Aktuelle Version: v0.9g+ → v0.9h (Goals Complete + Dynamic Focus Areas) 🎯 27.03.2026
|
||||||
|
|
||||||
### Letzte Updates (27.03.2026 - Phase 1 Fixes) 🆕
|
**Status:** BEREIT FÜR RELEASE v0.9h
|
||||||
|
**Branch:** develop
|
||||||
|
**Nächster Schritt:** Testing → Prod Deploy → Code Splitting → Phase 0b (120+ Platzhalter)
|
||||||
|
|
||||||
|
### Letzte Updates (27.03.2026 - Dynamic Focus Areas v2.0 Complete) 🆕
|
||||||
|
|
||||||
|
#### Dynamic Focus Areas v2.0 System ✅
|
||||||
|
- ✅ **Migration 031-032:** Vollständiges dynamisches System
|
||||||
|
- `focus_area_definitions` - 26 Basis-Bereiche in 7 Kategorien (admin-erweiterbar)
|
||||||
|
- `goal_focus_contributions` - Many-to-Many (Goals ↔ Focus Areas) mit Gewichtung
|
||||||
|
- `user_focus_area_weights` - User-spezifische Präferenzen (dynamisch)
|
||||||
|
- ✅ **Backend:** `routers/focus_areas.py` (~350 Zeilen)
|
||||||
|
- CRUD für Focus Area Definitions (Admin only)
|
||||||
|
- User preferences mit Auto-Normalisierung zu Prozenten
|
||||||
|
- Stats endpoint (Progress per Focus Area)
|
||||||
|
- ✅ **Frontend:** Komplett überarbeitet
|
||||||
|
- GoalsPage: Dynamische Kacheln (nur Bereiche mit Gewicht > 0)
|
||||||
|
- Edit-Modus: Alle 26 Bereiche mit Schiebereglern (gruppiert nach Kategorie)
|
||||||
|
- Ziel-Formular: Nur gewichtete Focus Areas zur Auswahl (cleaner UX)
|
||||||
|
- AdminFocusAreasPage: Volle CRUD-UI für Admin
|
||||||
|
- ✅ **Architektur-Verbesserungen:**
|
||||||
|
- Kein Goal Mode mehr (ersetzt durch dynamische Focus Areas)
|
||||||
|
- M:N Relationship: Ein Ziel zahlt auf 1-n Focus Areas ein
|
||||||
|
- Contribution Weights: Prozentuale Gewichtung pro Zuordnung
|
||||||
|
- User-extensible: Admin kann beliebige neue Bereiche hinzufügen
|
||||||
|
|
||||||
|
#### Bug Fixes (alle deployed) ✅
|
||||||
|
- ✅ **Focus Contributions speichern:** `focus_contributions` fehlte in API-Payload (GoalsPage:232)
|
||||||
|
- ✅ **Focus Area Filtering:** Nur gewichtete Areas im Ziel-Formular (bessere UX)
|
||||||
|
- ✅ **Vitals Baseline Fix:** Parameter mismatch in dynamischer Query-Generierung behoben
|
||||||
|
|
||||||
|
#### Custom Goals Page (Capture/Eigene Ziele) ✅
|
||||||
|
- ✅ **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
|
- ✅ **Abstraction Layer:** goal_utils.py für zukunftssichere Phase 0b Platzhalter
|
||||||
- ✅ **Primary Goal Toggle Fix:** is_primary Update funktioniert korrekt
|
- ✅ **Primary Goal Toggle Fix:** is_primary Update funktioniert korrekt
|
||||||
- ✅ **Lean Mass Berechnung:** Magermasse current_value wird berechnet
|
- ✅ **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()
|
||||||
+161
-55
@@ -24,9 +24,8 @@ def get_focus_weights(conn, profile_id: str) -> Dict[str, float]:
|
|||||||
"""
|
"""
|
||||||
Get focus area weights for a profile.
|
Get focus area weights for a profile.
|
||||||
|
|
||||||
This is an abstraction layer that will evolve:
|
V2 (Goal System v2.0): Reads from focus_areas table with custom user weights.
|
||||||
- V1 (now): Maps goal_mode → predefined weights
|
Falls back to goal_mode mapping if focus_areas not set.
|
||||||
- V2 (later): Reads from focus_areas table → custom user weights
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
conn: Database connection
|
conn: Database connection
|
||||||
@@ -55,7 +54,29 @@ def get_focus_weights(conn, profile_id: str) -> Dict[str, float]:
|
|||||||
"""
|
"""
|
||||||
cur = get_cursor(conn)
|
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(
|
cur.execute(
|
||||||
"SELECT goal_mode FROM profiles WHERE id = %s",
|
"SELECT goal_mode FROM profiles WHERE id = %s",
|
||||||
(profile_id,)
|
(profile_id,)
|
||||||
@@ -63,59 +84,68 @@ def get_focus_weights(conn, profile_id: str) -> Dict[str, float]:
|
|||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
|
|
||||||
if not row:
|
if not row:
|
||||||
# Fallback: balanced health focus
|
# Ultimate fallback: balanced health focus
|
||||||
return {
|
return {
|
||||||
'weight_loss': 0.0,
|
'weight_loss': 0.0,
|
||||||
'muscle_gain': 0.0,
|
'muscle_gain': 0.0,
|
||||||
'strength': 0.0,
|
'strength': 0.10,
|
||||||
'endurance': 0.0,
|
'endurance': 0.20,
|
||||||
'flexibility': 0.0,
|
'flexibility': 0.15,
|
||||||
'health': 1.0
|
'health': 0.55
|
||||||
}
|
}
|
||||||
|
|
||||||
goal_mode = row['goal_mode'] or 'health'
|
goal_mode = row['goal_mode']
|
||||||
|
|
||||||
# V1: Predefined weight mappings per goal_mode
|
if not goal_mode:
|
||||||
# These represent "typical" focus distributions for each 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_MAPPINGS = {
|
||||||
'weight_loss': {
|
'weight_loss': {
|
||||||
'weight_loss': 0.60, # Primary: fat loss
|
'weight_loss': 0.60,
|
||||||
'endurance': 0.20, # Support: cardio for calorie burn
|
'endurance': 0.20,
|
||||||
'muscle_gain': 0.0, # Not compatible
|
'muscle_gain': 0.0,
|
||||||
'strength': 0.10, # Maintain muscle during deficit
|
'strength': 0.10,
|
||||||
'flexibility': 0.05, # Minor: mobility work
|
'flexibility': 0.05,
|
||||||
'health': 0.05 # Minor: general wellness
|
'health': 0.05
|
||||||
},
|
},
|
||||||
'strength': {
|
'strength': {
|
||||||
'strength': 0.50, # Primary: strength gains
|
'strength': 0.50,
|
||||||
'muscle_gain': 0.40, # Support: hypertrophy
|
'muscle_gain': 0.40,
|
||||||
'endurance': 0.10, # Minor: work capacity
|
'endurance': 0.10,
|
||||||
'weight_loss': 0.0, # Not compatible with strength focus
|
'weight_loss': 0.0,
|
||||||
'flexibility': 0.0,
|
'flexibility': 0.0,
|
||||||
'health': 0.0
|
'health': 0.0
|
||||||
},
|
},
|
||||||
'endurance': {
|
'endurance': {
|
||||||
'endurance': 0.70, # Primary: aerobic capacity
|
'endurance': 0.70,
|
||||||
'health': 0.20, # Support: cardiovascular health
|
'health': 0.20,
|
||||||
'flexibility': 0.10, # Support: mobility for running
|
'flexibility': 0.10,
|
||||||
'weight_loss': 0.0,
|
'weight_loss': 0.0,
|
||||||
'muscle_gain': 0.0,
|
'muscle_gain': 0.0,
|
||||||
'strength': 0.0
|
'strength': 0.0
|
||||||
},
|
},
|
||||||
'recomposition': {
|
'recomposition': {
|
||||||
'weight_loss': 0.30, # Equal: lose fat
|
'weight_loss': 0.30,
|
||||||
'muscle_gain': 0.30, # Equal: gain muscle
|
'muscle_gain': 0.30,
|
||||||
'strength': 0.25, # Support: progressive overload
|
'strength': 0.25,
|
||||||
'endurance': 0.10, # Minor: conditioning
|
'endurance': 0.10,
|
||||||
'flexibility': 0.05, # Minor: mobility
|
'flexibility': 0.05,
|
||||||
'health': 0.0
|
'health': 0.0
|
||||||
},
|
},
|
||||||
'health': {
|
'health': {
|
||||||
'health': 0.50, # Primary: general wellness
|
'health': 0.50,
|
||||||
'endurance': 0.20, # Support: cardio health
|
'endurance': 0.20,
|
||||||
'flexibility': 0.15, # Support: mobility
|
'flexibility': 0.15,
|
||||||
'strength': 0.10, # Support: functional strength
|
'strength': 0.10,
|
||||||
'weight_loss': 0.05, # Minor: maintain healthy weight
|
'weight_loss': 0.05,
|
||||||
'muscle_gain': 0.0
|
'muscle_gain': 0.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -181,7 +211,7 @@ def get_goal_type_config(conn, type_key: str) -> Optional[Dict[str, Any]]:
|
|||||||
|
|
||||||
cur.execute("""
|
cur.execute("""
|
||||||
SELECT type_key, source_table, source_column, aggregation_method,
|
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
|
FROM goal_type_definitions
|
||||||
WHERE type_key = %s AND is_active = true
|
WHERE type_key = %s AND is_active = true
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
@@ -221,7 +251,8 @@ def get_current_value_for_goal(conn, profile_id: str, goal_type: str) -> Optiona
|
|||||||
profile_id,
|
profile_id,
|
||||||
config['source_table'],
|
config['source_table'],
|
||||||
config['source_column'],
|
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,
|
profile_id: str,
|
||||||
table: str,
|
table: str,
|
||||||
column: str,
|
column: str,
|
||||||
method: str
|
method: str,
|
||||||
|
filter_conditions: Optional[Any] = None
|
||||||
) -> Optional[float]:
|
) -> Optional[float]:
|
||||||
"""
|
"""
|
||||||
Fetch value using specified aggregation method.
|
Fetch value using specified aggregation method.
|
||||||
@@ -244,78 +276,134 @@ def _fetch_by_aggregation_method(
|
|||||||
- count_30d: Count of entries in last 30 days
|
- count_30d: Count of entries in last 30 days
|
||||||
- min_30d: Minimum value in last 30 days
|
- min_30d: Minimum value in last 30 days
|
||||||
- max_30d: Maximum value in last 30 days
|
- max_30d: Maximum value in last 30 days
|
||||||
|
|
||||||
|
Args:
|
||||||
|
filter_conditions: Optional JSON filters (e.g., {"training_category": "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)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
try:
|
||||||
if method == 'latest':
|
if method == 'latest':
|
||||||
|
params = [profile_id] + filter_params
|
||||||
cur.execute(f"""
|
cur.execute(f"""
|
||||||
SELECT {column} FROM {table}
|
SELECT {column} FROM {table}
|
||||||
WHERE profile_id = %s AND {column} IS NOT NULL
|
WHERE profile_id = %s AND {column} IS NOT NULL{filter_sql}
|
||||||
ORDER BY date DESC LIMIT 1
|
ORDER BY {date_col} DESC LIMIT 1
|
||||||
""", (profile_id,))
|
""", params)
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
return float(row[column]) if row else None
|
return float(row[column]) if row else None
|
||||||
|
|
||||||
elif method == 'avg_7d':
|
elif method == 'avg_7d':
|
||||||
days_ago = date.today() - timedelta(days=7)
|
days_ago = date.today() - timedelta(days=7)
|
||||||
|
params = [profile_id, days_ago] + filter_params
|
||||||
cur.execute(f"""
|
cur.execute(f"""
|
||||||
SELECT AVG({column}) as avg_value FROM {table}
|
SELECT AVG({column}) as avg_value FROM {table}
|
||||||
WHERE profile_id = %s AND date >= %s AND {column} IS NOT NULL
|
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||||
""", (profile_id, days_ago))
|
""", params)
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
return float(row['avg_value']) if row and row['avg_value'] is not None else None
|
return float(row['avg_value']) if row and row['avg_value'] is not None else None
|
||||||
|
|
||||||
elif method == 'avg_30d':
|
elif method == 'avg_30d':
|
||||||
days_ago = date.today() - timedelta(days=30)
|
days_ago = date.today() - timedelta(days=30)
|
||||||
|
params = [profile_id, days_ago] + filter_params
|
||||||
cur.execute(f"""
|
cur.execute(f"""
|
||||||
SELECT AVG({column}) as avg_value FROM {table}
|
SELECT AVG({column}) as avg_value FROM {table}
|
||||||
WHERE profile_id = %s AND date >= %s AND {column} IS NOT NULL
|
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||||
""", (profile_id, days_ago))
|
""", params)
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
return float(row['avg_value']) if row and row['avg_value'] is not None else None
|
return float(row['avg_value']) if row and row['avg_value'] is not None else None
|
||||||
|
|
||||||
elif method == 'sum_30d':
|
elif method == 'sum_30d':
|
||||||
days_ago = date.today() - timedelta(days=30)
|
days_ago = date.today() - timedelta(days=30)
|
||||||
|
params = [profile_id, days_ago] + filter_params
|
||||||
cur.execute(f"""
|
cur.execute(f"""
|
||||||
SELECT SUM({column}) as sum_value FROM {table}
|
SELECT SUM({column}) as sum_value FROM {table}
|
||||||
WHERE profile_id = %s AND date >= %s AND {column} IS NOT NULL
|
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||||
""", (profile_id, days_ago))
|
""", params)
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
return float(row['sum_value']) if row and row['sum_value'] is not None else None
|
return float(row['sum_value']) if row and row['sum_value'] is not None else None
|
||||||
|
|
||||||
elif method == 'count_7d':
|
elif method == 'count_7d':
|
||||||
days_ago = date.today() - timedelta(days=7)
|
days_ago = date.today() - timedelta(days=7)
|
||||||
|
params = [profile_id, days_ago] + filter_params
|
||||||
cur.execute(f"""
|
cur.execute(f"""
|
||||||
SELECT COUNT(*) as count_value FROM {table}
|
SELECT COUNT(*) as count_value FROM {table}
|
||||||
WHERE profile_id = %s AND date >= %s
|
WHERE profile_id = %s AND {date_col} >= %s{filter_sql}
|
||||||
""", (profile_id, days_ago))
|
""", params)
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
return float(row['count_value']) if row else 0.0
|
return float(row['count_value']) if row else 0.0
|
||||||
|
|
||||||
elif method == 'count_30d':
|
elif method == 'count_30d':
|
||||||
days_ago = date.today() - timedelta(days=30)
|
days_ago = date.today() - timedelta(days=30)
|
||||||
|
params = [profile_id, days_ago] + filter_params
|
||||||
cur.execute(f"""
|
cur.execute(f"""
|
||||||
SELECT COUNT(*) as count_value FROM {table}
|
SELECT COUNT(*) as count_value FROM {table}
|
||||||
WHERE profile_id = %s AND date >= %s
|
WHERE profile_id = %s AND {date_col} >= %s{filter_sql}
|
||||||
""", (profile_id, days_ago))
|
""", params)
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
return float(row['count_value']) if row else 0.0
|
return float(row['count_value']) if row else 0.0
|
||||||
|
|
||||||
elif method == 'min_30d':
|
elif method == 'min_30d':
|
||||||
days_ago = date.today() - timedelta(days=30)
|
days_ago = date.today() - timedelta(days=30)
|
||||||
|
params = [profile_id, days_ago] + filter_params
|
||||||
cur.execute(f"""
|
cur.execute(f"""
|
||||||
SELECT MIN({column}) as min_value FROM {table}
|
SELECT MIN({column}) as min_value FROM {table}
|
||||||
WHERE profile_id = %s AND date >= %s AND {column} IS NOT NULL
|
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||||
""", (profile_id, days_ago))
|
""", params)
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
return float(row['min_value']) if row and row['min_value'] is not None else None
|
return float(row['min_value']) if row and row['min_value'] is not None else None
|
||||||
|
|
||||||
elif method == 'max_30d':
|
elif method == 'max_30d':
|
||||||
days_ago = date.today() - timedelta(days=30)
|
days_ago = date.today() - timedelta(days=30)
|
||||||
|
params = [profile_id, days_ago] + filter_params
|
||||||
cur.execute(f"""
|
cur.execute(f"""
|
||||||
SELECT MAX({column}) as max_value FROM {table}
|
SELECT MAX({column}) as max_value FROM {table}
|
||||||
WHERE profile_id = %s AND date >= %s AND {column} IS NOT NULL
|
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||||
""", (profile_id, days_ago))
|
""", params)
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
return float(row['max_value']) if row and row['max_value'] is not None else None
|
return float(row['max_value']) if row and row['max_value'] is not None else None
|
||||||
|
|
||||||
@@ -323,6 +411,24 @@ def _fetch_by_aggregation_method(
|
|||||||
print(f"[WARNING] Unknown aggregation method: {method}")
|
print(f"[WARNING] Unknown aggregation method: {method}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
# Log detailed error for debugging
|
||||||
|
print(f"[ERROR] Failed to fetch value from {table}.{column} using {method}: {e}")
|
||||||
|
print(f"[ERROR] Filter conditions: {filter_conditions}")
|
||||||
|
print(f"[ERROR] Filter SQL: {filter_sql}")
|
||||||
|
print(f"[ERROR] Filter params: {filter_params}")
|
||||||
|
|
||||||
|
# CRITICAL: Rollback transaction to avoid InFailedSqlTransaction errors
|
||||||
|
try:
|
||||||
|
conn.rollback()
|
||||||
|
print(f"[INFO] Transaction rolled back after query error")
|
||||||
|
except Exception as rollback_err:
|
||||||
|
print(f"[WARNING] Rollback failed: {rollback_err}")
|
||||||
|
|
||||||
|
# Return None so goal creation can continue without current_value
|
||||||
|
# (current_value will be NULL in the goal record)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _execute_calculation_formula(conn, profile_id: str, formula_json: str) -> Optional[float]:
|
def _execute_calculation_formula(conn, profile_id: str, formula_json: str) -> Optional[float]:
|
||||||
"""
|
"""
|
||||||
|
|||||||
+8
-2
@@ -23,7 +23,8 @@ from routers import user_restrictions, access_grants, training_types, admin_trai
|
|||||||
from routers import admin_activity_mappings, sleep, rest_days
|
from routers import admin_activity_mappings, sleep, rest_days
|
||||||
from routers import vitals_baseline, blood_pressure # v9d Phase 2d Refactored
|
from routers import vitals_baseline, blood_pressure # v9d Phase 2d Refactored
|
||||||
from routers import evaluation # v9d/v9e Training Type Profiles (#15)
|
from routers import evaluation # v9d/v9e Training Type Profiles (#15)
|
||||||
from routers import goals # v9e Goal System (Strategic + Tactical)
|
from routers import goals, focus_areas # v9e/v9g Goal System v2.0 (Dynamic Focus Areas)
|
||||||
|
from routers import goal_types, goal_progress, training_phases, fitness_tests # v9h Goal System (Split routers)
|
||||||
|
|
||||||
# ── App Configuration ─────────────────────────────────────────────────────────
|
# ── App Configuration ─────────────────────────────────────────────────────────
|
||||||
DATA_DIR = Path(os.getenv("DATA_DIR", "./data"))
|
DATA_DIR = Path(os.getenv("DATA_DIR", "./data"))
|
||||||
@@ -98,7 +99,12 @@ app.include_router(rest_days.router) # /api/rest-days/* (v9d Phase 2a
|
|||||||
app.include_router(vitals_baseline.router) # /api/vitals/baseline/* (v9d Phase 2d Refactored)
|
app.include_router(vitals_baseline.router) # /api/vitals/baseline/* (v9d Phase 2d Refactored)
|
||||||
app.include_router(blood_pressure.router) # /api/blood-pressure/* (v9d Phase 2d Refactored)
|
app.include_router(blood_pressure.router) # /api/blood-pressure/* (v9d Phase 2d Refactored)
|
||||||
app.include_router(evaluation.router) # /api/evaluation/* (v9d/v9e Training Profiles #15)
|
app.include_router(evaluation.router) # /api/evaluation/* (v9d/v9e Training Profiles #15)
|
||||||
app.include_router(goals.router) # /api/goals/* (v9e Goal System Strategic + Tactical)
|
app.include_router(goals.router) # /api/goals/* (v9h Goal System Core CRUD + Focus Areas)
|
||||||
|
app.include_router(goal_types.router) # /api/goals/goal-types/* (v9h Goal Type Definitions)
|
||||||
|
app.include_router(goal_progress.router) # /api/goals/{goal_id}/progress/* (v9h Progress Tracking)
|
||||||
|
app.include_router(training_phases.router) # /api/goals/phases/* (v9h Training Phases)
|
||||||
|
app.include_router(fitness_tests.router) # /api/goals/tests/* (v9h Fitness Tests)
|
||||||
|
app.include_router(focus_areas.router) # /api/focus-areas/* (v9g Focus Area System v2.0 - Dynamic)
|
||||||
|
|
||||||
# ── Health Check ──────────────────────────────────────────────────────────────
|
# ── Health Check ──────────────────────────────────────────────────────────────
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
|
|||||||
@@ -36,9 +36,7 @@ CREATE TABLE IF NOT EXISTS goal_type_definitions (
|
|||||||
|
|
||||||
-- Audit
|
-- Audit
|
||||||
created_at TIMESTAMP DEFAULT NOW(),
|
created_at TIMESTAMP DEFAULT NOW(),
|
||||||
updated_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
|
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_goal_type_definitions_active ON goal_type_definitions(is_active) WHERE is_active = true;
|
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', 'Gewicht', 'Weight', 'kg', '⚖️', 'body',
|
||||||
'weight_log', 'weight', 'latest',
|
'weight_log', 'weight', 'latest',
|
||||||
'Aktuelles Körpergewicht', true
|
'Aktuelles Körpergewicht', true
|
||||||
);
|
)
|
||||||
|
ON CONFLICT (type_key) DO NOTHING;
|
||||||
|
|
||||||
-- 2. Body Fat (simple - latest value)
|
-- 2. Body Fat (simple - latest value)
|
||||||
INSERT INTO goal_type_definitions (
|
INSERT INTO goal_type_definitions (
|
||||||
@@ -74,7 +73,8 @@ INSERT INTO goal_type_definitions (
|
|||||||
'body_fat', 'Körperfett', 'Body Fat', '%', '📊', 'body',
|
'body_fat', 'Körperfett', 'Body Fat', '%', '📊', 'body',
|
||||||
'caliper_log', 'body_fat_pct', 'latest',
|
'caliper_log', 'body_fat_pct', 'latest',
|
||||||
'Körperfettanteil aus Caliper-Messung', true
|
'Körperfettanteil aus Caliper-Messung', true
|
||||||
);
|
)
|
||||||
|
ON CONFLICT (type_key) DO NOTHING;
|
||||||
|
|
||||||
-- 3. Lean Mass (complex - calculation formula)
|
-- 3. Lean Mass (complex - calculation formula)
|
||||||
INSERT INTO goal_type_definitions (
|
INSERT INTO goal_type_definitions (
|
||||||
@@ -85,7 +85,8 @@ INSERT INTO goal_type_definitions (
|
|||||||
'lean_mass', 'Muskelmasse', 'Lean Mass', 'kg', '💪', 'body',
|
'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)"}',
|
'{"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
|
'Fettfreie Körpermasse (berechnet aus Gewicht und Körperfett)', true
|
||||||
);
|
)
|
||||||
|
ON CONFLICT (type_key) DO NOTHING;
|
||||||
|
|
||||||
-- 4. VO2 Max (simple - latest value)
|
-- 4. VO2 Max (simple - latest value)
|
||||||
INSERT INTO goal_type_definitions (
|
INSERT INTO goal_type_definitions (
|
||||||
@@ -96,7 +97,8 @@ INSERT INTO goal_type_definitions (
|
|||||||
'vo2max', 'VO2Max', 'VO2Max', 'ml/kg/min', '🫁', 'recovery',
|
'vo2max', 'VO2Max', 'VO2Max', 'ml/kg/min', '🫁', 'recovery',
|
||||||
'vitals_baseline', 'vo2_max', 'latest',
|
'vitals_baseline', 'vo2_max', 'latest',
|
||||||
'Maximale Sauerstoffaufnahme (geschätzt oder gemessen)', true
|
'Maximale Sauerstoffaufnahme (geschätzt oder gemessen)', true
|
||||||
);
|
)
|
||||||
|
ON CONFLICT (type_key) DO NOTHING;
|
||||||
|
|
||||||
-- 5. Resting Heart Rate (simple - latest value)
|
-- 5. Resting Heart Rate (simple - latest value)
|
||||||
INSERT INTO goal_type_definitions (
|
INSERT INTO goal_type_definitions (
|
||||||
@@ -107,7 +109,8 @@ INSERT INTO goal_type_definitions (
|
|||||||
'rhr', 'Ruhepuls', 'Resting Heart Rate', 'bpm', '💓', 'recovery',
|
'rhr', 'Ruhepuls', 'Resting Heart Rate', 'bpm', '💓', 'recovery',
|
||||||
'vitals_baseline', 'resting_hr', 'latest',
|
'vitals_baseline', 'resting_hr', 'latest',
|
||||||
'Ruhepuls morgens vor dem Aufstehen', true
|
'Ruhepuls morgens vor dem Aufstehen', true
|
||||||
);
|
)
|
||||||
|
ON CONFLICT (type_key) DO NOTHING;
|
||||||
|
|
||||||
-- 6. Blood Pressure (placeholder - compound goal for v2.0)
|
-- 6. Blood Pressure (placeholder - compound goal for v2.0)
|
||||||
-- Currently limited to single value, v2.0 will support systolic/diastolic
|
-- 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',
|
'bp', 'Blutdruck', 'Blood Pressure', 'mmHg', '❤️', 'recovery',
|
||||||
'blood_pressure_log', 'systolic', 'latest',
|
'blood_pressure_log', 'systolic', 'latest',
|
||||||
'Blutdruck (aktuell nur systolisch, v2.0: beide Werte)', true
|
'Blutdruck (aktuell nur systolisch, v2.0: beide Werte)', true
|
||||||
);
|
)
|
||||||
|
ON CONFLICT (type_key) DO NOTHING;
|
||||||
|
|
||||||
-- 7. Strength (placeholder - no data source yet)
|
-- 7. Strength (placeholder - no data source yet)
|
||||||
INSERT INTO goal_type_definitions (
|
INSERT INTO goal_type_definitions (
|
||||||
@@ -128,7 +132,8 @@ INSERT INTO goal_type_definitions (
|
|||||||
) VALUES (
|
) VALUES (
|
||||||
'strength', 'Kraft', 'Strength', 'kg', '🏋️', 'activity',
|
'strength', 'Kraft', 'Strength', 'kg', '🏋️', 'activity',
|
||||||
'Maximalkraft (Platzhalter, Datenquelle in v2.0)', true, false
|
'Maximalkraft (Platzhalter, Datenquelle in v2.0)', true, false
|
||||||
);
|
)
|
||||||
|
ON CONFLICT (type_key) DO NOTHING;
|
||||||
|
|
||||||
-- 8. Flexibility (placeholder - no data source yet)
|
-- 8. Flexibility (placeholder - no data source yet)
|
||||||
INSERT INTO goal_type_definitions (
|
INSERT INTO goal_type_definitions (
|
||||||
@@ -137,7 +142,8 @@ INSERT INTO goal_type_definitions (
|
|||||||
) VALUES (
|
) VALUES (
|
||||||
'flexibility', 'Beweglichkeit', 'Flexibility', 'cm', '🤸', 'activity',
|
'flexibility', 'Beweglichkeit', 'Flexibility', 'cm', '🤸', 'activity',
|
||||||
'Beweglichkeit (Platzhalter, Datenquelle in v2.0)', true, false
|
'Beweglichkeit (Platzhalter, Datenquelle in v2.0)', true, false
|
||||||
);
|
)
|
||||||
|
ON CONFLICT (type_key) DO NOTHING;
|
||||||
|
|
||||||
-- ============================================================================
|
-- ============================================================================
|
||||||
-- Example: Future custom goal types (commented out, for reference)
|
-- 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';
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
-- Migration 031: Focus Area System v2.0
|
||||||
|
-- Date: 2026-03-27
|
||||||
|
-- Purpose: Dynamic, extensible focus areas with Many-to-Many goal contributions
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- Part 1: New Tables
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
-- Focus Area Definitions (dynamic, user-extensible)
|
||||||
|
CREATE TABLE IF NOT EXISTS focus_area_definitions (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
key VARCHAR(50) UNIQUE NOT NULL, -- e.g. 'strength', 'aerobic_endurance'
|
||||||
|
name_de VARCHAR(100) NOT NULL,
|
||||||
|
name_en VARCHAR(100),
|
||||||
|
icon VARCHAR(10),
|
||||||
|
description TEXT,
|
||||||
|
category VARCHAR(50), -- 'body_composition', 'training', 'endurance', 'coordination', 'mental', 'recovery', 'health'
|
||||||
|
is_active BOOLEAN DEFAULT true,
|
||||||
|
created_at TIMESTAMP DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMP DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_focus_area_key ON focus_area_definitions(key);
|
||||||
|
CREATE INDEX idx_focus_area_category ON focus_area_definitions(category);
|
||||||
|
|
||||||
|
COMMENT ON TABLE focus_area_definitions IS 'Dynamic focus area registry - defines all available focus dimensions';
|
||||||
|
COMMENT ON COLUMN focus_area_definitions.key IS 'Unique identifier for programmatic access';
|
||||||
|
COMMENT ON COLUMN focus_area_definitions.category IS 'Grouping for UI display';
|
||||||
|
|
||||||
|
-- Many-to-Many: Goals contribute to Focus Areas
|
||||||
|
CREATE TABLE IF NOT EXISTS goal_focus_contributions (
|
||||||
|
goal_id UUID NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
|
||||||
|
focus_area_id UUID NOT NULL REFERENCES focus_area_definitions(id) ON DELETE CASCADE,
|
||||||
|
contribution_weight DECIMAL(5,2) DEFAULT 100.00 CHECK (contribution_weight >= 0 AND contribution_weight <= 100),
|
||||||
|
created_at TIMESTAMP DEFAULT NOW(),
|
||||||
|
PRIMARY KEY (goal_id, focus_area_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_gfc_goal ON goal_focus_contributions(goal_id);
|
||||||
|
CREATE INDEX idx_gfc_focus_area ON goal_focus_contributions(focus_area_id);
|
||||||
|
|
||||||
|
COMMENT ON TABLE goal_focus_contributions IS 'Maps goals to focus areas with contribution weights (0-100%)';
|
||||||
|
COMMENT ON COLUMN goal_focus_contributions.contribution_weight IS 'How much this goal contributes to the focus area (0-100%)';
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- Part 2: Rename existing focus_areas table
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
-- Old focus_areas table becomes user_focus_preferences
|
||||||
|
ALTER TABLE focus_areas RENAME TO user_focus_preferences;
|
||||||
|
|
||||||
|
-- Add reference to new focus_area_definitions (for future use)
|
||||||
|
ALTER TABLE user_focus_preferences ADD COLUMN IF NOT EXISTS notes TEXT;
|
||||||
|
|
||||||
|
COMMENT ON TABLE user_focus_preferences IS 'User-specific focus area weightings (legacy flat structure + new references)';
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- Part 3: Seed Data - Basis Focus Areas
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
INSERT INTO focus_area_definitions (key, name_de, name_en, icon, category, description) VALUES
|
||||||
|
-- Body Composition
|
||||||
|
('weight_loss', 'Gewichtsverlust', 'Weight Loss', '📉', 'body_composition', 'Körpergewicht reduzieren'),
|
||||||
|
('muscle_gain', 'Muskelaufbau', 'Muscle Gain', '💪', 'body_composition', 'Muskelmasse aufbauen'),
|
||||||
|
('body_recomposition', 'Body Recomposition', 'Body Recomposition', '⚖️', 'body_composition', 'Gleichzeitig Fett abbauen und Muskeln aufbauen'),
|
||||||
|
|
||||||
|
-- Training - Kraft
|
||||||
|
('strength', 'Maximalkraft', 'Strength', '🏋️', 'training', 'Maximale Kraftfähigkeit'),
|
||||||
|
('strength_endurance', 'Kraftausdauer', 'Strength Endurance', '💪🏃', 'training', 'Kraft über längere Zeit aufrechterhalten'),
|
||||||
|
('power', 'Schnellkraft', 'Power', '⚡', 'training', 'Kraft in kurzer Zeit entfalten'),
|
||||||
|
|
||||||
|
-- Training - Beweglichkeit
|
||||||
|
('flexibility', 'Beweglichkeit', 'Flexibility', '🤸', 'training', 'Gelenkigkeit und Bewegungsumfang'),
|
||||||
|
('mobility', 'Mobilität', 'Mobility', '🦴', 'training', 'Aktive Beweglichkeit und Kontrolle'),
|
||||||
|
|
||||||
|
-- Ausdauer
|
||||||
|
('aerobic_endurance', 'Aerobe Ausdauer', 'Aerobic Endurance', '🫁', 'endurance', 'VO2Max, lange moderate Belastung'),
|
||||||
|
('anaerobic_endurance', 'Anaerobe Ausdauer', 'Anaerobic Endurance', '⚡', 'endurance', 'Laktattoleranz, kurze intensive Belastung'),
|
||||||
|
('cardiovascular_health', 'Herz-Kreislauf', 'Cardiovascular Health', '❤️', 'endurance', 'Herzgesundheit und Ausdauer'),
|
||||||
|
|
||||||
|
-- Koordination
|
||||||
|
('balance', 'Gleichgewicht', 'Balance', '⚖️', 'coordination', 'Statisches und dynamisches Gleichgewicht'),
|
||||||
|
('reaction', 'Reaktionsfähigkeit', 'Reaction', '⚡', 'coordination', 'Schnelligkeit der Reaktion auf Reize'),
|
||||||
|
('rhythm', 'Rhythmusgefühl', 'Rhythm', '🎵', 'coordination', 'Zeitliche Abstimmung von Bewegungen'),
|
||||||
|
('coordination', 'Koordination', 'Coordination', '🎯', 'coordination', 'Zusammenspiel verschiedener Bewegungen'),
|
||||||
|
|
||||||
|
-- Mental
|
||||||
|
('stress_resistance', 'Stressresistenz', 'Stress Resistance', '🧘', 'mental', 'Umgang mit mentalem und physischem Stress'),
|
||||||
|
('concentration', 'Konzentration', 'Concentration', '🎯', 'mental', 'Fokussierung und Aufmerksamkeit'),
|
||||||
|
('willpower', 'Willenskraft', 'Willpower', '💎', 'mental', 'Durchhaltevermögen und Selbstdisziplin'),
|
||||||
|
('mental_health', 'Mentale Gesundheit', 'Mental Health', '🧠', 'mental', 'Psychisches Wohlbefinden'),
|
||||||
|
|
||||||
|
-- Recovery
|
||||||
|
('sleep_quality', 'Schlafqualität', 'Sleep Quality', '😴', 'recovery', 'Erholsamer Schlaf'),
|
||||||
|
('regeneration', 'Regeneration', 'Regeneration', '♻️', 'recovery', 'Körperliche Erholung'),
|
||||||
|
('rest', 'Ruhe', 'Rest', '🛌', 'recovery', 'Aktive und passive Erholung'),
|
||||||
|
|
||||||
|
-- Health
|
||||||
|
('metabolic_health', 'Stoffwechselgesundheit', 'Metabolic Health', '🔥', 'health', 'Blutzucker, Insulin, Stoffwechsel'),
|
||||||
|
('blood_pressure', 'Blutdruck', 'Blood Pressure', '❤️🩹', 'health', 'Gesunder Blutdruck'),
|
||||||
|
('hrv', 'Herzratenvariabilität', 'HRV', '💓', 'health', 'Autonomes Nervensystem'),
|
||||||
|
('general_health', 'Allgemeine Gesundheit', 'General Health', '🏥', 'health', 'Vitale Gesundheit und Wohlbefinden')
|
||||||
|
ON CONFLICT (key) DO NOTHING;
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- Part 4: Auto-Mapping - Bestehende Goals zu Focus Areas
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
-- Helper function to get focus_area_id by key
|
||||||
|
CREATE OR REPLACE FUNCTION get_focus_area_id(area_key VARCHAR)
|
||||||
|
RETURNS UUID AS $$
|
||||||
|
BEGIN
|
||||||
|
RETURN (SELECT id FROM focus_area_definitions WHERE key = area_key LIMIT 1);
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
-- Weight goals → weight_loss (100%)
|
||||||
|
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||||
|
SELECT g.id, get_focus_area_id('weight_loss'), 100.00
|
||||||
|
FROM goals g
|
||||||
|
WHERE g.goal_type = 'weight'
|
||||||
|
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||||
|
|
||||||
|
-- Body Fat goals → weight_loss (60%) + body_recomposition (40%)
|
||||||
|
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||||
|
SELECT g.id, fa.id,
|
||||||
|
CASE fa.key
|
||||||
|
WHEN 'weight_loss' THEN 60.00
|
||||||
|
WHEN 'body_recomposition' THEN 40.00
|
||||||
|
END
|
||||||
|
FROM goals g
|
||||||
|
CROSS JOIN focus_area_definitions fa
|
||||||
|
WHERE g.goal_type = 'body_fat'
|
||||||
|
AND fa.key IN ('weight_loss', 'body_recomposition')
|
||||||
|
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||||
|
|
||||||
|
-- Lean Mass goals → muscle_gain (70%) + body_recomposition (30%)
|
||||||
|
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||||
|
SELECT g.id, fa.id,
|
||||||
|
CASE fa.key
|
||||||
|
WHEN 'muscle_gain' THEN 70.00
|
||||||
|
WHEN 'body_recomposition' THEN 30.00
|
||||||
|
END
|
||||||
|
FROM goals g
|
||||||
|
CROSS JOIN focus_area_definitions fa
|
||||||
|
WHERE g.goal_type = 'lean_mass'
|
||||||
|
AND fa.key IN ('muscle_gain', 'body_recomposition')
|
||||||
|
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||||
|
|
||||||
|
-- Strength goals → strength (70%) + muscle_gain (30%)
|
||||||
|
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||||
|
SELECT g.id, fa.id,
|
||||||
|
CASE fa.key
|
||||||
|
WHEN 'strength' THEN 70.00
|
||||||
|
WHEN 'muscle_gain' THEN 30.00
|
||||||
|
END
|
||||||
|
FROM goals g
|
||||||
|
CROSS JOIN focus_area_definitions fa
|
||||||
|
WHERE g.goal_type = 'strength'
|
||||||
|
AND fa.key IN ('strength', 'muscle_gain')
|
||||||
|
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||||
|
|
||||||
|
-- Flexibility goals → flexibility (100%)
|
||||||
|
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||||
|
SELECT g.id, get_focus_area_id('flexibility'), 100.00
|
||||||
|
FROM goals g
|
||||||
|
WHERE g.goal_type = 'flexibility'
|
||||||
|
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||||
|
|
||||||
|
-- VO2Max goals → aerobic_endurance (80%) + cardiovascular_health (20%)
|
||||||
|
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||||
|
SELECT g.id, fa.id,
|
||||||
|
CASE fa.key
|
||||||
|
WHEN 'aerobic_endurance' THEN 80.00
|
||||||
|
WHEN 'cardiovascular_health' THEN 20.00
|
||||||
|
END
|
||||||
|
FROM goals g
|
||||||
|
CROSS JOIN focus_area_definitions fa
|
||||||
|
WHERE g.goal_type = 'vo2max'
|
||||||
|
AND fa.key IN ('aerobic_endurance', 'cardiovascular_health')
|
||||||
|
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||||
|
|
||||||
|
-- Resting Heart Rate goals → cardiovascular_health (100%)
|
||||||
|
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||||
|
SELECT g.id, get_focus_area_id('cardiovascular_health'), 100.00
|
||||||
|
FROM goals g
|
||||||
|
WHERE g.goal_type = 'rhr'
|
||||||
|
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||||
|
|
||||||
|
-- Blood Pressure goals → blood_pressure (80%) + cardiovascular_health (20%)
|
||||||
|
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||||
|
SELECT g.id, fa.id,
|
||||||
|
CASE fa.key
|
||||||
|
WHEN 'blood_pressure' THEN 80.00
|
||||||
|
WHEN 'cardiovascular_health' THEN 20.00
|
||||||
|
END
|
||||||
|
FROM goals g
|
||||||
|
CROSS JOIN focus_area_definitions fa
|
||||||
|
WHERE g.goal_type = 'bp'
|
||||||
|
AND fa.key IN ('blood_pressure', 'cardiovascular_health')
|
||||||
|
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||||
|
|
||||||
|
-- HRV goals → hrv (70%) + stress_resistance (30%)
|
||||||
|
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||||
|
SELECT g.id, fa.id,
|
||||||
|
CASE fa.key
|
||||||
|
WHEN 'hrv' THEN 70.00
|
||||||
|
WHEN 'stress_resistance' THEN 30.00
|
||||||
|
END
|
||||||
|
FROM goals g
|
||||||
|
CROSS JOIN focus_area_definitions fa
|
||||||
|
WHERE g.goal_type = 'hrv'
|
||||||
|
AND fa.key IN ('hrv', 'stress_resistance')
|
||||||
|
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||||
|
|
||||||
|
-- Sleep Quality goals → sleep_quality (100%)
|
||||||
|
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||||
|
SELECT g.id, get_focus_area_id('sleep_quality'), 100.00
|
||||||
|
FROM goals g
|
||||||
|
WHERE g.goal_type = 'sleep_quality'
|
||||||
|
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||||
|
|
||||||
|
-- Training Frequency goals → general catch-all (strength + endurance)
|
||||||
|
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||||
|
SELECT g.id, fa.id,
|
||||||
|
CASE fa.key
|
||||||
|
WHEN 'strength' THEN 40.00
|
||||||
|
WHEN 'aerobic_endurance' THEN 40.00
|
||||||
|
WHEN 'general_health' THEN 20.00
|
||||||
|
END
|
||||||
|
FROM goals g
|
||||||
|
CROSS JOIN focus_area_definitions fa
|
||||||
|
WHERE g.goal_type = 'training_frequency'
|
||||||
|
AND fa.key IN ('strength', 'aerobic_endurance', 'general_health')
|
||||||
|
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||||
|
|
||||||
|
-- Cleanup helper function
|
||||||
|
DROP FUNCTION IF EXISTS get_focus_area_id(VARCHAR);
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- Summary
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
COMMENT ON TABLE focus_area_definitions IS
|
||||||
|
'v2.0: Dynamic focus areas - replaces hardcoded 6-dimension system.
|
||||||
|
26 base areas across 7 categories. User-extensible via admin UI.';
|
||||||
|
|
||||||
|
COMMENT ON TABLE goal_focus_contributions IS
|
||||||
|
'Many-to-Many mapping: Goals contribute to multiple focus areas with weights.
|
||||||
|
Auto-mapped from goal_type, editable by user.';
|
||||||
|
|
||||||
|
COMMENT ON TABLE user_focus_preferences IS
|
||||||
|
'Legacy flat structure (weight_loss_pct, muscle_gain_pct, etc.) remains for backward compatibility.
|
||||||
|
Future: Use focus_area_definitions + dynamic preferences.';
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
-- Migration 032: User Focus Area Weights
|
||||||
|
-- Date: 2026-03-27
|
||||||
|
-- Purpose: Allow users to set custom weights for focus areas (dynamic preferences)
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- User Focus Area Weights (many-to-many with weights)
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS user_focus_area_weights (
|
||||||
|
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||||
|
focus_area_id UUID NOT NULL REFERENCES focus_area_definitions(id) ON DELETE CASCADE,
|
||||||
|
weight INTEGER NOT NULL DEFAULT 0 CHECK (weight >= 0 AND weight <= 100),
|
||||||
|
created_at TIMESTAMP DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMP DEFAULT NOW(),
|
||||||
|
PRIMARY KEY (profile_id, focus_area_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_user_focus_weights_profile ON user_focus_area_weights(profile_id);
|
||||||
|
CREATE INDEX idx_user_focus_weights_area ON user_focus_area_weights(focus_area_id);
|
||||||
|
|
||||||
|
COMMENT ON TABLE user_focus_area_weights IS 'User-specific weights for focus areas (dynamic system)';
|
||||||
|
COMMENT ON COLUMN user_focus_area_weights.weight IS 'Relative weight (0-100) - will be normalized to percentages in UI';
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- Migrate legacy preferences to dynamic weights
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
-- For each user with legacy preferences, create weights for the 6 base areas
|
||||||
|
INSERT INTO user_focus_area_weights (profile_id, focus_area_id, weight)
|
||||||
|
SELECT
|
||||||
|
ufp.profile_id,
|
||||||
|
fad.id as focus_area_id,
|
||||||
|
CASE fad.key
|
||||||
|
WHEN 'weight_loss' THEN ufp.weight_loss_pct
|
||||||
|
WHEN 'muscle_gain' THEN ufp.muscle_gain_pct
|
||||||
|
WHEN 'strength' THEN ufp.strength_pct
|
||||||
|
WHEN 'aerobic_endurance' THEN ufp.endurance_pct
|
||||||
|
WHEN 'flexibility' THEN ufp.flexibility_pct
|
||||||
|
WHEN 'general_health' THEN ufp.health_pct
|
||||||
|
ELSE 0
|
||||||
|
END as weight
|
||||||
|
FROM user_focus_preferences ufp
|
||||||
|
CROSS JOIN focus_area_definitions fad
|
||||||
|
WHERE fad.key IN ('weight_loss', 'muscle_gain', 'strength', 'aerobic_endurance', 'flexibility', 'general_health')
|
||||||
|
AND (
|
||||||
|
(fad.key = 'weight_loss' AND ufp.weight_loss_pct > 0) OR
|
||||||
|
(fad.key = 'muscle_gain' AND ufp.muscle_gain_pct > 0) OR
|
||||||
|
(fad.key = 'strength' AND ufp.strength_pct > 0) OR
|
||||||
|
(fad.key = 'aerobic_endurance' AND ufp.endurance_pct > 0) OR
|
||||||
|
(fad.key = 'flexibility' AND ufp.flexibility_pct > 0) OR
|
||||||
|
(fad.key = 'general_health' AND ufp.health_pct > 0)
|
||||||
|
)
|
||||||
|
ON CONFLICT (profile_id, focus_area_id) DO NOTHING;
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
"""
|
||||||
|
Fitness Tests Router - Fitness Test Recording & Norm Tracking
|
||||||
|
|
||||||
|
Endpoints for managing fitness tests:
|
||||||
|
- List fitness tests
|
||||||
|
- Record fitness test results
|
||||||
|
- Calculate norm categories
|
||||||
|
|
||||||
|
Part of v9h Goal System.
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from typing import Optional
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/goals", tags=["fitness-tests"])
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Pydantic Models
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
class FitnessTestCreate(BaseModel):
|
||||||
|
"""Record fitness test result"""
|
||||||
|
test_type: str
|
||||||
|
result_value: float
|
||||||
|
result_unit: str
|
||||||
|
test_date: date
|
||||||
|
test_conditions: Optional[str] = None
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Endpoints
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
@router.get("/tests")
|
||||||
|
def list_fitness_tests(session: dict = Depends(require_auth)):
|
||||||
|
"""List all fitness tests"""
|
||||||
|
pid = session['profile_id']
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("""
|
||||||
|
SELECT id, test_type, result_value, result_unit,
|
||||||
|
test_date, test_conditions, norm_category, created_at
|
||||||
|
FROM fitness_tests
|
||||||
|
WHERE profile_id = %s
|
||||||
|
ORDER BY test_date DESC
|
||||||
|
""", (pid,))
|
||||||
|
|
||||||
|
return [r2d(row) for row in cur.fetchall()]
|
||||||
|
|
||||||
|
@router.post("/tests")
|
||||||
|
def create_fitness_test(data: FitnessTestCreate, session: dict = Depends(require_auth)):
|
||||||
|
"""Record fitness test result"""
|
||||||
|
pid = session['profile_id']
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Calculate norm category (simplified for now)
|
||||||
|
norm_category = _calculate_norm_category(
|
||||||
|
data.test_type,
|
||||||
|
data.result_value,
|
||||||
|
data.result_unit
|
||||||
|
)
|
||||||
|
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO fitness_tests (
|
||||||
|
profile_id, test_type, result_value, result_unit,
|
||||||
|
test_date, test_conditions, norm_category
|
||||||
|
) VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""", (
|
||||||
|
pid, data.test_type, data.result_value, data.result_unit,
|
||||||
|
data.test_date, data.test_conditions, norm_category
|
||||||
|
))
|
||||||
|
|
||||||
|
test_id = cur.fetchone()['id']
|
||||||
|
|
||||||
|
return {"id": test_id, "norm_category": norm_category}
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Helper Functions
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
def _calculate_norm_category(test_type: str, value: float, unit: str) -> Optional[str]:
|
||||||
|
"""
|
||||||
|
Calculate norm category for fitness test
|
||||||
|
(Simplified - would need age/gender-specific norms)
|
||||||
|
"""
|
||||||
|
# Placeholder - should use proper norm tables
|
||||||
|
return None
|
||||||
@@ -0,0 +1,378 @@
|
|||||||
|
"""
|
||||||
|
Focus Areas Router
|
||||||
|
Manages dynamic focus area definitions and user preferences
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter, HTTPException, Depends
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from typing import Optional, List
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/focus-areas", tags=["focus-areas"])
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Models
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
class FocusAreaCreate(BaseModel):
|
||||||
|
"""Create new focus area definition"""
|
||||||
|
key: str
|
||||||
|
name_de: str
|
||||||
|
name_en: Optional[str] = None
|
||||||
|
icon: Optional[str] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
category: str = 'custom'
|
||||||
|
|
||||||
|
class FocusAreaUpdate(BaseModel):
|
||||||
|
"""Update focus area definition"""
|
||||||
|
name_de: Optional[str] = None
|
||||||
|
name_en: Optional[str] = None
|
||||||
|
icon: Optional[str] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
category: Optional[str] = None
|
||||||
|
is_active: Optional[bool] = None
|
||||||
|
|
||||||
|
class UserFocusPreferences(BaseModel):
|
||||||
|
"""User's focus area weightings (dynamic)"""
|
||||||
|
preferences: dict # {focus_area_id: weight_pct}
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Focus Area Definitions (Admin)
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
@router.get("/definitions")
|
||||||
|
def list_focus_area_definitions(
|
||||||
|
session: dict = Depends(require_auth),
|
||||||
|
include_inactive: bool = False
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
List all available focus area definitions.
|
||||||
|
|
||||||
|
Query params:
|
||||||
|
- include_inactive: Include inactive focus areas (default: false)
|
||||||
|
|
||||||
|
Returns focus areas grouped by category.
|
||||||
|
"""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
query = """
|
||||||
|
SELECT id, key, name_de, name_en, icon, description, category, is_active,
|
||||||
|
created_at, updated_at
|
||||||
|
FROM focus_area_definitions
|
||||||
|
WHERE is_active = true OR %s
|
||||||
|
ORDER BY category, name_de
|
||||||
|
"""
|
||||||
|
|
||||||
|
cur.execute(query, (include_inactive,))
|
||||||
|
areas = [r2d(row) for row in cur.fetchall()]
|
||||||
|
|
||||||
|
# Group by category
|
||||||
|
grouped = {}
|
||||||
|
for area in areas:
|
||||||
|
cat = area['category'] or 'other'
|
||||||
|
if cat not in grouped:
|
||||||
|
grouped[cat] = []
|
||||||
|
grouped[cat].append(area)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"areas": areas,
|
||||||
|
"grouped": grouped,
|
||||||
|
"total": len(areas)
|
||||||
|
}
|
||||||
|
|
||||||
|
@router.post("/definitions")
|
||||||
|
def create_focus_area_definition(
|
||||||
|
data: FocusAreaCreate,
|
||||||
|
session: dict = Depends(require_auth)
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Create new focus area definition (Admin only).
|
||||||
|
|
||||||
|
Note: Requires admin role.
|
||||||
|
"""
|
||||||
|
# Admin check
|
||||||
|
if session.get('role') != 'admin':
|
||||||
|
raise HTTPException(status_code=403, detail="Admin-Rechte erforderlich")
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Check if key already exists
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id FROM focus_area_definitions WHERE key = %s",
|
||||||
|
(data.key,)
|
||||||
|
)
|
||||||
|
if cur.fetchone():
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Focus Area mit Key '{data.key}' existiert bereits"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Insert
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO focus_area_definitions
|
||||||
|
(key, name_de, name_en, icon, description, category)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""", (
|
||||||
|
data.key, data.name_de, data.name_en,
|
||||||
|
data.icon, data.description, data.category
|
||||||
|
))
|
||||||
|
|
||||||
|
area_id = cur.fetchone()['id']
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": area_id,
|
||||||
|
"message": f"Focus Area '{data.name_de}' erstellt"
|
||||||
|
}
|
||||||
|
|
||||||
|
@router.put("/definitions/{area_id}")
|
||||||
|
def update_focus_area_definition(
|
||||||
|
area_id: str,
|
||||||
|
data: FocusAreaUpdate,
|
||||||
|
session: dict = Depends(require_auth)
|
||||||
|
):
|
||||||
|
"""Update focus area definition (Admin only)"""
|
||||||
|
# Admin check
|
||||||
|
if session.get('role') != 'admin':
|
||||||
|
raise HTTPException(status_code=403, detail="Admin-Rechte erforderlich")
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Build dynamic UPDATE
|
||||||
|
updates = []
|
||||||
|
values = []
|
||||||
|
|
||||||
|
if data.name_de is not None:
|
||||||
|
updates.append("name_de = %s")
|
||||||
|
values.append(data.name_de)
|
||||||
|
if data.name_en is not None:
|
||||||
|
updates.append("name_en = %s")
|
||||||
|
values.append(data.name_en)
|
||||||
|
if data.icon is not None:
|
||||||
|
updates.append("icon = %s")
|
||||||
|
values.append(data.icon)
|
||||||
|
if data.description is not None:
|
||||||
|
updates.append("description = %s")
|
||||||
|
values.append(data.description)
|
||||||
|
if data.category is not None:
|
||||||
|
updates.append("category = %s")
|
||||||
|
values.append(data.category)
|
||||||
|
if data.is_active is not None:
|
||||||
|
updates.append("is_active = %s")
|
||||||
|
values.append(data.is_active)
|
||||||
|
|
||||||
|
if not updates:
|
||||||
|
raise HTTPException(status_code=400, detail="Keine Änderungen angegeben")
|
||||||
|
|
||||||
|
updates.append("updated_at = NOW()")
|
||||||
|
values.append(area_id)
|
||||||
|
|
||||||
|
query = f"""
|
||||||
|
UPDATE focus_area_definitions
|
||||||
|
SET {', '.join(updates)}
|
||||||
|
WHERE id = %s
|
||||||
|
RETURNING id
|
||||||
|
"""
|
||||||
|
|
||||||
|
cur.execute(query, values)
|
||||||
|
|
||||||
|
if not cur.fetchone():
|
||||||
|
raise HTTPException(status_code=404, detail="Focus Area nicht gefunden")
|
||||||
|
|
||||||
|
return {"message": "Focus Area aktualisiert"}
|
||||||
|
|
||||||
|
@router.delete("/definitions/{area_id}")
|
||||||
|
def delete_focus_area_definition(
|
||||||
|
area_id: str,
|
||||||
|
session: dict = Depends(require_auth)
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Delete focus area definition (Admin only).
|
||||||
|
|
||||||
|
Cascades: Deletes all goal_focus_contributions referencing this area.
|
||||||
|
"""
|
||||||
|
# Admin check
|
||||||
|
if session.get('role') != 'admin':
|
||||||
|
raise HTTPException(status_code=403, detail="Admin-Rechte erforderlich")
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Check if area is used
|
||||||
|
cur.execute(
|
||||||
|
"SELECT COUNT(*) as count FROM goal_focus_contributions WHERE focus_area_id = %s",
|
||||||
|
(area_id,)
|
||||||
|
)
|
||||||
|
count = cur.fetchone()['count']
|
||||||
|
|
||||||
|
if count > 0:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Focus Area wird von {count} Ziel(en) verwendet. "
|
||||||
|
"Bitte erst Zuordnungen entfernen oder auf 'inaktiv' setzen."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Delete
|
||||||
|
cur.execute(
|
||||||
|
"DELETE FROM focus_area_definitions WHERE id = %s RETURNING id",
|
||||||
|
(area_id,)
|
||||||
|
)
|
||||||
|
|
||||||
|
if not cur.fetchone():
|
||||||
|
raise HTTPException(status_code=404, detail="Focus Area nicht gefunden")
|
||||||
|
|
||||||
|
return {"message": "Focus Area gelöscht"}
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# User Focus Preferences
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
@router.get("/user-preferences")
|
||||||
|
def get_user_focus_preferences(session: dict = Depends(require_auth)):
|
||||||
|
"""
|
||||||
|
Get user's focus area weightings (dynamic system).
|
||||||
|
|
||||||
|
Returns focus areas with user-set weights, grouped by category.
|
||||||
|
"""
|
||||||
|
pid = session['profile_id']
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Get dynamic preferences (Migration 032)
|
||||||
|
try:
|
||||||
|
cur.execute("""
|
||||||
|
SELECT
|
||||||
|
fa.id, fa.key, fa.name_de, fa.name_en, fa.icon,
|
||||||
|
fa.category, fa.description,
|
||||||
|
ufw.weight
|
||||||
|
FROM user_focus_area_weights ufw
|
||||||
|
JOIN focus_area_definitions fa ON ufw.focus_area_id = fa.id
|
||||||
|
WHERE ufw.profile_id = %s AND ufw.weight > 0
|
||||||
|
ORDER BY fa.category, fa.name_de
|
||||||
|
""", (pid,))
|
||||||
|
|
||||||
|
weights = [r2d(row) for row in cur.fetchall()]
|
||||||
|
|
||||||
|
# Calculate percentages from weights
|
||||||
|
total_weight = sum(w['weight'] for w in weights)
|
||||||
|
if total_weight > 0:
|
||||||
|
for w in weights:
|
||||||
|
w['percentage'] = round((w['weight'] / total_weight) * 100)
|
||||||
|
else:
|
||||||
|
for w in weights:
|
||||||
|
w['percentage'] = 0
|
||||||
|
|
||||||
|
# Group by category
|
||||||
|
grouped = {}
|
||||||
|
for w in weights:
|
||||||
|
cat = w['category'] or 'other'
|
||||||
|
if cat not in grouped:
|
||||||
|
grouped[cat] = []
|
||||||
|
grouped[cat].append(w)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"weights": weights,
|
||||||
|
"grouped": grouped,
|
||||||
|
"total_weight": total_weight
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
# Migration 032 not applied yet - return empty
|
||||||
|
print(f"[WARNING] user_focus_area_weights not found: {e}")
|
||||||
|
return {
|
||||||
|
"weights": [],
|
||||||
|
"grouped": {},
|
||||||
|
"total_weight": 0
|
||||||
|
}
|
||||||
|
|
||||||
|
@router.put("/user-preferences")
|
||||||
|
def update_user_focus_preferences(
|
||||||
|
data: dict,
|
||||||
|
session: dict = Depends(require_auth)
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Update user's focus area weightings (dynamic system).
|
||||||
|
|
||||||
|
Expects: { "weights": { "focus_area_id": weight, ... } }
|
||||||
|
Weights are relative (0-100), normalized in display only.
|
||||||
|
"""
|
||||||
|
pid = session['profile_id']
|
||||||
|
|
||||||
|
if 'weights' not in data:
|
||||||
|
raise HTTPException(status_code=400, detail="'weights' field required")
|
||||||
|
|
||||||
|
weights = data['weights'] # Dict: focus_area_id → weight
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Delete existing weights
|
||||||
|
cur.execute(
|
||||||
|
"DELETE FROM user_focus_area_weights WHERE profile_id = %s",
|
||||||
|
(pid,)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Insert new weights (only non-zero)
|
||||||
|
for focus_area_id, weight in weights.items():
|
||||||
|
weight_int = int(weight)
|
||||||
|
if weight_int > 0:
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO user_focus_area_weights
|
||||||
|
(profile_id, focus_area_id, weight)
|
||||||
|
VALUES (%s, %s, %s)
|
||||||
|
ON CONFLICT (profile_id, focus_area_id)
|
||||||
|
DO UPDATE SET
|
||||||
|
weight = EXCLUDED.weight,
|
||||||
|
updated_at = NOW()
|
||||||
|
""", (pid, focus_area_id, weight_int))
|
||||||
|
|
||||||
|
return {
|
||||||
|
"message": "Focus Area Gewichtungen aktualisiert",
|
||||||
|
"count": len([w for w in weights.values() if int(w) > 0])
|
||||||
|
}
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Stats & Analytics
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
@router.get("/stats")
|
||||||
|
def get_focus_area_stats(session: dict = Depends(require_auth)):
|
||||||
|
"""
|
||||||
|
Get focus area statistics for current user.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- Progress per focus area (avg of all contributing goals)
|
||||||
|
- Goal count per focus area
|
||||||
|
- Top/bottom performing areas
|
||||||
|
"""
|
||||||
|
pid = session['profile_id']
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
cur.execute("""
|
||||||
|
SELECT
|
||||||
|
fa.id, fa.key, fa.name_de, fa.icon, fa.category,
|
||||||
|
COUNT(DISTINCT gfc.goal_id) as goal_count,
|
||||||
|
AVG(g.progress_pct) as avg_progress,
|
||||||
|
SUM(gfc.contribution_weight) as total_contribution
|
||||||
|
FROM focus_area_definitions fa
|
||||||
|
LEFT JOIN goal_focus_contributions gfc ON fa.id = gfc.focus_area_id
|
||||||
|
LEFT JOIN goals g ON gfc.goal_id = g.id AND g.profile_id = %s
|
||||||
|
WHERE fa.is_active = true
|
||||||
|
GROUP BY fa.id
|
||||||
|
HAVING COUNT(DISTINCT gfc.goal_id) > 0 -- Only areas with goals
|
||||||
|
ORDER BY avg_progress DESC NULLS LAST
|
||||||
|
""", (pid,))
|
||||||
|
|
||||||
|
stats = [r2d(row) for row in cur.fetchall()]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"stats": stats,
|
||||||
|
"top_area": stats[0] if stats else None,
|
||||||
|
"bottom_area": stats[-1] if len(stats) > 1 else None
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
"""
|
||||||
|
Goal Progress Router - Progress Tracking for Goals
|
||||||
|
|
||||||
|
Endpoints for logging and managing goal progress:
|
||||||
|
- Get progress history
|
||||||
|
- Create manual progress entries
|
||||||
|
- Delete progress entries
|
||||||
|
|
||||||
|
Part of v9h Goal System.
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from typing import Optional
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/goals", tags=["goal-progress"])
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Pydantic Models
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# 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"}
|
||||||
@@ -0,0 +1,426 @@
|
|||||||
|
"""
|
||||||
|
Goal Types Router - Custom Goal Type Definitions
|
||||||
|
|
||||||
|
Endpoints for managing goal type definitions (admin-only):
|
||||||
|
- CRUD for goal type definitions
|
||||||
|
- Schema info for building custom types
|
||||||
|
|
||||||
|
Part of v9h Goal System.
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from typing import Optional
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/goals", tags=["goal-types"])
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Pydantic Models
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
class GoalTypeCreate(BaseModel):
|
||||||
|
"""Create custom goal type definition"""
|
||||||
|
type_key: str
|
||||||
|
label_de: str
|
||||||
|
label_en: Optional[str] = None
|
||||||
|
unit: str
|
||||||
|
icon: Optional[str] = None
|
||||||
|
category: Optional[str] = 'custom'
|
||||||
|
source_table: Optional[str] = None
|
||||||
|
source_column: Optional[str] = None
|
||||||
|
aggregation_method: Optional[str] = 'latest'
|
||||||
|
calculation_formula: Optional[str] = None
|
||||||
|
filter_conditions: Optional[dict] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
|
||||||
|
class GoalTypeUpdate(BaseModel):
|
||||||
|
"""Update goal type definition"""
|
||||||
|
label_de: Optional[str] = None
|
||||||
|
label_en: Optional[str] = None
|
||||||
|
unit: Optional[str] = None
|
||||||
|
icon: Optional[str] = None
|
||||||
|
category: Optional[str] = None
|
||||||
|
source_table: Optional[str] = None
|
||||||
|
source_column: Optional[str] = None
|
||||||
|
aggregation_method: Optional[str] = None
|
||||||
|
calculation_formula: Optional[str] = None
|
||||||
|
filter_conditions: Optional[dict] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
is_active: Optional[bool] = None
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Endpoints
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
@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)):
|
||||||
|
"""
|
||||||
|
Get all active goal type definitions.
|
||||||
|
|
||||||
|
Public endpoint - returns all available goal types for dropdown.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
cur.execute("""
|
||||||
|
SELECT id, type_key, label_de, label_en, unit, icon, category,
|
||||||
|
source_table, source_column, aggregation_method,
|
||||||
|
calculation_formula, filter_conditions, description, is_system, is_active,
|
||||||
|
created_at, updated_at
|
||||||
|
FROM goal_type_definitions
|
||||||
|
WHERE is_active = true
|
||||||
|
ORDER BY
|
||||||
|
CASE
|
||||||
|
WHEN is_system = true THEN 0
|
||||||
|
ELSE 1
|
||||||
|
END,
|
||||||
|
label_de
|
||||||
|
""")
|
||||||
|
|
||||||
|
results = [r2d(row) for row in cur.fetchall()]
|
||||||
|
print(f"[DEBUG] Loaded {len(results)} goal types")
|
||||||
|
return results
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[ERROR] list_goal_type_definitions failed: {e}")
|
||||||
|
print(traceback.format_exc())
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=500,
|
||||||
|
detail=f"Fehler beim Laden der Goal Types: {str(e)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
@router.post("/goal-types")
|
||||||
|
def create_goal_type_definition(
|
||||||
|
data: GoalTypeCreate,
|
||||||
|
session: dict = Depends(require_auth)
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Create custom goal type definition.
|
||||||
|
|
||||||
|
Admin-only endpoint for creating new goal types.
|
||||||
|
Users with admin role can define custom metrics.
|
||||||
|
"""
|
||||||
|
pid = session['profile_id']
|
||||||
|
|
||||||
|
# Check admin role
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
|
||||||
|
profile = cur.fetchone()
|
||||||
|
|
||||||
|
if not profile or profile['role'] != 'admin':
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Admin-Zugriff erforderlich"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Validate type_key is unique
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id FROM goal_type_definitions WHERE type_key = %s",
|
||||||
|
(data.type_key,)
|
||||||
|
)
|
||||||
|
if cur.fetchone():
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Goal Type '{data.type_key}' existiert bereits"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Insert new goal type
|
||||||
|
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, 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, filter_json, data.description,
|
||||||
|
True, False # is_active=True, is_system=False
|
||||||
|
))
|
||||||
|
|
||||||
|
goal_type_id = cur.fetchone()['id']
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": goal_type_id,
|
||||||
|
"message": f"Goal Type '{data.label_de}' erstellt"
|
||||||
|
}
|
||||||
|
|
||||||
|
@router.put("/goal-types/{goal_type_id}")
|
||||||
|
def update_goal_type_definition(
|
||||||
|
goal_type_id: str,
|
||||||
|
data: GoalTypeUpdate,
|
||||||
|
session: dict = Depends(require_auth)
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Update goal type definition.
|
||||||
|
|
||||||
|
Admin-only. System goal types can be updated but not deleted.
|
||||||
|
"""
|
||||||
|
pid = session['profile_id']
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Check admin role
|
||||||
|
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
|
||||||
|
profile = cur.fetchone()
|
||||||
|
|
||||||
|
if not profile or profile['role'] != 'admin':
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Admin-Zugriff erforderlich"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Check goal type exists
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id FROM goal_type_definitions WHERE id = %s",
|
||||||
|
(goal_type_id,)
|
||||||
|
)
|
||||||
|
if not cur.fetchone():
|
||||||
|
raise HTTPException(status_code=404, detail="Goal Type nicht gefunden")
|
||||||
|
|
||||||
|
# Build update query
|
||||||
|
updates = []
|
||||||
|
params = []
|
||||||
|
|
||||||
|
if data.label_de is not None:
|
||||||
|
updates.append("label_de = %s")
|
||||||
|
params.append(data.label_de)
|
||||||
|
|
||||||
|
if data.label_en is not None:
|
||||||
|
updates.append("label_en = %s")
|
||||||
|
params.append(data.label_en)
|
||||||
|
|
||||||
|
if data.unit is not None:
|
||||||
|
updates.append("unit = %s")
|
||||||
|
params.append(data.unit)
|
||||||
|
|
||||||
|
if data.icon is not None:
|
||||||
|
updates.append("icon = %s")
|
||||||
|
params.append(data.icon)
|
||||||
|
|
||||||
|
if data.category is not None:
|
||||||
|
updates.append("category = %s")
|
||||||
|
params.append(data.category)
|
||||||
|
|
||||||
|
if data.source_table is not None:
|
||||||
|
updates.append("source_table = %s")
|
||||||
|
params.append(data.source_table)
|
||||||
|
|
||||||
|
if data.source_column is not None:
|
||||||
|
updates.append("source_column = %s")
|
||||||
|
params.append(data.source_column)
|
||||||
|
|
||||||
|
if data.aggregation_method is not None:
|
||||||
|
updates.append("aggregation_method = %s")
|
||||||
|
params.append(data.aggregation_method)
|
||||||
|
|
||||||
|
if data.calculation_formula is not None:
|
||||||
|
updates.append("calculation_formula = %s")
|
||||||
|
params.append(data.calculation_formula)
|
||||||
|
|
||||||
|
if data.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)
|
||||||
|
|
||||||
|
if data.is_active is not None:
|
||||||
|
updates.append("is_active = %s")
|
||||||
|
params.append(data.is_active)
|
||||||
|
|
||||||
|
if not updates:
|
||||||
|
raise HTTPException(status_code=400, detail="Keine Änderungen angegeben")
|
||||||
|
|
||||||
|
updates.append("updated_at = NOW()")
|
||||||
|
params.append(goal_type_id)
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
f"UPDATE goal_type_definitions SET {', '.join(updates)} WHERE id = %s",
|
||||||
|
tuple(params)
|
||||||
|
)
|
||||||
|
|
||||||
|
return {"message": "Goal Type aktualisiert"}
|
||||||
|
|
||||||
|
@router.delete("/goal-types/{goal_type_id}")
|
||||||
|
def delete_goal_type_definition(
|
||||||
|
goal_type_id: str,
|
||||||
|
session: dict = Depends(require_auth)
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Delete (deactivate) goal type definition.
|
||||||
|
|
||||||
|
Admin-only. System goal types cannot be deleted, only deactivated.
|
||||||
|
Custom goal types can be fully deleted if no goals reference them.
|
||||||
|
"""
|
||||||
|
pid = session['profile_id']
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Check admin role
|
||||||
|
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
|
||||||
|
profile = cur.fetchone()
|
||||||
|
|
||||||
|
if not profile or profile['role'] != 'admin':
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Admin-Zugriff erforderlich"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Get goal type info
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id, type_key, is_system FROM goal_type_definitions WHERE id = %s",
|
||||||
|
(goal_type_id,)
|
||||||
|
)
|
||||||
|
goal_type = cur.fetchone()
|
||||||
|
|
||||||
|
if not goal_type:
|
||||||
|
raise HTTPException(status_code=404, detail="Goal Type nicht gefunden")
|
||||||
|
|
||||||
|
# Check if any goals use this type
|
||||||
|
cur.execute(
|
||||||
|
"SELECT COUNT(*) as count FROM goals WHERE goal_type = %s",
|
||||||
|
(goal_type['type_key'],)
|
||||||
|
)
|
||||||
|
count = cur.fetchone()['count']
|
||||||
|
|
||||||
|
if count > 0:
|
||||||
|
# Deactivate instead of delete
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE goal_type_definitions SET is_active = false WHERE id = %s",
|
||||||
|
(goal_type_id,)
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"message": f"Goal Type deaktiviert ({count} Ziele nutzen diesen Typ)"
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
if goal_type['is_system']:
|
||||||
|
# System types: only deactivate
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE goal_type_definitions SET is_active = false WHERE id = %s",
|
||||||
|
(goal_type_id,)
|
||||||
|
)
|
||||||
|
return {"message": "System Goal Type deaktiviert"}
|
||||||
|
else:
|
||||||
|
# Custom types: delete
|
||||||
|
cur.execute(
|
||||||
|
"DELETE FROM goal_type_definitions WHERE id = %s",
|
||||||
|
(goal_type_id,)
|
||||||
|
)
|
||||||
|
return {"message": "Goal Type gelöscht"}
|
||||||
+345
-447
@@ -1,20 +1,23 @@
|
|||||||
"""
|
"""
|
||||||
Goals Router - Goal System (Strategic + Tactical)
|
Goals Router - Core Goal CRUD & Focus Areas (Streamlined v2.0)
|
||||||
|
|
||||||
Endpoints for managing:
|
Endpoints for managing:
|
||||||
- Strategic goal modes (weight_loss, strength, etc.)
|
- Strategic focus areas (weighted multi-goal system)
|
||||||
- Tactical goal targets (concrete values with deadlines)
|
- Tactical goal targets (concrete values with deadlines)
|
||||||
- Training phase detection
|
- Grouped goal views
|
||||||
- Fitness tests
|
|
||||||
|
|
||||||
Part of v9e Goal System implementation.
|
Part of v9h Goal System (Phase 0a).
|
||||||
|
|
||||||
|
NOTE: Code split complete! Related endpoints moved to:
|
||||||
|
- goal_types.py → Goal Type Definitions (Admin CRUD)
|
||||||
|
- goal_progress.py → Progress tracking
|
||||||
|
- training_phases.py → Training phase management
|
||||||
|
- fitness_tests.py → Fitness test recording
|
||||||
"""
|
"""
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from typing import Optional, List
|
from typing import Optional, List
|
||||||
from datetime import date, datetime, timedelta
|
from datetime import date, timedelta
|
||||||
from decimal import Decimal
|
|
||||||
import traceback
|
|
||||||
|
|
||||||
from db import get_db, get_cursor, r2d
|
from db import get_db, get_cursor, r2d
|
||||||
from auth import require_auth
|
from auth import require_auth
|
||||||
@@ -27,70 +30,47 @@ router = APIRouter(prefix="/api/goals", tags=["goals"])
|
|||||||
# ============================================================================
|
# ============================================================================
|
||||||
|
|
||||||
class GoalModeUpdate(BaseModel):
|
class GoalModeUpdate(BaseModel):
|
||||||
"""Update strategic goal mode"""
|
"""Update strategic goal mode (deprecated - use FocusAreasUpdate)"""
|
||||||
goal_mode: str # weight_loss, strength, endurance, recomposition, health
|
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 FocusContribution(BaseModel):
|
||||||
|
"""Focus area contribution (v2.0)"""
|
||||||
|
focus_area_id: str
|
||||||
|
contribution_weight: float = 100.0 # 0-100%
|
||||||
|
|
||||||
class GoalCreate(BaseModel):
|
class GoalCreate(BaseModel):
|
||||||
"""Create or update a concrete goal"""
|
"""Create or update a concrete goal"""
|
||||||
goal_type: str # weight, body_fat, lean_mass, vo2max, strength, flexibility, bp, rhr
|
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
|
target_value: float
|
||||||
unit: str # kg, %, ml/kg/min, bpm, mmHg, cm, reps
|
unit: str # kg, %, ml/kg/min, bpm, mmHg, cm, reps
|
||||||
target_date: Optional[date] = None
|
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
|
name: Optional[str] = None
|
||||||
description: Optional[str] = None
|
description: Optional[str] = None
|
||||||
|
focus_contributions: Optional[List[FocusContribution]] = [] # v2.0: Many-to-Many
|
||||||
|
|
||||||
class GoalUpdate(BaseModel):
|
class GoalUpdate(BaseModel):
|
||||||
"""Update existing goal"""
|
"""Update existing goal"""
|
||||||
target_value: Optional[float] = None
|
target_value: Optional[float] = None
|
||||||
target_date: Optional[date] = None
|
target_date: Optional[date] = None
|
||||||
status: Optional[str] = None # active, reached, abandoned, expired
|
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
|
name: Optional[str] = None
|
||||||
description: Optional[str] = None
|
description: Optional[str] = None
|
||||||
|
focus_contributions: Optional[List[FocusContribution]] = None # v2.0: Many-to-Many
|
||||||
class TrainingPhaseCreate(BaseModel):
|
|
||||||
"""Create training phase (manual or auto-detected)"""
|
|
||||||
phase_type: str # calorie_deficit, calorie_surplus, deload, maintenance, periodization
|
|
||||||
start_date: date
|
|
||||||
end_date: Optional[date] = None
|
|
||||||
notes: Optional[str] = None
|
|
||||||
|
|
||||||
class FitnessTestCreate(BaseModel):
|
|
||||||
"""Record fitness test result"""
|
|
||||||
test_type: str
|
|
||||||
result_value: float
|
|
||||||
result_unit: str
|
|
||||||
test_date: date
|
|
||||||
test_conditions: Optional[str] = None
|
|
||||||
|
|
||||||
class GoalTypeCreate(BaseModel):
|
|
||||||
"""Create custom goal type definition"""
|
|
||||||
type_key: str
|
|
||||||
label_de: str
|
|
||||||
label_en: Optional[str] = None
|
|
||||||
unit: str
|
|
||||||
icon: Optional[str] = None
|
|
||||||
category: Optional[str] = 'custom'
|
|
||||||
source_table: Optional[str] = None
|
|
||||||
source_column: Optional[str] = None
|
|
||||||
aggregation_method: Optional[str] = 'latest'
|
|
||||||
calculation_formula: Optional[str] = None
|
|
||||||
description: Optional[str] = None
|
|
||||||
|
|
||||||
class GoalTypeUpdate(BaseModel):
|
|
||||||
"""Update goal type definition"""
|
|
||||||
label_de: Optional[str] = None
|
|
||||||
label_en: Optional[str] = None
|
|
||||||
unit: Optional[str] = None
|
|
||||||
icon: Optional[str] = None
|
|
||||||
category: Optional[str] = None
|
|
||||||
source_table: Optional[str] = None
|
|
||||||
source_column: Optional[str] = None
|
|
||||||
aggregation_method: Optional[str] = None
|
|
||||||
calculation_formula: Optional[str] = None
|
|
||||||
description: Optional[str] = None
|
|
||||||
is_active: Optional[bool] = None
|
|
||||||
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
# Strategic Layer: Goal Modes
|
# Strategic Layer: Goal Modes
|
||||||
@@ -153,7 +133,193 @@ def _get_goal_mode_description(mode: str) -> str:
|
|||||||
return descriptions.get(mode, 'Unbekannt')
|
return descriptions.get(mode, 'Unbekannt')
|
||||||
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
# Tactical Layer: Concrete Goals
|
# 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 (user_focus_preferences after Migration 031)
|
||||||
|
try:
|
||||||
|
cur.execute("""
|
||||||
|
SELECT weight_loss_pct, muscle_gain_pct, strength_pct,
|
||||||
|
endurance_pct, flexibility_pct, health_pct,
|
||||||
|
created_at, updated_at
|
||||||
|
FROM user_focus_preferences
|
||||||
|
WHERE profile_id = %s
|
||||||
|
LIMIT 1
|
||||||
|
""", (pid,))
|
||||||
|
row = cur.fetchone()
|
||||||
|
except Exception as e:
|
||||||
|
# Migration 031 not applied yet, try old table name
|
||||||
|
print(f"[WARNING] user_focus_preferences not found, trying old focus_areas: {e}")
|
||||||
|
try:
|
||||||
|
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()
|
||||||
|
except:
|
||||||
|
row = None
|
||||||
|
|
||||||
|
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 - Core CRUD
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
|
|
||||||
@router.get("/list")
|
@router.get("/list")
|
||||||
@@ -161,6 +327,7 @@ def list_goals(session: dict = Depends(require_auth)):
|
|||||||
"""List all goals for current user"""
|
"""List all goals for current user"""
|
||||||
pid = session['profile_id']
|
pid = session['profile_id']
|
||||||
|
|
||||||
|
try:
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
cur.execute("""
|
cur.execute("""
|
||||||
@@ -176,13 +343,27 @@ def list_goals(session: dict = Depends(require_auth)):
|
|||||||
""", (pid,))
|
""", (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
|
# Update current values for each goal
|
||||||
for goal in goals:
|
for goal in goals:
|
||||||
|
try:
|
||||||
_update_goal_progress(conn, pid, goal)
|
_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")
|
@router.post("/create")
|
||||||
def create_goal(data: GoalCreate, session: dict = Depends(require_auth)):
|
def create_goal(data: GoalCreate, session: dict = Depends(require_auth)):
|
||||||
"""Create new goal"""
|
"""Create new goal"""
|
||||||
@@ -206,17 +387,28 @@ def create_goal(data: GoalCreate, session: dict = Depends(require_auth)):
|
|||||||
INSERT INTO goals (
|
INSERT INTO goals (
|
||||||
profile_id, goal_type, is_primary,
|
profile_id, goal_type, is_primary,
|
||||||
target_value, current_value, start_value, unit,
|
target_value, current_value, start_value, unit,
|
||||||
target_date, name, description
|
target_date, category, priority, name, description
|
||||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
RETURNING id
|
RETURNING id
|
||||||
""", (
|
""", (
|
||||||
pid, data.goal_type, data.is_primary,
|
pid, data.goal_type, data.is_primary,
|
||||||
data.target_value, current_value, current_value, data.unit,
|
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']
|
goal_id = cur.fetchone()['id']
|
||||||
|
|
||||||
|
# v2.0: Insert focus area contributions
|
||||||
|
if data.focus_contributions:
|
||||||
|
for contrib in data.focus_contributions:
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO goal_focus_contributions
|
||||||
|
(goal_id, focus_area_id, contribution_weight)
|
||||||
|
VALUES (%s, %s, %s)
|
||||||
|
ON CONFLICT (goal_id, focus_area_id) DO UPDATE
|
||||||
|
SET contribution_weight = EXCLUDED.contribution_weight
|
||||||
|
""", (goal_id, contrib.focus_area_id, contrib.contribution_weight))
|
||||||
|
|
||||||
return {"id": goal_id, "message": "Ziel erstellt"}
|
return {"id": goal_id, "message": "Ziel erstellt"}
|
||||||
|
|
||||||
@router.put("/{goal_id}")
|
@router.put("/{goal_id}")
|
||||||
@@ -264,6 +456,14 @@ def update_goal(goal_id: str, data: GoalUpdate, session: dict = Depends(require_
|
|||||||
updates.append("is_primary = %s")
|
updates.append("is_primary = %s")
|
||||||
params.append(data.is_primary)
|
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:
|
if data.name is not None:
|
||||||
updates.append("name = %s")
|
updates.append("name = %s")
|
||||||
params.append(data.name)
|
params.append(data.name)
|
||||||
@@ -272,9 +472,26 @@ def update_goal(goal_id: str, data: GoalUpdate, session: dict = Depends(require_
|
|||||||
updates.append("description = %s")
|
updates.append("description = %s")
|
||||||
params.append(data.description)
|
params.append(data.description)
|
||||||
|
|
||||||
if not updates:
|
# Handle focus_contributions separately (can be updated even if no other changes)
|
||||||
|
if data.focus_contributions is not None:
|
||||||
|
# Delete existing contributions
|
||||||
|
cur.execute(
|
||||||
|
"DELETE FROM goal_focus_contributions WHERE goal_id = %s",
|
||||||
|
(goal_id,)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Insert new contributions
|
||||||
|
for contrib in data.focus_contributions:
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO goal_focus_contributions
|
||||||
|
(goal_id, focus_area_id, contribution_weight)
|
||||||
|
VALUES (%s, %s, %s)
|
||||||
|
""", (goal_id, contrib.focus_area_id, contrib.contribution_weight))
|
||||||
|
|
||||||
|
if not updates and data.focus_contributions is None:
|
||||||
raise HTTPException(status_code=400, detail="Keine Änderungen angegeben")
|
raise HTTPException(status_code=400, detail="Keine Änderungen angegeben")
|
||||||
|
|
||||||
|
if updates:
|
||||||
updates.append("updated_at = NOW()")
|
updates.append("updated_at = NOW()")
|
||||||
params.extend([goal_id, pid])
|
params.extend([goal_id, pid])
|
||||||
|
|
||||||
@@ -302,133 +519,89 @@ def delete_goal(goal_id: str, session: dict = Depends(require_auth)):
|
|||||||
|
|
||||||
return {"message": "Ziel gelöscht"}
|
return {"message": "Ziel gelöscht"}
|
||||||
|
|
||||||
# ============================================================================
|
@router.get("/grouped")
|
||||||
# Training Phases
|
def get_goals_grouped(session: dict = Depends(require_auth)):
|
||||||
# ============================================================================
|
"""
|
||||||
|
Get all goals grouped by category.
|
||||||
|
|
||||||
@router.get("/phases")
|
Returns structure:
|
||||||
def list_training_phases(session: dict = Depends(require_auth)):
|
{
|
||||||
"""List training phases"""
|
"body": [{"id": "...", "goal_type": "weight", "priority": 1, ...}, ...],
|
||||||
|
"training": [...],
|
||||||
|
"nutrition": [...],
|
||||||
|
"recovery": [...],
|
||||||
|
"health": [...],
|
||||||
|
"other": [...]
|
||||||
|
}
|
||||||
|
"""
|
||||||
pid = session['profile_id']
|
pid = session['profile_id']
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Get all active goals with type definitions
|
||||||
cur.execute("""
|
cur.execute("""
|
||||||
SELECT id, phase_type, detected_automatically, confidence_score,
|
SELECT
|
||||||
status, start_date, end_date, duration_days,
|
g.id, g.goal_type, g.target_value, g.current_value, g.start_value,
|
||||||
detection_params, notes, created_at
|
g.unit, g.target_date, g.status, g.is_primary, g.category, g.priority,
|
||||||
FROM training_phases
|
g.name, g.description, g.progress_pct, g.on_track, g.projection_date,
|
||||||
WHERE profile_id = %s
|
g.created_at, g.updated_at,
|
||||||
ORDER BY start_date DESC
|
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,))
|
""", (pid,))
|
||||||
|
|
||||||
return [r2d(row) for row in cur.fetchall()]
|
goals = cur.fetchall()
|
||||||
|
|
||||||
@router.post("/phases")
|
# v2.0: Load focus_contributions for each goal
|
||||||
def create_training_phase(data: TrainingPhaseCreate, session: dict = Depends(require_auth)):
|
goal_ids = [g['id'] for g in goals]
|
||||||
"""Create training phase (manual)"""
|
focus_map = {} # goal_id → [contributions]
|
||||||
pid = session['profile_id']
|
|
||||||
|
|
||||||
with get_db() as conn:
|
if goal_ids:
|
||||||
cur = get_cursor(conn)
|
try:
|
||||||
|
placeholders = ','.join(['%s'] * len(goal_ids))
|
||||||
|
cur.execute(f"""
|
||||||
|
SELECT
|
||||||
|
gfc.goal_id, gfc.contribution_weight,
|
||||||
|
fa.id as focus_area_id, fa.key, fa.name_de, fa.icon, fa.category
|
||||||
|
FROM goal_focus_contributions gfc
|
||||||
|
JOIN focus_area_definitions fa ON gfc.focus_area_id = fa.id
|
||||||
|
WHERE gfc.goal_id IN ({placeholders})
|
||||||
|
ORDER BY gfc.contribution_weight DESC
|
||||||
|
""", tuple(goal_ids))
|
||||||
|
|
||||||
duration = None
|
for row in cur.fetchall():
|
||||||
if data.end_date:
|
gid = row['goal_id']
|
||||||
duration = (data.end_date - data.start_date).days
|
if gid not in focus_map:
|
||||||
|
focus_map[gid] = []
|
||||||
|
focus_map[gid].append({
|
||||||
|
'focus_area_id': row['focus_area_id'],
|
||||||
|
'key': row['key'],
|
||||||
|
'name_de': row['name_de'],
|
||||||
|
'icon': row['icon'],
|
||||||
|
'category': row['category'],
|
||||||
|
'contribution_weight': float(row['contribution_weight'])
|
||||||
|
})
|
||||||
|
except Exception as e:
|
||||||
|
# Migration 031 not yet applied - focus_contributions tables don't exist
|
||||||
|
print(f"[WARNING] Could not load focus_contributions: {e}")
|
||||||
|
# Continue without focus_contributions (backward compatible)
|
||||||
|
|
||||||
cur.execute("""
|
# Group by category and attach focus_contributions
|
||||||
INSERT INTO training_phases (
|
grouped = {}
|
||||||
profile_id, phase_type, detected_automatically,
|
for goal in goals:
|
||||||
status, start_date, end_date, duration_days, notes
|
cat = goal['category'] or 'other'
|
||||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
if cat not in grouped:
|
||||||
RETURNING id
|
grouped[cat] = []
|
||||||
""", (
|
|
||||||
pid, data.phase_type, False,
|
|
||||||
'active', data.start_date, data.end_date, duration, data.notes
|
|
||||||
))
|
|
||||||
|
|
||||||
phase_id = cur.fetchone()['id']
|
goal_dict = r2d(goal)
|
||||||
|
goal_dict['focus_contributions'] = focus_map.get(goal['id'], [])
|
||||||
|
grouped[cat].append(goal_dict)
|
||||||
|
|
||||||
return {"id": phase_id, "message": "Trainingsphase erstellt"}
|
return grouped
|
||||||
|
|
||||||
@router.put("/phases/{phase_id}/status")
|
|
||||||
def update_phase_status(
|
|
||||||
phase_id: str,
|
|
||||||
status: str,
|
|
||||||
session: dict = Depends(require_auth)
|
|
||||||
):
|
|
||||||
"""Update training phase status (accept/reject auto-detected phases)"""
|
|
||||||
pid = session['profile_id']
|
|
||||||
|
|
||||||
valid_statuses = ['suggested', 'accepted', 'active', 'completed', 'rejected']
|
|
||||||
if status not in valid_statuses:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=400,
|
|
||||||
detail=f"Ungültiger Status. Erlaubt: {', '.join(valid_statuses)}"
|
|
||||||
)
|
|
||||||
|
|
||||||
with get_db() as conn:
|
|
||||||
cur = get_cursor(conn)
|
|
||||||
cur.execute(
|
|
||||||
"UPDATE training_phases SET status = %s WHERE id = %s AND profile_id = %s",
|
|
||||||
(status, phase_id, pid)
|
|
||||||
)
|
|
||||||
|
|
||||||
if cur.rowcount == 0:
|
|
||||||
raise HTTPException(status_code=404, detail="Trainingsphase nicht gefunden")
|
|
||||||
|
|
||||||
return {"message": "Status aktualisiert"}
|
|
||||||
|
|
||||||
# ============================================================================
|
|
||||||
# Fitness Tests
|
|
||||||
# ============================================================================
|
|
||||||
|
|
||||||
@router.get("/tests")
|
|
||||||
def list_fitness_tests(session: dict = Depends(require_auth)):
|
|
||||||
"""List all fitness tests"""
|
|
||||||
pid = session['profile_id']
|
|
||||||
|
|
||||||
with get_db() as conn:
|
|
||||||
cur = get_cursor(conn)
|
|
||||||
cur.execute("""
|
|
||||||
SELECT id, test_type, result_value, result_unit,
|
|
||||||
test_date, test_conditions, norm_category, created_at
|
|
||||||
FROM fitness_tests
|
|
||||||
WHERE profile_id = %s
|
|
||||||
ORDER BY test_date DESC
|
|
||||||
""", (pid,))
|
|
||||||
|
|
||||||
return [r2d(row) for row in cur.fetchall()]
|
|
||||||
|
|
||||||
@router.post("/tests")
|
|
||||||
def create_fitness_test(data: FitnessTestCreate, session: dict = Depends(require_auth)):
|
|
||||||
"""Record fitness test result"""
|
|
||||||
pid = session['profile_id']
|
|
||||||
|
|
||||||
with get_db() as conn:
|
|
||||||
cur = get_cursor(conn)
|
|
||||||
|
|
||||||
# Calculate norm category (simplified for now)
|
|
||||||
norm_category = _calculate_norm_category(
|
|
||||||
data.test_type,
|
|
||||||
data.result_value,
|
|
||||||
data.result_unit
|
|
||||||
)
|
|
||||||
|
|
||||||
cur.execute("""
|
|
||||||
INSERT INTO fitness_tests (
|
|
||||||
profile_id, test_type, result_value, result_unit,
|
|
||||||
test_date, test_conditions, norm_category
|
|
||||||
) VALUES (%s, %s, %s, %s, %s, %s, %s)
|
|
||||||
RETURNING id
|
|
||||||
""", (
|
|
||||||
pid, data.test_type, data.result_value, data.result_unit,
|
|
||||||
data.test_date, data.test_conditions, norm_category
|
|
||||||
))
|
|
||||||
|
|
||||||
test_id = cur.fetchone()['id']
|
|
||||||
|
|
||||||
return {"id": test_id, "norm_category": norm_category}
|
|
||||||
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
# Helper Functions
|
# Helper Functions
|
||||||
@@ -480,278 +653,3 @@ def _update_goal_progress(conn, profile_id: str, goal: dict):
|
|||||||
# Check if on track
|
# Check if on track
|
||||||
if goal['target_date'] and goal['projection_date']:
|
if goal['target_date'] and goal['projection_date']:
|
||||||
goal['on_track'] = goal['projection_date'] <= goal['target_date']
|
goal['on_track'] = goal['projection_date'] <= goal['target_date']
|
||||||
|
|
||||||
def _calculate_norm_category(test_type: str, value: float, unit: str) -> Optional[str]:
|
|
||||||
"""
|
|
||||||
Calculate norm category for fitness test
|
|
||||||
(Simplified - would need age/gender-specific norms)
|
|
||||||
"""
|
|
||||||
# Placeholder - should use proper norm tables
|
|
||||||
return None
|
|
||||||
|
|
||||||
# ============================================================================
|
|
||||||
# Goal Type Definitions (Phase 1.5 - Flexible Goal System)
|
|
||||||
# ============================================================================
|
|
||||||
|
|
||||||
@router.get("/goal-types")
|
|
||||||
def list_goal_type_definitions(session: dict = Depends(require_auth)):
|
|
||||||
"""
|
|
||||||
Get all active goal type definitions.
|
|
||||||
|
|
||||||
Public endpoint - returns all available goal types for dropdown.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
with get_db() as conn:
|
|
||||||
cur = get_cursor(conn)
|
|
||||||
|
|
||||||
cur.execute("""
|
|
||||||
SELECT id, type_key, label_de, label_en, unit, icon, category,
|
|
||||||
source_table, source_column, aggregation_method,
|
|
||||||
calculation_formula, description, is_system, is_active,
|
|
||||||
created_at, updated_at
|
|
||||||
FROM goal_type_definitions
|
|
||||||
WHERE is_active = true
|
|
||||||
ORDER BY
|
|
||||||
CASE
|
|
||||||
WHEN is_system = true THEN 0
|
|
||||||
ELSE 1
|
|
||||||
END,
|
|
||||||
label_de
|
|
||||||
""")
|
|
||||||
|
|
||||||
results = [r2d(row) for row in cur.fetchall()]
|
|
||||||
print(f"[DEBUG] Loaded {len(results)} goal types")
|
|
||||||
return results
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[ERROR] list_goal_type_definitions failed: {e}")
|
|
||||||
print(traceback.format_exc())
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=500,
|
|
||||||
detail=f"Fehler beim Laden der Goal Types: {str(e)}"
|
|
||||||
)
|
|
||||||
|
|
||||||
@router.post("/goal-types")
|
|
||||||
def create_goal_type_definition(
|
|
||||||
data: GoalTypeCreate,
|
|
||||||
session: dict = Depends(require_auth)
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Create custom goal type definition.
|
|
||||||
|
|
||||||
Admin-only endpoint for creating new goal types.
|
|
||||||
Users with admin role can define custom metrics.
|
|
||||||
"""
|
|
||||||
pid = session['profile_id']
|
|
||||||
|
|
||||||
# Check admin role
|
|
||||||
with get_db() as conn:
|
|
||||||
cur = get_cursor(conn)
|
|
||||||
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
|
|
||||||
profile = cur.fetchone()
|
|
||||||
|
|
||||||
if not profile or profile['role'] != 'admin':
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=403,
|
|
||||||
detail="Admin-Zugriff erforderlich"
|
|
||||||
)
|
|
||||||
|
|
||||||
# Validate type_key is unique
|
|
||||||
cur.execute(
|
|
||||||
"SELECT id FROM goal_type_definitions WHERE type_key = %s",
|
|
||||||
(data.type_key,)
|
|
||||||
)
|
|
||||||
if cur.fetchone():
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=400,
|
|
||||||
detail=f"Goal Type '{data.type_key}' existiert bereits"
|
|
||||||
)
|
|
||||||
|
|
||||||
# Insert new goal type
|
|
||||||
cur.execute("""
|
|
||||||
INSERT INTO goal_type_definitions (
|
|
||||||
type_key, label_de, label_en, unit, icon, category,
|
|
||||||
source_table, source_column, aggregation_method,
|
|
||||||
calculation_formula, description, is_active, is_system,
|
|
||||||
created_by, updated_by
|
|
||||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
|
||||||
RETURNING id
|
|
||||||
""", (
|
|
||||||
data.type_key, data.label_de, data.label_en, data.unit, data.icon,
|
|
||||||
data.category, data.source_table, data.source_column,
|
|
||||||
data.aggregation_method, data.calculation_formula, data.description,
|
|
||||||
True, False, # is_active=True, is_system=False
|
|
||||||
pid, pid
|
|
||||||
))
|
|
||||||
|
|
||||||
goal_type_id = cur.fetchone()['id']
|
|
||||||
|
|
||||||
return {
|
|
||||||
"id": goal_type_id,
|
|
||||||
"message": f"Goal Type '{data.label_de}' erstellt"
|
|
||||||
}
|
|
||||||
|
|
||||||
@router.put("/goal-types/{goal_type_id}")
|
|
||||||
def update_goal_type_definition(
|
|
||||||
goal_type_id: str,
|
|
||||||
data: GoalTypeUpdate,
|
|
||||||
session: dict = Depends(require_auth)
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Update goal type definition.
|
|
||||||
|
|
||||||
Admin-only. System goal types can be updated but not deleted.
|
|
||||||
"""
|
|
||||||
pid = session['profile_id']
|
|
||||||
|
|
||||||
with get_db() as conn:
|
|
||||||
cur = get_cursor(conn)
|
|
||||||
|
|
||||||
# Check admin role
|
|
||||||
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
|
|
||||||
profile = cur.fetchone()
|
|
||||||
|
|
||||||
if not profile or profile['role'] != 'admin':
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=403,
|
|
||||||
detail="Admin-Zugriff erforderlich"
|
|
||||||
)
|
|
||||||
|
|
||||||
# Check goal type exists
|
|
||||||
cur.execute(
|
|
||||||
"SELECT id FROM goal_type_definitions WHERE id = %s",
|
|
||||||
(goal_type_id,)
|
|
||||||
)
|
|
||||||
if not cur.fetchone():
|
|
||||||
raise HTTPException(status_code=404, detail="Goal Type nicht gefunden")
|
|
||||||
|
|
||||||
# Build update query
|
|
||||||
updates = []
|
|
||||||
params = []
|
|
||||||
|
|
||||||
if data.label_de is not None:
|
|
||||||
updates.append("label_de = %s")
|
|
||||||
params.append(data.label_de)
|
|
||||||
|
|
||||||
if data.label_en is not None:
|
|
||||||
updates.append("label_en = %s")
|
|
||||||
params.append(data.label_en)
|
|
||||||
|
|
||||||
if data.unit is not None:
|
|
||||||
updates.append("unit = %s")
|
|
||||||
params.append(data.unit)
|
|
||||||
|
|
||||||
if data.icon is not None:
|
|
||||||
updates.append("icon = %s")
|
|
||||||
params.append(data.icon)
|
|
||||||
|
|
||||||
if data.category is not None:
|
|
||||||
updates.append("category = %s")
|
|
||||||
params.append(data.category)
|
|
||||||
|
|
||||||
if data.source_table is not None:
|
|
||||||
updates.append("source_table = %s")
|
|
||||||
params.append(data.source_table)
|
|
||||||
|
|
||||||
if data.source_column is not None:
|
|
||||||
updates.append("source_column = %s")
|
|
||||||
params.append(data.source_column)
|
|
||||||
|
|
||||||
if data.aggregation_method is not None:
|
|
||||||
updates.append("aggregation_method = %s")
|
|
||||||
params.append(data.aggregation_method)
|
|
||||||
|
|
||||||
if data.calculation_formula is not None:
|
|
||||||
updates.append("calculation_formula = %s")
|
|
||||||
params.append(data.calculation_formula)
|
|
||||||
|
|
||||||
if data.description is not None:
|
|
||||||
updates.append("description = %s")
|
|
||||||
params.append(data.description)
|
|
||||||
|
|
||||||
if data.is_active is not None:
|
|
||||||
updates.append("is_active = %s")
|
|
||||||
params.append(data.is_active)
|
|
||||||
|
|
||||||
if not updates:
|
|
||||||
raise HTTPException(status_code=400, detail="Keine Änderungen angegeben")
|
|
||||||
|
|
||||||
updates.append("updated_at = NOW()")
|
|
||||||
updates.append("updated_by = %s")
|
|
||||||
params.append(pid)
|
|
||||||
params.append(goal_type_id)
|
|
||||||
|
|
||||||
cur.execute(
|
|
||||||
f"UPDATE goal_type_definitions SET {', '.join(updates)} WHERE id = %s",
|
|
||||||
tuple(params)
|
|
||||||
)
|
|
||||||
|
|
||||||
return {"message": "Goal Type aktualisiert"}
|
|
||||||
|
|
||||||
@router.delete("/goal-types/{goal_type_id}")
|
|
||||||
def delete_goal_type_definition(
|
|
||||||
goal_type_id: str,
|
|
||||||
session: dict = Depends(require_auth)
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Delete (deactivate) goal type definition.
|
|
||||||
|
|
||||||
Admin-only. System goal types cannot be deleted, only deactivated.
|
|
||||||
Custom goal types can be fully deleted if no goals reference them.
|
|
||||||
"""
|
|
||||||
pid = session['profile_id']
|
|
||||||
|
|
||||||
with get_db() as conn:
|
|
||||||
cur = get_cursor(conn)
|
|
||||||
|
|
||||||
# Check admin role
|
|
||||||
cur.execute("SELECT role FROM profiles WHERE id = %s", (pid,))
|
|
||||||
profile = cur.fetchone()
|
|
||||||
|
|
||||||
if not profile or profile['role'] != 'admin':
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=403,
|
|
||||||
detail="Admin-Zugriff erforderlich"
|
|
||||||
)
|
|
||||||
|
|
||||||
# Get goal type info
|
|
||||||
cur.execute(
|
|
||||||
"SELECT id, type_key, is_system FROM goal_type_definitions WHERE id = %s",
|
|
||||||
(goal_type_id,)
|
|
||||||
)
|
|
||||||
goal_type = cur.fetchone()
|
|
||||||
|
|
||||||
if not goal_type:
|
|
||||||
raise HTTPException(status_code=404, detail="Goal Type nicht gefunden")
|
|
||||||
|
|
||||||
# Check if any goals use this type
|
|
||||||
cur.execute(
|
|
||||||
"SELECT COUNT(*) as count FROM goals WHERE goal_type = %s",
|
|
||||||
(goal_type['type_key'],)
|
|
||||||
)
|
|
||||||
count = cur.fetchone()['count']
|
|
||||||
|
|
||||||
if count > 0:
|
|
||||||
# Deactivate instead of delete
|
|
||||||
cur.execute(
|
|
||||||
"UPDATE goal_type_definitions SET is_active = false WHERE id = %s",
|
|
||||||
(goal_type_id,)
|
|
||||||
)
|
|
||||||
return {
|
|
||||||
"message": f"Goal Type deaktiviert ({count} Ziele nutzen diesen Typ)"
|
|
||||||
}
|
|
||||||
else:
|
|
||||||
if goal_type['is_system']:
|
|
||||||
# System types: only deactivate
|
|
||||||
cur.execute(
|
|
||||||
"UPDATE goal_type_definitions SET is_active = false WHERE id = %s",
|
|
||||||
(goal_type_id,)
|
|
||||||
)
|
|
||||||
return {"message": "System Goal Type deaktiviert"}
|
|
||||||
else:
|
|
||||||
# Custom types: delete
|
|
||||||
cur.execute(
|
|
||||||
"DELETE FROM goal_type_definitions WHERE id = %s",
|
|
||||||
(goal_type_id,)
|
|
||||||
)
|
|
||||||
return {"message": "Goal Type gelöscht"}
|
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
"""
|
||||||
|
Training Phases Router - Training Phase Detection & Management
|
||||||
|
|
||||||
|
Endpoints for managing training phases:
|
||||||
|
- List training phases
|
||||||
|
- Create manual training phases
|
||||||
|
- Update phase status (accept/reject auto-detected phases)
|
||||||
|
|
||||||
|
Part of v9h Goal System.
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from typing import Optional
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/goals", tags=["training-phases"])
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Pydantic Models
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
class TrainingPhaseCreate(BaseModel):
|
||||||
|
"""Create training phase (manual or auto-detected)"""
|
||||||
|
phase_type: str # calorie_deficit, calorie_surplus, deload, maintenance, periodization
|
||||||
|
start_date: date
|
||||||
|
end_date: Optional[date] = None
|
||||||
|
notes: Optional[str] = None
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Endpoints
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
@router.get("/phases")
|
||||||
|
def list_training_phases(session: dict = Depends(require_auth)):
|
||||||
|
"""List training phases"""
|
||||||
|
pid = session['profile_id']
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("""
|
||||||
|
SELECT id, phase_type, detected_automatically, confidence_score,
|
||||||
|
status, start_date, end_date, duration_days,
|
||||||
|
detection_params, notes, created_at
|
||||||
|
FROM training_phases
|
||||||
|
WHERE profile_id = %s
|
||||||
|
ORDER BY start_date DESC
|
||||||
|
""", (pid,))
|
||||||
|
|
||||||
|
return [r2d(row) for row in cur.fetchall()]
|
||||||
|
|
||||||
|
@router.post("/phases")
|
||||||
|
def create_training_phase(data: TrainingPhaseCreate, session: dict = Depends(require_auth)):
|
||||||
|
"""Create training phase (manual)"""
|
||||||
|
pid = session['profile_id']
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
duration = None
|
||||||
|
if data.end_date:
|
||||||
|
duration = (data.end_date - data.start_date).days
|
||||||
|
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO training_phases (
|
||||||
|
profile_id, phase_type, detected_automatically,
|
||||||
|
status, start_date, end_date, duration_days, notes
|
||||||
|
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""", (
|
||||||
|
pid, data.phase_type, False,
|
||||||
|
'active', data.start_date, data.end_date, duration, data.notes
|
||||||
|
))
|
||||||
|
|
||||||
|
phase_id = cur.fetchone()['id']
|
||||||
|
|
||||||
|
return {"id": phase_id, "message": "Trainingsphase erstellt"}
|
||||||
|
|
||||||
|
@router.put("/phases/{phase_id}/status")
|
||||||
|
def update_phase_status(
|
||||||
|
phase_id: str,
|
||||||
|
status: str,
|
||||||
|
session: dict = Depends(require_auth)
|
||||||
|
):
|
||||||
|
"""Update training phase status (accept/reject auto-detected phases)"""
|
||||||
|
pid = session['profile_id']
|
||||||
|
|
||||||
|
valid_statuses = ['suggested', 'accepted', 'active', 'completed', 'rejected']
|
||||||
|
if status not in valid_statuses:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Ungültiger Status. Erlaubt: {', '.join(valid_statuses)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE training_phases SET status = %s WHERE id = %s AND profile_id = %s",
|
||||||
|
(status, phase_id, pid)
|
||||||
|
)
|
||||||
|
|
||||||
|
if cur.rowcount == 0:
|
||||||
|
raise HTTPException(status_code=404, detail="Trainingsphase nicht gefunden")
|
||||||
|
|
||||||
|
return {"message": "Status aktualisiert"}
|
||||||
+33
-30
@@ -140,63 +140,66 @@ def create_vitals(
|
|||||||
x_profile_id: Optional[str] = Header(default=None),
|
x_profile_id: Optional[str] = Header(default=None),
|
||||||
session: dict = Depends(require_auth)
|
session: dict = Depends(require_auth)
|
||||||
):
|
):
|
||||||
"""Create or update vitals entry (upsert)."""
|
"""
|
||||||
|
Create or update vitals entry (upsert).
|
||||||
|
|
||||||
|
Post-Migration-015: Routes to vitals_baseline (for RHR, HRV, etc.)
|
||||||
|
Note: BP measurements should use /api/blood-pressure endpoint instead.
|
||||||
|
"""
|
||||||
pid = get_pid(x_profile_id, session)
|
pid = get_pid(x_profile_id, session)
|
||||||
|
|
||||||
# Validation: at least one vital must be provided
|
# Validation: at least one baseline vital must be provided
|
||||||
has_data = any([
|
has_baseline = any([
|
||||||
entry.resting_hr, entry.hrv, entry.blood_pressure_systolic,
|
entry.resting_hr, entry.hrv, entry.vo2_max,
|
||||||
entry.blood_pressure_diastolic, entry.vo2_max, entry.spo2,
|
entry.spo2, entry.respiratory_rate
|
||||||
entry.respiratory_rate
|
|
||||||
])
|
])
|
||||||
if not has_data:
|
|
||||||
raise HTTPException(400, "Mindestens ein Vitalwert muss angegeben werden")
|
if not has_baseline:
|
||||||
|
raise HTTPException(400, "Mindestens ein Vitalwert muss angegeben werden (RHR, HRV, VO2Max, SpO2, oder Atemfrequenz)")
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
# Upsert: insert or update if date already exists
|
# Upsert into vitals_baseline (Migration 015)
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO vitals_log (
|
INSERT INTO vitals_baseline (
|
||||||
profile_id, date, resting_hr, hrv,
|
profile_id, date, resting_hr, hrv,
|
||||||
blood_pressure_systolic, blood_pressure_diastolic, pulse,
|
|
||||||
vo2_max, spo2, respiratory_rate,
|
vo2_max, spo2, respiratory_rate,
|
||||||
irregular_heartbeat, possible_afib,
|
|
||||||
note, source
|
note, source
|
||||||
)
|
)
|
||||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'manual')
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'manual')
|
||||||
ON CONFLICT (profile_id, date)
|
ON CONFLICT (profile_id, date)
|
||||||
DO UPDATE SET
|
DO UPDATE SET
|
||||||
resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_log.resting_hr),
|
resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_baseline.resting_hr),
|
||||||
hrv = COALESCE(EXCLUDED.hrv, vitals_log.hrv),
|
hrv = COALESCE(EXCLUDED.hrv, vitals_baseline.hrv),
|
||||||
blood_pressure_systolic = COALESCE(EXCLUDED.blood_pressure_systolic, vitals_log.blood_pressure_systolic),
|
vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_baseline.vo2_max),
|
||||||
blood_pressure_diastolic = COALESCE(EXCLUDED.blood_pressure_diastolic, vitals_log.blood_pressure_diastolic),
|
spo2 = COALESCE(EXCLUDED.spo2, vitals_baseline.spo2),
|
||||||
pulse = COALESCE(EXCLUDED.pulse, vitals_log.pulse),
|
respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_baseline.respiratory_rate),
|
||||||
vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_log.vo2_max),
|
note = COALESCE(EXCLUDED.note, vitals_baseline.note),
|
||||||
spo2 = COALESCE(EXCLUDED.spo2, vitals_log.spo2),
|
|
||||||
respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_log.respiratory_rate),
|
|
||||||
irregular_heartbeat = COALESCE(EXCLUDED.irregular_heartbeat, vitals_log.irregular_heartbeat),
|
|
||||||
possible_afib = COALESCE(EXCLUDED.possible_afib, vitals_log.possible_afib),
|
|
||||||
note = COALESCE(EXCLUDED.note, vitals_log.note),
|
|
||||||
updated_at = CURRENT_TIMESTAMP
|
updated_at = CURRENT_TIMESTAMP
|
||||||
RETURNING id, profile_id, date, resting_hr, hrv,
|
RETURNING id, profile_id, date, resting_hr, hrv,
|
||||||
blood_pressure_systolic, blood_pressure_diastolic, pulse,
|
|
||||||
vo2_max, spo2, respiratory_rate,
|
vo2_max, spo2, respiratory_rate,
|
||||||
irregular_heartbeat, possible_afib,
|
|
||||||
note, source, created_at, updated_at
|
note, source, created_at, updated_at
|
||||||
""",
|
""",
|
||||||
(pid, entry.date, entry.resting_hr, entry.hrv,
|
(pid, entry.date, entry.resting_hr, entry.hrv,
|
||||||
entry.blood_pressure_systolic, entry.blood_pressure_diastolic, entry.pulse,
|
|
||||||
entry.vo2_max, entry.spo2, entry.respiratory_rate,
|
entry.vo2_max, entry.spo2, entry.respiratory_rate,
|
||||||
entry.irregular_heartbeat, entry.possible_afib,
|
|
||||||
entry.note)
|
entry.note)
|
||||||
)
|
)
|
||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
logger.info(f"[VITALS] Upserted vitals for {pid} on {entry.date}")
|
logger.info(f"[VITALS] Upserted baseline vitals for {pid} on {entry.date}")
|
||||||
return r2d(row)
|
|
||||||
|
# Return in legacy format for backward compatibility
|
||||||
|
result = r2d(row)
|
||||||
|
result['blood_pressure_systolic'] = None
|
||||||
|
result['blood_pressure_diastolic'] = None
|
||||||
|
result['pulse'] = None
|
||||||
|
result['irregular_heartbeat'] = None
|
||||||
|
result['possible_afib'] = None
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
@router.put("/{vitals_id}")
|
@router.put("/{vitals_id}")
|
||||||
|
|||||||
@@ -99,52 +99,90 @@ def create_or_update_baseline(
|
|||||||
"""Create or update baseline entry (upsert on date)."""
|
"""Create or update baseline entry (upsert on date)."""
|
||||||
pid = get_pid(x_profile_id)
|
pid = get_pid(x_profile_id)
|
||||||
|
|
||||||
# Build dynamic update columns (only non-None fields)
|
# Build dynamic INSERT columns, placeholders, UPDATE fields, and values list
|
||||||
fields = []
|
# All arrays must stay synchronized
|
||||||
values = [pid, entry.date]
|
insert_cols = []
|
||||||
|
insert_placeholders = []
|
||||||
|
update_fields = []
|
||||||
|
param_values = [] # Will contain ALL values including pid and date
|
||||||
|
|
||||||
|
# Always include profile_id and date
|
||||||
|
param_values.append(pid)
|
||||||
|
param_values.append(entry.date)
|
||||||
|
|
||||||
if entry.resting_hr is not None:
|
if entry.resting_hr is not None:
|
||||||
fields.append("resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_baseline.resting_hr)")
|
insert_cols.append("resting_hr")
|
||||||
values.append(entry.resting_hr)
|
insert_placeholders.append("%s")
|
||||||
|
update_fields.append("resting_hr = EXCLUDED.resting_hr")
|
||||||
|
param_values.append(entry.resting_hr)
|
||||||
|
|
||||||
if entry.hrv is not None:
|
if entry.hrv is not None:
|
||||||
fields.append("hrv = COALESCE(EXCLUDED.hrv, vitals_baseline.hrv)")
|
insert_cols.append("hrv")
|
||||||
values.append(entry.hrv)
|
insert_placeholders.append("%s")
|
||||||
|
update_fields.append("hrv = EXCLUDED.hrv")
|
||||||
|
param_values.append(entry.hrv)
|
||||||
|
|
||||||
if entry.vo2_max is not None:
|
if entry.vo2_max is not None:
|
||||||
fields.append("vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_baseline.vo2_max)")
|
insert_cols.append("vo2_max")
|
||||||
values.append(entry.vo2_max)
|
insert_placeholders.append("%s")
|
||||||
|
update_fields.append("vo2_max = EXCLUDED.vo2_max")
|
||||||
|
param_values.append(entry.vo2_max)
|
||||||
|
|
||||||
if entry.spo2 is not None:
|
if entry.spo2 is not None:
|
||||||
fields.append("spo2 = COALESCE(EXCLUDED.spo2, vitals_baseline.spo2)")
|
insert_cols.append("spo2")
|
||||||
values.append(entry.spo2)
|
insert_placeholders.append("%s")
|
||||||
|
update_fields.append("spo2 = EXCLUDED.spo2")
|
||||||
|
param_values.append(entry.spo2)
|
||||||
|
|
||||||
if entry.respiratory_rate is not None:
|
if entry.respiratory_rate is not None:
|
||||||
fields.append("respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_baseline.respiratory_rate)")
|
insert_cols.append("respiratory_rate")
|
||||||
values.append(entry.respiratory_rate)
|
insert_placeholders.append("%s")
|
||||||
|
update_fields.append("respiratory_rate = EXCLUDED.respiratory_rate")
|
||||||
|
param_values.append(entry.respiratory_rate)
|
||||||
|
|
||||||
if entry.body_temperature is not None:
|
if entry.body_temperature is not None:
|
||||||
fields.append("body_temperature = COALESCE(EXCLUDED.body_temperature, vitals_baseline.body_temperature)")
|
insert_cols.append("body_temperature")
|
||||||
values.append(entry.body_temperature)
|
insert_placeholders.append("%s")
|
||||||
|
update_fields.append("body_temperature = EXCLUDED.body_temperature")
|
||||||
|
param_values.append(entry.body_temperature)
|
||||||
|
|
||||||
if entry.resting_metabolic_rate is not None:
|
if entry.resting_metabolic_rate is not None:
|
||||||
fields.append("resting_metabolic_rate = COALESCE(EXCLUDED.resting_metabolic_rate, vitals_baseline.resting_metabolic_rate)")
|
insert_cols.append("resting_metabolic_rate")
|
||||||
values.append(entry.resting_metabolic_rate)
|
insert_placeholders.append("%s")
|
||||||
|
update_fields.append("resting_metabolic_rate = EXCLUDED.resting_metabolic_rate")
|
||||||
|
param_values.append(entry.resting_metabolic_rate)
|
||||||
|
|
||||||
if entry.note:
|
if entry.note:
|
||||||
fields.append("note = COALESCE(EXCLUDED.note, vitals_baseline.note)")
|
insert_cols.append("note")
|
||||||
values.append(entry.note)
|
insert_placeholders.append("%s")
|
||||||
|
update_fields.append("note = EXCLUDED.note")
|
||||||
|
param_values.append(entry.note)
|
||||||
|
|
||||||
# At least one field must be provided
|
# At least one field must be provided
|
||||||
if not fields:
|
if not insert_cols:
|
||||||
raise HTTPException(400, "At least one baseline vital must be provided")
|
raise HTTPException(400, "At least one baseline vital must be provided")
|
||||||
|
|
||||||
# Build value placeholders
|
|
||||||
placeholders = ", ".join([f"${i}" for i in range(1, len(values) + 1)])
|
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Build complete column list and placeholder list
|
||||||
|
# IMPORTANT: psycopg2 uses %s placeholders, NOT $1/$2/$3
|
||||||
|
all_cols = f"profile_id, date, {', '.join(insert_cols)}"
|
||||||
|
all_placeholders = f"%s, %s, {', '.join(insert_placeholders)}"
|
||||||
|
|
||||||
query = f"""
|
query = f"""
|
||||||
INSERT INTO vitals_baseline (profile_id, date, {', '.join([f.split('=')[0].strip() for f in fields])})
|
INSERT INTO vitals_baseline ({all_cols})
|
||||||
VALUES ($1, $2, {', '.join([f'${i}' for i in range(3, len(values) + 1)])})
|
VALUES ({all_placeholders})
|
||||||
ON CONFLICT (profile_id, date)
|
ON CONFLICT (profile_id, date)
|
||||||
DO UPDATE SET {', '.join(fields)}, updated_at = NOW()
|
DO UPDATE SET {', '.join(update_fields)}, updated_at = NOW()
|
||||||
RETURNING *
|
RETURNING *
|
||||||
"""
|
"""
|
||||||
cur.execute(query, values)
|
|
||||||
|
# Debug logging
|
||||||
|
print(f"[DEBUG] Vitals baseline query: {query}")
|
||||||
|
print(f"[DEBUG] Param values ({len(param_values)}): {param_values}")
|
||||||
|
|
||||||
|
cur.execute(query, tuple(param_values))
|
||||||
return r2d(cur.fetchone())
|
return r2d(cur.fetchone())
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,196 @@
|
|||||||
|
# Dokumentation Abgeschlossen - 27. März 2026
|
||||||
|
|
||||||
|
## ✅ Was wurde dokumentiert?
|
||||||
|
|
||||||
|
### 1. Hauptstatus-Dokument
|
||||||
|
📄 **`docs/STATUS_2026-03-27.md`** (NEU)
|
||||||
|
- Vollständiger aktueller Zustand
|
||||||
|
- Gitea Issues Status (offen/geschlossen)
|
||||||
|
- Nächste Schritte (Testing → Release → Code Splitting → Phase 0b)
|
||||||
|
- Code-Metriken und technische Schulden
|
||||||
|
- Entscheidungspunkte und Risiken
|
||||||
|
- **Wiederanstiegspunkt für zukünftige Sessions**
|
||||||
|
|
||||||
|
### 2. Neue Issue dokumentiert
|
||||||
|
📄 **`docs/issues/issue-52-blood-pressure-dual-targets.md`** (NEU)
|
||||||
|
- Blutdruck-Ziele benötigen zwei Zielfelder (systolisch/diastolisch)
|
||||||
|
- Migration 033 geplant
|
||||||
|
- UI-Anpassungen beschrieben
|
||||||
|
- 2-3h Aufwand geschätzt
|
||||||
|
|
||||||
|
### 3. CLAUDE.md aktualisiert
|
||||||
|
📄 **`CLAUDE.md`**
|
||||||
|
- Version: v0.9g+ → v0.9h
|
||||||
|
- Dynamic Focus Areas v2.0 Sektion hinzugefügt
|
||||||
|
- Bug Fixes dokumentiert
|
||||||
|
- Status: BEREIT FÜR RELEASE v0.9h
|
||||||
|
|
||||||
|
### 4. Roadmap aktualisiert
|
||||||
|
📄 **`.claude/docs/ROADMAP.md`**
|
||||||
|
- Phase 0a: ✅ COMPLETE
|
||||||
|
- Phase 0b: 🎯 NEXT (detaillierter Plan)
|
||||||
|
- Timeline aktualisiert
|
||||||
|
- Phasen-Übersicht neu strukturiert
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 Gitea Issues - Aktueller Stand
|
||||||
|
|
||||||
|
### Geprüft ✅
|
||||||
|
- Alle offenen Issues durchgesehen (49, 47, 46, 45, 43, 42, 40, 39, 38, 37, 36, 35, 34, 33, 32, 30, 29, 27, 26, 25)
|
||||||
|
- Geschlossene Issues verifiziert (#50, #51, #48, #44, #28)
|
||||||
|
|
||||||
|
### Manuelle Aktionen erforderlich ⚠️
|
||||||
|
|
||||||
|
Du musst noch in Gitea (http://192.168.2.144:3000/Lars/mitai-jinkendo/issues):
|
||||||
|
|
||||||
|
1. **Issue #25 schließen:**
|
||||||
|
- Titel: "[FEAT] Ziele-System (Goals) - v9e Kernfeature"
|
||||||
|
- Status: ✅ KOMPLETT (Phase 0a + Dynamic Focus Areas v2.0)
|
||||||
|
- Aktion: Manuell auf "Closed" setzen
|
||||||
|
- Kommentar: "Completed in v0.9g-h: Phase 0a + Dynamic Focus Areas v2.0. See issue #50 and #51 for details."
|
||||||
|
|
||||||
|
2. **Issue #52 erstellen:**
|
||||||
|
- Titel: "Enhancement: Blutdruck-Ziele benötigen zwei Zielfelder (systolisch/diastolisch)"
|
||||||
|
- Labels: enhancement, goals, blood-pressure
|
||||||
|
- Priorität: Medium
|
||||||
|
- Beschreibung: Kopiere aus `docs/issues/issue-52-blood-pressure-dual-targets.md`
|
||||||
|
- Aufwand: 2-3h
|
||||||
|
- Milestone: v0.10a (nach Phase 0b)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 Nächste Schritte (wenn du weitermachst)
|
||||||
|
|
||||||
|
### Sofort (nach Deployment-Test):
|
||||||
|
1. **Teste Vitals Baseline Fix**
|
||||||
|
- Ruhepuls eintragen (sollte jetzt funktionieren)
|
||||||
|
- Andere Baseline-Werte testen
|
||||||
|
|
||||||
|
2. **Beginne Goals Testing**
|
||||||
|
- Siehe Checklist in `STATUS_2026-03-27.md`
|
||||||
|
- 2-3 Tage gründliches Testing
|
||||||
|
|
||||||
|
### Dann:
|
||||||
|
3. **Release v0.9h vorbereiten**
|
||||||
|
- Release Notes schreiben
|
||||||
|
- Merge develop → main
|
||||||
|
- Tag v0.9h
|
||||||
|
- Deploy to Production
|
||||||
|
|
||||||
|
4. **Code Splitting durchführen**
|
||||||
|
- goals.py → 5 separate Router
|
||||||
|
- Optional: insights.py prüfen
|
||||||
|
|
||||||
|
5. **Phase 0b starten**
|
||||||
|
- 120+ goal-aware Platzhalter
|
||||||
|
- Score-System
|
||||||
|
- 16-20h Aufwand
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📚 Wichtige Dokumente - Lesereihenfolge
|
||||||
|
|
||||||
|
Wenn du zu diesem Punkt zurückkehrst:
|
||||||
|
|
||||||
|
### 1. Zuerst lesen:
|
||||||
|
- **`docs/STATUS_2026-03-27.md`** ← START HIER
|
||||||
|
- **`CLAUDE.md`** (aktuelle Version)
|
||||||
|
- **`docs/NEXT_STEPS_2026-03-26.md`** (Phase 0b Details)
|
||||||
|
|
||||||
|
### 2. Bei Bedarf:
|
||||||
|
- **`.claude/docs/ROADMAP.md`** (Gesamtübersicht)
|
||||||
|
- **`docs/issues/issue-50-phase-0a-goal-system.md`** (Was wurde gebaut)
|
||||||
|
- **`docs/issues/issue-52-blood-pressure-dual-targets.md`** (Nächstes Enhancement)
|
||||||
|
|
||||||
|
### 3. Funktionale Specs:
|
||||||
|
- **`.claude/docs/functional/AI_PROMPTS.md`** (Prompt-System)
|
||||||
|
- **`.claude/docs/functional/TRAINING_TYPES.md`** (Trainingstypen + Abilities)
|
||||||
|
|
||||||
|
### 4. Technische Specs:
|
||||||
|
- **`.claude/docs/technical/MEMBERSHIP_SYSTEM.md`** (Feature-Enforcement)
|
||||||
|
- **`.claude/docs/architecture/`** (Wenn vorhanden)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔄 Wiederanstiegspunkt für Claude Code
|
||||||
|
|
||||||
|
### Context Prompt (copy-paste für neue Session):
|
||||||
|
```
|
||||||
|
Wir sind bei v0.9g/h Release-Vorbereitung.
|
||||||
|
|
||||||
|
AKTUELLER STAND:
|
||||||
|
- Phase 0a (Goals System) + Dynamic Focus Areas v2.0: ✅ KOMPLETT
|
||||||
|
- Vitals baseline fix: deployed (needs testing)
|
||||||
|
- Branch: develop (6 commits ahead of main)
|
||||||
|
- Status: BEREIT FÜR RELEASE v0.9h
|
||||||
|
|
||||||
|
NÄCHSTER SCHRITT:
|
||||||
|
- Testing (Goals + Vitals)
|
||||||
|
- Dann: Release v0.9h → Code Splitting → Phase 0b
|
||||||
|
|
||||||
|
LIES ZUERST:
|
||||||
|
- docs/STATUS_2026-03-27.md (vollständiger Zustand)
|
||||||
|
- CLAUDE.md (aktuelle Version)
|
||||||
|
|
||||||
|
FRAGE MICH:
|
||||||
|
"Was ist der aktuelle Schritt?" → Dann sage ich dir Testing/Release/Splitting/Phase 0b
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 Zusammenfassung - Was ist fertig?
|
||||||
|
|
||||||
|
### ✅ Komplett implementiert
|
||||||
|
- Goals System (Phase 0a)
|
||||||
|
- Strategic Layer (goal_mode, goals CRUD)
|
||||||
|
- Tactical Layer (CustomGoalsPage)
|
||||||
|
- Training Phases Framework (tables, backend)
|
||||||
|
- Fitness Tests Framework (tables, backend)
|
||||||
|
- Dynamic Focus Areas v2.0
|
||||||
|
- 26 Basis-Bereiche in 7 Kategorien
|
||||||
|
- User-extensible (Admin CRUD UI)
|
||||||
|
- Many-to-Many Goals ↔ Focus Areas
|
||||||
|
- User preferences mit Gewichtungen
|
||||||
|
- Bug Fixes
|
||||||
|
- Focus contributions speichern
|
||||||
|
- Filtering (nur gewichtete Areas)
|
||||||
|
- Vitals baseline endpoint
|
||||||
|
|
||||||
|
### 🔲 Noch zu tun (dokumentiert)
|
||||||
|
- Code Splitting (goals.py → 5 Router)
|
||||||
|
- Phase 0b (120+ Platzhalter, Score-System)
|
||||||
|
- Issue #52 (BP dual targets)
|
||||||
|
- Responsive UI (Issue #30)
|
||||||
|
- Weitere Features (siehe Roadmap)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎉 Dokumentations-Qualität
|
||||||
|
|
||||||
|
**Vollständigkeit:** ⭐⭐⭐⭐⭐
|
||||||
|
- Alle wichtigen Dokumente aktualisiert
|
||||||
|
- Neue Dokumente erstellt
|
||||||
|
- Gitea Issues geprüft
|
||||||
|
- Wiederanstiegspunkt klar definiert
|
||||||
|
|
||||||
|
**Nachvollziehbarkeit:** ⭐⭐⭐⭐⭐
|
||||||
|
- Status-Dokument mit allen Details
|
||||||
|
- Entscheidungen dokumentiert
|
||||||
|
- Nächste Schritte klar beschrieben
|
||||||
|
|
||||||
|
**Wartbarkeit:** ⭐⭐⭐⭐⭐
|
||||||
|
- Strukturierte Dokumentation
|
||||||
|
- Klare Verweise zwischen Dokumenten
|
||||||
|
- Lesereihenfolge definiert
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Erstellt:** 27. März 2026, 23:00 Uhr
|
||||||
|
**Von:** Claude Code (Sonnet 4.5)
|
||||||
|
**Commit:** eb5c099 (docs: comprehensive status update v0.9h pre-release)
|
||||||
|
|
||||||
|
**Du kannst jetzt:**
|
||||||
|
✅ Sicher pausieren
|
||||||
|
✅ Deployment testen
|
||||||
|
✅ Jederzeit exakt an diesem Punkt weitermachen
|
||||||
@@ -0,0 +1,272 @@
|
|||||||
|
# Projekt-Status: 27. März 2026
|
||||||
|
|
||||||
|
**Branch:** `develop`
|
||||||
|
**Letzte Version:** v0.9g+ (vor Release v0.9h)
|
||||||
|
**Deployment:** dev.mitai.jinkendo.de
|
||||||
|
**Nächster Meilenstein:** Release v0.9h → Code Splitting → Phase 0b
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 Aktueller Zustand: BEREIT FÜR RELEASE v0.9h
|
||||||
|
|
||||||
|
### Was ist fertig? ✅
|
||||||
|
|
||||||
|
#### Goals System (Phase 0a + Dynamic Focus Areas v2.0)
|
||||||
|
- ✅ **Migration 022:** goals, training_phases, fitness_tests tables
|
||||||
|
- ✅ **Migration 027-032:** Dynamic Focus Areas
|
||||||
|
- 26 Basis-Bereiche in 7 Kategorien (user-extensible)
|
||||||
|
- Many-to-Many: Goals ↔ Focus Areas mit contribution weights
|
||||||
|
- User preferences mit dynamischen Gewichtungen
|
||||||
|
- ✅ **Backend:**
|
||||||
|
- `routers/goals.py` - CRUD für Goals (~1200 Zeilen, **needs splitting**)
|
||||||
|
- `routers/focus_areas.py` - Dynamic system CRUD (~350 Zeilen)
|
||||||
|
- ✅ **Frontend:**
|
||||||
|
- `GoalsPage.jsx` - Strategic layer (~1180 Zeilen, **needs component extraction**)
|
||||||
|
- `CustomGoalsPage.jsx` - Tactical daily entry
|
||||||
|
- `AdminFocusAreasPage.jsx` - Admin UI für Focus Areas
|
||||||
|
- ✅ **Navigation:** Dashboard + Analysis integriert
|
||||||
|
|
||||||
|
#### Bug Fixes (alle committed, deployed pending)
|
||||||
|
- ✅ Focus area contributions speichern (fehlte in API payload)
|
||||||
|
- ✅ Filtering: Nur gewichtete Focus Areas im Ziel-Formular
|
||||||
|
- ✅ Vitals baseline endpoint (parameter mismatch behoben)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 Gitea Issues - Status
|
||||||
|
|
||||||
|
### Geschlossen ✅
|
||||||
|
- ✅ **#50:** Goals System v1 (Phase 0a)
|
||||||
|
- ✅ **#51:** Dynamic Focus Areas v2.0
|
||||||
|
- ✅ **#48:** Flexibles KI Prompt System
|
||||||
|
- ✅ **#44:** BUG - Analysen löschen
|
||||||
|
- ✅ **#28:** AI-Prompts Flexibilisierung
|
||||||
|
- ⏳ **#25:** Goals System (sollte geschlossen werden - ist fertig!)
|
||||||
|
|
||||||
|
### Offen - Priorisiert 🔲
|
||||||
|
- 🔲 **#52:** NEW - Blutdruck-Ziele mit dual targets (systolic/diastolic) - 2-3h
|
||||||
|
- 🔲 **#49:** Prompt-Zuordnung zu Verlaufsseiten (6-8h, Quick Win)
|
||||||
|
- 🔲 **#47:** Wertetabelle Optimierung (4-6h, nach Phase 0b)
|
||||||
|
- 🔲 **#30:** Responsive UI - Desktop Sidebar (8-10h)
|
||||||
|
- 🔲 **#29:** Abilities-Matrix UI (6-8h)
|
||||||
|
|
||||||
|
### Offen - Backlog 📦
|
||||||
|
- 📦 #46, #45: KI Prompt-Ersteller/-Optimierer (später)
|
||||||
|
- 📦 #43, #42: Enhanced Debug UI (später)
|
||||||
|
- 📦 #40: Logout-Button (kosmetisch)
|
||||||
|
- 📦 #39: Usage-Badges Dashboard (kosmetisch)
|
||||||
|
- 📦 #27: Korrelationen erweitern (Phase 2)
|
||||||
|
- 📦 #26: Charts erweitern (Phase 1)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 Nächste Schritte (User-Plan APPROVED)
|
||||||
|
|
||||||
|
### Phase 1: Testing + Release (2-3 Tage)
|
||||||
|
```
|
||||||
|
Tag 1-2: Umfassende Tests des Goals-Moduls
|
||||||
|
[ ] Goal Mode wechseln
|
||||||
|
[ ] Focus Areas gewichten (alle 26 testen)
|
||||||
|
[ ] Ziele erstellen mit focus_contributions
|
||||||
|
[ ] Ziele bearbeiten (contributions ändern)
|
||||||
|
[ ] Ist-Werte eintragen (CustomGoalsPage)
|
||||||
|
[ ] Progress Modal testen
|
||||||
|
[ ] Admin Focus Areas CRUD
|
||||||
|
[ ] Edge Cases (leere Daten, Extremwerte)
|
||||||
|
[ ] Vitals baseline entry (Ruhepuls) - nach neuem Deployment
|
||||||
|
|
||||||
|
Tag 3: Deploy + Release v0.9h
|
||||||
|
[ ] Final commit & push
|
||||||
|
[ ] Merge develop → main (PR in Gitea)
|
||||||
|
[ ] Tag v0.9h in Git
|
||||||
|
[ ] Deploy to Production
|
||||||
|
[ ] Smoke Tests
|
||||||
|
[ ] Release Notes schreiben
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 2: Code Splitting (1-2 Tage)
|
||||||
|
```
|
||||||
|
Tag 3-4: Backend Router Split
|
||||||
|
[ ] goals.py → 5 separate Router
|
||||||
|
- goals.py (core CRUD ~300 Zeilen)
|
||||||
|
- goal_types.py (~200 Zeilen)
|
||||||
|
- goal_progress.py (~150 Zeilen)
|
||||||
|
- training_phases.py (~150 Zeilen)
|
||||||
|
- fitness_tests.py (~150 Zeilen)
|
||||||
|
[ ] Imports anpassen
|
||||||
|
[ ] main.py: 5 neue Router registrieren
|
||||||
|
[ ] Optional: insights.py prüfen (wenn >800 Zeilen)
|
||||||
|
|
||||||
|
Tag 5: Testing nach Split
|
||||||
|
[ ] API-Endpoints vollständig testen
|
||||||
|
[ ] Frontend funktioniert
|
||||||
|
[ ] Deployment auf dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 3: Phase 0b - Goal-Aware Placeholders (4 Tage)
|
||||||
|
```
|
||||||
|
Aufwand: 16-20h
|
||||||
|
Neue Platzhalter: 120+ Funktionen
|
||||||
|
|
||||||
|
Tag 6: KÖRPER + ERNÄHRUNG (40 Funktionen)
|
||||||
|
- weight_7d_rolling_median, weight_28d_trend_slope
|
||||||
|
- fm_28d_delta, lbm_28d_delta, recomposition_score
|
||||||
|
- protein_g_per_kg, protein_g_per_kg_lbm
|
||||||
|
- nutrition_adherence_score, energy_availability
|
||||||
|
|
||||||
|
Tag 7: AKTIVITÄT + RECOVERY (37 Funktionen)
|
||||||
|
- activity_quality_avg_28d, activity_strain_28d
|
||||||
|
- activity_monotony_28d, ability_balance_score
|
||||||
|
- recovery_score, sleep_regularity_index, sleep_debt_hours
|
||||||
|
|
||||||
|
Tag 8: KORRELATIONEN + META + Scoring (20 Funktionen + System)
|
||||||
|
- corr_energy_weight_lag, plateau_detected
|
||||||
|
- goal_mode, data_quality_score, profile_age_years
|
||||||
|
- Score-Gewichtung pro goal_mode implementieren
|
||||||
|
|
||||||
|
Tag 9: Integration + Testing
|
||||||
|
- Prompts aktualisieren mit neuen Platzhaltern
|
||||||
|
- Testing mit verschiedenen goal_modes
|
||||||
|
- Dokumentation
|
||||||
|
|
||||||
|
Tag 10: Deploy v0.10a
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 Code-Metriken (Stand 27.03.2026)
|
||||||
|
|
||||||
|
### Große Dateien (Splitting-Kandidaten)
|
||||||
|
```
|
||||||
|
Backend:
|
||||||
|
- routers/goals.py ~1200 Zeilen ⚠️ SPLIT NEEDED
|
||||||
|
- routers/insights.py ~800 Zeilen (prüfen)
|
||||||
|
- routers/focus_areas.py ~350 Zeilen ✓ OK
|
||||||
|
|
||||||
|
Frontend:
|
||||||
|
- pages/GoalsPage.jsx ~1180 Zeilen ⚠️ Component extraction möglich
|
||||||
|
- pages/AdminPanel.jsx ~700 Zeilen ✓ OK
|
||||||
|
- pages/CustomGoalsPage.jsx ~350 Zeilen ✓ OK
|
||||||
|
```
|
||||||
|
|
||||||
|
### Migrations Status
|
||||||
|
```
|
||||||
|
Letzte Migration: 032_user_focus_area_weights.sql
|
||||||
|
Nächste: 033_dual_target_fields.sql (BP goals, Issue #52)
|
||||||
|
|
||||||
|
Alle Migrationen 001-032 erfolgreich angewandt auf dev ✅
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 Technische Schulden
|
||||||
|
|
||||||
|
### Hoch-Priorität
|
||||||
|
1. **Code Splitting:** goals.py zu groß für Context Window
|
||||||
|
2. **Component Extraction:** GoalsPage.jsx komponenten-basiert
|
||||||
|
3. **Testing Suite:** Automatisierte Tests fehlen komplett
|
||||||
|
|
||||||
|
### Mittel-Priorität
|
||||||
|
4. **Responsive UI:** Desktop-Sidebar fehlt (Issue #30)
|
||||||
|
5. **Error Handling:** Mehr defensive Programmierung nötig
|
||||||
|
6. **API Documentation:** Swagger/OpenAPI fehlt
|
||||||
|
|
||||||
|
### Niedrig-Priorität
|
||||||
|
7. **Type Hints:** Mehr Python Type Annotations
|
||||||
|
8. **Performance:** Einige N+1 Queries optimieren
|
||||||
|
9. **Caching:** Redis für häufige Abfragen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📚 Dokumentation - Status
|
||||||
|
|
||||||
|
### Aktuell ✅
|
||||||
|
- ✅ `CLAUDE.md` - Hauptdokumentation
|
||||||
|
- ✅ `docs/STATUS_2026-03-27.md` - Dieser Status (NEU)
|
||||||
|
- ✅ `docs/NEXT_STEPS_2026-03-26.md` - Roadmap Phase 0b
|
||||||
|
- ✅ `docs/issues/issue-50-phase-0a-goal-system.md` - Phase 0a abgeschlossen
|
||||||
|
- ✅ `docs/issues/issue-52-blood-pressure-dual-targets.md` - Neue Issue (NEU)
|
||||||
|
- ✅ `.claude/docs/functional/AI_PROMPTS.md` - Prompt-System komplett
|
||||||
|
- ✅ `.claude/docs/technical/MEMBERSHIP_SYSTEM.md` - Feature-Enforcement
|
||||||
|
|
||||||
|
### Zu aktualisieren 📝
|
||||||
|
- 📝 `CLAUDE.md` - v0.9g/h Updates eintragen
|
||||||
|
- 📝 `.claude/docs/ROADMAP.md` - Phase 0a als ✅ markieren
|
||||||
|
- 📝 `.claude/library/` - Nach v0.9h Release aktualisieren
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 Decision Points
|
||||||
|
|
||||||
|
### Entschieden ✅
|
||||||
|
1. **User-Plan APPROVED:** Testing → Release → Split → Phase 0b
|
||||||
|
2. **Code Splitting:** Backend Router zuerst, Frontend optional
|
||||||
|
3. **Phase 0b:** Szenario 2 (Strategic Depth first) - 120+ Platzhalter
|
||||||
|
4. **Release Strategy:** v0.9h als stabiler Rollback-Punkt
|
||||||
|
|
||||||
|
### Offen 🤔
|
||||||
|
1. **Issue #52 (BP dual targets):** Vor oder nach Phase 0b? → **Empfehlung: Nach Phase 0b**
|
||||||
|
2. **Frontend Components:** Extract während oder nach Split? → **Empfehlung: Nach, wenn Zeit**
|
||||||
|
3. **Issue #49 (Prompt pages):** Vor oder nach Phase 0b? → **Empfehlung: Nach Phase 0b**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚨 Aktuelle Blocker / Risiken
|
||||||
|
|
||||||
|
### Keine kritischen Blocker ✅
|
||||||
|
|
||||||
|
**Kleine Risiken:**
|
||||||
|
1. ⚠️ **Vitals baseline fix:** Gerade deployed, needs testing
|
||||||
|
2. ⚠️ **Migration 032:** Muss auf Prod laufen (dev läuft bereits)
|
||||||
|
3. ⚠️ **Code Splitting:** Könnte Regressionen einführen → gründliches Testing
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📞 Ansprechpunkte für Wiederaufnahme
|
||||||
|
|
||||||
|
**Wenn du zu diesem Stand zurückkehrst:**
|
||||||
|
|
||||||
|
1. **Lies zuerst:**
|
||||||
|
- Dieses Dokument (STATUS_2026-03-27.md)
|
||||||
|
- CLAUDE.md (aktuelle Version)
|
||||||
|
- docs/NEXT_STEPS_2026-03-26.md (Roadmap)
|
||||||
|
|
||||||
|
2. **Prüfe:**
|
||||||
|
- Ist v0.9h deployed? `git describe --tags`
|
||||||
|
- Läuft dev/prod? `curl https://dev.mitai.jinkendo.de/api/version`
|
||||||
|
- Gitea Issues-Status aktuell?
|
||||||
|
|
||||||
|
3. **Nächster Schritt:**
|
||||||
|
- Falls v0.9h deployed: Start Code Splitting
|
||||||
|
- Falls nicht: Führe Testing-Checklist aus (siehe Phase 1 oben)
|
||||||
|
|
||||||
|
4. **Claude Code Context:**
|
||||||
|
```
|
||||||
|
"Wir sind bei v0.9h Release. Goals-System ist komplett (Phase 0a + Dynamic Focus Areas v2.0).
|
||||||
|
Nächster Schritt: [Testing/Code Splitting/Phase 0b] - siehe STATUS_2026-03-27.md"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📈 Metriken seit letztem Stand
|
||||||
|
|
||||||
|
**Commits seit v0.9g:**
|
||||||
|
- 6 Commits (Goals fixes, Focus Areas v2.0, Vitals baseline fix)
|
||||||
|
- +1200 Zeilen (neue Features)
|
||||||
|
- -400 Zeilen (Refactoring)
|
||||||
|
|
||||||
|
**Issues:**
|
||||||
|
- 3 geschlossen (#50, #51, #48)
|
||||||
|
- 1 neu (#52)
|
||||||
|
- 1 sollte geschlossen werden (#25)
|
||||||
|
|
||||||
|
**Deployment:**
|
||||||
|
- Letzte 3 Deployments erfolgreich
|
||||||
|
- Dev-Environment stabil
|
||||||
|
- Prod auf v0.9g (stabil)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Erstellt:** 27. März 2026, 22:30 Uhr
|
||||||
|
**Von:** Claude Code (Sonnet 4.5)
|
||||||
|
**Nächstes Update:** Nach v0.9h Release
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
# Issue #52: Blutdruck-Ziele benötigen zwei Zielfelder
|
||||||
|
|
||||||
|
**Status:** 🔲 OFFEN
|
||||||
|
**Erstellt:** 27.03.2026
|
||||||
|
**Priorität:** Medium
|
||||||
|
**Typ:** Enhancement
|
||||||
|
**Labels:** goals, blood-pressure, enhancement
|
||||||
|
**Aufwand:** 2-3h
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Problem
|
||||||
|
|
||||||
|
**Aktuell:**
|
||||||
|
- Blutdruck-Ziele (goal_type = 'bp') haben nur EIN Zielfeld (`target_value`)
|
||||||
|
- Blutdruck besteht aber aus ZWEI Werten: Systolisch + Diastolisch
|
||||||
|
- Beispiel-Ziel: "Blutdruck senken auf 120/80 mmHg"
|
||||||
|
- Systolisch (oberer Wert): 120
|
||||||
|
- Diastolisch (unterer Wert): 80
|
||||||
|
|
||||||
|
**Konsequenz:**
|
||||||
|
- User kann nur einen Wert als Ziel eingeben
|
||||||
|
- Unvollständige Zieldefinition
|
||||||
|
- Progress-Tracking ungenau
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Lösung
|
||||||
|
|
||||||
|
### Option A: Dual Target Fields (empfohlen)
|
||||||
|
|
||||||
|
**Schema-Änderung:**
|
||||||
|
```sql
|
||||||
|
-- Migration 033
|
||||||
|
ALTER TABLE goals ADD COLUMN target_value_secondary DECIMAL(10,2);
|
||||||
|
ALTER TABLE goals ADD COLUMN current_value_secondary DECIMAL(10,2);
|
||||||
|
ALTER TABLE goals ADD COLUMN start_value_secondary DECIMAL(10,2);
|
||||||
|
|
||||||
|
COMMENT ON COLUMN goals.target_value_secondary IS 'Secondary target (e.g., diastolic BP for bp goal type)';
|
||||||
|
```
|
||||||
|
|
||||||
|
**Anwendung:**
|
||||||
|
- `bp` goal type:
|
||||||
|
- `target_value` = Systolisch (120)
|
||||||
|
- `target_value_secondary` = Diastolisch (80)
|
||||||
|
- Andere goal types: `target_value_secondary` = NULL
|
||||||
|
|
||||||
|
**UI-Anpassung:**
|
||||||
|
```jsx
|
||||||
|
// GoalForm - conditional rendering
|
||||||
|
{formData.goal_type === 'bp' && (
|
||||||
|
<div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
|
||||||
|
<div>
|
||||||
|
<label>Systolisch (oben)</label>
|
||||||
|
<input type="number" value={formData.target_value} />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label>Diastolisch (unten)</label>
|
||||||
|
<input type="number" value={formData.target_value_secondary} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Progress-Berechnung:**
|
||||||
|
```python
|
||||||
|
def calculate_bp_progress(goal):
|
||||||
|
"""
|
||||||
|
Berechnet Progress für Blutdruck-Ziele.
|
||||||
|
Nimmt Durchschnitt von systolischem und diastolischem Progress.
|
||||||
|
"""
|
||||||
|
systolic_progress = calculate_single_progress(
|
||||||
|
goal.current_value, goal.start_value, goal.target_value
|
||||||
|
)
|
||||||
|
diastolic_progress = calculate_single_progress(
|
||||||
|
goal.current_value_secondary,
|
||||||
|
goal.start_value_secondary,
|
||||||
|
goal.target_value_secondary
|
||||||
|
)
|
||||||
|
|
||||||
|
return (systolic_progress + diastolic_progress) / 2
|
||||||
|
```
|
||||||
|
|
||||||
|
**Display:**
|
||||||
|
```
|
||||||
|
🎯 Blutdruck
|
||||||
|
━━━━━━━━━━━━━━━━━━━━
|
||||||
|
Ziel: 120/80 mmHg
|
||||||
|
Aktuell: 135/88 mmHg
|
||||||
|
Fortschritt: 68% (sys: 60%, dia: 75%)
|
||||||
|
━━━━━━━━━━━━━━━━━━━━
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Option B: JSON Target (flexibler, komplexer)
|
||||||
|
|
||||||
|
```sql
|
||||||
|
ALTER TABLE goals ADD COLUMN target_json JSONB;
|
||||||
|
|
||||||
|
-- Beispiel:
|
||||||
|
{
|
||||||
|
"systolic": 120,
|
||||||
|
"diastolic": 80,
|
||||||
|
"unit": "mmHg"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Nachteil:** Komplexer zu abfragen, weniger SQL-freundlich.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Betroffene Dateien
|
||||||
|
|
||||||
|
**Backend:**
|
||||||
|
- `backend/migrations/033_dual_target_fields.sql` (NEU)
|
||||||
|
- `backend/routers/goals.py` - Progress-Berechnung erweitern
|
||||||
|
- `backend/routers/goal_utils.py` - `_get_current_value_for_goal_type()` für BP
|
||||||
|
|
||||||
|
**Frontend:**
|
||||||
|
- `frontend/src/pages/GoalsPage.jsx` - Form conditional rendering
|
||||||
|
- `frontend/src/pages/GoalsPage.jsx` - Display conditional rendering
|
||||||
|
- `frontend/src/pages/CustomGoalsPage.jsx` - Dual input für BP
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
- [ ] Migration 033 erstellt und angewandt
|
||||||
|
- [ ] GoalForm zeigt zwei Felder für BP-Ziele (Systolisch/Diastolisch)
|
||||||
|
- [ ] Progress-Berechnung berücksichtigt beide Werte
|
||||||
|
- [ ] Display zeigt "120/80 mmHg" Format
|
||||||
|
- [ ] CustomGoalsPage erlaubt Eingabe beider Werte
|
||||||
|
- [ ] Backward compatible (alte BP-Ziele mit nur target_value funktionieren noch)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verwandte Issues
|
||||||
|
|
||||||
|
- Issue #50: Goals System v1 ✅
|
||||||
|
- Issue #51: Dynamic Focus Areas v2.0 ✅
|
||||||
|
- Migration 022: goals table (Basis)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Timeline
|
||||||
|
|
||||||
|
**Geschätzt:** 2-3 Stunden
|
||||||
|
- Migration: 30 min
|
||||||
|
- Backend Logic: 1h
|
||||||
|
- Frontend UI: 1-1.5h
|
||||||
|
- Testing: 30 min
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Erstellt von:** Claude Code
|
||||||
|
**Review benötigt:** Vor Implementierung mit User abstimmen (Option A vs. B)
|
||||||
@@ -32,11 +32,13 @@ import AdminActivityMappingsPage from './pages/AdminActivityMappingsPage'
|
|||||||
import AdminTrainingProfiles from './pages/AdminTrainingProfiles'
|
import AdminTrainingProfiles from './pages/AdminTrainingProfiles'
|
||||||
import AdminPromptsPage from './pages/AdminPromptsPage'
|
import AdminPromptsPage from './pages/AdminPromptsPage'
|
||||||
import AdminGoalTypesPage from './pages/AdminGoalTypesPage'
|
import AdminGoalTypesPage from './pages/AdminGoalTypesPage'
|
||||||
|
import AdminFocusAreasPage from './pages/AdminFocusAreasPage'
|
||||||
import SubscriptionPage from './pages/SubscriptionPage'
|
import SubscriptionPage from './pages/SubscriptionPage'
|
||||||
import SleepPage from './pages/SleepPage'
|
import SleepPage from './pages/SleepPage'
|
||||||
import RestDaysPage from './pages/RestDaysPage'
|
import RestDaysPage from './pages/RestDaysPage'
|
||||||
import VitalsPage from './pages/VitalsPage'
|
import VitalsPage from './pages/VitalsPage'
|
||||||
import GoalsPage from './pages/GoalsPage'
|
import GoalsPage from './pages/GoalsPage'
|
||||||
|
import CustomGoalsPage from './pages/CustomGoalsPage'
|
||||||
import './app.css'
|
import './app.css'
|
||||||
|
|
||||||
function Nav() {
|
function Nav() {
|
||||||
@@ -175,6 +177,7 @@ function AppShell() {
|
|||||||
<Route path="/rest-days" element={<RestDaysPage/>}/>
|
<Route path="/rest-days" element={<RestDaysPage/>}/>
|
||||||
<Route path="/vitals" element={<VitalsPage/>}/>
|
<Route path="/vitals" element={<VitalsPage/>}/>
|
||||||
<Route path="/goals" element={<GoalsPage/>}/>
|
<Route path="/goals" element={<GoalsPage/>}/>
|
||||||
|
<Route path="/custom-goals" element={<CustomGoalsPage/>}/>
|
||||||
<Route path="/nutrition" element={<NutritionPage/>}/>
|
<Route path="/nutrition" element={<NutritionPage/>}/>
|
||||||
<Route path="/activity" element={<ActivityPage/>}/>
|
<Route path="/activity" element={<ActivityPage/>}/>
|
||||||
<Route path="/analysis" element={<Analysis/>}/>
|
<Route path="/analysis" element={<Analysis/>}/>
|
||||||
@@ -190,6 +193,7 @@ function AppShell() {
|
|||||||
<Route path="/admin/training-profiles" element={<AdminTrainingProfiles/>}/>
|
<Route path="/admin/training-profiles" element={<AdminTrainingProfiles/>}/>
|
||||||
<Route path="/admin/prompts" element={<AdminPromptsPage/>}/>
|
<Route path="/admin/prompts" element={<AdminPromptsPage/>}/>
|
||||||
<Route path="/admin/goal-types" element={<AdminGoalTypesPage/>}/>
|
<Route path="/admin/goal-types" element={<AdminGoalTypesPage/>}/>
|
||||||
|
<Route path="/admin/focus-areas" element={<AdminFocusAreasPage/>}/>
|
||||||
<Route path="/subscription" element={<SubscriptionPage/>}/>
|
<Route path="/subscription" element={<SubscriptionPage/>}/>
|
||||||
</Routes>
|
</Routes>
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -0,0 +1,475 @@
|
|||||||
|
import { useState, useEffect } from 'react'
|
||||||
|
import { Plus, Pencil, Trash2, Save, X, Eye, EyeOff } from 'lucide-react'
|
||||||
|
import { api } from '../utils/api'
|
||||||
|
|
||||||
|
const CATEGORIES = [
|
||||||
|
{ value: 'body_composition', label: 'Körperzusammensetzung' },
|
||||||
|
{ value: 'training', label: 'Training' },
|
||||||
|
{ value: 'endurance', label: 'Ausdauer' },
|
||||||
|
{ value: 'coordination', label: 'Koordination' },
|
||||||
|
{ value: 'mental', label: 'Mental' },
|
||||||
|
{ value: 'recovery', label: 'Erholung' },
|
||||||
|
{ value: 'health', label: 'Gesundheit' },
|
||||||
|
{ value: 'custom', label: 'Eigene' }
|
||||||
|
]
|
||||||
|
|
||||||
|
export default function AdminFocusAreasPage() {
|
||||||
|
const [data, setData] = useState({ areas: [], grouped: {}, total: 0 })
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [error, setError] = useState(null)
|
||||||
|
const [showInactive, setShowInactive] = useState(false)
|
||||||
|
const [editingId, setEditingId] = useState(null)
|
||||||
|
const [creating, setCreating] = useState(false)
|
||||||
|
const [formData, setFormData] = useState({
|
||||||
|
key: '',
|
||||||
|
name_de: '',
|
||||||
|
name_en: '',
|
||||||
|
icon: '',
|
||||||
|
description: '',
|
||||||
|
category: 'custom'
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadData()
|
||||||
|
}, [showInactive])
|
||||||
|
|
||||||
|
const loadData = async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true)
|
||||||
|
const result = await api.listFocusAreaDefinitions(showInactive)
|
||||||
|
setData(result)
|
||||||
|
setError(null)
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to load focus areas:', err)
|
||||||
|
setError(err.message)
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCreate = async () => {
|
||||||
|
if (!formData.key || !formData.name_de) {
|
||||||
|
setError('Key und Name (DE) sind erforderlich')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await api.createFocusAreaDefinition(formData)
|
||||||
|
setCreating(false)
|
||||||
|
setFormData({
|
||||||
|
key: '',
|
||||||
|
name_de: '',
|
||||||
|
name_en: '',
|
||||||
|
icon: '',
|
||||||
|
description: '',
|
||||||
|
category: 'custom'
|
||||||
|
})
|
||||||
|
await loadData()
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleUpdate = async (id) => {
|
||||||
|
try {
|
||||||
|
const area = data.areas.find(a => a.id === id)
|
||||||
|
await api.updateFocusAreaDefinition(id, {
|
||||||
|
name_de: area.name_de,
|
||||||
|
name_en: area.name_en,
|
||||||
|
icon: area.icon,
|
||||||
|
description: area.description,
|
||||||
|
category: area.category,
|
||||||
|
is_active: area.is_active
|
||||||
|
})
|
||||||
|
setEditingId(null)
|
||||||
|
await loadData()
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDelete = async (id) => {
|
||||||
|
if (!confirm('Focus Area wirklich löschen?')) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
await api.deleteFocusAreaDefinition(id)
|
||||||
|
await loadData()
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleToggleActive = async (id) => {
|
||||||
|
const area = data.areas.find(a => a.id === id)
|
||||||
|
try {
|
||||||
|
await api.updateFocusAreaDefinition(id, {
|
||||||
|
is_active: !area.is_active
|
||||||
|
})
|
||||||
|
await loadData()
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateField = (id, field, value) => {
|
||||||
|
setData(prev => ({
|
||||||
|
...prev,
|
||||||
|
areas: prev.areas.map(a =>
|
||||||
|
a.id === id ? { ...a, [field]: value } : a
|
||||||
|
)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 20, textAlign: 'center' }}>
|
||||||
|
<div className="spinner" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 16, paddingBottom: 80 }}>
|
||||||
|
{/* Header */}
|
||||||
|
<div style={{
|
||||||
|
display: 'flex',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
alignItems: 'center',
|
||||||
|
marginBottom: 16
|
||||||
|
}}>
|
||||||
|
<h1 style={{ fontSize: 24, fontWeight: 700, margin: 0 }}>
|
||||||
|
🎯 Focus Areas ({data.total})
|
||||||
|
</h1>
|
||||||
|
<div style={{ display: 'flex', gap: 8 }}>
|
||||||
|
<button
|
||||||
|
className="btn-secondary"
|
||||||
|
onClick={() => setShowInactive(!showInactive)}
|
||||||
|
style={{ padding: '8px 12px', fontSize: 13 }}
|
||||||
|
>
|
||||||
|
{showInactive ? <Eye size={14} /> : <EyeOff size={14} />}
|
||||||
|
{showInactive ? 'Inaktive ausblenden' : 'Inaktive anzeigen'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="btn-primary"
|
||||||
|
onClick={() => setCreating(true)}
|
||||||
|
style={{ padding: '8px 16px' }}
|
||||||
|
>
|
||||||
|
<Plus size={16} /> Neue Focus Area
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div style={{
|
||||||
|
padding: 12,
|
||||||
|
background: '#FEE2E2',
|
||||||
|
color: '#991B1B',
|
||||||
|
borderRadius: 8,
|
||||||
|
marginBottom: 16,
|
||||||
|
fontSize: 14
|
||||||
|
}}>
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Create Form */}
|
||||||
|
{creating && (
|
||||||
|
<div className="card" style={{ marginBottom: 16, background: 'var(--accent-light)' }}>
|
||||||
|
<h3 style={{ fontSize: 16, marginBottom: 12, color: 'var(--accent)' }}>
|
||||||
|
Neue Focus Area
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<div style={{ display: 'grid', gap: 12 }}>
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 4 }}>
|
||||||
|
Key (Eindeutig, z.B. "explosive_power")
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
className="form-input"
|
||||||
|
value={formData.key}
|
||||||
|
onChange={(e) => setFormData({ ...formData, key: e.target.value })}
|
||||||
|
placeholder="explosive_power"
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 4 }}>
|
||||||
|
Name (Deutsch) *
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
className="form-input"
|
||||||
|
value={formData.name_de}
|
||||||
|
onChange={(e) => setFormData({ ...formData, name_de: e.target.value })}
|
||||||
|
placeholder="Explosivkraft"
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 4 }}>
|
||||||
|
Name (English)
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
className="form-input"
|
||||||
|
value={formData.name_en}
|
||||||
|
onChange={(e) => setFormData({ ...formData, name_en: e.target.value })}
|
||||||
|
placeholder="Explosive Power"
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 4 }}>
|
||||||
|
Icon (Emoji)
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
className="form-input"
|
||||||
|
value={formData.icon}
|
||||||
|
onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
|
||||||
|
placeholder="💥"
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 4 }}>
|
||||||
|
Kategorie
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
className="form-input"
|
||||||
|
value={formData.category}
|
||||||
|
onChange={(e) => setFormData({ ...formData, category: e.target.value })}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
>
|
||||||
|
{CATEGORIES.map(cat => (
|
||||||
|
<option key={cat.value} value={cat.value}>{cat.label}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 4 }}>
|
||||||
|
Beschreibung
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
className="form-input"
|
||||||
|
value={formData.description}
|
||||||
|
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
||||||
|
placeholder="Kraft in kürzester Zeit explosiv entfalten"
|
||||||
|
rows={2}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ display: 'flex', gap: 8 }}>
|
||||||
|
<button className="btn-primary" onClick={handleCreate} style={{ flex: 1 }}>
|
||||||
|
<Save size={14} /> Erstellen
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="btn-secondary"
|
||||||
|
onClick={() => {
|
||||||
|
setCreating(false)
|
||||||
|
setFormData({
|
||||||
|
key: '',
|
||||||
|
name_de: '',
|
||||||
|
name_en: '',
|
||||||
|
icon: '',
|
||||||
|
description: '',
|
||||||
|
category: 'custom'
|
||||||
|
})
|
||||||
|
}}
|
||||||
|
style={{ flex: 1 }}
|
||||||
|
>
|
||||||
|
<X size={14} /> Abbrechen
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Grouped Areas */}
|
||||||
|
{Object.entries(data.grouped).map(([category, areas]) => (
|
||||||
|
<div key={category} style={{ marginBottom: 24 }}>
|
||||||
|
<h2 style={{
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: 600,
|
||||||
|
color: 'var(--text2)',
|
||||||
|
textTransform: 'uppercase',
|
||||||
|
letterSpacing: '0.05em',
|
||||||
|
marginBottom: 12
|
||||||
|
}}>
|
||||||
|
{CATEGORIES.find(c => c.value === category)?.label || category} ({areas.length})
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||||
|
{areas.map(area => {
|
||||||
|
const isEditing = editingId === area.id
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={area.id}
|
||||||
|
className="card"
|
||||||
|
style={{
|
||||||
|
opacity: area.is_active ? 1 : 0.5,
|
||||||
|
borderLeft: area.is_active
|
||||||
|
? '4px solid var(--accent)'
|
||||||
|
: '4px solid var(--border)'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{isEditing ? (
|
||||||
|
<div style={{ display: 'grid', gap: 12 }}>
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>
|
||||||
|
Name (DE)
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
className="form-input"
|
||||||
|
value={area.name_de}
|
||||||
|
onChange={(e) => updateField(area.id, 'name_de', e.target.value)}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>
|
||||||
|
Icon
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
className="form-input"
|
||||||
|
value={area.icon || ''}
|
||||||
|
onChange={(e) => updateField(area.id, 'icon', e.target.value)}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>
|
||||||
|
Beschreibung
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
className="form-input"
|
||||||
|
value={area.description || ''}
|
||||||
|
onChange={(e) => updateField(area.id, 'description', e.target.value)}
|
||||||
|
rows={2}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ display: 'flex', gap: 8 }}>
|
||||||
|
<button
|
||||||
|
className="btn-primary"
|
||||||
|
onClick={() => handleUpdate(area.id)}
|
||||||
|
style={{ flex: 1 }}
|
||||||
|
>
|
||||||
|
<Save size={14} /> Speichern
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="btn-secondary"
|
||||||
|
onClick={() => {
|
||||||
|
setEditingId(null)
|
||||||
|
loadData()
|
||||||
|
}}
|
||||||
|
style={{ flex: 1 }}
|
||||||
|
>
|
||||||
|
<X size={14} /> Abbrechen
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div style={{
|
||||||
|
display: 'flex',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
alignItems: 'flex-start',
|
||||||
|
gap: 12
|
||||||
|
}}>
|
||||||
|
<div style={{ flex: 1 }}>
|
||||||
|
<div style={{
|
||||||
|
fontSize: 16,
|
||||||
|
fontWeight: 600,
|
||||||
|
marginBottom: 4,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: 8
|
||||||
|
}}>
|
||||||
|
{area.icon && <span>{area.icon}</span>}
|
||||||
|
<span>{area.name_de}</span>
|
||||||
|
{!area.is_active && (
|
||||||
|
<span style={{
|
||||||
|
fontSize: 11,
|
||||||
|
padding: '2px 6px',
|
||||||
|
background: 'var(--border)',
|
||||||
|
borderRadius: 4,
|
||||||
|
color: 'var(--text3)'
|
||||||
|
}}>
|
||||||
|
Inaktiv
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ fontSize: 12, color: 'var(--text3)', marginBottom: 4 }}>
|
||||||
|
Key: <code style={{
|
||||||
|
background: 'var(--surface2)',
|
||||||
|
padding: '2px 4px',
|
||||||
|
borderRadius: 4
|
||||||
|
}}>
|
||||||
|
{area.key}
|
||||||
|
</code>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{area.description && (
|
||||||
|
<div style={{ fontSize: 13, color: 'var(--text2)', marginTop: 4 }}>
|
||||||
|
{area.description}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
|
||||||
|
<button
|
||||||
|
className="btn-secondary"
|
||||||
|
onClick={() => handleToggleActive(area.id)}
|
||||||
|
style={{ padding: '6px 12px' }}
|
||||||
|
title={area.is_active ? 'Deaktivieren' : 'Aktivieren'}
|
||||||
|
>
|
||||||
|
{area.is_active ? <EyeOff size={14} /> : <Eye size={14} />}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
className="btn-secondary"
|
||||||
|
onClick={() => setEditingId(area.id)}
|
||||||
|
style={{ padding: '6px 12px' }}
|
||||||
|
title="Bearbeiten"
|
||||||
|
>
|
||||||
|
<Pencil size={14} />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
className="btn-secondary"
|
||||||
|
onClick={() => handleDelete(area.id)}
|
||||||
|
style={{ padding: '6px 12px', color: '#DC2626' }}
|
||||||
|
title="Löschen"
|
||||||
|
>
|
||||||
|
<Trash2 size={14} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{data.areas.length === 0 && (
|
||||||
|
<div style={{
|
||||||
|
padding: 40,
|
||||||
|
textAlign: 'center',
|
||||||
|
color: 'var(--text3)'
|
||||||
|
}}>
|
||||||
|
Keine Focus Areas vorhanden
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import { api } from '../utils/api'
|
|||||||
|
|
||||||
export default function AdminGoalTypesPage() {
|
export default function AdminGoalTypesPage() {
|
||||||
const [goalTypes, setGoalTypes] = useState([])
|
const [goalTypes, setGoalTypes] = useState([])
|
||||||
|
const [schemaInfo, setSchemaInfo] = useState(null)
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [error, setError] = useState(null)
|
const [error, setError] = useState(null)
|
||||||
const [showForm, setShowForm] = useState(false)
|
const [showForm, setShowForm] = useState(false)
|
||||||
@@ -19,6 +20,7 @@ export default function AdminGoalTypesPage() {
|
|||||||
source_table: '',
|
source_table: '',
|
||||||
source_column: '',
|
source_column: '',
|
||||||
aggregation_method: 'latest',
|
aggregation_method: 'latest',
|
||||||
|
filter_conditions: '',
|
||||||
description: ''
|
description: ''
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -42,9 +44,14 @@ export default function AdminGoalTypesPage() {
|
|||||||
setLoading(true)
|
setLoading(true)
|
||||||
setError(null)
|
setError(null)
|
||||||
try {
|
try {
|
||||||
const data = await api.listGoalTypeDefinitions()
|
const [typesData, schema] = await Promise.all([
|
||||||
console.log('[DEBUG] Loaded goal types:', data)
|
api.listGoalTypeDefinitions(),
|
||||||
setGoalTypes(data || [])
|
api.getSchemaInfo()
|
||||||
|
])
|
||||||
|
console.log('[DEBUG] Loaded goal types:', typesData)
|
||||||
|
console.log('[DEBUG] Loaded schema info:', schema)
|
||||||
|
setGoalTypes(typesData || [])
|
||||||
|
setSchemaInfo(schema || {})
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[ERROR] Failed to load goal types:', err)
|
console.error('[ERROR] Failed to load goal types:', err)
|
||||||
setError(`Fehler beim Laden der Goal Types: ${err.message || err.toString()}`)
|
setError(`Fehler beim Laden der Goal Types: ${err.message || err.toString()}`)
|
||||||
@@ -69,6 +76,7 @@ export default function AdminGoalTypesPage() {
|
|||||||
source_table: '',
|
source_table: '',
|
||||||
source_column: '',
|
source_column: '',
|
||||||
aggregation_method: 'latest',
|
aggregation_method: 'latest',
|
||||||
|
filter_conditions: '',
|
||||||
description: ''
|
description: ''
|
||||||
})
|
})
|
||||||
setShowForm(true)
|
setShowForm(true)
|
||||||
@@ -85,6 +93,7 @@ export default function AdminGoalTypesPage() {
|
|||||||
source_table: type.source_table || '',
|
source_table: type.source_table || '',
|
||||||
source_column: type.source_column || '',
|
source_column: type.source_column || '',
|
||||||
aggregation_method: type.aggregation_method || 'latest',
|
aggregation_method: type.aggregation_method || 'latest',
|
||||||
|
filter_conditions: type.filter_conditions ? JSON.stringify(type.filter_conditions, null, 2) : '',
|
||||||
description: type.description || ''
|
description: type.description || ''
|
||||||
})
|
})
|
||||||
setShowForm(true)
|
setShowForm(true)
|
||||||
@@ -96,16 +105,29 @@ export default function AdminGoalTypesPage() {
|
|||||||
return
|
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 {
|
try {
|
||||||
if (editingType) {
|
if (editingType) {
|
||||||
await api.updateGoalType(editingType, formData)
|
await api.updateGoalType(editingType, payload)
|
||||||
showToast('✓ Goal Type aktualisiert')
|
showToast('✓ Goal Type aktualisiert')
|
||||||
} else {
|
} else {
|
||||||
if (!formData.type_key) {
|
if (!formData.type_key) {
|
||||||
setError('Bitte eindeutigen Key angeben (z.B. meditation_minutes)')
|
setError('Bitte eindeutigen Key angeben (z.B. meditation_minutes)')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
await api.createGoalType(formData)
|
await api.createGoalType(payload)
|
||||||
showToast('✓ Goal Type erstellt')
|
showToast('✓ Goal Type erstellt')
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -375,25 +397,59 @@ export default function AdminGoalTypesPage() {
|
|||||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
|
||||||
<div>
|
<div>
|
||||||
<label className="form-label">Tabelle</label>
|
<label className="form-label">Tabelle</label>
|
||||||
|
{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
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
className="form-input"
|
className="form-input"
|
||||||
style={{ width: '100%' }}
|
style={{ width: '100%' }}
|
||||||
value={formData.source_table}
|
value={formData.source_table}
|
||||||
onChange={e => setFormData(f => ({ ...f, source_table: e.target.value }))}
|
onChange={e => setFormData(f => ({ ...f, source_table: e.target.value }))}
|
||||||
placeholder="z.B. meditation_log"
|
placeholder="Lade Schema..."
|
||||||
|
disabled
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label className="form-label">Spalte</label>
|
<label className="form-label">Spalte</label>
|
||||||
|
{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
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
className="form-input"
|
className="form-input"
|
||||||
style={{ width: '100%' }}
|
style={{ width: '100%' }}
|
||||||
value={formData.source_column}
|
value={formData.source_column}
|
||||||
onChange={e => setFormData(f => ({ ...f, source_column: e.target.value }))}
|
onChange={e => setFormData(f => ({ ...f, source_column: e.target.value }))}
|
||||||
placeholder="z.B. duration_minutes"
|
placeholder={formData.source_table ? "Spalte wählen..." : "Erst Tabelle wählen"}
|
||||||
|
disabled={!formData.source_table}
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -412,6 +468,21 @@ export default function AdminGoalTypesPage() {
|
|||||||
</select>
|
</select>
|
||||||
</div>
|
</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 */}
|
{/* Description */}
|
||||||
<div>
|
<div>
|
||||||
<label className="form-label">Beschreibung (optional)</label>
|
<label className="form-label">Beschreibung (optional)</label>
|
||||||
|
|||||||
@@ -453,7 +453,7 @@ export default function AdminPanel() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* KI-Prompts Section */}
|
{/* 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}}>
|
<div style={{fontWeight:700,fontSize:14,marginBottom:12,display:'flex',alignItems:'center',gap:6}}>
|
||||||
<Settings size={16} color="var(--accent)"/> KI-Prompts (v9f)
|
<Settings size={16} color="var(--accent)"/> KI-Prompts (v9f)
|
||||||
</div>
|
</div>
|
||||||
@@ -468,6 +468,40 @@ export default function AdminPanel() {
|
|||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</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>
|
||||||
|
|
||||||
|
{/* Focus Areas 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)"/> Focus Areas (v9g)
|
||||||
|
</div>
|
||||||
|
<div style={{fontSize:12,color:'var(--text3)',marginBottom:12,lineHeight:1.5}}>
|
||||||
|
Verwalte Focus Area Definitionen: Dynamisches, erweiterbares System mit 26+ Bereichen über 7 Kategorien.
|
||||||
|
</div>
|
||||||
|
<div style={{display:'grid',gap:8}}>
|
||||||
|
<Link to="/admin/focus-areas">
|
||||||
|
<button className="btn btn-secondary btn-full">
|
||||||
|
🎯 Focus Areas verwalten
|
||||||
|
</button>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -66,6 +66,13 @@ const ENTRIES = [
|
|||||||
to: '/vitals',
|
to: '/vitals',
|
||||||
color: '#E74C3C',
|
color: '#E74C3C',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
icon: '🎯',
|
||||||
|
label: 'Eigene Ziele',
|
||||||
|
sub: 'Fortschritte für individuelle Ziele erfassen',
|
||||||
|
to: '/custom-goals',
|
||||||
|
color: '#1D9E75',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
icon: '📖',
|
icon: '📖',
|
||||||
label: 'Messanleitung',
|
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>
|
||||||
|
)
|
||||||
|
}
|
||||||
+893
-156
File diff suppressed because it is too large.
Load diff
@@ -334,16 +334,28 @@ export const api = {
|
|||||||
// v9e: Goals System (Strategic + Tactical)
|
// v9e: Goals System (Strategic + Tactical)
|
||||||
getGoalMode: () => req('/goals/mode'),
|
getGoalMode: () => req('/goals/mode'),
|
||||||
updateGoalMode: (mode) => req('/goals/mode', jput({goal_mode: 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'),
|
listGoals: () => req('/goals/list'),
|
||||||
|
listGoalsGrouped: () => req('/goals/grouped'),
|
||||||
createGoal: (d) => req('/goals/create', json(d)),
|
createGoal: (d) => req('/goals/create', json(d)),
|
||||||
updateGoal: (id,d) => req(`/goals/${id}`, jput(d)),
|
updateGoal: (id,d) => req(`/goals/${id}`, jput(d)),
|
||||||
deleteGoal: (id) => req(`/goals/${id}`, {method:'DELETE'}),
|
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)
|
// Goal Type Definitions (Phase 1.5)
|
||||||
listGoalTypeDefinitions: () => req('/goals/goal-types'),
|
listGoalTypeDefinitions: () => req('/goals/goal-types'),
|
||||||
createGoalType: (d) => req('/goals/goal-types', json(d)),
|
createGoalType: (d) => req('/goals/goal-types', json(d)),
|
||||||
updateGoalType: (id,d) => req(`/goals/goal-types/${id}`, jput(d)),
|
updateGoalType: (id,d) => req(`/goals/goal-types/${id}`, jput(d)),
|
||||||
deleteGoalType: (id) => req(`/goals/goal-types/${id}`, {method:'DELETE'}),
|
deleteGoalType: (id) => req(`/goals/goal-types/${id}`, {method:'DELETE'}),
|
||||||
|
getSchemaInfo: () => req('/goals/schema-info'),
|
||||||
|
|
||||||
// Training Phases
|
// Training Phases
|
||||||
listTrainingPhases: () => req('/goals/phases'),
|
listTrainingPhases: () => req('/goals/phases'),
|
||||||
@@ -353,4 +365,13 @@ export const api = {
|
|||||||
// Fitness Tests
|
// Fitness Tests
|
||||||
listFitnessTests: () => req('/goals/tests'),
|
listFitnessTests: () => req('/goals/tests'),
|
||||||
createFitnessTest: (d) => req('/goals/tests', json(d)),
|
createFitnessTest: (d) => req('/goals/tests', json(d)),
|
||||||
|
|
||||||
|
// Focus Areas (v2.0)
|
||||||
|
listFocusAreaDefinitions: (includeInactive=false) => req(`/focus-areas/definitions?include_inactive=${includeInactive}`),
|
||||||
|
createFocusAreaDefinition: (d) => req('/focus-areas/definitions', json(d)),
|
||||||
|
updateFocusAreaDefinition: (id,d) => req(`/focus-areas/definitions/${id}`, jput(d)),
|
||||||
|
deleteFocusAreaDefinition: (id) => req(`/focus-areas/definitions/${id}`, {method:'DELETE'}),
|
||||||
|
getUserFocusPreferences: () => req('/focus-areas/user-preferences'),
|
||||||
|
updateUserFocusPreferences: (d) => req('/focus-areas/user-preferences', jput(d)),
|
||||||
|
getFocusAreaStats: () => req('/focus-areas/stats'),
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user