**User Feedback:** "Macht es nicht Sinn, den nächsten verfügbaren Wert
am oder nach dem Startdatum automatisch zu ermitteln und auch das
Startdatum dann automatisch auf den Wert zu setzen?"
**New Logic:**
1. User sets start_date: 2026-01-01
2. System finds FIRST measurement >= 2026-01-01 (e.g., 2026-01-15: 88 kg)
3. System auto-adjusts:
- start_date → 2026-01-15
- start_value → 88 kg
4. User sees: "Start: 88 kg (15.01.26)" ✓
**Benefits:**
- User doesn't need to know exact date of first measurement
- More user-friendly UX
- Automatically finds closest available data
**Implementation:**
- Changed query from "BETWEEN date ±7 days" to "WHERE date >= target_date"
- Returns dict with {'value': float, 'date': date}
- Both create_goal() and update_goal() now adjust start_date automatically
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
**Error:**
function pg_catalog.extract(unknown, integer) does not exist
HINT: No function matches the given name and argument types.
**Problem:**
In PostgreSQL, date - date returns INTEGER (days), not INTERVAL.
EXTRACT(EPOCH FROM integer) fails because EPOCH expects timestamp/interval.
**Solution:**
Changed from:
ORDER BY ABS(EXTRACT(EPOCH FROM (date - '2026-01-01')))
To:
ORDER BY ABS(date - '2026-01-01'::date)
This directly uses the day difference (integer) for sorting,
which is exactly what we need to find the closest date.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
**Bug:** start_date was not being loaded into edit form or sent in update request
**Fixed:**
1. handleEditGoal() - Added start_date to formData when editing
2. handleSaveGoal() - Added start_date to API payload for both create and update
Now when editing a goal:
- start_date field is populated with existing value
- Changing start_date triggers backend to recalculate start_value
- Update request includes start_date
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Added start_date field to goal creation/editing form:
1. New "Startdatum" input field before "Zieldatum"
- Defaults to today
- Hint: "Startwert wird automatisch aus historischen Daten ermittelt"
2. Display start_date in goals list
- Shows next to start_value: "85 kg (01.01.26)"
- Compact format for better readability
3. Updated formData state
- Added start_date with today as default
- API calls automatically include it
User can now:
- Set historical start date (e.g., 3 months ago)
- Backend auto-populates start_value from that date
- See exact start date and value for each goal
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
**Problem:** Goals created today had start_value = current_value,
showing 0% progress even after months of tracking.
**Solution:**
1. Added start_date and start_value to GoalCreate/GoalUpdate models
2. New function _get_historical_value_for_goal_type():
- Queries source table for value on specific date
- ±7 day window for closest match
- Works with all goal types via goal_type_definitions
3. create_goal() logic:
- If start_date < today → auto-populate from historical data
- If start_date = today → use current value
- User can override start_value manually
4. update_goal() logic:
- Changing start_date recalculates start_value
- Can manually override start_value
**Example:**
- Goal created today with start_date = 3 months ago
- System finds weight on that date (88 kg)
- Current weight: 85.2 kg, Target: 82 kg
- Progress: (85.2 - 88) / (82 - 88) = 47% ✓
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Goal progress placeholders were filtering out all goals because
start_value was missing from the SELECT statement.
Added start_value to both:
- get_active_goals() - for placeholder formatters
- get_goal_by_id() - for consistency
This will fix:
- active_goals_md progress column (was all "-")
- top_3_goals_behind_schedule (was "keine Ziele")
- top_3_goals_on_track (was "keine Ziele")
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Fixed 2 critical placeholder issues:
1. focus_areas_weighted_json was empty:
- Query used 'area_key' but column is 'key' in focus_area_definitions
- Changed to SELECT key, not area_key
2. Goal progress placeholders showed "nicht verfügbar":
- progress_pct in goals table is NULL (not auto-calculated)
- Added manual calculation in all 3 formatter functions:
* _format_goals_as_markdown() - shows % in table
* _format_goals_behind() - finds lowest progress
* _format_goals_on_track() - finds >= 50% progress
All placeholders should now return proper values.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
TypeError: unsupported operand type(s) for -: 'decimal.Decimal' and 'float'
PostgreSQL NUMERIC columns return Decimal objects. Must convert
current_value, target_value, start_value to float before passing
to calculate_goal_progress_pct().
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Fixed remaining placeholder calculation issues:
1. body_progress_score returning 0:
- When start_value is NULL, query oldest weight from last 90 days
- Prevents progress = 0% when start equals current
2. focus_areas_weighted_json empty:
- Changed from goal_utils.get_focus_weights_v2() to scores.get_user_focus_weights()
- Now uses same function as focus_area_weights_json
3. Implemented 5 TODO markdown formatting functions:
- _format_goals_as_markdown() - table with progress bars
- _format_focus_areas_as_markdown() - weighted list
- _format_top_focus_areas() - top N by weight
- _format_goals_behind() - lowest progress goals
- _format_goals_on_track() - goals >= 50% progress
All placeholders should now return proper values.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Root cause: Two TODO stubs always returned '[]'
Implemented:
- active_goals_json: Calls get_active_goals() from goal_utils
- focus_areas_weighted_json: Builds weighted list with names/categories
Result:
- active_goals_json now shows actual goals
- body_progress_score should calculate correctly
- top_3_goals placeholders will work
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Previous commit only converted weight values, but missed:
- avg_intake (calories from DB)
- avg_protein (protein_g from DB)
- protein_per_kg calculations in loops
All DB numeric values now converted to float BEFORE arithmetic.
Fixed locations:
- Line 44: avg_intake conversion
- Line 126: avg_protein conversion
- Line 175: protein_per_kg in loop
- Line 213: protein_values list comprehension
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
TypeError: unsupported operand type(s) for *: 'decimal.Decimal' and 'float'
TypeError: unsupported operand type(s) for -: 'float' and 'decimal.Decimal'
PostgreSQL NUMERIC/DECIMAL columns return decimal.Decimal objects,
not float. These cannot be mixed in arithmetic operations.
Fixed 3 locations:
- Line 62: float(weight_row['weight']) * 32.5
- Line 153: float(weight_row['weight']) for protein_per_kg
- Line 202: float(weight_row['avg_weight']) for adequacy calc
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
ImportError: cannot import name 'get_goals_by_type' from 'goal_utils'
Changes:
- body_metrics.py: Use get_active_goals() + filter by type_key
- nutrition_metrics.py: Remove unused import (dead code)
Result: Score functions no longer crash on import error.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Root cause: All 3 score functions returned None because they queried
German focus area keys that don't exist in database (migration 031
uses English keys).
Changes:
- body_progress_score: körpergewicht/körperfett/muskelmasse
→ weight_loss/muscle_gain/body_recomposition
- nutrition_score: ernährung_basis/proteinzufuhr/kalorienbilanz
→ protein_intake/calorie_balance/macro_consistency/meal_timing/hydration
- activity_score: kraftaufbau/cardio/bewegungsumfang/trainingsqualität
→ strength/aerobic_endurance/flexibility/rhythm/coordination (grouped)
Result: Scores now calculate correctly with existing focus area weights.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Calculates average count per week over 30 days
- Use case: Training frequency per week (smoothed)
- Formula: (count in 30 days) / 4.285 weeks
- Documentation: .claude/docs/technical/AGGREGATION_METHODS.md
Fixed remaining sleep_log column name errors in calculate_health_stability_score:
- SELECT: total_sleep_min, deep_min, rem_min → duration_minutes, deep_minutes, rem_minutes
- _score_sleep_quality: Updated dict access to use new column names
This was blocking goal_progress_score from calculating.
Changes:
- scores.py: Fixed sleep_log SELECT query and _score_sleep_quality dict access
This should be the LAST column name bug! All Phase 0b calculations should now work.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Final bug fixes:
1. blood_pressure_log query - changed 'date' column to 'measured_at' (correct column for TIMESTAMP)
2. top_goal_name KeyError - added 'name' to SELECT in get_active_goals()
3. top_goal_name fallback - use goal_type if name is NULL
Changes:
- scores.py: Fixed blood_pressure_log query to use measured_at instead of date
- goal_utils.py: Added 'name' column to get_active_goals() SELECT
- placeholder_resolver.py: Added fallback to goal_type if name is None
These were the last 2 errors showing in logs. All major calculation bugs should now be fixed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Fixed unterminated string literal in get_placeholder_catalog()
- Line 1037 had extra quote: ('quality_sessions_pct', 'Qualitätssessions (%)'),'
- Should be: ('quality_sessions_pct', 'Qualitätssessions (%)'),
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Problem: All _safe_* functions were silently catching exceptions and returning 'nicht verfügbar',
making it impossible to debug why calculations fail.
Solution: Add detailed error logging with traceback to all 4 wrapper functions:
- _safe_int(): Logs function name, exception type, message, full stack trace
- _safe_float(): Same logging
- _safe_str(): Same logging
- _safe_json(): Same logging
Now when placeholders return 'nicht verfügbar', the backend logs will show:
- Which placeholder function failed
- What exception occurred
- Full stack trace for debugging
Example log output:
[ERROR] _safe_int(goal_progress_score, uuid): ModuleNotFoundError: No module named 'calculations'
Traceback (most recent call last):
...
This will help identify if issue is:
- Missing calculations module import
- Missing data in database
- Wrong column names
- Calculation logic errors
This file was replaced by the refactored vitals system:
- vitals_baseline.py (morning measurements)
- blood_pressure.py (BP tracking with context)
Migration 015 completed the split in v9d Phase 2d.
File was no longer imported in main.py.
Cleanup result: -684 lines of dead code
Bug 1 Final Fix:
- Changed all placeholders from $1, $2, $3 to %s
- psycopg2 expects Python-style %s, converts to $N internally
- Using $N directly causes 'there is no parameter $1' error
- Removed param_idx counter (not needed with %s)
Root cause: Mixing PostgreSQL native syntax with psycopg2 driver
This is THE fix that will finally work!
Bug 3 Fix: filter_conditions was missing from SELECT statement in
list_goal_type_definitions(), preventing edit form from loading
existing filter JSON.
- Added filter_conditions to line 1087
- Now edit form correctly populates filter textarea
Final documentation summary for v0.9h pre-release state.
**Includes:**
- Complete documentation checklist
- Gitea manual actions required
- Resumption guide for future sessions
- Reading order for all documents
- Context prompt for Claude Code
**Status:** All documentation up to date, ready to pause/resume safely.
**Bug:** POST /api/vitals/baseline threw UndefinedParameter
**Cause:** Dynamic SQL generation had desynchronized column names and placeholders
**Fix:** Rewrote to use synchronized insert_cols, insert_placeholders, update_fields arrays
- Track param_idx correctly (start at 3 after pid and date)
- Build INSERT columns and placeholders in parallel
- Cleaner, more maintainable code
- Fixes Ruhepuls entry error
**Bug 1: Focus contributions not saved**
- GoalsPage: Added focus_contributions to data object (line 232)
- Was missing from API payload, causing loss of focus area assignments
**Bug 2: Filter focus areas in goal form**
- Only show focus areas user has weighted (weight > 0)
- Cleaner UX, avoids confusion with non-prioritized areas
- Filters focusAreasGrouped by userFocusWeights
**Bug 3: Vitals RHR entry - Internal Server Error**
- Fixed: Endpoint tried to INSERT into vitals_log (renamed in Migration 015)
- Now uses vitals_baseline table (correct post-migration table)
- Removed BP fields from baseline endpoint (use /blood-pressure instead)
- Backward compatible return format
All fixes tested and ready for production.
**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)
- Restored GOAL_MODES constant and selection cards at top
- Fixed focusAreas/focusPreferences variable confusion
- Legacy 6 focus preferences show correctly in Fokus-Bereiche card
- Dynamic 26 focus areas should display in goal form
- Goal Mode cards now visible and functional again
- get_focus_areas now tries user_focus_preferences first (Migration 031)
- Falls back to old focus_areas table if Migration 031 not applied
- get_goals_grouped wraps focus_contributions loading in try/catch
- Graceful degradation until migrations run
- Wrap focus_contributions loading in try/catch
- If tables don't exist (migration not run), continue without them
- Backward compatible with pre-migration state
- Logs warning but doesn't crash