Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
79cb3e0100 | ||
|
|
9d22e7e8af | ||
|
|
f46c367c27 | ||
|
|
ac4c6760d7 | ||
|
|
5a6a140dfd | ||
|
|
931012c16b | ||
|
|
03f4b871a9 | ||
|
|
601fc80178 | ||
|
|
3ff2a1bf45 | ||
|
|
51aa57f304 | ||
|
|
ca4411f30f | ||
|
|
b551365fb5 | ||
|
|
272c123952 | ||
|
|
9387670a7b | ||
|
|
d4a8401a6a | ||
|
|
aaf88a6f12 | ||
|
|
b789c1bd44 | ||
|
|
5062aa8068 | ||
|
|
8a042589e7 | ||
|
|
3898b5ad45 | ||
|
|
9d15336144 |
No files matched your search
@@ -76,40 +76,9 @@ frontend/src/
|
|||||||
└── technical/ # MEMBERSHIP_SYSTEM.md
|
└── technical/ # MEMBERSHIP_SYSTEM.md
|
||||||
```
|
```
|
||||||
|
|
||||||
## Aktuelle Version: v0.9g+ → v0.9h (Goals Complete + Dynamic Focus Areas) 🎯 27.03.2026
|
## Aktuelle Version: v9e+ (Phase 1 Goal System Fixes) 🎯 Ready for Phase 0b - 27.03.2026
|
||||||
|
|
||||||
**Status:** BEREIT FÜR RELEASE v0.9h
|
### Letzte Updates (27.03.2026 - Phase 1 Complete) 🆕
|
||||||
**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):**
|
- ✅ **Custom Goals Page (Capture/Eigene Ziele):**
|
||||||
- Neue Seite für tägliche Werterfassung individueller Ziele
|
- Neue Seite für tägliche Werterfassung individueller Ziele
|
||||||
- Dedizierte UI für custom goals (ohne automatische Datenquelle)
|
- Dedizierte UI für custom goals (ohne automatische Datenquelle)
|
||||||
|
|||||||
+1
-15
@@ -278,7 +278,7 @@ def _fetch_by_aggregation_method(
|
|||||||
- max_30d: Maximum value in last 30 days
|
- max_30d: Maximum value in last 30 days
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
filter_conditions: Optional JSON filters (e.g., {"training_category": "strength"})
|
filter_conditions: Optional JSON filters (e.g., {"training_type": "strength"})
|
||||||
"""
|
"""
|
||||||
# Guard: source_table/column required for simple aggregation
|
# Guard: source_table/column required for simple aggregation
|
||||||
if not table or not column:
|
if not table or not column:
|
||||||
@@ -412,21 +412,7 @@ def _fetch_by_aggregation_method(
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
except Exception as e:
|
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] 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
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+1
-6
@@ -24,7 +24,6 @@ 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, focus_areas # v9e/v9g Goal System v2.0 (Dynamic Focus Areas)
|
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"))
|
||||||
@@ -99,11 +98,7 @@ 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/* (v9h Goal System Core CRUD + Focus Areas)
|
app.include_router(goals.router) # /api/goals/* (v9e Goal System Strategic + Tactical)
|
||||||
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)
|
app.include_router(focus_areas.router) # /api/focus-areas/* (v9g Focus Area System v2.0 - Dynamic)
|
||||||
|
|
||||||
# ── Health Check ──────────────────────────────────────────────────────────────
|
# ── Health Check ──────────────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -1,94 +0,0 @@
|
|||||||
"""
|
|
||||||
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
|
|
||||||
@@ -1,155 +0,0 @@
|
|||||||
"""
|
|
||||||
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"}
|
|
||||||
@@ -1,426 +0,0 @@
|
|||||||
"""
|
|
||||||
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"}
|
|
||||||
+697
-13
@@ -1,23 +1,20 @@
|
|||||||
"""
|
"""
|
||||||
Goals Router - Core Goal CRUD & Focus Areas (Streamlined v2.0)
|
Goals Router - Goal System (Strategic + Tactical)
|
||||||
|
|
||||||
Endpoints for managing:
|
Endpoints for managing:
|
||||||
- Strategic focus areas (weighted multi-goal system)
|
- Strategic goal modes (weight_loss, strength, etc.)
|
||||||
- Tactical goal targets (concrete values with deadlines)
|
- Tactical goal targets (concrete values with deadlines)
|
||||||
- Grouped goal views
|
- Training phase detection
|
||||||
|
- Fitness tests
|
||||||
|
|
||||||
Part of v9h Goal System (Phase 0a).
|
Part of v9e Goal System implementation.
|
||||||
|
|
||||||
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, timedelta
|
from datetime import date, datetime, 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
|
||||||
@@ -72,6 +69,62 @@ class GoalUpdate(BaseModel):
|
|||||||
description: Optional[str] = None
|
description: Optional[str] = None
|
||||||
focus_contributions: Optional[List[FocusContribution]] = None # v2.0: Many-to-Many
|
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 GoalProgressCreate(BaseModel):
|
||||||
|
"""Log progress for a goal"""
|
||||||
|
date: date
|
||||||
|
value: float
|
||||||
|
note: Optional[str] = None
|
||||||
|
|
||||||
|
class GoalProgressUpdate(BaseModel):
|
||||||
|
"""Update progress entry"""
|
||||||
|
value: Optional[float] = None
|
||||||
|
note: Optional[str] = None
|
||||||
|
|
||||||
|
class GoalTypeCreate(BaseModel):
|
||||||
|
"""Create custom goal type definition"""
|
||||||
|
type_key: str
|
||||||
|
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
|
||||||
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
# Strategic Layer: Goal Modes
|
# Strategic Layer: Goal Modes
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
@@ -319,7 +372,7 @@ def update_focus_areas(data: FocusAreasUpdate, session: dict = Depends(require_a
|
|||||||
}
|
}
|
||||||
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
# Tactical Layer: Concrete Goals - Core CRUD
|
# Tactical Layer: Concrete Goals
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
|
|
||||||
@router.get("/list")
|
@router.get("/list")
|
||||||
@@ -519,10 +572,131 @@ def delete_goal(goal_id: str, session: dict = Depends(require_auth)):
|
|||||||
|
|
||||||
return {"message": "Ziel gelöscht"}
|
return {"message": "Ziel gelöscht"}
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Goal Progress Endpoints
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
@router.get("/{goal_id}/progress")
|
||||||
|
def get_goal_progress(goal_id: str, session: dict = Depends(require_auth)):
|
||||||
|
"""Get progress history for a goal"""
|
||||||
|
pid = session['profile_id']
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Verify ownership
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id FROM goals WHERE id = %s AND profile_id = %s",
|
||||||
|
(goal_id, pid)
|
||||||
|
)
|
||||||
|
if not cur.fetchone():
|
||||||
|
raise HTTPException(status_code=404, detail="Ziel nicht gefunden")
|
||||||
|
|
||||||
|
# Get progress entries
|
||||||
|
cur.execute("""
|
||||||
|
SELECT id, date, value, note, source, created_at
|
||||||
|
FROM goal_progress_log
|
||||||
|
WHERE goal_id = %s
|
||||||
|
ORDER BY date DESC
|
||||||
|
""", (goal_id,))
|
||||||
|
|
||||||
|
entries = cur.fetchall()
|
||||||
|
return [r2d(e) for e in entries]
|
||||||
|
|
||||||
|
@router.post("/{goal_id}/progress")
|
||||||
|
def create_goal_progress(goal_id: str, data: GoalProgressCreate, session: dict = Depends(require_auth)):
|
||||||
|
"""Log new progress for a goal"""
|
||||||
|
pid = session['profile_id']
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Verify ownership and check if manual entry is allowed
|
||||||
|
cur.execute("""
|
||||||
|
SELECT g.id, g.unit, gt.source_table
|
||||||
|
FROM goals g
|
||||||
|
LEFT JOIN goal_type_definitions gt ON g.goal_type = gt.type_key
|
||||||
|
WHERE g.id = %s AND g.profile_id = %s
|
||||||
|
""", (goal_id, pid))
|
||||||
|
goal = cur.fetchone()
|
||||||
|
if not goal:
|
||||||
|
raise HTTPException(status_code=404, detail="Ziel nicht gefunden")
|
||||||
|
|
||||||
|
# Prevent manual entries for goals with automatic data sources
|
||||||
|
if goal['source_table']:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Manuelle Einträge nicht erlaubt für automatisch erfasste Ziele. "
|
||||||
|
f"Bitte nutze die entsprechende Erfassungsseite (z.B. Gewicht, Aktivität)."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Insert progress entry
|
||||||
|
try:
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO goal_progress_log (goal_id, profile_id, date, value, note, source)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, 'manual')
|
||||||
|
RETURNING id
|
||||||
|
""", (goal_id, pid, data.date, data.value, data.note))
|
||||||
|
|
||||||
|
progress_id = cur.fetchone()['id']
|
||||||
|
|
||||||
|
# Trigger will auto-update goals.current_value
|
||||||
|
return {
|
||||||
|
"id": progress_id,
|
||||||
|
"message": f"Fortschritt erfasst: {data.value} {goal['unit']}"
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
if "unique_progress_per_day" in str(e):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Für {data.date} existiert bereits ein Eintrag. Bitte bearbeite den existierenden Eintrag."
|
||||||
|
)
|
||||||
|
raise HTTPException(status_code=500, detail=f"Fehler beim Speichern: {str(e)}")
|
||||||
|
|
||||||
|
@router.delete("/{goal_id}/progress/{progress_id}")
|
||||||
|
def delete_goal_progress(goal_id: str, progress_id: str, session: dict = Depends(require_auth)):
|
||||||
|
"""Delete progress entry"""
|
||||||
|
pid = session['profile_id']
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Verify ownership
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id FROM goals WHERE id = %s AND profile_id = %s",
|
||||||
|
(goal_id, pid)
|
||||||
|
)
|
||||||
|
if not cur.fetchone():
|
||||||
|
raise HTTPException(status_code=404, detail="Ziel nicht gefunden")
|
||||||
|
|
||||||
|
# Delete progress entry
|
||||||
|
cur.execute(
|
||||||
|
"DELETE FROM goal_progress_log WHERE id = %s AND goal_id = %s AND profile_id = %s",
|
||||||
|
(progress_id, goal_id, pid)
|
||||||
|
)
|
||||||
|
|
||||||
|
if cur.rowcount == 0:
|
||||||
|
raise HTTPException(status_code=404, detail="Progress-Eintrag nicht gefunden")
|
||||||
|
|
||||||
|
# After deletion, recalculate current_value from remaining entries
|
||||||
|
cur.execute("""
|
||||||
|
UPDATE goals
|
||||||
|
SET current_value = (
|
||||||
|
SELECT value FROM goal_progress_log
|
||||||
|
WHERE goal_id = %s
|
||||||
|
ORDER BY date DESC
|
||||||
|
LIMIT 1
|
||||||
|
)
|
||||||
|
WHERE id = %s
|
||||||
|
""", (goal_id, goal_id))
|
||||||
|
|
||||||
|
return {"message": "Progress-Eintrag gelöscht"}
|
||||||
|
|
||||||
@router.get("/grouped")
|
@router.get("/grouped")
|
||||||
def get_goals_grouped(session: dict = Depends(require_auth)):
|
def get_goals_grouped(session: dict = Depends(require_auth)):
|
||||||
"""
|
"""
|
||||||
Get all goals grouped by category.
|
Get goals grouped by category, sorted by priority.
|
||||||
|
|
||||||
Returns structure:
|
Returns structure:
|
||||||
{
|
{
|
||||||
@@ -603,6 +777,134 @@ def get_goals_grouped(session: dict = Depends(require_auth)):
|
|||||||
|
|
||||||
return grouped
|
return grouped
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Training Phases
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
@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"}
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# 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
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
@@ -653,3 +955,385 @@ 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("/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, 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"}
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
"""
|
|
||||||
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"}
|
|
||||||
@@ -99,90 +99,52 @@ 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 INSERT columns, placeholders, UPDATE fields, and values list
|
# Build dynamic update columns (only non-None fields)
|
||||||
# All arrays must stay synchronized
|
fields = []
|
||||||
insert_cols = []
|
values = [pid, entry.date]
|
||||||
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:
|
||||||
insert_cols.append("resting_hr")
|
fields.append("resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_baseline.resting_hr)")
|
||||||
insert_placeholders.append("%s")
|
values.append(entry.resting_hr)
|
||||||
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:
|
||||||
insert_cols.append("hrv")
|
fields.append("hrv = COALESCE(EXCLUDED.hrv, vitals_baseline.hrv)")
|
||||||
insert_placeholders.append("%s")
|
values.append(entry.hrv)
|
||||||
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:
|
||||||
insert_cols.append("vo2_max")
|
fields.append("vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_baseline.vo2_max)")
|
||||||
insert_placeholders.append("%s")
|
values.append(entry.vo2_max)
|
||||||
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:
|
||||||
insert_cols.append("spo2")
|
fields.append("spo2 = COALESCE(EXCLUDED.spo2, vitals_baseline.spo2)")
|
||||||
insert_placeholders.append("%s")
|
values.append(entry.spo2)
|
||||||
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:
|
||||||
insert_cols.append("respiratory_rate")
|
fields.append("respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_baseline.respiratory_rate)")
|
||||||
insert_placeholders.append("%s")
|
values.append(entry.respiratory_rate)
|
||||||
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:
|
||||||
insert_cols.append("body_temperature")
|
fields.append("body_temperature = COALESCE(EXCLUDED.body_temperature, vitals_baseline.body_temperature)")
|
||||||
insert_placeholders.append("%s")
|
values.append(entry.body_temperature)
|
||||||
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:
|
||||||
insert_cols.append("resting_metabolic_rate")
|
fields.append("resting_metabolic_rate = COALESCE(EXCLUDED.resting_metabolic_rate, vitals_baseline.resting_metabolic_rate)")
|
||||||
insert_placeholders.append("%s")
|
values.append(entry.resting_metabolic_rate)
|
||||||
update_fields.append("resting_metabolic_rate = EXCLUDED.resting_metabolic_rate")
|
|
||||||
param_values.append(entry.resting_metabolic_rate)
|
|
||||||
|
|
||||||
if entry.note:
|
if entry.note:
|
||||||
insert_cols.append("note")
|
fields.append("note = COALESCE(EXCLUDED.note, vitals_baseline.note)")
|
||||||
insert_placeholders.append("%s")
|
values.append(entry.note)
|
||||||
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 insert_cols:
|
if not fields:
|
||||||
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 ({all_cols})
|
INSERT INTO vitals_baseline (profile_id, date, {', '.join([f.split('=')[0].strip() for f in fields])})
|
||||||
VALUES ({all_placeholders})
|
VALUES ($1, $2, {', '.join([f'${i}' for i in range(3, len(values) + 1)])})
|
||||||
ON CONFLICT (profile_id, date)
|
ON CONFLICT (profile_id, date)
|
||||||
DO UPDATE SET {', '.join(update_fields)}, updated_at = NOW()
|
DO UPDATE SET {', '.join(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())
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,196 +0,0 @@
|
|||||||
# 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
|
|
||||||
@@ -1,272 +0,0 @@
|
|||||||
# 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
|
|
||||||
@@ -1,157 +0,0 @@
|
|||||||
# 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)
|
|
||||||
Reference in new issue
Block a user