Compare commits
37
Commits
2f51b26418
...
V0.9g
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d22e7e8af | ||
|
|
0a1da37197 | ||
|
|
495f218f9a | ||
|
|
fac8820208 | ||
|
|
217990d417 | ||
|
|
1960ae4924 | ||
|
|
bcb867da69 | ||
|
|
398c645a98 | ||
|
|
7db98a4fa6 | ||
|
|
ce37afb2bb | ||
|
|
db90f397e8 | ||
|
|
498ad7a47f | ||
|
|
9e95fd8416 | ||
|
|
ca4f722b47 | ||
|
|
1c00238414 | ||
|
|
448d19b840 | ||
|
|
caebc37da0 | ||
|
|
6a3a782bff | ||
|
|
f46c367c27 | ||
|
|
ac4c6760d7 | ||
|
|
5a6a140dfd | ||
|
|
931012c16b | ||
|
|
03f4b871a9 | ||
|
|
601fc80178 | ||
|
|
3ff2a1bf45 | ||
|
|
51aa57f304 | ||
|
|
ca4411f30f | ||
|
|
b551365fb5 | ||
|
|
272c123952 | ||
|
|
9387670a7b | ||
|
|
d4a8401a6a | ||
|
|
aaf88a6f12 | ||
|
|
b789c1bd44 | ||
|
|
5062aa8068 | ||
|
|
8a042589e7 | ||
|
|
3898b5ad45 | ||
|
|
9d15336144 |
No files matched your search
@@ -78,7 +78,22 @@ frontend/src/
|
||||
|
||||
## Aktuelle Version: v9e+ (Phase 1 Goal System Fixes) 🎯 Ready for Phase 0b - 27.03.2026
|
||||
|
||||
### Letzte Updates (27.03.2026 - Phase 1 Fixes) 🆕
|
||||
### Letzte Updates (27.03.2026 - Phase 1 Complete) 🆕
|
||||
- ✅ **Custom Goals Page (Capture/Eigene Ziele):**
|
||||
- Neue Seite für tägliche Werterfassung individueller Ziele
|
||||
- Dedizierte UI für custom goals (ohne automatische Datenquelle)
|
||||
- Verhindert Verwechslung mit automatischem Tracking (Gewicht, Aktivität, etc.)
|
||||
- Clean UX: Zielauswahl → Schnellerfassung → Verlauf (letzte 5 Einträge)
|
||||
- Navigation: Capture Hub + direkter Link
|
||||
- ✅ **UX-Improvements Progress Modal:**
|
||||
- Volle Breite Eingabefelder, Labels als Überschriften, linksbündiger Text
|
||||
- Progress-Button nur bei custom goals sichtbar (source_table IS NULL)
|
||||
- ✅ **Architektur-Klarstellung:**
|
||||
- Analysis/Goals → Strategisch (Ziele definieren, Prioritäten setzen)
|
||||
- Capture/Custom Goals → Taktisch (tägliche Ist-Wert-Erfassung)
|
||||
- History → Auswertung (Zielerreichungs-Analysen)
|
||||
|
||||
### Updates (27.03.2026 - Phase 1 Fixes)
|
||||
- ✅ **Abstraction Layer:** goal_utils.py für zukunftssichere Phase 0b Platzhalter
|
||||
- ✅ **Primary Goal Toggle Fix:** is_primary Update funktioniert korrekt
|
||||
- ✅ **Lean Mass Berechnung:** Magermasse current_value wird berechnet
|
||||
|
||||
+23
-8
@@ -285,6 +285,21 @@ def _fetch_by_aggregation_method(
|
||||
print(f"[WARNING] Missing source_table or source_column for aggregation")
|
||||
return None
|
||||
|
||||
# Table-specific date column mapping (some tables use different column names)
|
||||
DATE_COLUMN_MAP = {
|
||||
'blood_pressure_log': 'measured_at',
|
||||
'activity_log': 'date',
|
||||
'weight_log': 'date',
|
||||
'circumference_log': 'date',
|
||||
'caliper_log': 'date',
|
||||
'nutrition_log': 'date',
|
||||
'sleep_log': 'date',
|
||||
'vitals_baseline': 'date',
|
||||
'rest_days': 'date',
|
||||
'fitness_tests': 'test_date'
|
||||
}
|
||||
date_col = DATE_COLUMN_MAP.get(table, 'date')
|
||||
|
||||
# Build filter SQL from JSON conditions
|
||||
filter_sql = ""
|
||||
filter_params = []
|
||||
@@ -317,7 +332,7 @@ def _fetch_by_aggregation_method(
|
||||
cur.execute(f"""
|
||||
SELECT {column} FROM {table}
|
||||
WHERE profile_id = %s AND {column} IS NOT NULL{filter_sql}
|
||||
ORDER BY date DESC LIMIT 1
|
||||
ORDER BY {date_col} DESC LIMIT 1
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
return float(row[column]) if row else None
|
||||
@@ -327,7 +342,7 @@ def _fetch_by_aggregation_method(
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT AVG({column}) as avg_value FROM {table}
|
||||
WHERE profile_id = %s AND date >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
return float(row['avg_value']) if row and row['avg_value'] is not None else None
|
||||
@@ -337,7 +352,7 @@ def _fetch_by_aggregation_method(
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT AVG({column}) as avg_value FROM {table}
|
||||
WHERE profile_id = %s AND date >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
return float(row['avg_value']) if row and row['avg_value'] is not None else None
|
||||
@@ -347,7 +362,7 @@ def _fetch_by_aggregation_method(
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT SUM({column}) as sum_value FROM {table}
|
||||
WHERE profile_id = %s AND date >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
return float(row['sum_value']) if row and row['sum_value'] is not None else None
|
||||
@@ -357,7 +372,7 @@ def _fetch_by_aggregation_method(
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT COUNT(*) as count_value FROM {table}
|
||||
WHERE profile_id = %s AND date >= %s{filter_sql}
|
||||
WHERE profile_id = %s AND {date_col} >= %s{filter_sql}
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
return float(row['count_value']) if row else 0.0
|
||||
@@ -367,7 +382,7 @@ def _fetch_by_aggregation_method(
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT COUNT(*) as count_value FROM {table}
|
||||
WHERE profile_id = %s AND date >= %s{filter_sql}
|
||||
WHERE profile_id = %s AND {date_col} >= %s{filter_sql}
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
return float(row['count_value']) if row else 0.0
|
||||
@@ -377,7 +392,7 @@ def _fetch_by_aggregation_method(
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT MIN({column}) as min_value FROM {table}
|
||||
WHERE profile_id = %s AND date >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
return float(row['min_value']) if row and row['min_value'] is not None else None
|
||||
@@ -387,7 +402,7 @@ def _fetch_by_aggregation_method(
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT MAX({column}) as max_value FROM {table}
|
||||
WHERE profile_id = %s AND date >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
return float(row['max_value']) if row and row['max_value'] is not None else None
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
-- Migration 028: Goal Categories and Priorities
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Multi-dimensional goal priorities (one primary goal per category)
|
||||
|
||||
-- ============================================================================
|
||||
-- Add category and priority columns
|
||||
-- ============================================================================
|
||||
|
||||
ALTER TABLE goals
|
||||
ADD COLUMN category VARCHAR(50),
|
||||
ADD COLUMN priority INTEGER DEFAULT 2 CHECK (priority >= 1 AND priority <= 3);
|
||||
|
||||
COMMENT ON COLUMN goals.category IS 'Goal category: body, training, nutrition, recovery, health, other';
|
||||
COMMENT ON COLUMN goals.priority IS 'Priority level: 1=high, 2=medium, 3=low';
|
||||
|
||||
-- ============================================================================
|
||||
-- Migrate existing goals to categories based on goal_type
|
||||
-- ============================================================================
|
||||
|
||||
UPDATE goals SET category = CASE
|
||||
-- Body composition goals
|
||||
WHEN goal_type IN ('weight', 'body_fat', 'lean_mass') THEN 'body'
|
||||
|
||||
-- Training goals
|
||||
WHEN goal_type IN ('strength', 'flexibility', 'training_frequency') THEN 'training'
|
||||
|
||||
-- Health/cardio goals
|
||||
WHEN goal_type IN ('vo2max', 'rhr', 'bp', 'hrv') THEN 'health'
|
||||
|
||||
-- Recovery goals
|
||||
WHEN goal_type IN ('sleep_quality', 'sleep_duration', 'rest_days') THEN 'recovery'
|
||||
|
||||
-- Nutrition goals
|
||||
WHEN goal_type IN ('calories', 'protein', 'healthy_eating') THEN 'nutrition'
|
||||
|
||||
-- Default
|
||||
ELSE 'other'
|
||||
END
|
||||
WHERE category IS NULL;
|
||||
|
||||
-- ============================================================================
|
||||
-- Set priority based on is_primary
|
||||
-- ============================================================================
|
||||
|
||||
UPDATE goals SET priority = CASE
|
||||
WHEN is_primary = true THEN 1 -- Primary goals get priority 1
|
||||
ELSE 2 -- Others get priority 2 (medium)
|
||||
END;
|
||||
|
||||
-- ============================================================================
|
||||
-- Create index for category-based queries
|
||||
-- ============================================================================
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_goals_category_priority
|
||||
ON goals(profile_id, category, priority);
|
||||
|
||||
COMMENT ON INDEX idx_goals_category_priority IS 'Fast lookup for category-grouped goals sorted by priority';
|
||||
@@ -0,0 +1,74 @@
|
||||
-- Migration 029: Fix Missing Goal Types (flexibility, strength)
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Ensure flexibility and strength goal types are active and properly configured
|
||||
|
||||
-- These types were created earlier but are inactive or misconfigured
|
||||
-- This migration fixes them without breaking if they don't exist
|
||||
|
||||
-- ============================================================================
|
||||
-- Upsert flexibility goal type
|
||||
-- ============================================================================
|
||||
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
calculation_formula, filter_conditions, description, is_active
|
||||
) VALUES (
|
||||
'flexibility',
|
||||
'Beweglichkeit',
|
||||
'Flexibility',
|
||||
'cm',
|
||||
'🤸',
|
||||
'training',
|
||||
NULL, -- No automatic data source
|
||||
NULL,
|
||||
'latest',
|
||||
NULL,
|
||||
NULL,
|
||||
'Beweglichkeit und Mobilität - manuelle Erfassung',
|
||||
true
|
||||
)
|
||||
ON CONFLICT (type_key)
|
||||
DO UPDATE SET
|
||||
label_de = 'Beweglichkeit',
|
||||
label_en = 'Flexibility',
|
||||
unit = 'cm',
|
||||
icon = '🤸',
|
||||
category = 'training',
|
||||
is_active = true,
|
||||
description = 'Beweglichkeit und Mobilität - manuelle Erfassung';
|
||||
|
||||
-- ============================================================================
|
||||
-- Upsert strength goal type
|
||||
-- ============================================================================
|
||||
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
calculation_formula, filter_conditions, description, is_active
|
||||
) VALUES (
|
||||
'strength',
|
||||
'Kraftniveau',
|
||||
'Strength',
|
||||
'Punkte',
|
||||
'💪',
|
||||
'training',
|
||||
NULL, -- No automatic data source
|
||||
NULL,
|
||||
'latest',
|
||||
NULL,
|
||||
NULL,
|
||||
'Allgemeines Kraftniveau - manuelle Erfassung',
|
||||
true
|
||||
)
|
||||
ON CONFLICT (type_key)
|
||||
DO UPDATE SET
|
||||
label_de = 'Kraftniveau',
|
||||
label_en = 'Strength',
|
||||
unit = 'Punkte',
|
||||
icon = '💪',
|
||||
category = 'training',
|
||||
is_active = true,
|
||||
description = 'Allgemeines Kraftniveau - manuelle Erfassung';
|
||||
|
||||
COMMENT ON TABLE goal_type_definitions IS 'Goal type registry - defines all available goal types (v1.5: DB-driven, flexible system)';
|
||||
@@ -0,0 +1,64 @@
|
||||
-- Migration 030: Goal Progress Log
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Track progress history for all goals (especially custom goals without data source)
|
||||
|
||||
-- ============================================================================
|
||||
-- Goal Progress Log Table
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS goal_progress_log (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
goal_id UUID NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
|
||||
-- Progress data
|
||||
date DATE NOT NULL,
|
||||
value DECIMAL(10,2) NOT NULL,
|
||||
note TEXT,
|
||||
|
||||
-- Metadata
|
||||
source VARCHAR(20) DEFAULT 'manual' CHECK (source IN ('manual', 'automatic', 'import')),
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW(),
|
||||
|
||||
-- Constraints
|
||||
CONSTRAINT unique_progress_per_day UNIQUE(goal_id, date)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_goal_progress_goal_date ON goal_progress_log(goal_id, date DESC);
|
||||
CREATE INDEX idx_goal_progress_profile ON goal_progress_log(profile_id);
|
||||
|
||||
COMMENT ON TABLE goal_progress_log IS 'Progress history for goals - enables manual tracking for custom goals and charts';
|
||||
COMMENT ON COLUMN goal_progress_log.value IS 'Progress value in goal unit (e.g., kg, cm, points)';
|
||||
COMMENT ON COLUMN goal_progress_log.source IS 'manual: user entered, automatic: computed from data source, import: CSV/API';
|
||||
|
||||
-- ============================================================================
|
||||
-- Function: Update goal current_value from latest progress
|
||||
-- ============================================================================
|
||||
|
||||
CREATE OR REPLACE FUNCTION update_goal_current_value()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
-- Update current_value in goals table with latest progress entry
|
||||
UPDATE goals
|
||||
SET current_value = (
|
||||
SELECT value
|
||||
FROM goal_progress_log
|
||||
WHERE goal_id = NEW.goal_id
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
),
|
||||
updated_at = NOW()
|
||||
WHERE id = NEW.goal_id;
|
||||
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- Trigger: Auto-update current_value when progress is added/updated
|
||||
CREATE TRIGGER trigger_update_goal_current_value
|
||||
AFTER INSERT OR UPDATE ON goal_progress_log
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_goal_current_value();
|
||||
|
||||
COMMENT ON FUNCTION update_goal_current_value IS 'Auto-update goal.current_value when new progress is logged';
|
||||
+196
-5
@@ -42,10 +42,12 @@ class FocusAreasUpdate(BaseModel):
|
||||
class GoalCreate(BaseModel):
|
||||
"""Create or update a concrete goal"""
|
||||
goal_type: str # weight, body_fat, lean_mass, vo2max, strength, flexibility, bp, rhr
|
||||
is_primary: bool = False
|
||||
is_primary: bool = False # Kept for backward compatibility
|
||||
target_value: float
|
||||
unit: str # kg, %, ml/kg/min, bpm, mmHg, cm, reps
|
||||
target_date: Optional[date] = None
|
||||
category: Optional[str] = 'other' # body, training, nutrition, recovery, health, other
|
||||
priority: Optional[int] = 2 # 1=high, 2=medium, 3=low
|
||||
name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
@@ -54,7 +56,9 @@ class GoalUpdate(BaseModel):
|
||||
target_value: Optional[float] = None
|
||||
target_date: Optional[date] = None
|
||||
status: Optional[str] = None # active, reached, abandoned, expired
|
||||
is_primary: Optional[bool] = None
|
||||
is_primary: Optional[bool] = None # Kept for backward compatibility
|
||||
category: Optional[str] = None # body, training, nutrition, recovery, health, other
|
||||
priority: Optional[int] = None # 1=high, 2=medium, 3=low
|
||||
name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
@@ -73,6 +77,17 @@ class FitnessTestCreate(BaseModel):
|
||||
test_date: date
|
||||
test_conditions: Optional[str] = None
|
||||
|
||||
class GoalProgressCreate(BaseModel):
|
||||
"""Log progress for a goal"""
|
||||
date: date
|
||||
value: float
|
||||
note: Optional[str] = None
|
||||
|
||||
class GoalProgressUpdate(BaseModel):
|
||||
"""Update progress entry"""
|
||||
value: Optional[float] = None
|
||||
note: Optional[str] = None
|
||||
|
||||
class GoalTypeCreate(BaseModel):
|
||||
"""Create custom goal type definition"""
|
||||
type_key: str
|
||||
@@ -403,13 +418,13 @@ def create_goal(data: GoalCreate, session: dict = Depends(require_auth)):
|
||||
INSERT INTO goals (
|
||||
profile_id, goal_type, is_primary,
|
||||
target_value, current_value, start_value, unit,
|
||||
target_date, name, description
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
target_date, category, priority, name, description
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""", (
|
||||
pid, data.goal_type, data.is_primary,
|
||||
data.target_value, current_value, current_value, data.unit,
|
||||
data.target_date, data.name, data.description
|
||||
data.target_date, data.category, data.priority, data.name, data.description
|
||||
))
|
||||
|
||||
goal_id = cur.fetchone()['id']
|
||||
@@ -461,6 +476,14 @@ def update_goal(goal_id: str, data: GoalUpdate, session: dict = Depends(require_
|
||||
updates.append("is_primary = %s")
|
||||
params.append(data.is_primary)
|
||||
|
||||
if data.category is not None:
|
||||
updates.append("category = %s")
|
||||
params.append(data.category)
|
||||
|
||||
if data.priority is not None:
|
||||
updates.append("priority = %s")
|
||||
params.append(data.priority)
|
||||
|
||||
if data.name is not None:
|
||||
updates.append("name = %s")
|
||||
params.append(data.name)
|
||||
@@ -499,6 +522,174 @@ def delete_goal(goal_id: str, session: dict = Depends(require_auth)):
|
||||
|
||||
return {"message": "Ziel gelöscht"}
|
||||
|
||||
# ============================================================================
|
||||
# Goal Progress Endpoints
|
||||
# ============================================================================
|
||||
|
||||
@router.get("/{goal_id}/progress")
|
||||
def get_goal_progress(goal_id: str, session: dict = Depends(require_auth)):
|
||||
"""Get progress history for a goal"""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Verify ownership
|
||||
cur.execute(
|
||||
"SELECT id FROM goals WHERE id = %s AND profile_id = %s",
|
||||
(goal_id, pid)
|
||||
)
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(status_code=404, detail="Ziel nicht gefunden")
|
||||
|
||||
# Get progress entries
|
||||
cur.execute("""
|
||||
SELECT id, date, value, note, source, created_at
|
||||
FROM goal_progress_log
|
||||
WHERE goal_id = %s
|
||||
ORDER BY date DESC
|
||||
""", (goal_id,))
|
||||
|
||||
entries = cur.fetchall()
|
||||
return [r2d(e) for e in entries]
|
||||
|
||||
@router.post("/{goal_id}/progress")
|
||||
def create_goal_progress(goal_id: str, data: GoalProgressCreate, session: dict = Depends(require_auth)):
|
||||
"""Log new progress for a goal"""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Verify ownership and check if manual entry is allowed
|
||||
cur.execute("""
|
||||
SELECT g.id, g.unit, gt.source_table
|
||||
FROM goals g
|
||||
LEFT JOIN goal_type_definitions gt ON g.goal_type = gt.type_key
|
||||
WHERE g.id = %s AND g.profile_id = %s
|
||||
""", (goal_id, pid))
|
||||
goal = cur.fetchone()
|
||||
if not goal:
|
||||
raise HTTPException(status_code=404, detail="Ziel nicht gefunden")
|
||||
|
||||
# Prevent manual entries for goals with automatic data sources
|
||||
if goal['source_table']:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Manuelle Einträge nicht erlaubt für automatisch erfasste Ziele. "
|
||||
f"Bitte nutze die entsprechende Erfassungsseite (z.B. Gewicht, Aktivität)."
|
||||
)
|
||||
|
||||
# Insert progress entry
|
||||
try:
|
||||
cur.execute("""
|
||||
INSERT INTO goal_progress_log (goal_id, profile_id, date, value, note, source)
|
||||
VALUES (%s, %s, %s, %s, %s, 'manual')
|
||||
RETURNING id
|
||||
""", (goal_id, pid, data.date, data.value, data.note))
|
||||
|
||||
progress_id = cur.fetchone()['id']
|
||||
|
||||
# Trigger will auto-update goals.current_value
|
||||
return {
|
||||
"id": progress_id,
|
||||
"message": f"Fortschritt erfasst: {data.value} {goal['unit']}"
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
if "unique_progress_per_day" in str(e):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Für {data.date} existiert bereits ein Eintrag. Bitte bearbeite den existierenden Eintrag."
|
||||
)
|
||||
raise HTTPException(status_code=500, detail=f"Fehler beim Speichern: {str(e)}")
|
||||
|
||||
@router.delete("/{goal_id}/progress/{progress_id}")
|
||||
def delete_goal_progress(goal_id: str, progress_id: str, session: dict = Depends(require_auth)):
|
||||
"""Delete progress entry"""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Verify ownership
|
||||
cur.execute(
|
||||
"SELECT id FROM goals WHERE id = %s AND profile_id = %s",
|
||||
(goal_id, pid)
|
||||
)
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(status_code=404, detail="Ziel nicht gefunden")
|
||||
|
||||
# Delete progress entry
|
||||
cur.execute(
|
||||
"DELETE FROM goal_progress_log WHERE id = %s AND goal_id = %s AND profile_id = %s",
|
||||
(progress_id, goal_id, pid)
|
||||
)
|
||||
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(status_code=404, detail="Progress-Eintrag nicht gefunden")
|
||||
|
||||
# After deletion, recalculate current_value from remaining entries
|
||||
cur.execute("""
|
||||
UPDATE goals
|
||||
SET current_value = (
|
||||
SELECT value FROM goal_progress_log
|
||||
WHERE goal_id = %s
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
)
|
||||
WHERE id = %s
|
||||
""", (goal_id, goal_id))
|
||||
|
||||
return {"message": "Progress-Eintrag gelöscht"}
|
||||
|
||||
@router.get("/grouped")
|
||||
def get_goals_grouped(session: dict = Depends(require_auth)):
|
||||
"""
|
||||
Get goals grouped by category, sorted by priority.
|
||||
|
||||
Returns structure:
|
||||
{
|
||||
"body": [{"id": "...", "goal_type": "weight", "priority": 1, ...}, ...],
|
||||
"training": [...],
|
||||
"nutrition": [...],
|
||||
"recovery": [...],
|
||||
"health": [...],
|
||||
"other": [...]
|
||||
}
|
||||
"""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get all active goals with type definitions
|
||||
cur.execute("""
|
||||
SELECT
|
||||
g.id, g.goal_type, g.target_value, g.current_value, g.start_value,
|
||||
g.unit, g.target_date, g.status, g.is_primary, g.category, g.priority,
|
||||
g.name, g.description, g.progress_pct, g.on_track, g.projection_date,
|
||||
g.created_at, g.updated_at,
|
||||
gt.label_de, gt.icon, gt.category as type_category,
|
||||
gt.source_table, gt.source_column
|
||||
FROM goals g
|
||||
LEFT JOIN goal_type_definitions gt ON g.goal_type = gt.type_key
|
||||
WHERE g.profile_id = %s
|
||||
ORDER BY g.category, g.priority ASC, g.created_at DESC
|
||||
""", (pid,))
|
||||
|
||||
goals = cur.fetchall()
|
||||
|
||||
# Group by category
|
||||
grouped = {}
|
||||
for goal in goals:
|
||||
cat = goal['category'] or 'other'
|
||||
if cat not in grouped:
|
||||
grouped[cat] = []
|
||||
grouped[cat].append(r2d(goal))
|
||||
|
||||
return grouped
|
||||
|
||||
# ============================================================================
|
||||
# Training Phases
|
||||
# ============================================================================
|
||||
|
||||
@@ -37,6 +37,7 @@ import SleepPage from './pages/SleepPage'
|
||||
import RestDaysPage from './pages/RestDaysPage'
|
||||
import VitalsPage from './pages/VitalsPage'
|
||||
import GoalsPage from './pages/GoalsPage'
|
||||
import CustomGoalsPage from './pages/CustomGoalsPage'
|
||||
import './app.css'
|
||||
|
||||
function Nav() {
|
||||
@@ -175,6 +176,7 @@ function AppShell() {
|
||||
<Route path="/rest-days" element={<RestDaysPage/>}/>
|
||||
<Route path="/vitals" element={<VitalsPage/>}/>
|
||||
<Route path="/goals" element={<GoalsPage/>}/>
|
||||
<Route path="/custom-goals" element={<CustomGoalsPage/>}/>
|
||||
<Route path="/nutrition" element={<NutritionPage/>}/>
|
||||
<Route path="/activity" element={<ActivityPage/>}/>
|
||||
<Route path="/analysis" element={<Analysis/>}/>
|
||||
|
||||
@@ -453,7 +453,7 @@ export default function AdminPanel() {
|
||||
</div>
|
||||
|
||||
{/* KI-Prompts Section */}
|
||||
<div className="card">
|
||||
<div className="card section-gap" style={{marginTop:16}}>
|
||||
<div style={{fontWeight:700,fontSize:14,marginBottom:12,display:'flex',alignItems:'center',gap:6}}>
|
||||
<Settings size={16} color="var(--accent)"/> KI-Prompts (v9f)
|
||||
</div>
|
||||
@@ -468,6 +468,23 @@ export default function AdminPanel() {
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Goal Types Section */}
|
||||
<div className="card section-gap" style={{marginTop:16}}>
|
||||
<div style={{fontWeight:700,fontSize:14,marginBottom:12,display:'flex',alignItems:'center',gap:6}}>
|
||||
<Settings size={16} color="var(--accent)"/> Ziel-Typen (v9e)
|
||||
</div>
|
||||
<div style={{fontSize:12,color:'var(--text3)',marginBottom:12,lineHeight:1.5}}>
|
||||
Verwalte Goal-Type-Definitionen: Erstelle custom goal types mit oder ohne automatische Datenquelle.
|
||||
</div>
|
||||
<div style={{display:'grid',gap:8}}>
|
||||
<Link to="/admin/goal-types">
|
||||
<button className="btn btn-secondary btn-full">
|
||||
🎯 Ziel-Typen verwalten
|
||||
</button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -66,6 +66,13 @@ const ENTRIES = [
|
||||
to: '/vitals',
|
||||
color: '#E74C3C',
|
||||
},
|
||||
{
|
||||
icon: '🎯',
|
||||
label: 'Eigene Ziele',
|
||||
sub: 'Fortschritte für individuelle Ziele erfassen',
|
||||
to: '/custom-goals',
|
||||
color: '#1D9E75',
|
||||
},
|
||||
{
|
||||
icon: '📖',
|
||||
label: 'Messanleitung',
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { api } from '../utils/api'
|
||||
import { Target, TrendingUp, Calendar, CheckCircle2, AlertCircle } from 'lucide-react'
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
export default function CustomGoalsPage() {
|
||||
const [customGoals, setCustomGoals] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState(null)
|
||||
const [selectedGoal, setSelectedGoal] = useState(null)
|
||||
const [formData, setFormData] = useState({
|
||||
date: new Date().toISOString().split('T')[0],
|
||||
value: '',
|
||||
note: ''
|
||||
})
|
||||
const [recentProgress, setRecentProgress] = useState([])
|
||||
|
||||
useEffect(() => {
|
||||
loadCustomGoals()
|
||||
}, [])
|
||||
|
||||
const loadCustomGoals = async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
const grouped = await api.listGoalsGrouped()
|
||||
|
||||
// Extract all goals and filter for custom only (no source_table)
|
||||
const allGoals = Object.values(grouped).flat()
|
||||
const custom = allGoals.filter(g => !g.source_table)
|
||||
|
||||
setCustomGoals(custom)
|
||||
setError(null)
|
||||
} catch (err) {
|
||||
console.error('Failed to load custom goals:', err)
|
||||
setError(err.message || 'Fehler beim Laden')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const loadRecentProgress = async (goalId) => {
|
||||
try {
|
||||
const entries = await api.listGoalProgress(goalId)
|
||||
setRecentProgress(entries.slice(0, 5)) // Last 5 entries
|
||||
} catch (err) {
|
||||
console.error('Failed to load progress:', err)
|
||||
setRecentProgress([])
|
||||
}
|
||||
}
|
||||
|
||||
const handleSelectGoal = async (goal) => {
|
||||
setSelectedGoal(goal)
|
||||
setFormData({
|
||||
date: new Date().toISOString().split('T')[0],
|
||||
value: goal.current_value || '',
|
||||
note: ''
|
||||
})
|
||||
await loadRecentProgress(goal.id)
|
||||
}
|
||||
|
||||
const handleSaveProgress = async () => {
|
||||
if (!formData.value || !formData.date) {
|
||||
setError('Bitte Datum und Wert eingeben')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const data = {
|
||||
date: formData.date,
|
||||
value: parseFloat(formData.value),
|
||||
note: formData.note || null
|
||||
}
|
||||
|
||||
await api.createGoalProgress(selectedGoal.id, data)
|
||||
|
||||
// Reset form and reload
|
||||
setFormData({
|
||||
date: new Date().toISOString().split('T')[0],
|
||||
value: '',
|
||||
note: ''
|
||||
})
|
||||
|
||||
await loadCustomGoals()
|
||||
await loadRecentProgress(selectedGoal.id)
|
||||
|
||||
// Update selected goal with new current_value
|
||||
const updated = customGoals.find(g => g.id === selectedGoal.id)
|
||||
if (updated) setSelectedGoal(updated)
|
||||
|
||||
setError(null)
|
||||
} catch (err) {
|
||||
console.error('Failed to save progress:', err)
|
||||
setError(err.message || 'Fehler beim Speichern')
|
||||
}
|
||||
}
|
||||
|
||||
const getProgressPercentage = (goal) => {
|
||||
if (!goal.current_value || !goal.target_value) return 0
|
||||
|
||||
const current = parseFloat(goal.current_value)
|
||||
const target = parseFloat(goal.target_value)
|
||||
const start = parseFloat(goal.start_value) || 0
|
||||
|
||||
if (goal.direction === 'decrease') {
|
||||
return Math.min(100, Math.max(0, ((start - current) / (start - target)) * 100))
|
||||
} else {
|
||||
return Math.min(100, Math.max(0, ((current - start) / (target - start)) * 100))
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{ padding: 20, textAlign: 'center' }}>
|
||||
<div className="spinner" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ paddingBottom: 80 }}>
|
||||
{/* Header */}
|
||||
<div style={{
|
||||
background: 'linear-gradient(135deg, var(--accent) 0%, var(--accent-dark) 100%)',
|
||||
color: 'white',
|
||||
padding: '24px 16px',
|
||||
marginBottom: 16
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
|
||||
<Target size={28} />
|
||||
<h1 style={{ fontSize: 24, fontWeight: 700, margin: 0 }}>Eigene Ziele</h1>
|
||||
</div>
|
||||
<div style={{ fontSize: 14, opacity: 0.9 }}>
|
||||
Erfasse Fortschritte für deine individuellen Ziele
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div style={{
|
||||
margin: '0 16px 16px',
|
||||
padding: 12,
|
||||
background: '#FEE2E2',
|
||||
color: '#991B1B',
|
||||
borderRadius: 8,
|
||||
fontSize: 14
|
||||
}}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{customGoals.length === 0 ? (
|
||||
<div className="card" style={{ margin: 16, textAlign: 'center', padding: 40 }}>
|
||||
<Target size={48} style={{ color: 'var(--text3)', margin: '0 auto 16px' }} />
|
||||
<div style={{ fontSize: 16, color: 'var(--text2)', marginBottom: 8 }}>
|
||||
Keine eigenen Ziele vorhanden
|
||||
</div>
|
||||
<div style={{ fontSize: 14, color: 'var(--text3)' }}>
|
||||
Erstelle eigene Ziele über die Ziele-Seite in der Analyse
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, padding: 16 }}>
|
||||
{/* Goal Selection */}
|
||||
<div className="card">
|
||||
<h2 style={{ fontSize: 16, marginBottom: 12, fontWeight: 600 }}>
|
||||
Ziel auswählen ({customGoals.length})
|
||||
</h2>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{customGoals.map(goal => {
|
||||
const progress = getProgressPercentage(goal)
|
||||
const isSelected = selectedGoal?.id === goal.id
|
||||
|
||||
return (
|
||||
<button
|
||||
key={goal.id}
|
||||
onClick={() => handleSelectGoal(goal)}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: 12,
|
||||
background: isSelected ? 'var(--accent)' : 'var(--surface2)',
|
||||
color: isSelected ? 'white' : 'var(--text1)',
|
||||
border: 'none',
|
||||
borderRadius: 8,
|
||||
cursor: 'pointer',
|
||||
textAlign: 'left',
|
||||
transition: 'all 0.2s'
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
|
||||
<span style={{ fontWeight: 600 }}>
|
||||
{goal.name || goal.label_de || goal.goal_type}
|
||||
</span>
|
||||
{goal.current_value && (
|
||||
<span style={{
|
||||
fontSize: 18,
|
||||
fontWeight: 700,
|
||||
opacity: isSelected ? 1 : 0.8
|
||||
}}>
|
||||
{goal.current_value} {goal.unit}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{goal.target_value && (
|
||||
<>
|
||||
<div style={{ fontSize: 13, opacity: isSelected ? 0.9 : 0.7, marginBottom: 6 }}>
|
||||
Ziel: {goal.target_value} {goal.unit}
|
||||
</div>
|
||||
|
||||
<div style={{
|
||||
width: '100%',
|
||||
height: 6,
|
||||
background: isSelected ? 'rgba(255,255,255,0.2)' : 'var(--surface)',
|
||||
borderRadius: 3,
|
||||
overflow: 'hidden'
|
||||
}}>
|
||||
<div style={{
|
||||
width: `${progress}%`,
|
||||
height: '100%',
|
||||
background: isSelected ? 'white' : 'var(--accent)',
|
||||
transition: 'width 0.3s'
|
||||
}} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Progress Entry Form */}
|
||||
{selectedGoal && (
|
||||
<div className="card">
|
||||
<h2 style={{ fontSize: 16, marginBottom: 16, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<TrendingUp size={20} style={{ color: 'var(--accent)' }} />
|
||||
Fortschritt erfassen
|
||||
</h2>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
|
||||
<div>
|
||||
<div style={{
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
marginBottom: 8,
|
||||
color: 'var(--text1)'
|
||||
}}>
|
||||
Datum
|
||||
</div>
|
||||
<input
|
||||
type="date"
|
||||
className="form-input"
|
||||
value={formData.date}
|
||||
onChange={(e) => setFormData({ ...formData, date: e.target.value })}
|
||||
max={new Date().toISOString().split('T')[0]}
|
||||
style={{ width: '100%', textAlign: 'left' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div style={{
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
marginBottom: 8,
|
||||
color: 'var(--text1)'
|
||||
}}>
|
||||
Wert ({selectedGoal.unit})
|
||||
</div>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
className="form-input"
|
||||
value={formData.value}
|
||||
onChange={(e) => setFormData({ ...formData, value: e.target.value })}
|
||||
placeholder={`Aktueller Wert in ${selectedGoal.unit}`}
|
||||
style={{ width: '100%', textAlign: 'left' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div style={{
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
marginBottom: 8,
|
||||
color: 'var(--text1)'
|
||||
}}>
|
||||
Notiz (optional)
|
||||
</div>
|
||||
<textarea
|
||||
className="form-input"
|
||||
value={formData.note}
|
||||
onChange={(e) => setFormData({ ...formData, note: e.target.value })}
|
||||
placeholder="Optionale Notiz zu dieser Messung..."
|
||||
rows={2}
|
||||
style={{ width: '100%', textAlign: 'left' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
className="btn-primary"
|
||||
onClick={handleSaveProgress}
|
||||
disabled={!formData.value}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
<CheckCircle2 size={18} style={{ marginRight: 8 }} />
|
||||
Wert speichern
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Recent Progress */}
|
||||
{selectedGoal && recentProgress.length > 0 && (
|
||||
<div className="card">
|
||||
<h2 style={{ fontSize: 16, marginBottom: 12, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<Calendar size={20} style={{ color: 'var(--accent)' }} />
|
||||
Letzte Einträge
|
||||
</h2>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{recentProgress.map(entry => (
|
||||
<div key={entry.id} style={{
|
||||
padding: 12,
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: 8
|
||||
}}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
|
||||
<span style={{ fontSize: 14, color: 'var(--text2)' }}>
|
||||
{dayjs(entry.date).format('DD.MM.YYYY')}
|
||||
</span>
|
||||
<span style={{ fontSize: 18, fontWeight: 600, color: 'var(--accent)' }}>
|
||||
{entry.value} {selectedGoal.unit}
|
||||
</span>
|
||||
</div>
|
||||
{entry.note && (
|
||||
<div style={{ fontSize: 13, color: 'var(--text3)' }}>
|
||||
{entry.note}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Help Card */}
|
||||
{!selectedGoal && (
|
||||
<div style={{
|
||||
padding: 16,
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: 8,
|
||||
border: '1px solid var(--border)'
|
||||
}}>
|
||||
<div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
|
||||
<AlertCircle size={20} style={{ color: 'var(--accent)', flexShrink: 0, marginTop: 2 }} />
|
||||
<div style={{ fontSize: 14, color: 'var(--text2)' }}>
|
||||
<div style={{ fontWeight: 600, marginBottom: 4, color: 'var(--text1)' }}>
|
||||
Eigene Ziele erfassen
|
||||
</div>
|
||||
Wähle ein Ziel aus und erfasse regelmäßig deine Fortschritte.
|
||||
Die Werte werden automatisch in deine Zielverfolgung übernommen.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+566
-209
@@ -5,44 +5,55 @@ import dayjs from 'dayjs'
|
||||
import 'dayjs/locale/de'
|
||||
dayjs.locale('de')
|
||||
|
||||
// Goal Mode Definitions
|
||||
const GOAL_MODES = [
|
||||
{
|
||||
id: 'weight_loss',
|
||||
icon: '📉',
|
||||
label: 'Gewichtsreduktion',
|
||||
description: 'Kaloriendefizit, Fettabbau',
|
||||
color: '#D85A30'
|
||||
},
|
||||
{
|
||||
id: 'strength',
|
||||
icon: '💪',
|
||||
label: 'Kraftaufbau',
|
||||
description: 'Muskelwachstum, progressive Belastung',
|
||||
color: '#378ADD'
|
||||
},
|
||||
{
|
||||
id: 'endurance',
|
||||
icon: '🏃',
|
||||
label: 'Ausdauer',
|
||||
description: 'VO2Max, aerobe Kapazität',
|
||||
color: '#1D9E75'
|
||||
},
|
||||
{
|
||||
id: 'recomposition',
|
||||
icon: '⚖️',
|
||||
label: 'Körperkomposition',
|
||||
description: 'Gleichzeitig Fett ab- & Muskeln aufbauen',
|
||||
color: '#7B68EE'
|
||||
},
|
||||
{
|
||||
id: 'health',
|
||||
icon: '❤️',
|
||||
label: 'Allgemeine Gesundheit',
|
||||
description: 'Ausgewogen, präventiv',
|
||||
color: '#E67E22'
|
||||
// Goal Categories
|
||||
const GOAL_CATEGORIES = {
|
||||
body: { label: 'Körper', icon: '📉', color: '#D85A30', description: 'Gewicht, Körperfett, Muskelmasse' },
|
||||
training: { label: 'Training', icon: '🏋️', color: '#378ADD', description: 'Kraft, Frequenz, Performance' },
|
||||
nutrition: { label: 'Ernährung', icon: '🍎', color: '#1D9E75', description: 'Kalorien, Makros, Essgewohnheiten' },
|
||||
recovery: { label: 'Erholung', icon: '😴', color: '#7B68EE', description: 'Schlaf, Regeneration, Ruhetage' },
|
||||
health: { label: 'Gesundheit', icon: '❤️', color: '#E67E22', description: 'Vitalwerte, Blutdruck, HRV' },
|
||||
other: { label: 'Sonstiges', icon: '📌', color: '#94A3B8', description: 'Weitere Ziele' }
|
||||
}
|
||||
|
||||
// Priority Levels
|
||||
const PRIORITY_LEVELS = {
|
||||
1: { label: 'Hoch', stars: '⭐⭐⭐', color: 'var(--accent)' },
|
||||
2: { label: 'Mittel', stars: '⭐⭐', color: '#94A3B8' },
|
||||
3: { label: 'Niedrig', stars: '⭐', color: '#CBD5E1' }
|
||||
}
|
||||
|
||||
// Auto-assign category based on goal_type
|
||||
const getCategoryForGoalType = (goalType) => {
|
||||
const mapping = {
|
||||
// Body composition
|
||||
'weight': 'body',
|
||||
'body_fat': 'body',
|
||||
'lean_mass': 'body',
|
||||
|
||||
// Training
|
||||
'strength': 'training',
|
||||
'flexibility': 'training',
|
||||
'training_frequency': 'training',
|
||||
|
||||
// Health/Vitals
|
||||
'vo2max': 'health',
|
||||
'rhr': 'health',
|
||||
'bp': 'health',
|
||||
'hrv': 'health',
|
||||
|
||||
// Recovery
|
||||
'sleep_quality': 'recovery',
|
||||
'sleep_duration': 'recovery',
|
||||
'rest_days': 'recovery',
|
||||
|
||||
// Nutrition
|
||||
'calories': 'nutrition',
|
||||
'protein': 'nutrition',
|
||||
'healthy_eating': 'nutrition'
|
||||
}
|
||||
]
|
||||
|
||||
return mapping[goalType] || 'other'
|
||||
}
|
||||
|
||||
export default function GoalsPage() {
|
||||
const [goalMode, setGoalMode] = useState(null)
|
||||
@@ -56,11 +67,20 @@ export default function GoalsPage() {
|
||||
flexibility_pct: 0,
|
||||
health_pct: 0
|
||||
})
|
||||
const [goals, setGoals] = useState([])
|
||||
const [goals, setGoals] = useState([]) // Kept for backward compat
|
||||
const [groupedGoals, setGroupedGoals] = useState({}) // Category-grouped goals
|
||||
const [goalTypes, setGoalTypes] = useState([]) // Dynamic from DB (Phase 1.5)
|
||||
const [goalTypesMap, setGoalTypesMap] = useState({}) // For quick lookup
|
||||
const [showGoalForm, setShowGoalForm] = useState(false)
|
||||
const [editingGoal, setEditingGoal] = useState(null)
|
||||
const [showProgressModal, setShowProgressModal] = useState(false)
|
||||
const [progressGoal, setProgressGoal] = useState(null)
|
||||
const [progressEntries, setProgressEntries] = useState([])
|
||||
const [progressFormData, setProgressFormData] = useState({
|
||||
date: new Date().toISOString().split('T')[0],
|
||||
value: '',
|
||||
note: ''
|
||||
})
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState(null)
|
||||
const [toast, setToast] = useState(null)
|
||||
@@ -69,6 +89,8 @@ export default function GoalsPage() {
|
||||
const [formData, setFormData] = useState({
|
||||
goal_type: 'weight',
|
||||
is_primary: false,
|
||||
category: 'body',
|
||||
priority: 2,
|
||||
target_value: '',
|
||||
unit: 'kg',
|
||||
target_date: '',
|
||||
@@ -84,14 +106,16 @@ export default function GoalsPage() {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const [modeData, goalsData, typesData, focusData] = await Promise.all([
|
||||
const [modeData, goalsData, groupedData, typesData, focusData] = await Promise.all([
|
||||
api.getGoalMode(),
|
||||
api.listGoals(),
|
||||
api.listGoalsGrouped(), // v2.1: Load grouped by category
|
||||
api.listGoalTypeDefinitions(), // Phase 1.5: Load from DB
|
||||
api.getFocusAreas() // v2.0: Load focus areas
|
||||
])
|
||||
setGoalMode(modeData.goal_mode)
|
||||
setGoals(goalsData)
|
||||
setGroupedGoals(groupedData)
|
||||
|
||||
// Ensure all focus fields are present and numeric
|
||||
const sanitizedFocus = {
|
||||
@@ -158,6 +182,8 @@ export default function GoalsPage() {
|
||||
setFormData({
|
||||
goal_type: firstType,
|
||||
is_primary: goals.length === 0, // First goal is primary by default
|
||||
category: getCategoryForGoalType(firstType), // Auto-assign based on type
|
||||
priority: 2,
|
||||
target_value: '',
|
||||
unit: goalTypesMap[firstType]?.unit || 'kg',
|
||||
target_date: '',
|
||||
@@ -172,6 +198,8 @@ export default function GoalsPage() {
|
||||
setFormData({
|
||||
goal_type: goal.goal_type,
|
||||
is_primary: goal.is_primary,
|
||||
category: goal.category || 'other',
|
||||
priority: goal.priority || 2,
|
||||
target_value: goal.target_value,
|
||||
unit: goal.unit,
|
||||
target_date: goal.target_date || '',
|
||||
@@ -185,7 +213,8 @@ export default function GoalsPage() {
|
||||
setFormData(f => ({
|
||||
...f,
|
||||
goal_type: type,
|
||||
unit: goalTypesMap[type]?.unit || 'unit'
|
||||
unit: goalTypesMap[type]?.unit || 'unit',
|
||||
category: getCategoryForGoalType(type) // Auto-assign category
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -199,6 +228,8 @@ export default function GoalsPage() {
|
||||
const data = {
|
||||
goal_type: formData.goal_type,
|
||||
is_primary: formData.is_primary,
|
||||
category: formData.category,
|
||||
priority: formData.priority,
|
||||
target_value: parseFloat(formData.target_value),
|
||||
unit: formData.unit,
|
||||
target_date: formData.target_date || null,
|
||||
@@ -238,6 +269,82 @@ export default function GoalsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleOpenProgressModal = async (goal) => {
|
||||
setProgressGoal(goal)
|
||||
setProgressFormData({
|
||||
date: new Date().toISOString().split('T')[0],
|
||||
value: goal.current_value || '',
|
||||
note: ''
|
||||
})
|
||||
|
||||
// Load progress history
|
||||
try {
|
||||
const entries = await api.listGoalProgress(goal.id)
|
||||
setProgressEntries(entries)
|
||||
} catch (err) {
|
||||
console.error('Failed to load progress:', err)
|
||||
setProgressEntries([])
|
||||
}
|
||||
|
||||
setShowProgressModal(true)
|
||||
setError(null)
|
||||
}
|
||||
|
||||
const handleSaveProgress = async () => {
|
||||
if (!progressFormData.value || !progressFormData.date) {
|
||||
setError('Bitte Datum und Wert eingeben')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const data = {
|
||||
date: progressFormData.date,
|
||||
value: parseFloat(progressFormData.value),
|
||||
note: progressFormData.note || null
|
||||
}
|
||||
|
||||
await api.createGoalProgress(progressGoal.id, data)
|
||||
showToast('✓ Fortschritt erfasst')
|
||||
|
||||
// Reload progress history
|
||||
const entries = await api.listGoalProgress(progressGoal.id)
|
||||
setProgressEntries(entries)
|
||||
|
||||
// Reset form
|
||||
setProgressFormData({
|
||||
date: new Date().toISOString().split('T')[0],
|
||||
value: '',
|
||||
note: ''
|
||||
})
|
||||
|
||||
// Reload goals to update current_value
|
||||
await loadData()
|
||||
setError(null)
|
||||
} catch (err) {
|
||||
console.error('Failed to save progress:', err)
|
||||
setError(err.message || 'Fehler beim Speichern')
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteProgress = async (progressId) => {
|
||||
if (!confirm('Eintrag wirklich löschen?')) return
|
||||
|
||||
try {
|
||||
await api.deleteGoalProgress(progressGoal.id, progressId)
|
||||
showToast('✓ Eintrag gelöscht')
|
||||
|
||||
// Reload progress history
|
||||
const entries = await api.listGoalProgress(progressGoal.id)
|
||||
setProgressEntries(entries)
|
||||
|
||||
// Reload goals to update current_value
|
||||
await loadData()
|
||||
} catch (err) {
|
||||
console.error('Failed to delete progress:', err)
|
||||
setError('Fehler beim Löschen')
|
||||
}
|
||||
}
|
||||
|
||||
const getProgressColor = (progress) => {
|
||||
if (progress >= 100) return 'var(--accent)'
|
||||
if (progress >= 75) return '#1D9E75'
|
||||
@@ -367,32 +474,6 @@ export default function GoalsPage() {
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Weight Total Display */}
|
||||
<div style={{
|
||||
padding: 12,
|
||||
background: 'var(--surface2)',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: 8,
|
||||
marginBottom: 16
|
||||
}}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<span style={{ fontWeight: 600, color: 'var(--text2)' }}>
|
||||
Gewichtung gesamt:
|
||||
</span>
|
||||
<span style={{ fontSize: 18, fontWeight: 600, color: 'var(--text1)' }}>
|
||||
{(() => {
|
||||
const total = Object.entries(focusTemp)
|
||||
.filter(([k]) => k.endsWith('_pct'))
|
||||
.reduce((acc, [k, v]) => acc + (Number(v) || 0), 0)
|
||||
return (total / 10).toFixed(1)
|
||||
})()}
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ fontSize: 12, marginTop: 4, color: 'var(--text3)' }}>
|
||||
💡 Die Prozentanteile werden automatisch berechnet
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div style={{ display: 'flex', gap: 12 }}>
|
||||
<button
|
||||
@@ -482,7 +563,7 @@ export default function GoalsPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tactical Goals List */}
|
||||
{/* Tactical Goals List - Category Grouped */}
|
||||
<div className="card">
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
|
||||
<h2 style={{ margin: 0 }}>🎯 Konkrete Ziele</h2>
|
||||
@@ -491,7 +572,7 @@ export default function GoalsPage() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{goals.length === 0 ? (
|
||||
{Object.keys(groupedGoals).length === 0 ? (
|
||||
<div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--text2)' }}>
|
||||
<Target size={48} style={{ opacity: 0.3, marginBottom: 16 }} />
|
||||
<p>Noch keine Ziele definiert</p>
|
||||
@@ -500,128 +581,161 @@ export default function GoalsPage() {
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
{goals.map(goal => {
|
||||
const typeInfo = goalTypesMap[goal.goal_type] || { label: goal.goal_type, unit: '', icon: '📊' }
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 32 }}>
|
||||
{Object.entries(GOAL_CATEGORIES).map(([catKey, catInfo]) => {
|
||||
const categoryGoals = groupedGoals[catKey] || []
|
||||
if (categoryGoals.length === 0) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
key={goal.id}
|
||||
className="card"
|
||||
style={{
|
||||
background: 'var(--surface2)',
|
||||
border: goal.is_primary ? '2px solid var(--accent)' : '1px solid var(--border)'
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
|
||||
<div key={catKey}>
|
||||
{/* Category Header */}
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 12,
|
||||
marginBottom: 16,
|
||||
paddingBottom: 12,
|
||||
borderBottom: `3px solid ${catInfo.color}`
|
||||
}}>
|
||||
<span style={{ fontSize: 28 }}>{catInfo.icon}</span>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
|
||||
<span style={{ fontSize: 20 }}>{typeInfo.icon}</span>
|
||||
<span style={{ fontWeight: 600 }}>
|
||||
{goal.name || typeInfo.label}
|
||||
</span>
|
||||
{goal.is_primary && (
|
||||
<span style={{
|
||||
background: 'var(--accent)',
|
||||
color: 'white',
|
||||
fontSize: 11,
|
||||
padding: '2px 8px',
|
||||
borderRadius: 4
|
||||
}}>
|
||||
PRIMÄR
|
||||
</span>
|
||||
)}
|
||||
<span style={{
|
||||
background: goal.status === 'active' ? '#E6F4F1' : '#F3F4F6',
|
||||
color: goal.status === 'active' ? 'var(--accent)' : 'var(--text2)',
|
||||
fontSize: 11,
|
||||
padding: '2px 8px',
|
||||
borderRadius: 4
|
||||
}}>
|
||||
{goal.status === 'active' ? 'AKTIV' : goal.status?.toUpperCase()}
|
||||
</span>
|
||||
</div>
|
||||
<h3 style={{ margin: 0, color: catInfo.color, fontSize: 18 }}>{catInfo.label}</h3>
|
||||
<p style={{ margin: 0, fontSize: 13, color: 'var(--text3)' }}>{catInfo.description}</p>
|
||||
</div>
|
||||
<span style={{
|
||||
background: catInfo.color,
|
||||
color: 'white',
|
||||
padding: '4px 12px',
|
||||
borderRadius: 16,
|
||||
fontSize: 13,
|
||||
fontWeight: 600
|
||||
}}>
|
||||
{categoryGoals.length} {categoryGoals.length === 1 ? 'Ziel' : 'Ziele'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: 24, marginBottom: 12, fontSize: 14 }}>
|
||||
<div>
|
||||
<span style={{ color: 'var(--text2)' }}>Start:</span>{' '}
|
||||
<strong>{goal.start_value} {goal.unit}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span style={{ color: 'var(--text2)' }}>Aktuell:</span>{' '}
|
||||
<strong>{goal.current_value || '—'} {goal.unit}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span style={{ color: 'var(--text2)' }}>Ziel:</span>{' '}
|
||||
<strong>{goal.target_value} {goal.unit}</strong>
|
||||
</div>
|
||||
{goal.target_date && (
|
||||
<div>
|
||||
<Calendar size={14} style={{ verticalAlign: 'middle', marginRight: 4 }} />
|
||||
{dayjs(goal.target_date).format('DD.MM.YYYY')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* Goals in Category */}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
{categoryGoals.map(goal => {
|
||||
const typeInfo = goalTypesMap[goal.goal_type] || { label_de: goal.goal_type, unit: '', icon: '📊' }
|
||||
const priorityInfo = PRIORITY_LEVELS[goal.priority] || PRIORITY_LEVELS[2]
|
||||
|
||||
{goal.progress_pct !== null && (
|
||||
<div>
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
fontSize: 12,
|
||||
marginBottom: 4
|
||||
}}>
|
||||
<span>Fortschritt</span>
|
||||
<span style={{ fontWeight: 600 }}>{goal.progress_pct}%</span>
|
||||
</div>
|
||||
<div style={{
|
||||
width: '100%',
|
||||
height: 6,
|
||||
background: 'var(--surface)',
|
||||
borderRadius: 3,
|
||||
overflow: 'hidden'
|
||||
}}>
|
||||
<div style={{
|
||||
width: `${Math.min(100, Math.max(0, goal.progress_pct))}%`,
|
||||
height: '100%',
|
||||
background: getProgressColor(goal.progress_pct),
|
||||
transition: 'width 0.3s ease'
|
||||
}} />
|
||||
</div>
|
||||
|
||||
{goal.on_track !== null && (
|
||||
<div style={{ marginTop: 8, fontSize: 12 }}>
|
||||
{goal.on_track ? (
|
||||
<span style={{ color: 'var(--accent)' }}>
|
||||
✓ Ziel voraussichtlich erreichbar bis {dayjs(goal.target_date).format('DD.MM.YYYY')}
|
||||
return (
|
||||
<div
|
||||
key={goal.id}
|
||||
className="card"
|
||||
style={{
|
||||
background: 'var(--surface2)',
|
||||
border: `1px solid var(--border)`,
|
||||
borderLeft: `5px solid ${catInfo.color}`
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16 }}>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8, flexWrap: 'wrap' }}>
|
||||
<span style={{ fontSize: 20 }}>{goal.icon || typeInfo.icon}</span>
|
||||
<span style={{ fontWeight: 600, fontSize: 16 }}>
|
||||
{goal.name || goal.label_de || typeInfo.label_de || goal.goal_type}
|
||||
</span>
|
||||
) : (
|
||||
<span style={{ color: '#D85A30' }}>
|
||||
⚠ Prognose: {goal.projection_date ? dayjs(goal.projection_date).format('DD.MM.YYYY') : 'Offen'}
|
||||
{goal.target_date && ' (später als geplant)'}
|
||||
<span style={{ fontSize: 16 }} title={priorityInfo.label}>
|
||||
{priorityInfo.stars}
|
||||
</span>
|
||||
<span style={{
|
||||
background: goal.status === 'active' ? '#E6F4F1' : '#F3F4F6',
|
||||
color: goal.status === 'active' ? 'var(--accent)' : 'var(--text2)',
|
||||
fontSize: 11,
|
||||
padding: '3px 8px',
|
||||
borderRadius: 4,
|
||||
fontWeight: 500
|
||||
}}>
|
||||
{goal.status === 'active' ? 'AKTIV' : goal.status?.toUpperCase() || 'AKTIV'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: 20, marginBottom: 12, fontSize: 14, flexWrap: 'wrap' }}>
|
||||
<div>
|
||||
<span style={{ color: 'var(--text2)' }}>Start:</span>{' '}
|
||||
<strong>{goal.start_value} {goal.unit}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span style={{ color: 'var(--text2)' }}>Aktuell:</span>{' '}
|
||||
<strong>{goal.current_value || '—'} {goal.unit}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span style={{ color: 'var(--text2)' }}>Ziel:</span>{' '}
|
||||
<strong style={{ color: catInfo.color }}>{goal.target_value} {goal.unit}</strong>
|
||||
</div>
|
||||
{goal.target_date && (
|
||||
<div style={{ color: 'var(--text2)' }}>
|
||||
<Calendar size={14} style={{ verticalAlign: 'middle', marginRight: 4 }} />
|
||||
{dayjs(goal.target_date).format('DD.MM.YYYY')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{goal.progress_pct !== null && (
|
||||
<div>
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
fontSize: 12,
|
||||
marginBottom: 4,
|
||||
color: 'var(--text2)'
|
||||
}}>
|
||||
<span>Fortschritt</span>
|
||||
<span style={{ fontWeight: 600, color: 'var(--text1)' }}>{goal.progress_pct}%</span>
|
||||
</div>
|
||||
<div style={{
|
||||
width: '100%',
|
||||
height: 8,
|
||||
background: 'var(--surface)',
|
||||
borderRadius: 4,
|
||||
overflow: 'hidden'
|
||||
}}>
|
||||
<div style={{
|
||||
width: `${Math.min(100, Math.max(0, goal.progress_pct))}%`,
|
||||
height: '100%',
|
||||
background: catInfo.color,
|
||||
transition: 'width 0.3s ease'
|
||||
}} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button
|
||||
className="btn-secondary"
|
||||
onClick={() => handleEditGoal(goal)}
|
||||
style={{ padding: '6px 12px' }}
|
||||
>
|
||||
<Pencil size={14} />
|
||||
</button>
|
||||
<button
|
||||
className="btn-secondary"
|
||||
onClick={() => handleDeleteGoal(goal.id)}
|
||||
style={{ padding: '6px 12px', color: '#DC2626' }}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
|
||||
{/* Progress button only for custom goals (no automatic data source) */}
|
||||
{!goal.source_table && (
|
||||
<button
|
||||
className="btn-secondary"
|
||||
onClick={() => handleOpenProgressModal(goal)}
|
||||
style={{ padding: '6px 12px' }}
|
||||
title="Fortschritt erfassen"
|
||||
>
|
||||
<TrendingUp size={14} />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className="btn-secondary"
|
||||
onClick={() => handleEditGoal(goal)}
|
||||
style={{ padding: '6px 12px' }}
|
||||
title="Bearbeiten"
|
||||
>
|
||||
<Pencil size={14} />
|
||||
</button>
|
||||
<button
|
||||
className="btn-secondary"
|
||||
onClick={() => handleDeleteGoal(goal.id)}
|
||||
style={{ padding: '6px 12px', color: '#DC2626' }}
|
||||
title="Löschen"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -817,34 +931,61 @@ export default function GoalsPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Primärziel */}
|
||||
<div style={{
|
||||
padding: 12,
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: 8,
|
||||
marginBottom: 20
|
||||
}}>
|
||||
<label style={{
|
||||
display: 'flex',
|
||||
alignItems: 'flex-start',
|
||||
gap: 10,
|
||||
cursor: 'pointer'
|
||||
}}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={formData.is_primary}
|
||||
onChange={e => setFormData(f => ({ ...f, is_primary: e.target.checked }))}
|
||||
style={{ marginTop: 2 }}
|
||||
/>
|
||||
<div>
|
||||
<div style={{ fontSize: 13, fontWeight: 600, marginBottom: 2 }}>
|
||||
Als Primärziel setzen
|
||||
</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--text2)' }}>
|
||||
Dein Primärziel hat höchste Priorität in Analysen und Charts
|
||||
</div>
|
||||
</div>
|
||||
</label>
|
||||
{/* Category & Priority */}
|
||||
<div style={{ fontSize: 14, fontWeight: 600, marginBottom: 8, marginTop: 20, color: 'var(--text1)' }}>
|
||||
📂 Kategorisierung
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: 12, marginBottom: 16 }}>
|
||||
{/* Category */}
|
||||
<div style={{ flex: 1 }}>
|
||||
<label style={{
|
||||
display: 'block',
|
||||
fontSize: 13,
|
||||
fontWeight: 500,
|
||||
marginBottom: 4,
|
||||
color: 'var(--text2)'
|
||||
}}>
|
||||
Kategorie *
|
||||
</label>
|
||||
<select
|
||||
className="form-input"
|
||||
style={{ width: '100%' }}
|
||||
value={formData.category}
|
||||
onChange={e => setFormData(f => ({ ...f, category: e.target.value }))}
|
||||
>
|
||||
{Object.entries(GOAL_CATEGORIES).map(([key, info]) => (
|
||||
<option key={key} value={key}>
|
||||
{info.icon} {info.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Priority */}
|
||||
<div style={{ flex: 1 }}>
|
||||
<label style={{
|
||||
display: 'block',
|
||||
fontSize: 13,
|
||||
fontWeight: 500,
|
||||
marginBottom: 4,
|
||||
color: 'var(--text2)'
|
||||
}}>
|
||||
Priorität *
|
||||
</label>
|
||||
<select
|
||||
className="form-input"
|
||||
style={{ width: '100%' }}
|
||||
value={formData.priority}
|
||||
onChange={e => setFormData(f => ({ ...f, priority: parseInt(e.target.value) }))}
|
||||
>
|
||||
{Object.entries(PRIORITY_LEVELS).map(([level, info]) => (
|
||||
<option key={level} value={level}>
|
||||
{info.stars} {info.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Buttons */}
|
||||
@@ -868,6 +1009,222 @@ export default function GoalsPage() {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Progress Modal */}
|
||||
{showProgressModal && progressGoal && (
|
||||
<div style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
background: 'rgba(0,0,0,0.5)',
|
||||
display: 'flex',
|
||||
alignItems: 'flex-start',
|
||||
justifyContent: 'center',
|
||||
zIndex: 1000,
|
||||
padding: 16,
|
||||
overflowY: 'auto'
|
||||
}}>
|
||||
<div className="card" style={{
|
||||
width: '100%',
|
||||
maxWidth: 600,
|
||||
marginTop: 40,
|
||||
marginBottom: 40
|
||||
}}>
|
||||
<h2 style={{ marginBottom: 20, display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<TrendingUp size={24} style={{ color: 'var(--accent)' }} />
|
||||
Fortschritt erfassen
|
||||
</h2>
|
||||
|
||||
<div style={{
|
||||
padding: 12,
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: 8,
|
||||
marginBottom: 24,
|
||||
borderLeft: `4px solid ${GOAL_CATEGORIES[progressGoal.category]?.color || 'var(--accent)'}`
|
||||
}}>
|
||||
<div style={{ fontWeight: 600, marginBottom: 4 }}>
|
||||
{progressGoal.name || progressGoal.label_de || progressGoal.goal_type}
|
||||
</div>
|
||||
<div style={{ fontSize: 14, color: 'var(--text2)' }}>
|
||||
Ziel: {progressGoal.target_value} {progressGoal.unit}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Progress Form */}
|
||||
<div style={{ marginBottom: 24 }}>
|
||||
<h3 style={{ fontSize: 16, marginBottom: 16 }}>Neuer Eintrag</h3>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
|
||||
<div>
|
||||
<div style={{
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
marginBottom: 8,
|
||||
color: 'var(--text1)'
|
||||
}}>
|
||||
Datum
|
||||
</div>
|
||||
<input
|
||||
type="date"
|
||||
className="form-input"
|
||||
value={progressFormData.date}
|
||||
onChange={(e) => setProgressFormData({ ...progressFormData, date: e.target.value })}
|
||||
max={new Date().toISOString().split('T')[0]}
|
||||
style={{ width: '100%', textAlign: 'left' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div style={{
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
marginBottom: 8,
|
||||
color: 'var(--text1)'
|
||||
}}>
|
||||
Wert ({progressGoal.unit})
|
||||
</div>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
className="form-input"
|
||||
value={progressFormData.value}
|
||||
onChange={(e) => setProgressFormData({ ...progressFormData, value: e.target.value })}
|
||||
placeholder={`z.B. ${progressGoal.current_value || progressGoal.target_value}`}
|
||||
style={{ width: '100%', textAlign: 'left' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div style={{
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
marginBottom: 8,
|
||||
color: 'var(--text1)'
|
||||
}}>
|
||||
Notiz (optional)
|
||||
</div>
|
||||
<textarea
|
||||
className="form-input"
|
||||
value={progressFormData.note}
|
||||
onChange={(e) => setProgressFormData({ ...progressFormData, note: e.target.value })}
|
||||
placeholder="Optionale Notiz..."
|
||||
rows={2}
|
||||
style={{ width: '100%', textAlign: 'left' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
className="btn-primary"
|
||||
onClick={handleSaveProgress}
|
||||
disabled={!progressFormData.value}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
Eintrag speichern
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Progress History */}
|
||||
<div>
|
||||
<h3 style={{ fontSize: 16, marginBottom: 12 }}>
|
||||
Verlauf ({progressEntries.length} Einträge)
|
||||
</h3>
|
||||
|
||||
{progressEntries.length === 0 ? (
|
||||
<div style={{
|
||||
padding: 24,
|
||||
textAlign: 'center',
|
||||
color: 'var(--text2)',
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: 8
|
||||
}}>
|
||||
Noch keine Einträge vorhanden
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{progressEntries.map(entry => (
|
||||
<div key={entry.id} style={{
|
||||
padding: 12,
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: 8,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center'
|
||||
}}>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 4 }}>
|
||||
<span style={{ fontWeight: 600 }}>
|
||||
{dayjs(entry.date).format('DD.MM.YYYY')}
|
||||
</span>
|
||||
<span style={{
|
||||
fontSize: 18,
|
||||
fontWeight: 600,
|
||||
color: 'var(--accent)'
|
||||
}}>
|
||||
{entry.value} {progressGoal.unit}
|
||||
</span>
|
||||
{entry.source !== 'manual' && (
|
||||
<span style={{
|
||||
fontSize: 11,
|
||||
padding: '2px 6px',
|
||||
background: 'var(--surface)',
|
||||
borderRadius: 4,
|
||||
color: 'var(--text3)'
|
||||
}}>
|
||||
{entry.source}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{entry.note && (
|
||||
<div style={{ fontSize: 13, color: 'var(--text2)' }}>
|
||||
{entry.note}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{entry.source === 'manual' && (
|
||||
<button
|
||||
className="btn-secondary"
|
||||
onClick={() => handleDeleteProgress(entry.id)}
|
||||
style={{
|
||||
padding: '6px 12px',
|
||||
color: '#DC2626',
|
||||
flexShrink: 0
|
||||
}}
|
||||
title="Löschen"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Close Button */}
|
||||
<div style={{ marginTop: 24, display: 'flex', justifyContent: 'flex-end' }}>
|
||||
<button
|
||||
className="btn-secondary"
|
||||
onClick={() => {
|
||||
setShowProgressModal(false)
|
||||
setProgressGoal(null)
|
||||
setProgressEntries([])
|
||||
setProgressFormData({
|
||||
date: new Date().toISOString().split('T')[0],
|
||||
value: '',
|
||||
note: ''
|
||||
})
|
||||
}}
|
||||
>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -340,10 +340,16 @@ export const api = {
|
||||
updateFocusAreas: (d) => req('/goals/focus-areas', jput(d)),
|
||||
|
||||
listGoals: () => req('/goals/list'),
|
||||
listGoalsGrouped: () => req('/goals/grouped'),
|
||||
createGoal: (d) => req('/goals/create', json(d)),
|
||||
updateGoal: (id,d) => req(`/goals/${id}`, jput(d)),
|
||||
deleteGoal: (id) => req(`/goals/${id}`, {method:'DELETE'}),
|
||||
|
||||
// Goal Progress (v2.1)
|
||||
listGoalProgress: (id) => req(`/goals/${id}/progress`),
|
||||
createGoalProgress: (id,d) => req(`/goals/${id}/progress`, json(d)),
|
||||
deleteGoalProgress: (gid,pid) => req(`/goals/${gid}/progress/${pid}`, {method:'DELETE'}),
|
||||
|
||||
// Goal Type Definitions (Phase 1.5)
|
||||
listGoalTypeDefinitions: () => req('/goals/goal-types'),
|
||||
createGoalType: (d) => req('/goals/goal-types', json(d)),
|
||||
|
||||
Reference in new issue
Block a user