feat: Dynamic Focus Areas system v2.0 - fully implemented
**Migration 032:** - user_focus_area_weights table (profile_id, focus_area_id, weight) - Migrates legacy 6 preferences to dynamic weights **Backend (focus_areas.py):** - GET /user-preferences: Returns dynamic focus weights with percentages - PUT /user-preferences: Saves user weights (dict: focus_area_id → weight) - Auto-calculates percentages from relative weights - Graceful fallback if Migration 032 not applied **Frontend (GoalsPage.jsx):** - REMOVED: Goal Mode cards (obsolete) - REMOVED: 6 hardcoded legacy focus sliders - NEW: Dynamic focus area cards (weight > 0 only) - NEW: Edit mode with sliders for all 26 areas (grouped by category) - Clean responsive design **How it works:** 1. Admin defines focus areas in /admin/focus-areas (26 default) 2. User sets weights for areas they care about (0-100 relative) 3. System calculates percentages automatically 4. Cards show only weighted areas 5. Goals assign to 1-n focus areas (existing functionality)
This commit is contained in:
1 parent
dfcdfbe335
commit
3116fbbc91
3 files changed
+281
-364
No files matched your search
@@ -0,0 +1,53 @@
|
||||
-- Migration 032: User Focus Area Weights
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Allow users to set custom weights for focus areas (dynamic preferences)
|
||||
|
||||
-- ============================================================================
|
||||
-- User Focus Area Weights (many-to-many with weights)
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_focus_area_weights (
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
focus_area_id UUID NOT NULL REFERENCES focus_area_definitions(id) ON DELETE CASCADE,
|
||||
weight INTEGER NOT NULL DEFAULT 0 CHECK (weight >= 0 AND weight <= 100),
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW(),
|
||||
PRIMARY KEY (profile_id, focus_area_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_user_focus_weights_profile ON user_focus_area_weights(profile_id);
|
||||
CREATE INDEX idx_user_focus_weights_area ON user_focus_area_weights(focus_area_id);
|
||||
|
||||
COMMENT ON TABLE user_focus_area_weights IS 'User-specific weights for focus areas (dynamic system)';
|
||||
COMMENT ON COLUMN user_focus_area_weights.weight IS 'Relative weight (0-100) - will be normalized to percentages in UI';
|
||||
|
||||
-- ============================================================================
|
||||
-- Migrate legacy preferences to dynamic weights
|
||||
-- ============================================================================
|
||||
|
||||
-- For each user with legacy preferences, create weights for the 6 base areas
|
||||
INSERT INTO user_focus_area_weights (profile_id, focus_area_id, weight)
|
||||
SELECT
|
||||
ufp.profile_id,
|
||||
fad.id as focus_area_id,
|
||||
CASE fad.key
|
||||
WHEN 'weight_loss' THEN ufp.weight_loss_pct
|
||||
WHEN 'muscle_gain' THEN ufp.muscle_gain_pct
|
||||
WHEN 'strength' THEN ufp.strength_pct
|
||||
WHEN 'aerobic_endurance' THEN ufp.endurance_pct
|
||||
WHEN 'flexibility' THEN ufp.flexibility_pct
|
||||
WHEN 'general_health' THEN ufp.health_pct
|
||||
ELSE 0
|
||||
END as weight
|
||||
FROM user_focus_preferences ufp
|
||||
CROSS JOIN focus_area_definitions fad
|
||||
WHERE fad.key IN ('weight_loss', 'muscle_gain', 'strength', 'aerobic_endurance', 'flexibility', 'general_health')
|
||||
AND (
|
||||
(fad.key = 'weight_loss' AND ufp.weight_loss_pct > 0) OR
|
||||
(fad.key = 'muscle_gain' AND ufp.muscle_gain_pct > 0) OR
|
||||
(fad.key = 'strength' AND ufp.strength_pct > 0) OR
|
||||
(fad.key = 'aerobic_endurance' AND ufp.endurance_pct > 0) OR
|
||||
(fad.key = 'flexibility' AND ufp.flexibility_pct > 0) OR
|
||||
(fad.key = 'general_health' AND ufp.health_pct > 0)
|
||||
)
|
||||
ON CONFLICT (profile_id, focus_area_id) DO NOTHING;
|
||||
@@ -233,45 +233,61 @@ def delete_focus_area_definition(
|
||||
@router.get("/user-preferences")
|
||||
def get_user_focus_preferences(session: dict = Depends(require_auth)):
|
||||
"""
|
||||
Get user's focus area weightings.
|
||||
Get user's focus area weightings (dynamic system).
|
||||
|
||||
Returns:
|
||||
- legacy: Old flat structure (weight_loss_pct, muscle_gain_pct, etc.)
|
||||
- dynamic: New dynamic preferences (focus_area_id → weight_pct)
|
||||
Returns focus areas with user-set weights, grouped by category.
|
||||
"""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get legacy preferences
|
||||
cur.execute("""
|
||||
SELECT weight_loss_pct, muscle_gain_pct, strength_pct,
|
||||
endurance_pct, flexibility_pct, health_pct
|
||||
FROM user_focus_preferences
|
||||
WHERE profile_id = %s
|
||||
""", (pid,))
|
||||
|
||||
legacy = cur.fetchone()
|
||||
if legacy:
|
||||
legacy = r2d(legacy)
|
||||
else:
|
||||
# Create default if not exists
|
||||
# Get dynamic preferences (Migration 032)
|
||||
try:
|
||||
cur.execute("""
|
||||
INSERT INTO user_focus_preferences (profile_id)
|
||||
VALUES (%s)
|
||||
RETURNING weight_loss_pct, muscle_gain_pct, strength_pct,
|
||||
endurance_pct, flexibility_pct, health_pct
|
||||
SELECT
|
||||
fa.id, fa.key, fa.name_de, fa.name_en, fa.icon,
|
||||
fa.category, fa.description,
|
||||
ufw.weight
|
||||
FROM user_focus_area_weights ufw
|
||||
JOIN focus_area_definitions fa ON ufw.focus_area_id = fa.id
|
||||
WHERE ufw.profile_id = %s AND ufw.weight > 0
|
||||
ORDER BY fa.category, fa.name_de
|
||||
""", (pid,))
|
||||
legacy = r2d(cur.fetchone())
|
||||
|
||||
# TODO: Future - dynamic preferences from new table
|
||||
# For now, return legacy structure
|
||||
weights = [r2d(row) for row in cur.fetchall()]
|
||||
|
||||
return {
|
||||
"legacy": legacy,
|
||||
"dynamic": {} # Placeholder for future
|
||||
}
|
||||
# Calculate percentages from weights
|
||||
total_weight = sum(w['weight'] for w in weights)
|
||||
if total_weight > 0:
|
||||
for w in weights:
|
||||
w['percentage'] = round((w['weight'] / total_weight) * 100)
|
||||
else:
|
||||
for w in weights:
|
||||
w['percentage'] = 0
|
||||
|
||||
# Group by category
|
||||
grouped = {}
|
||||
for w in weights:
|
||||
cat = w['category'] or 'other'
|
||||
if cat not in grouped:
|
||||
grouped[cat] = []
|
||||
grouped[cat].append(w)
|
||||
|
||||
return {
|
||||
"weights": weights,
|
||||
"grouped": grouped,
|
||||
"total_weight": total_weight
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
# Migration 032 not applied yet - return empty
|
||||
print(f"[WARNING] user_focus_area_weights not found: {e}")
|
||||
return {
|
||||
"weights": [],
|
||||
"grouped": {},
|
||||
"total_weight": 0
|
||||
}
|
||||
|
||||
@router.put("/user-preferences")
|
||||
def update_user_focus_preferences(
|
||||
@@ -279,66 +295,44 @@ def update_user_focus_preferences(
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Update user's focus area weightings.
|
||||
Update user's focus area weightings (dynamic system).
|
||||
|
||||
Accepts flat structure (legacy) for now.
|
||||
Auto-normalizes to sum=100%.
|
||||
Expects: { "weights": { "focus_area_id": weight, ... } }
|
||||
Weights are relative (0-100), normalized in display only.
|
||||
"""
|
||||
pid = session['profile_id']
|
||||
|
||||
# Extract percentages
|
||||
percentages = {
|
||||
'weight_loss_pct': data.get('weight_loss_pct', 0),
|
||||
'muscle_gain_pct': data.get('muscle_gain_pct', 0),
|
||||
'strength_pct': data.get('strength_pct', 0),
|
||||
'endurance_pct': data.get('endurance_pct', 0),
|
||||
'flexibility_pct': data.get('flexibility_pct', 0),
|
||||
'health_pct': data.get('health_pct', 0)
|
||||
}
|
||||
if 'weights' not in data:
|
||||
raise HTTPException(status_code=400, detail="'weights' field required")
|
||||
|
||||
# Normalize to 100%
|
||||
total = sum(percentages.values())
|
||||
if total > 0:
|
||||
for key in percentages:
|
||||
percentages[key] = round((percentages[key] / total) * 100)
|
||||
|
||||
# Adjust largest if sum != 100 due to rounding
|
||||
current_sum = sum(percentages.values())
|
||||
if current_sum != 100 and total > 0:
|
||||
largest_key = max(percentages, key=percentages.get)
|
||||
percentages[largest_key] += (100 - current_sum)
|
||||
weights = data['weights'] # Dict: focus_area_id → weight
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Upsert
|
||||
cur.execute("""
|
||||
INSERT INTO user_focus_preferences
|
||||
(profile_id, weight_loss_pct, muscle_gain_pct, strength_pct,
|
||||
endurance_pct, flexibility_pct, health_pct)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
ON CONFLICT (profile_id)
|
||||
DO UPDATE SET
|
||||
weight_loss_pct = EXCLUDED.weight_loss_pct,
|
||||
muscle_gain_pct = EXCLUDED.muscle_gain_pct,
|
||||
strength_pct = EXCLUDED.strength_pct,
|
||||
endurance_pct = EXCLUDED.endurance_pct,
|
||||
flexibility_pct = EXCLUDED.flexibility_pct,
|
||||
health_pct = EXCLUDED.health_pct,
|
||||
updated_at = NOW()
|
||||
""", (
|
||||
pid,
|
||||
percentages['weight_loss_pct'],
|
||||
percentages['muscle_gain_pct'],
|
||||
percentages['strength_pct'],
|
||||
percentages['endurance_pct'],
|
||||
percentages['flexibility_pct'],
|
||||
percentages['health_pct']
|
||||
))
|
||||
# Delete existing weights
|
||||
cur.execute(
|
||||
"DELETE FROM user_focus_area_weights WHERE profile_id = %s",
|
||||
(pid,)
|
||||
)
|
||||
|
||||
# Insert new weights (only non-zero)
|
||||
for focus_area_id, weight in weights.items():
|
||||
weight_int = int(weight)
|
||||
if weight_int > 0:
|
||||
cur.execute("""
|
||||
INSERT INTO user_focus_area_weights
|
||||
(profile_id, focus_area_id, weight)
|
||||
VALUES (%s, %s, %s)
|
||||
ON CONFLICT (profile_id, focus_area_id)
|
||||
DO UPDATE SET
|
||||
weight = EXCLUDED.weight,
|
||||
updated_at = NOW()
|
||||
""", (pid, focus_area_id, weight_int))
|
||||
|
||||
return {
|
||||
"message": "Focus Areas aktualisiert",
|
||||
"normalized": percentages
|
||||
"message": "Focus Area Gewichtungen aktualisiert",
|
||||
"count": len([w for w in weights.values() if int(w) > 0])
|
||||
}
|
||||
|
||||
# ============================================================================
|
||||
|
||||
Reference in new issue
Block a user