166 Commits
Author SHA1 Message Date
Lars 9d22e7e8af Merge pull request 'Goalsystem V1' (#50) from develop into main
Deploy Production / deploy (push) Successful in 49s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
Reviewed-on: #50
2026-03-27 17:40:50 +01:00
Lars 0a1da37197 fix: Remove g.direction from SELECT - column does not exist
Deploy Development / deploy (push) Successful in 51s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
2026-03-27 17:08:30 +01:00
Lars 495f218f9a feat: Add Goal Types admin link to Settings/AdminPanel
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
2026-03-27 17:05:42 +01:00
Lars fac8820208 fix: SQL error - direction is in goals table, not goal_type_definitions
Build Test / build-frontend (push) Waiting to run
Deploy Development / deploy (push) Has been cancelled
Build Test / lint-backend (push) Waiting to run
2026-03-27 17:05:14 +01:00
LarsandClaude Opus 4.6 217990d417 fix: Prevent manual progress entries for automatic goals
Deploy Development / deploy (push) Successful in 43s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
**Backend Safeguards:**
- get_goals_grouped: Added source_table, source_column, direction to SELECT
- create_goal_progress: Check source_table before allowing manual entry
- Returns HTTP 400 if user tries to log progress for automatic goals (weight, activity, etc.)

**Prevents:**
- Data confusion: Manual entries in goal_progress_log for weight/activity/etc.
- Dual tracking: Same data in multiple tables
- User error: Wrong data entry location

**Result:**
- Frontend filter (!goal.source_table) now works correctly
- CustomGoalsPage shows ONLY custom goals (flexibility, strength, etc.)
- Clear error message if manual entry attempted via API

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 17:00:53 +01:00
Lars 1960ae4924 docs: Update CLAUDE.md - Custom Goals Page
Deploy Development / deploy (push) Successful in 43s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
2026-03-27 15:32:44 +01:00
LarsandClaude Opus 4.6 bcb867da69 refactor: Separate goal tracking - strategic vs tactical
Build Test / build-frontend (push) Waiting to run
Deploy Development / deploy (push) Has been cancelled
Build Test / lint-backend (push) Waiting to run
**UX Improvements:**
- Progress modal: full-width inputs, label-as-heading, left-aligned text
- Progress button only visible for custom goals (no source_table)
- Prevents confusion with automatic tracking (Weight, Activity, etc.)

**New Page: Custom Goals (Capture/Eigene Ziele):**
- Dedicated page for daily custom goal value entry
- Clean goal selection with progress bars
- Quick entry form (date, value, note)
- Recent progress history (last 5 entries)
- Mobile-optimized for daily use

**Architecture:**
- Analysis/Goals → Strategic (define goals, set priorities)
- Capture/Custom Goals → Tactical (daily value entry)
- History → Evaluation (goal achievement analysis)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 15:32:15 +01:00
LarsandClaude Opus 4.6 398c645a98 feat: Goal Progress Log UI - complete frontend
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 0s
- Added Progress button (TrendingUp icon) to each goal card
- Created Progress Modal with:
  • Form to add new progress entry (date, value, note)
  • Historical entries list with delete option
  • Category-colored goal info header
  • Auto-disables manual delete for non-manual entries
- Integration complete: handlers → API → backend

Completes Phase 0a Progress Tracking (Migration 030 + Backend + Frontend)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 14:02:24 +01:00
LarsandClaude Opus 4.6 7db98a4fa6 feat: Goal Progress Log - backend + API (v2.1)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Implemented progress tracking system for all goals.

**Backend:**
- Migration 030: goal_progress_log table with unique constraint per day
- Trigger: Auto-update goal.current_value from latest progress
- Endpoints: GET/POST/DELETE /api/goals/{id}/progress
- Pydantic Models: GoalProgressCreate, GoalProgressUpdate

**Features:**
- Manual progress tracking for custom goals (flexibility, strength, etc.)
- Full history with date, value, note
- current_value always reflects latest progress entry
- One entry per day per goal (unique constraint)
- Cascade delete when goal is deleted

**API:**
- GET /api/goals/{goal_id}/progress - List all entries
- POST /api/goals/{goal_id}/progress - Log new progress
- DELETE /api/goals/{goal_id}/progress/{progress_id} - Delete entry

**Next:** Frontend UI (progress button, modal, history list)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 13:58:14 +01:00
LarsandClaude Opus 4.6 ce37afb2bb fix: Migration 029 - activate missing goal types (flexibility, strength)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 0s
These goal types existed but were inactive or misconfigured.

Uses UPSERT (INSERT ... ON CONFLICT DO UPDATE):
- If exists → activate + fix labels/icons/category
- If not exists → create properly

Idempotent: Safe to run multiple times, works on dev + prod.

Both types have no automatic data source (source_table = NULL),
so current_value must be updated manually.

Fixes: flexibility and strength goals not visible in admin

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 13:53:47 +01:00
LarsandClaude Opus 4.6 db90f397e8 feat: auto-assign goal category based on goal type
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Added intelligent category assignment:
- Weight, body_fat, lean_mass → Körper
- Strength, flexibility → Training
- BP, VO2Max, RHR, HRV → Gesundheit
- Sleep goals → Erholung
- Nutrition goals → Ernährung
- Unknown types → Sonstiges

Changes:
1. getCategoryForGoalType() mapping function
2. Auto-set category in handleGoalTypeChange()
3. Auto-set category in handleCreateGoal()

User can still manually change category if needed.

Fixes: Blood pressure goals wrongly categorized as 'Training'

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 13:09:34 +01:00
LarsandClaude Opus 4.6 498ad7a47f fix: show goal type label when name is empty
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 1s
Enhanced fallback chain for goal display:
1. goal.name (custom name if set)
2. goal.label_de (from backend JOIN)
3. typeInfo.label_de (from goalTypesMap)
4. goal.goal_type (raw key as last resort)

Also use goal.icon from backend if available.

Fixes: Empty goal names showing blank in list

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 12:51:24 +01:00
LarsandClaude Opus 4.6 9e95fd8416 fix: get_goals_grouped - remove is_active check (column doesn't exist)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
goals table doesn't have is_active column.
Removed AND g.is_active = true from WHERE clause.

Fixes: psycopg2.errors.UndefinedColumn: column g.is_active does not exist

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 12:45:03 +01:00
LarsandClaude Opus 4.6 ca4f722b47 fix: goal_utils - support different date column names
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 45s
Build Test / lint-backend (push) Successful in 0s
Fixed: column 'date' does not exist in blood_pressure_log

blood_pressure_log uses 'measured_at' instead of 'date'.
Added DATE_COLUMN_MAP for table-specific date columns:
- blood_pressure_log → measured_at
- fitness_tests → test_date
- all others → date

Replaced all hardcoded 'date' with dynamic date_col variable.

Fixes error: [ERROR] Failed to fetch value from blood_pressure_log.systolic

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 12:42:56 +01:00
LarsandClaude Opus 4.6 1c00238414 fix: get_goals_grouped - remove non-existent linear_projection column
Deploy Development / deploy (push) Successful in 52s
Build Test / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 0s
Fixed SQL error: column g.linear_projection does not exist
Replaced with: g.on_track, g.projection_date (actual columns)

This was causing Internal Server Error on /api/goals/grouped

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 12:41:06 +01:00
LarsandClaude Opus 4.6 448d19b840 fix: Migration 028 - remove is_active from index (column doesn't exist yet)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Migration 028 failed because goals table doesn't have is_active column yet.
Removed WHERE clause from index definition.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 12:36:58 +01:00
LarsandClaude Opus 4.6 caebc37da0 feat: goal categories UI - complete rebuild
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Completed frontend for multi-dimensional goal priorities.

**UI Changes:**
- Category-grouped goal display with color-coded headers
- Each category shows: icon, name, description, goal count
- Priority stars (⭐⭐⭐/⭐⭐/⭐) replace "PRIMÄR" badge
- Goals have category-colored left border
- Form fields: Category dropdown + Priority selector
- Removed "Gewichtung gesamt" display (useless UX)

**Categories:**
- 📉 Körper (body): Gewicht, Körperfett, Muskelmasse
- 🏋️ Training: Kraft, Frequenz, Performance
- 🍎 Ernährung: Kalorien, Makros, Essgewohnheiten
- 😴 Erholung: Schlaf, Regeneration, Ruhetage
- ❤️ Gesundheit: Vitalwerte, Blutdruck, HRV
- 📌 Sonstiges: Weitere Ziele

**Priority Levels:**
- ⭐⭐⭐ Hoch (1)
- ⭐⭐ Mittel (2)
- ⭐ Niedrig (3)

**Implementation:**
- Load groupedGoals via api.listGoalsGrouped()
- GOAL_CATEGORIES + PRIORITY_LEVELS constants
- handleEditGoal/handleSaveGoal/handleCreateGoal extended
- Backward compatible (is_primary still exists)

Next: Test migration + UI, then update Dashboard to show top-1 per category

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 12:33:17 +01:00
LarsandClaude Opus 4.6 6a3a782bff feat: goal categories and priorities - backend + API
Implemented multi-dimensional goal priorities (Option B).

**Backend Changes:**
- Migration 028: Added `category` + `priority` columns to goals table
- Auto-migration of existing goals to categories based on goal_type
- GoalCreate/GoalUpdate models extended with category + priority
- New endpoint: GET /api/goals/grouped (returns goals by category)
- Categories: body, training, nutrition, recovery, health, other
- Priorities: 1=high (⭐⭐⭐), 2=medium (⭐⭐), 3=low (⭐)

**API Changes:**
- Added api.listGoalsGrouped() binding

**Frontend (partial):**
- Added GOAL_CATEGORIES + PRIORITY_LEVELS constants
- Extended formData with category + priority fields
- Removed "Gewichtung gesamt" display (useless)
- Load groupedGoals in addition to flat goals list

Next: Complete frontend UI rebuild for category grouping

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 12:30:59 +01:00
LarsandClaude Opus 4.6 2f51b26418 fix: focus areas slider NaN values and validation
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Fixed multiple issues with relative weight sliders:
1. Sanitize focusData on load (ensure all 6 fields are numeric)
2. Sync focusTemp when clicking "Anpassen" button
3. Robust sum calculation filtering only *_pct fields
4. Convert NaN/undefined to 0 in all calculations
5. Safe Number() coercion before normalization

Fixes errors:
- "Gewichtung gesamt: NaN"
- "Input should be a valid integer, input: null"
- Prozent always showing 0%

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 12:20:01 +01:00
LarsandClaude Opus 4.6 92cc309489 feat: relative weight sliders for focus areas
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Improved UX for focus area configuration:
- Sliders now use relative weights (0-10) instead of percentages
- System automatically normalizes to percentages (sum=100%)
- Live preview shows "weight → percent%" (e.g., "5 → 50%")
- No more manual balancing required from user

User sets: Kraft=5, Ausdauer=3, Flexibilität=2
System calculates: 50%, 30%, 20%

Addresses user feedback: "Summe muss 100% sein" not user-friendly

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 12:10:56 +01:00
LarsandClaude Opus 4.6 1fdf91cb50 fix: Migration 027 - health mode missing dimensions
Deploy Development / deploy (push) Successful in 51s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Fixed health mode calculation to include all 6 dimensions.
Simplified CASE statements (single CASE instead of multiple additions).

Before: health mode only set flexibility (15%) + health (55%) = 70% ❌
After:  health mode sets all dimensions = 100% ✅
  - weight_loss: 5%
  - muscle_gain: 0%
  - strength: 10%
  - endurance: 20%
  - flexibility: 15%
  - health: 50%

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 10:56:53 +01:00
LarsandClaude Opus 4.6 80d57918ae fix: Migration 027 constraint violation - health mode sum
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Fixed health mode calculation in focus_areas migration.
Changed health_pct from 50 to 55 to ensure sum equals 100%.

Before: 0+0+10+20+15+50 = 95% (constraint violation)
After:  0+0+10+20+15+55 = 100% (valid)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 10:53:39 +01:00
Lars d97925d5a1 feat: Focus Areas Slider UI (Goal System v2.0 complete)
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Replaces single goal mode cards with weighted multi-focus system

UI Features:
- 6 sliders for focus dimensions (5% increments)
- Live sum calculation with visual feedback
- Validation: Sum must equal 100%
- Color-coded sliders per dimension
- Edit/Display mode toggle
- Shows derived values if not customized

UX Flow:
1. Default: Shows focus distribution (bars)
2. Click 'Anpassen': Shows sliders
3. Adjust percentages (sum = 100%)
4. Save → Updates backend + reloads

Visual:
- Active dimensions shown as colored cards (display mode)
- Gradient sliders with percentage labels (edit mode)
- Green box when sum = 100%, red when != 100%
- Info message if derived from old goal_mode

Complete v2.0:
✅ Backend (Migration 027, API, get_focus_weights V2)
✅ Frontend (Slider UI, state management, validation)
✅ Auto-migration (goal_mode → focus_areas)

Ready for: KI-Integration with weighted scoring
2026-03-27 10:36:42 +01:00
Lars 4a11d20c4d feat: Goal System v2.0 - Focus Areas with weighted priorities
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
BREAKING: Replaces single 'primary goal' with weighted multi-goal system

Migration 027:
- New table: focus_areas (6 dimensions with percentages)
- Constraint: Sum must equal 100%
- Auto-migration: goal_mode → focus_areas for existing users
- Unique constraint: One active focus_areas per profile

Backend:
- get_focus_weights() V2: Reads from focus_areas table
- Fallback: Uses goal_mode if focus_areas not set
- New endpoints: GET/PUT /api/goals/focus-areas
- Validation: Sum=100, range 0-100

API:
- getFocusAreas() - Get current weights
- updateFocusAreas(data) - Update weights (upsert)

Focus dimensions:
1. weight_loss_pct   (Fettabbau)
2. muscle_gain_pct   (Muskelaufbau)
3. strength_pct      (Kraftsteigerung)
4. endurance_pct     (Ausdauer)
5. flexibility_pct   (Beweglichkeit)
6. health_pct        (Allgemeine Gesundheit)

Benefits:
- Multiple goals with custom priorities
- More flexible than single primary goal
- KI can use weighted scores
- Ready for Phase 0b placeholder integration

UI: Coming in next commit (slider interface)
2026-03-27 08:38:03 +01:00
Lars 2303c04123 feat: filtered goal types - count specific training types
Deploy Development / deploy (push) Successful in 49s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
NEW FEATURE: Filter conditions for goal types
Enables counting/aggregating specific subsets of data.

Example use case: Count only strength training sessions per week
- Create goal type with filter: {"training_type": "strength"}
- count_7d now counts only strength training, not all activities

Implementation:
- Migration 026: filter_conditions JSONB column
- Backend: Dynamic WHERE clause building from JSON filters
- Supports single value: {"training_type": "strength"}
- Supports multiple values: {"training_type": ["strength", "hiit"]}
- Works with all 8 aggregation methods (count, avg, sum, min, max)
- Frontend: JSON textarea with example + validation
- Pydantic models: filter_conditions field added

Technical details:
- SQL injection safe (parameterized queries)
- Graceful degradation (invalid JSON ignored with warning)
- Backward compatible (NULL filters = no filtering)

Answers user question: 'Kann ich Trainingstypen wie Krafttraining separat zählen?'
Answer: YES! 🎯
2026-03-27 08:14:22 +01:00
Lars 2c978bf948 feat: dynamic schema dropdowns for goal type admin UI
Deploy Development / deploy (push) Successful in 50s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
Admin can now easily create custom goal types:
- New endpoint /api/goals/schema-info with table/column metadata
- 9 tables documented (weight, caliper, activity, nutrition, sleep, vitals, BP, rest_days, circumference)
- Table dropdown with descriptions (e.g., 'activity_log - Trainingseinheiten')
- Column dropdown dependent on selected table
- All columns documented in German with data types
- Fields optional (for complex calculation formulas)

UX improvements:
- No need to guess table/column names
- Clear descriptions for each field
- Type-safe selection (no typos)
- Cascading dropdowns (column depends on table)

Closes user feedback: 'Admin weiß nicht welche Tabellen/Spalten verfügbar sind'
2026-03-27 08:05:45 +01:00
Lars 210671059a debug: comprehensive error handling and logging for list_goals
Deploy Development / deploy (push) Successful in 45s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
- try-catch around entire endpoint
- try-catch for each goal progress update
- Detailed error logging with traceback
- Continue processing other goals if one fails
- Clear error message to frontend

This will show exact error location in logs.
2026-03-27 07:58:56 +01:00
Lars 1f4ee5021e fix: robust error handling in goal value fetcher
Deploy Development / deploy (push) Successful in 44s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 1s
Prevents crashes when:
- Goal types have NULL source_table/column (lean_mass, inactive placeholders)
- Old goals reference inactive goal types
- SQL queries fail for any reason

Changes:
- Guard clause checks table/column before SQL
- try-catch wraps all aggregation queries
- Returns None gracefully instead of crashing endpoint
- Logs warnings for debugging

Fixes: Goals page not loading due to /api/goals/list crash
2026-03-27 07:55:19 +01:00
Lars 1e758696fd feat: Migration 025 - automatic cleanup and seed for goal_type_definitions
Deploy Development / deploy (push) Successful in 46s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
Fixes cases where Migration 024 partially ran:
- Removes created_by/updated_by columns if they exist
- Re-inserts seed data with ON CONFLICT DO NOTHING
- Fully automated, no manual intervention needed
- Production-safe (idempotent)

This ensures clean deployment to production without manual DB changes.
2026-03-27 07:49:09 +01:00
Lars a039a0fad3 fix: Migration 024 - remove problematic FK constraints created_by/updated_by
Build Test / build-frontend (push) Waiting to run
Deploy Development / deploy (push) Has been cancelled
Build Test / lint-backend (push) Waiting to run
Goal type definitions are global system entities, not user-specific.
System types seeded in migration cannot have created_by FK.

Changes:
- Remove created_by/updated_by columns from goal_type_definitions
- Update CREATE/UPDATE endpoints to not use these fields
- Migration now runs cleanly on container start
- No manual intervention needed for production deployment
2026-03-27 07:48:23 +01:00
Lars b3cc588293 fix: make Migration 024 idempotent + add seed data fix script
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 1s
2026-03-27 07:40:42 +01:00
Lars c9e4b6aa02 debug: diagnostic script for Migration 024 state 2026-03-27 07:39:18 +01:00
LarsandClaude Opus 4.6 8be87bfdfb fix: Remove broken table_exists check
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Removed faulty EXISTS check that was causing "0" error.
Added debug logging and better error messages.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 07:34:29 +01:00
LarsandClaude Opus 4.6 484c25575d feat: manual migration 024 runner script
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Allows running Migration 024 manually if auto-migration failed.

Usage: python backend/run_migration_024.py

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 07:28:43 +01:00
LarsandClaude Opus 4.6 bbee44ecdc fix: Better error handling for goal types loading
Build Test / build-frontend (push) Waiting to run
Deploy Development / deploy (push) Has been cancelled
Build Test / lint-backend (push) Waiting to run
- Check if goal_type_definitions table exists
- Detailed error messages
- Fallback if goalTypes is empty
- Prevent form opening without types

Helps debugging Migration 024 issues.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 07:28:14 +01:00
LarsandClaude Opus 4.6 043bed4323 docs: Phase 1.5 complete - update roadmap
Deploy Development / deploy (push) Successful in 50s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Phase 1.5 (Flexible Goal System) erfolgreich abgeschlossen:
- 8h Aufwand (geplant 8-12h)
- Alle Tasks ✅
- System vollständig flexibel
- Phase 0b ready to start

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 06:52:18 +01:00
LarsandClaude Opus 4.6 640ef81257 feat: Phase 1.5 - Flexible Goal System (DB-Registry) Part 2/2 - COMPLETE
Build Test / build-frontend (push) Waiting to run
Build Test / lint-backend (push) Waiting to run
Deploy Development / deploy (push) Has been cancelled
Frontend dynamic goal types + Admin UI komplett implementiert.

Frontend GoalsPage:
- HARDCODED GOAL_TYPES entfernt
- Dynamic loading von goal_type_definitions via API
- goalTypes state + goalTypesMap für quick lookup
- Dropdown zeigt alle aktiven Types aus DB
- Vollständig flexibel - neue Types sofort verfügbar

Admin UI:
- AdminGoalTypesPage.jsx (400+ Zeilen)
  → Übersicht aller Goal Types (System + Custom)
  → Create/Edit/Delete Forms
  → CRUD via api.js (admin-only)
  → Validierung: System Types nur deaktivierbar, nicht löschbar
  → 8 Aggregationsmethoden im Dropdown
  → Category-Auswahl (body, mind, activity, nutrition, recovery, custom)
- Route registriert: /admin/goal-types
- Import in App.jsx

Phase 1.5 KOMPLETT:
✅ Migration 024 (goal_type_definitions)
✅ Universal Value Fetcher (goal_utils.py)
✅ CRUD API (goals.py)
✅ Frontend Dynamic Dropdown (GoalsPage.jsx)
✅ Admin UI (AdminGoalTypesPage.jsx)

System ist jetzt VOLLSTÄNDIG FLEXIBEL:
- Neue Goal Types via Admin UI ohne Code-Deploy
- Beispiele: Meditation, Trainingshäufigkeit, Planabweichung
- Phase 0b Platzhalter können alle Types nutzen
- Keine Doppelarbeit bei v2.0 Redesign

Nächster Schritt: Testing + Phase 0b (120+ Platzhalter)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 06:51:46 +01:00
LarsandClaude Opus 4.6 65ee5f898f feat: Phase 1.5 - Flexible Goal System (DB-Registry) Part 1/2
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 1s
KRITISCHE ARCHITEKTUR-ÄNDERUNG vor Phase 0b:
Ermöglicht dynamische Goal Types ohne Code-Änderungen.

Backend:
- Migration 024: goal_type_definitions Tabelle
  → 8 existierende Typen als Seed-Data migriert
  → Flexible Schema: source_table, aggregation_method, calculation_formula
  → System vs. Custom Types (is_system flag)
- goal_utils.py: Universal Value Fetcher
  → get_current_value_for_goal() ersetzt hardcoded if/elif chain
  → Unterstützt: latest, avg_7d, avg_30d, sum_30d, count_7d, etc.
  → Komplexe Formeln (lean_mass) via calculation_formula JSON
- goals.py: CRUD API für Goal Type Definitions
  → GET /goals/goal-types (public)
  → POST/PUT/DELETE /goals/goal-types (admin-only)
  → Schutz für System-Types (nicht löschbar)
- goals.py: _get_current_value_for_goal_type() delegiert zu Universal Fetcher

Frontend:
- api.js: 4 neue Funktionen (listGoalTypeDefinitions, create, update, delete)

Dokumentation:
- TODO_GOAL_SYSTEM.md: Phase 1.5 hinzugefügt, Roadmap aktualisiert

Part 2/2 (nächster Commit):
- Frontend: Dynamic Goal Types Dropdown
- Admin UI: Goal Type Management Page
- Testing

Warum JETZT (vor Phase 0b)?
- Phase 0b Platzhalter (120+) nutzen Goals für Score-Berechnungen
- Flexible Goals → automatisch in Platzhaltern verfügbar
- Später umbauen = Doppelarbeit (alle Platzhalter anpassen)

Zukünftige Custom Goals möglich:
- 🧘 Meditation (min/Tag)
- 📅 Trainingshäufigkeit (x/Woche)
- 📊 Planabweichung (%)
- 🎯 Ritual-Adherence (%)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 06:45:05 +01:00
LarsandClaude Opus 4.6 27a8af7008 debug: Add logging and warnings for Goal System issues
Deploy Development / deploy (push) Successful in 47s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Based on test feedback - 3 issues addressed:

1. Primary Toggle (Frontend Debug):
   - Add console.log in handleSaveGoal
   - Shows what data is sent to backend
   - Helps debug if checkbox state is correct

2. Lean Mass Display (Backend Debug):
   - Add error handling in lean_mass calculation
   - Log why calculation fails (missing weight/bf data)
   - Try-catch for value conversion errors

3. BP/Strength/Flexibility Warning (UI):
   - Yellow warning box for incomplete goal types
   - BP: "benötigt 2 Werte (geplant für v2.0)"
   - Strength/Flexibility: "Keine Datenquelle"
   - Transparent about limitations

Next: User re-tests with debug output to identify root cause.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 06:24:40 +01:00
LarsandClaude Opus 4.6 14d80fc903 docs: zentrale TODO-Liste für Goal System erstellt
Deploy Development / deploy (push) Successful in 51s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Tracking-Dokument für alle offenen Punkte:
- Phase 0b Tasks (120+ Platzhalter)
- v2.0 Redesign Probleme
- Gitea Issues Referenzen
- Timeline & Roadmap

Verhindert dass wichtige Punkte vergessen werden.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 06:17:57 +01:00
LarsandClaude Opus 4.6 87464ff138 fix: Phase 1 - Goal System Quick Fixes + Abstraction Layer
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 53s
Build Test / lint-backend (push) Successful in 0s
Behebt 4 kritische Bugs in Phase 0a und schafft Basis für Phase 0b
ohne spätere Doppelarbeit.

Backend:
- NEW: goal_utils.py mit get_focus_weights() Abstraction Layer
  → V1: Mappt goal_mode zu Gewichten
  → V2 (später): Liest aus focus_areas Tabelle
  → Phase 0b Platzhalter (120+) müssen NICHT umgeschrieben werden
- FIX: Primary goal toggle in goals.py (is_primary im GoalUpdate Model)
  → Beim Update auf primary werden andere Goals korrekt auf false gesetzt
- FIX: lean_mass current_value Berechnung implementiert
  → weight - (weight * body_fat_pct / 100)
- FIX: VO2Max Spaltenname vo2_max (statt vo2max)
  → Internal Server Error behoben

CLAUDE.md:
- Version Update: Phase 1 Fixes (27.03.2026)

Keine Doppelarbeit:
- Alle zukünftigen Phase 0b Platzhalter nutzen get_focus_weights()
- v2.0 Redesign = nur eine Funktion ändern, nicht 120+ Platzhalter

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 06:13:47 +01:00
LarsandClaude Opus 4.6 e3f1e399c2 docs: Goal System Redesign v2.0 - comprehensive concept
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
Created comprehensive redesign document addressing all identified issues:

Problems addressed:
1. Primary goal too simplistic → Weight system (0-100%)
2. Single goal mode too simple → Multi-mode with weights
3. Missing current values → All goal types with data sources
4. Abstract goal types → Concrete, measurable goals
5. Blood pressure single value → Compound goals (systolic/diastolic)
6. No user guidance → Norms, examples, age-specific values

New Concept:
- Focus Areas: Weighted distribution (30% weight loss + 25% endurance + ...)
- Goal Weights: Each goal has individual weight (not binary primary/not)
- Concrete Goal Types: cooper_test, pushups_max, squat_1rm, etc.
- Compound Goals: Support for multi-value targets (BP: 120/80)
- Guidance System: Age/gender-specific norms and examples

Schema Changes:
- New table: focus_areas (replaces single goal_mode)
- goals: Add goal_weight, target_value_secondary, current_value_secondary
- goals: Remove is_primary (replaced by weight)

UI/UX Redesign:
- Slider interface for focus areas (must sum to 100%)
- Goal editor with guidance and norms
- Weight indicators on all goals
- Special UI for compound goals

Implementation Phases: 16-21h total
- Phase 2: Backend Redesign (6-8h)
- Phase 3: Frontend Redesign (8-10h)
- Phase 4: Testing & Refinement (2-3h)

Status: WAITING FOR USER FEEDBACK & APPROVAL

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 22:05:05 +01:00
LarsandClaude Opus 4.6 3dd10d3dc7 docs: Phase 0a completion - comprehensive documentation
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
CLAUDE.md:
- Version updated to v9e+ (Phase 0a Goal System Complete)
- Added Phase 0a feature section with full details
- Updated 'Letzte Updates' with Phase 0a completion
- Links to new documentation files

docs/issues/issue-50-phase-0a-goal-system.md (NEW):
- Complete Phase 0a implementation documentation
- Technical details: Migration 022, goals.py, GoalsPage
- 4 commits documented (337667f to 5be52bc)
- Lessons learned section
- Basis for Phase 0b documented
- Testing checklist + acceptance criteria

docs/NEXT_STEPS_2026-03-26.md (NEW):
- Comprehensive planning document
- Option A: Issue #49 - Prompt Page Assignment (6-8h)
- Option B: Phase 0b - Goal-Aware Placeholders (16-20h)
- Option C: Issue #47 - Value Table Refinement (4-6h)
- Recommendation: Szenario 1 (Quick Wins first)
- Detailed technical breakdown for both options
- Timeline estimates (4h/day vs 8h/day)
- 120+ placeholder categorization for Phase 0b

All documentation reflects current state post Phase 0a.
Next decision: Choose between Issue #49 or Phase 0b.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 21:49:07 +01:00
LarsandClaude Opus 4.6 5be52bcfeb feat: goals navigation + UX improvements
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Analysis Page:
- Add 'Ziele' button next to page title
- Direct navigation to /goals from analysis page
- Thematic link: goals influence AI analysis weighting

Goals Page:
- Fix text-align for text inputs (name, date, description)
- Text fields now left-aligned (numbers remain right-aligned)
- Better UX for non-numeric inputs

Navigation strategy: Goals accessible from Analysis page where
goal_mode directly impacts score calculation and interpretation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 16:50:22 +01:00
LarsandClaude Opus 4.6 75f0a5dd6e refactor: mobile-friendly goal form design
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
- Full-width inputs throughout the form
- Labels above inputs (mobile best practice)
- Section headers with emoji (🎯 Zielwert)
- Consistent spacing (marginBottom: 16)
- Read-only unit display as styled badge
- Primary goal checkbox in highlighted section
- Full-width buttons (btn-full class)
- Scrollable modal with top padding
- Error display above form

Matches VitalsPage design pattern for consistency.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 16:32:37 +01:00
LarsandClaude Opus 4.6 906a3b7cdd fix: Migration 022 - remove invalid schema_migrations tracking
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
The migration system tracks migrations via filename automatically.
Removed manual DO block that used wrong column name (version vs filename).

Also removed unused json import from goals.py.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 16:26:48 +01:00
LarsandClaude Opus 4.6 337667fc07 feat: Phase 0a - Minimal Goal System (Strategic + Tactical)
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
- Strategic Layer: Goal modes (weight_loss, strength, endurance, recomposition, health)
- Tactical Layer: Concrete goal targets with progress tracking
- Training phases (manual + auto-detection framework)
- Fitness tests (standardized performance tracking)

Backend:
- Migration 022: goal_mode in profiles, goals, training_phases, fitness_tests tables
- New router: routers/goals.py with full CRUD for goals, phases, tests
- API endpoints: /api/goals/* (mode, list, create, update, delete)

Frontend:
- GoalsPage: Goal mode selector + goal management UI
- Dashboard: Goals preview card with link
- API integration: goal mode, CRUD operations, progress calculation

Basis for 120+ placeholders and goal-aware analyses (Phase 0b)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 16:20:35 +01:00
Lars ae93b9d428 docs: goal system priority analysis - hybrid approach
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Key Decision: Minimal Goal System BEFORE Placeholders

Critical Finding:
- Same data = different interpretation per goal
- Example: -5kg FM, -2kg LBM
  - weight_loss: 78/100 (good!)
  - strength: 32/100 (LBM loss critical!)
  - Without goal: 50/100 (generic, wrong for both)

Recommended Approach (Hybrid):
1. Phase 0a (2-3h): Minimal Goal System
   - DB: goal_mode field
   - API: Get/Set Goal
   - UI: Goal Selector
   - Default: health

2. Phase 0b (16-20h): Goal-Aware Placeholders
   - 84 placeholders with goal-dependent calculations
   - Scores use goal_mode from day 1
   - No rework needed later

3. Phase 2+ (6-8h): Full Goal System
   - Goal recognition from patterns
   - Secondary goals
   - Goal progression tracking

Why Hybrid Works:
✅ Charts show correct interpretations immediately
✅ No rework of 84 placeholders later
✅ Goal recognition can come later (needs placeholders anyway)
✅ System is "smart coach" from day 1

File: docs/GOAL_SYSTEM_PRIORITY_ANALYSIS.md (650 lines)
2026-03-26 16:08:00 +01:00
Lars 8398368ed7 docs: comprehensive functional concept analysis
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Analysis Results:
- 84 new placeholders needed from Fachkonzept
- Issues #26 & #27 too narrow (complementary, not conflicting)
- Recommend 4-phase approach: Placeholders → Charts → Rules → KI
- Transform: Data Collector → Active Coach

Key Findings:
- Fachkonzept defines 3 levels (Deskriptiv, Diagnostisch, Präskriptiv)
- 18 dedicated charts (K1-K5, E1-E5, A1-A8, C1-C6)
- Goal-mode dependent interpretation
- Lag-based correlations mandatory
- Confidence & data quality essential

Recommended Actions:
- Create Issues #52-55 (Baseline, Scores, Correlations, Metrics)
- Expand #26 & #27 based on Fachkonzept
- Start Phase 0: Implement 84 placeholders

File: docs/KONZEPT_ANALYSE_2026-03-26.md (385 lines)
2026-03-26 15:26:12 +01:00
Lars cd2609da7c feat: Feature Request #49 - Prompt-Zuordnung zu Verlaufsseiten
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
UX Enhancement: Kontextbezogene KI-Analysen

Features:
- Prompts auf Verlaufsseiten verfügbar machen
- Mehrfachauswahl: Prompt auf mehreren Seiten
- Inline-Analyse via Modal
- Wiederverwendbare PagePrompts Komponente

Technisch:
- DB: available_on JSONB column
- API: GET /api/prompts/for-page/{page_slug}
- UI: Page-Auswahl im Prompt-Editor

Aufwand: 6-8h, Priority: Medium
Gitea: Issue #49
2026-03-26 15:12:39 +01:00
Lars 39db23d417 docs: comprehensive status report 26.03.2026
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
Audit Results:
- 2 Issues closed: #28 (AI-Prompts), #44 (Delete bug)
- 1 Issue created: #47 (Value Table Refinement)
- 12 commits today, 3 major features completed
- All documentation synchronized with Gitea

Next: Testing on dev, then Production deployment
2026-03-26 14:53:45 +01:00
Lars 582f125897 docs: comprehensive status update and Gitea sync
Build Test / build-frontend (push) Has been cancelled
Deploy Development / deploy (push) Successful in 57s
Build Test / lint-backend (push) Successful in 0s
Updates:
- Clarify Gitea issue references (prefix with 'Gitea #')
- Mark #28 (AI-Prompts) as CLOSED
- Mark #44 (Delete insights) as CLOSED
- Update #47 reference (Wertetabelle Optimierung)
- Add 'Letzte Updates' section for 26.03.2026
- Document Issue-Management responsibility

Gitea Actions:
- Closed Issue #28 with completion comment
- Closed Issue #44 with fix details
- Created Issue #47 (Wertetabelle Optimierung)
2026-03-26 14:52:44 +01:00
Lars f46c367c27 Merge pull request 'Flexibles KI Prompt System' (#48) from develop into main
Deploy Production / deploy (push) Successful in 50s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
Reviewed-on: #48
2026-03-26 14:49:47 +01:00
Lars 21bdd9f2ba docs: add Claude Code responsibilities section
Deploy Development / deploy (push) Successful in 43s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
- Issue-Management via Gitea API
- Dokumentation pflegen
- Entwicklungs-Workflow
2026-03-26 14:46:20 +01:00
Lars 713f7475c9 docs: create Issue #50 - Value Table Refinement
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 0s
- Normal-Modus: Nur Einzelwerte (übersichtlich)
- Experten-Modus: Zusätzlich Stage-Rohdaten
- Beschreibungen für alle Platzhalter vervollständigen
- Schema-basierte Beschreibungen für extrahierte Werte

Aufwand: 4-6h, Priority: Medium
2026-03-26 14:43:23 +01:00
Lars 6e651b5bb5 fix: include stage outputs in debug info for value table
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 45s
Build Test / lint-backend (push) Successful in 0s
- stage_debug now includes 'output' dict with all stage outputs
- Fixes empty values for stage_X_outputkey in expert mode
- Stage outputs are the actual AI responses passed to next stage
2026-03-26 14:33:00 +01:00
Lars f37936c84d feat: show all stage outputs as collapsible JSON in expert mode
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 0s
Backend:
- Add ALL stage outputs to metadata (not just referenced ones)
- Format JSON with indent for readability
- Description: 'Zwischenergebnis aus Stage X'

Frontend:
- Stage raw values shown in collapsible <details> element
- JSON formatted in <pre> tag with syntax highlighting
- 'JSON anzeigen ▼' summary for better UX

Fixes: Stage X - Rohdaten now shows intermediate results
2026-03-26 13:17:58 +01:00
Lars 159fcab17a feat: circ_summary with best-of-each strategy and age annotations
Deploy Development / deploy (push) Successful in 42s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
- Each circumference point shows most recent value (even from different dates)
- Age annotations: heute, gestern, vor X Tagen/Wochen/Monaten
- Gives AI better context about measurement freshness
- Example: 'Brust 105cm (heute), Nacken 38cm (vor 2 Wochen)'
2026-03-26 13:09:38 +01:00
Lars d06d3d84de fix: circ_summary now checks all 8 circumference points
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
- Previously only checked c_chest, c_waist, c_hip
- Now includes c_neck, c_belly, c_thigh, c_calf, c_arm
- Fixes 'keine Daten' when entries exist with only non-primary measurements
2026-03-26 13:06:37 +01:00
Lars b0f80e0be7 docs: document Issue #47 completion in CLAUDE.md
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
- Added comprehensive documentation for Value Table feature
- Expert mode, category grouping, stage output extraction
- Updated version header to reflect #28 and #47 completion
2026-03-26 13:03:49 +01:00
Lars adb5dcea88 feat: category grouping in value table (Issue #47)
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 0s
FEATURE: Gruppierung nach Kategorien
- Wertetabelle jetzt nach Modulen/Kategorien gruppiert
- Bessere Übersicht und Zuordnung der Werte

BACKEND: Category Metadata
- Für normale Platzhalter: Kategorie aus Catalog (Profil, Körper, Ernährung, etc.)
- Für extrahierte Werte: "Stage X - [Output Name]"
- Für Rohdaten: "Stage X - Rohdaten"
- Fallback: "Sonstiges"

FRONTEND: Grouped Display
- sortedCategories: Sortierung (Normal → Stage Outputs → Rohdaten)
- Section Headers: Grauer Hintergrund mit Kategorie-Name
- React.Fragment für Gruppierung

SORTIERUNG:
1. Normale Kategorien (Profil, Körper, Ernährung, Training, etc.)
2. Stage Outputs (Stage 1 - Body, Stage 1 - Nutrition, etc.)
3. Rohdaten (Stage 1 - Rohdaten, Stage 2 - Rohdaten)
4. Innerhalb: Alphabetisch

BEISPIEL:
┌────────────────────────────────────────────┐
│ PROFIL                                     │
├────────────────────────────────────────────┤
│ name       │ Lars    │ Name des Nutzers   │
│ age        │ 55      │ Alter in Jahren    │
├────────────────────────────────────────────┤
│ KÖRPER                                     │
├────────────────────────────────────────────┤
│ weight_... │ 85.2 kg │ Aktuelles Gewicht  │
│ bmi        │ 26.6    │ Body Mass Index    │
├────────────────────────────────────────────┤
│ ERNÄHRUNG                                  │
├────────────────────────────────────────────┤
│ kcal_avg   │ 1427... │ Durchschn. Kalorien│
│ protein... │ 106g... │ Durchschn. Protein │
├────────────────────────────────────────────┤
│ STAGE 1 - BODY                             │
├────────────────────────────────────────────┤
│ ↳ bmi      │ 26.6    │ Aus Stage 1 (body) │
│ ↳ trend    │ sinkend │ Aus Stage 1 (body) │
├────────────────────────────────────────────┤
│ STAGE 1 - NUTRITION                        │
├────────────────────────────────────────────┤
│ ↳ kcal_... │ 1427    │ Aus Stage 1 (nutr.)│
└────────────────────────────────────────────┘

Experten-Modus zusätzlich:
├────────────────────────────────────────────┤
│ STAGE 1 - ROHDATEN                         │
├────────────────────────────────────────────┤
│ 🔬 stage...│ {"bmi"..│ Rohdaten Stage 1   │
└────────────────────────────────────────────┘

version: 9.10.0 (feature)
module: prompts 2.5.0, insights 1.8.0
2026-03-26 12:59:52 +01:00
Lars da803da816 feat: extract individual values from stage outputs (Issue #47)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
FEATURE: Basis-Analysen Einzelwerte
Vorher: stage_1_body → {"bmi": 26.6, "weight": "85.2kg"} (1 Zeile)
Jetzt:  bmi → 26.6 (eigene Zeile)
        weight → 85.2kg (eigene Zeile)

BACKEND: JSON-Extraktion
- Stage outputs (JSON) → extract individual fields
- extracted_values dict sammelt alle Einzelwerte
- Deduplizierung: Gleiche Keys nur einmal
- Flags:
  - is_extracted: true → Wert aus Stage-Output extrahiert
  - is_stage_raw: true → Rohdaten (JSON) nur Experten-Modus

BEISPIEL Stage 1 Output:
{
  "stage_1_body": {
    "bmi": 26.6,
    "weight": "85.2 kg",
    "trend": "sinkend"
  }
}

→ Metadata:
{
  "bmi": {
    value: "26.6",
    description: "Aus Stage 1 (stage_1_body)",
    is_extracted: true
  },
  "weight": {
    value: "85.2 kg",
    description: "Aus Stage 1 (stage_1_body)",
    is_extracted: true
  },
  "stage_1_body": {
    value: "{\"bmi\": 26.6, ...}",
    description: "Rohdaten Stage 1 (Basis-Analyse JSON)",
    is_stage_raw: true
  }
}

FRONTEND: Smart Filtering
Normal-Modus:
- Zeigt: Einzelwerte (bmi, weight, trend)
- Versteckt: Rohdaten (stage_1_body JSON)
- Filter: is_stage_raw === false

Experten-Modus:
- Zeigt: Alles (Einzelwerte + Rohdaten)
- Rohdaten: Grauer Hintergrund + 🔬 Icon

VISUAL Indicators:
↳ bmi        → Extrahierter Wert (grün)
  weight     → Normaler Platzhalter (accent)
🔬 stage_1_* → Rohdaten JSON (grau, klein, nur Experten)

ERGEBNIS:
┌──────────────────────────────────────────┐
│ 📊 Verwendete Werte (8) (+2 ausgeblendet)│
│ ┌────────────────────────────────────────┐│
│ │ weight_aktuell │ 85.2 kg   │ Gewicht ││ ← Normal
│ │ ↳ bmi          │ 26.6      │ Aus St..││ ← Extrahiert
│ │ ↳ trend        │ sinkend   │ Aus St..││ ← Extrahiert
│ └────────────────────────────────────────┘│
└──────────────────────────────────────────┘

Experten-Modus zusätzlich:
│ 🔬 stage_1_body │ {"bmi":...│ Rohdaten││ ← JSON

version: 9.9.0 (feature)
module: prompts 2.4.0, insights 1.7.0
2026-03-26 12:55:53 +01:00
Lars e799edbae4 feat: expert mode + stage outputs in value table (Issue #47)
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
FEATURE: Experten-Modus 🔬
- Toggle-Button in Wertetabelle
- Normal: Nur gefüllte Werte anzeigen
- Experten: Alle Platzhalter inkl. leere/technische
- Anzeige: "(+X ausgeblendet)" wenn Werte gefiltert
- Button-Style: Accent wenn aktiv

FILTER: Leere Werte ausblenden (Normal-Modus)
- Filtert: '', 'nicht verfügbar', '[Nicht verfügbar]'
- Zeigt nur relevante Nutzer-Daten
- Experten-Modus zeigt alles

FEATURE: Stage-Outputs in Wertetabelle ✅
ROOT CAUSE: stage_N_key Platzhalter hatten keine Werte
- Stage-Outputs (z.B. stage_1_body) sind Basis-Analysen-Ergebnisse
- Wurden nicht in cleaned_values gefunden (nur statische Platzhalter)
FIX:
- Collect stage outputs aus result.debug.stages[].output
- Store als stage_N_key dict
- Lookup: erst stage_outputs, dann cleaned_values
- Description: "Output aus Stage X (Basis-Analyse)"
- JSON-Werte automatisch serialisiert

BEISPIEL Pipeline-Wertetabelle:
┌──────────────────────────────────────────────┐
│ 📊 Verwendete Werte (8) (+3 ausgeblendet) 🔬│
│ ┌──────────────────────────────────────────┐ │
│ │ weight_aktuell  │ 85.2 kg   │ Gewicht  │ │
│ │ stage_1_body    │ {"bmi":...│ Output...│ │ ← Stage output!
│ │ stage_1_nutr... │ {"kcal"...│ Output...│ │
│ └──────────────────────────────────────────┘ │
└──────────────────────────────────────────────┘

AKTIVIERUNG Experten-Modus:
1. Analyse öffnen
2. "📊 Verwendete Werte" aufklappen
3. Button "🔬 Experten-Modus" klicken
4. Zeigt alle Platzhalter (auch leere stage outputs)

version: 9.8.0 (feature)
module: prompts 2.3.0, insights 1.6.0
2026-03-26 12:44:28 +01:00
Lars 15bd6cddeb feat: untruncated values + smart base prompt display (Issue #47)
Deploy Development / deploy (push) Successful in 43s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
FEATURE: Volle Werte (nicht abgeschnitten)
- Backend holt ungekürzten Werte direkt von placeholder_resolver
- get_placeholder_example_values() statt debug.resolved_placeholders
- Debug bleibt gekürzt (100 chars), Metadata ungekürzt

FEATURE: Smart Display für Basis-Prompts
- Basis-Prompts mit JSON-Output: Nur Wertetabelle anzeigen
- JSON-Output in Collapsible "Technische Daten" verschoben
- Wertetabelle auto-expanded bei Basis-Prompts
- Pipeline + Text-Prompts: Wie bisher (Content + Wertetabelle)

UI: Bessere Wertetabelle
- Werte: word-break + max-width (400px) → kein Overflow
- Alle Spalten: verticalAlign top für bessere Lesbarkeit
- Platzhalter: nowrap (keine Umbrüche)

BEISPIEL:
┌─────────────────────────────────────────┐
│ ℹ️ Basis-Prompt Rohdaten                │
│ [Technische Daten anzeigen ▼]           │
│                                          │
│ 📊 Verwendete Werte (8) ▼  ← expanded  │
│ ┌──────────────────────────────────────┐│
│ │ Platzhalter │ Vollständiger Wert... ││
│ │ kcal_avg    │ 1427 kcal/Tag (Ø 30...││ ← ungekürzt
│ └──────────────────────────────────────┘│
└─────────────────────────────────────────┘

version: 9.7.0 (feature)
module: prompts 2.2.0, insights 1.5.0
2026-03-26 12:37:52 +01:00
Lars 19414614bf fix: add metadata to newResult for immediate value table display
Deploy Development / deploy (push) Successful in 50s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
BUG: Wertetabelle wurde nicht angezeigt bei neuer Analyse
ROOT CAUSE: newResult hatte nur {scope, content}, kein metadata
FIX: Build metadata from result.debug.resolved_placeholders
- Für Base: direkt aus resolved_placeholders
- Für Pipeline: collect aus allen stages
- Metadata structure: {prompt_type, placeholders: {key: {value, description}}}

NOTE: Immediate preview hat keine descriptions (nur values)
Saved insights (nach loadAll) haben full metadata with descriptions aus DB

version: 9.6.2 (bugfix)
2026-03-26 12:29:05 +01:00
Lars 4a2bebe249 fix: value table metadata + |d modifier + cursor insertion (Issues #47, #48)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 0s
BUG: Wertetabelle wurde nicht angezeigt
FIX: enable_debug=true wenn save=true (für metadata collection)
- metadata wird nur gespeichert wenn debug aktiv
- jetzt: debug or save → metadata immer verfügbar

BUG: {{placeholder|d}} Modifier funktionierte nicht
ROOT CAUSE: catalog wurde bei Exception nicht zu variables hinzugefügt
FIX:
- variables['_catalog'] = catalog (auch wenn None)
- Warning-Log wenn catalog nicht geladen werden kann
- Debug warning wenn |d ohne catalog verwendet

BUG: Platzhalter in Pipeline-Stages am Ende statt an Cursor
FIX:
- stageTemplateRefs Map für alle Stage-Textareas
- onClick + onKeyUp tracking für Cursor-Position
- Insert at cursor: template.slice(0, pos) + placeholder + template.slice(pos)
- Focus + Cursor restore nach Insert

TECHNICAL:
- prompt_executor.py: Besseres Exception Handling für catalog
- UnifiedPromptModal.jsx: Refs für alle Template-Felder
- prompts.py: enable_debug=debug or save

version: 9.6.1 (bugfix)
module: prompts 2.1.1
2026-03-26 12:04:20 +01:00
Lars c0a50dedcd feat: value table + {{placeholder|d}} modifier (Issue #47)
Build Test / build-frontend (push) Successful in 15s
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
FEATURE #47: Wertetabelle nach KI-Analysen
- Migration 021: metadata JSONB column in ai_insights
- Backend sammelt resolved placeholders mit descriptions beim Speichern
- Frontend: Collapsible value table in InsightCard
  - Zeigt: Platzhalter | Wert | Beschreibung
  - Sortiert tabellarisch
  - Funktioniert für base + pipeline prompts

FEATURE #48: {{placeholder|d}} Modifier
- Syntax: {{weight_aktuell|d}} → "85.2 kg (Aktuelles Gewicht in kg)"
- resolve_placeholders() erkennt |d modifier
- Hängt description aus catalog an Wert
- Fein-granulare Kontrolle pro Platzhalter (nicht global)
- Optional: nur wo sinnvoll einsetzen

TECHNICAL:
- prompt_executor.py: catalog parameter durchgereicht
- execute_prompt_with_data() lädt catalog via get_placeholder_catalog()
- Catalog als _catalog in variables übergeben, in execute_prompt() extrahiert
- Base + Pipeline Prompts unterstützen |d modifier

EXAMPLE:
Template: "Gewicht: {{weight_aktuell|d}}, Alter: {{age}}"
Output:   "Gewicht: 85.2 kg (Aktuelles Gewicht in kg), Alter: 55"

version: 9.6.0 (feature)
module: prompts 2.1.0, insights 1.4.0
2026-03-26 11:52:26 +01:00
Lars c56d2b2201 fix: delete insights + placeholder cursor insertion (Issue #44)
BUG #44: Analysen löschen schlug fehl (kein Auth-Token)
FIX:
- api.deleteInsight() in api.js hinzugefügt
- Analysis.jsx nutzt jetzt api.js mit Error-Handling
- Nicht mehr raw fetch() ohne Token

BUG: Platzhalter wurden am Ende eingefügt statt an Cursor-Position
FIX:
- useRef für baseTemplateRef hinzugefügt
- Cursor-Position tracking (onClick + onKeyUp)
- Insert at cursor: template.slice(0, pos) + placeholder + template.slice(pos)
- Focus + Cursor-Position nach Insert wiederhergestellt

version: 9.5.2 (bugfix)
module: prompts 2.0.2, insights 1.3.1
2026-03-26 11:40:19 +01:00
Lars 7daa2e40c7 fix: sleep quality calculation using wrong key (stage vs phase)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
BUG: sleep_avg_quality showed 0% despite valid sleep data
ROOT CAUSE: sleep_segments use 'phase' key, not 'stage'
FIX: Changed s.get('stage') to s.get('phase') in get_sleep_avg_quality()

version: 9.5.1 (bugfix)
module: prompts 2.0.1
2026-03-26 10:31:39 +01:00
Lars ae6bd0d865 docs: Issue #28 completion documentation (v9e)
- Marked Issue #28 as complete
- Documented all 4 original phases
- Documented debug tools added 26.03.2026
- Documented placeholder enhancements (6 new functions, 7 reconstructed)
- Documented bug fixes (PIPELINE_MASTER, SQL columns, type errors)
- Listed related Gitea issues (#43, #44, #45, #46)
- Updated version status to v9e Ready for Production

version: 9.5.0 (documentation update)
2026-03-26 10:28:42 +01:00
LarsandClaude Opus 4.6 a43a9f129f fix: sleep_avg_quality uses lowercase stage names
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 1s
Problem: Schlafphasen werden lowercase gespeichert (deep, rem, light, awake),
aber get_sleep_avg_quality() prüfte Titlecase (Deep, REM) → 0% Match

Fix: Ändere Prüfung zu lowercase: ['deep', 'rem']

Jetzt wird {{sleep_avg_quality}} korrekt berechnet aus JSONB segments.

Quelle: backend/routers/sleep.py → phase_map speichert lowercase

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 10:22:55 +01:00
LarsandClaude Opus 4.6 3ad1a19dce fix: calculate_age now handles PostgreSQL date objects
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Problem: dob Spalte ist DATE (PostgreSQL) → Python bekommt datetime.date,
nicht String → strptime() schlägt fehl → age = "unbekannt"

Fix: Prüfe isinstance(dob, str) und handle beide Typen:
- String → strptime()
- date object → direkt verwenden

Jetzt funktioniert {{age}} Platzhalter korrekt.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 10:19:36 +01:00
LarsandClaude Opus 4.6 a9114bc40a feat: implement missing placeholder functions (sleep, vitals, rest)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Implementiert 6 fehlende Platzhalter-Funktionen die im Katalog waren
aber keine Berechnung hatten.

Neue Funktionen:
- get_sleep_avg_duration(7d) → "7.5h"
- get_sleep_avg_quality(7d) → "65% (Deep+REM)"
- get_rest_days_count(30d) → "5 Ruhetage"
- get_vitals_avg_hr(7d) → "58 bpm"
- get_vitals_avg_hrv(7d) → "45 ms"
- get_vitals_vo2_max() → "42.5 ml/kg/min"

Datenquellen:
- sleep_log (JSONB segments mit Deep/REM/Light/Awake)
- rest_days (Kraft/Cardio/Entspannung)
- vitals_baseline (resting_hr, hrv, vo2_max)

Jetzt in PLACEHOLDER_MAP registriert → sofort nutzbar.

Fixes: Platzhalter-Export zeigt jetzt alle Werte (statt "nicht verfügbar")

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 10:14:17 +01:00
LarsandClaude Opus 4.6 555ff62b56 feat: global placeholder export with values (Settings page)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 45s
Build Test / lint-backend (push) Successful in 0s
Zentraler Export aller verfügbaren Platzhalter mit aktuellen Werten.

Backend:
- GET /api/prompts/placeholders/export-values
  - Returns all placeholders organized by category
  - Includes resolved values for current profile
  - Includes metadata (description, example)
  - Flat list + categorized structure

Frontend SettingsPage:
- Button "📊 Platzhalter exportieren"
- Downloads: placeholders-{profile}-{date}.json
- Shows all 38+ placeholders with current values
- Useful for:
  - Understanding available data
  - Debugging prompt templates
  - Verifying placeholder resolution

Frontend api.js:
- exportPlaceholderValues()

Export Format:
{
  "export_date": "2026-03-26T...",
  "profile_id": "...",
  "count": 38,
  "all_placeholders": { "name": "Lars", ... },
  "placeholders_by_category": {
    "Profil": [...],
    "Körper": [...],
    ...
  }
}

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 10:05:11 +01:00
LarsandClaude Opus 4.6 7f94a41965 feat: batch import/export for prompts (Issue #28 Debug B)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 0s
Dev→Prod Sync in 2 Klicks: Export → Import

Backend:
- GET /api/prompts/export-all → JSON mit allen Prompts
- POST /api/prompts/import?overwrite=true/false → Import + Create/Update
  - Returns: created, updated, skipped counts
  - Validates JSON structure
  - Handles stages JSON conversion

Frontend AdminPromptsPage:
- Button "📦 Alle exportieren" → downloads all-prompts-{date}.json
- Button "📥 Importieren" → file upload dialog
  - User-Prompt: Überschreiben? Ja/Nein
  - Success-Message mit Statistik (created/updated/skipped)

Frontend api.js:
- exportAllPrompts()
- importPrompts(data, overwrite)

Use Cases:
1. Backup: Prompts als JSON sichern
2. Dev→Prod: Auf dev.mitai entwickeln → exportieren → auf mitai.jinkendo importieren
3. Versionierung: Prompts in Git speichern

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 09:44:08 +01:00
LarsandClaude Opus 4.6 8b287ca6c9 feat: export all placeholders from debug viewer (Issue #28 Debug A)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Added "📋 Platzhalter exportieren" button in debug viewer:
- Exports all resolved placeholders with values
- Includes all available_variables
- For pipelines: exports per-stage placeholder data
- JSON format with timestamp and prompt metadata
- Filename: placeholders-{slug}-{date}.json

Use case: Development aid - see exactly what data is available
for prompt templates without null values.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 09:40:26 +01:00
LarsandClaude Opus 4.6 97e57481f9 fix: Analysis page now uses unified prompt executor (Issue #28)
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
BREAKING: Analysis page switched from old /insights/run to new /prompts/execute

Changes:
- Backend: Added save=true parameter to /prompts/execute
  - When enabled, saves final output to ai_insights table
  - Extracts content from pipeline output (last stage)
- Frontend api.js: Added save parameter to executeUnifiedPrompt()
- Frontend Analysis.jsx: Switched from api.runInsight() to api.executeUnifiedPrompt()
  - Transforms new result format to match InsightCard expectations
  - Pipeline outputs properly extracted and displayed

Fixes: PIPELINE_MASTER responses (old template being sent to AI)
The old /insights/run endpoint used raw template field, which for the
legacy "pipeline" prompt was literally "PIPELINE_MASTER". The new
executor properly handles stages and data processing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 09:38:58 +01:00
LarsandClaude Opus 4.6 811ba8b3dc fix: convert Decimal to float before multiplication in protein targets
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
- get_protein_ziel_low: float(weight) * 1.6
- get_protein_ziel_high: float(weight) * 2.2

Fixes TypeError: unsupported operand type(s) for *: 'decimal.Decimal' and 'float'

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 09:23:50 +01:00
LarsandClaude Opus 4.6 b90c738fbb fix: make test button always visible in prompt editor
Build Test / build-frontend (push) Successful in 22s
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
- Removed conditional hiding of test button (prompt?.slug)
- Button now always visible with helpful tooltip
- handleTest already has save-check logic

Improves discoverability of test functionality.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 09:16:59 +01:00
LarsandClaude Opus 4.6 dfaf24d74c fix: correct SQL column names in placeholder_resolver
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
- caliper_summary: use body_fat_pct (not bf_jpl)
- circ_summary: use c_chest, c_waist, c_hip (not brust, taille, huefte)
- get_latest_bf: use body_fat_pct for consistency

Fixes SQL errors when running base prompts that feed pipeline prompts.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 09:10:55 +01:00
LarsandClaude Opus 4.6 0f2b85c6de fix: reconstruct missing placeholders + fix SQL column names
Deploy Development / deploy (push) Successful in 46s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Added missing placeholders:
- caliper_summary, circ_summary (body measurements)
- goal_weight, goal_bf_pct (goals from profile)
- nutrition_days (count of nutrition entries)
- protein_ziel_low/high (calculated from weight)

Fixed SQL errors:
- protein → protein_g
- fat → fat_g
- carb → carbs_g

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 09:03:35 +01:00
LarsandClaude Opus 4.6 f4d1fd4de1 feat: add activity_detail placeholder for detailed activity logs
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
- New placeholder: {{activity_detail}} returns formatted activity log
- Shows last 20 activities with date, type, duration, kcal, HR
- Makes activity analysis prompts work properly

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 08:20:18 +01:00
LarsandClaude Opus 4.6 ba92d66880 fix: remove {{ }} from placeholder keys before resolution
Build Test / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 1s
Placeholder resolver returns keys with {{ }} wrappers,
but resolve_placeholders expects clean keys.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 08:17:22 +01:00
LarsandClaude Opus 4.6 afc70b5a95 fix: integrate placeholder resolver + JSON unwrapping (Issue #28)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
- Backend: integrate get_placeholder_example_values in execute_prompt_with_data
- Backend: now provides BOTH raw data AND processed placeholders
- Backend: unwrap Markdown-wrapped JSON (```json ... ```)
- Fixes old-style prompts that expect name, weight_trend, caliper_summary

Resolves unresolved placeholders issue.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 08:14:41 +01:00
LarsandClaude Opus 4.6 84dad07e15 fix: show debug info on errors + prompt export function
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 1s
- Frontend: debug viewer now shows even when test fails
- Frontend: export button to download complete prompt config as JSON
- Backend: attach debug info to JSON validation errors
- Backend: include raw output and length in error details

Users can now debug failed prompts and export configs for analysis.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 08:07:34 +01:00
LarsandClaude Opus 4.6 7f2ba4fbad feat: debug system for prompt execution (Issue #28)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
- Backend: debug mode in prompt_executor with placeholder tracking
- Backend: show resolved/unresolved placeholders, final prompts, AI responses
- Frontend: test button in UnifiedPromptModal for saved prompts
- Frontend: debug output viewer with JSON preview
- Frontend: wider placeholder example fields in PlaceholderPicker

Resolves pipeline execution debugging issues.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 08:01:33 +01:00
LarsandClaude Opus 4.6 4ba03c2a94 feat: Analysis page pipeline-only + wider placeholder examples (Issue #28)
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 1s
- PlaceholderPicker: Example values in separate full-width row
- Analysis.jsx: Show only pipeline-type prompts
- Analysis.jsx: Remove base prompts and Prompts tab
- Cleanup: Remove PromptEditor component and unused imports

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 07:50:13 +01:00
Lars 8036c99883 feat: dynamic placeholder picker with categories and search (Issue #28)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 1s
Major improvements:
1. PlaceholderPicker component (new)
   - Loads placeholders dynamically from backend catalog
   - Grouped by categories: Profil, Körper, Ernährung, Training, etc.
   - Search/filter functionality
   - Shows live example values from user data
   - Popup modal with expand/collapse categories

2. Replaced hardcoded placeholder chips
   - 'Platzhalter einfügen' button opens picker
   - Works in both base templates and pipeline inline templates
   - Auto-closes after selection

3. Uses existing backend system
   - GET /api/prompts/placeholders
   - placeholder_resolver.py with PLACEHOLDER_MAP
   - Dynamic, module-based placeholder system
   - No manual updates needed when modules add new placeholders

Benefits:
- Scalable: New modules can add placeholders without frontend changes
- User-friendly: Search and categorization
- Context-aware: Shows real example values
- Future-proof: Backend-driven catalog
2026-03-25 22:08:14 +01:00
Lars b058b0fd6f feat: placeholder chips + convert to base prompt (Issue #28)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
New features:
1. Placeholder chips now visible in pipeline inline templates
   - Click to insert: weight_data, nutrition_data, activity_data, etc.
   - Same UX as base prompts

2. Convert to Base Prompt button
   - New icon (ArrowDownToLine) in actions column
   - Only visible for 1-stage pipeline prompts
   - Converts pipeline → base by extracting inline template
   - Validates: must be 1-stage, 1-prompt, inline source

This allows migrated prompts to be properly categorized as base prompts
for reuse in other pipelines.
2026-03-25 21:59:43 +01:00
Lars 7dda520c9b fix: UI improvements for unified prompt system (Issue #28)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 1s
Fixes:
1. Template field in stages now full width (was too narrow)
2. Table horizontal scrollbar for mobile (overflow-x: auto)
3. Table min-width 900px to prevent icon clipping
4. Added clickable placeholder chips below base template
   - Click to insert placeholders into template
   - Shows: weight_data, nutrition_data, activity_data, sleep_data, etc.

UI now mobile-ready and more user-friendly.
2026-03-25 21:52:58 +01:00
Lars 0a3e76128a fix: simplified JSX string to avoid escaping issues
Deploy Development / deploy (push) Successful in 43s
Build Test / build-frontend (push) Successful in 18s
Build Test / lint-backend (push) Successful in 0s
2026-03-25 21:42:01 +01:00
Lars 5249cd6939 fix: JSX syntax error in UnifiedPromptModal (Issue #28)
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Failing after 32s
Build Test / lint-backend (push) Successful in 1s
Fixed curly brace escaping in JSX string.
Changed from {{'{{'}} to {'{{'}}
2026-03-25 21:40:22 +01:00
Lars 2f3314cd36 feat: Issue #28 complete - unified prompt system (Phase 4)
Deploy Development / deploy (push) Failing after 34s
Build Test / build-frontend (push) Successful in 15s
Build Test / lint-backend (push) Successful in 1s
Cleanup & Documentation:
- Removed deprecated components: PipelineConfigModal, PromptEditModal
- Updated CLAUDE.md with Issue #28 summary
- Kept old backend endpoints for backward-compatibility

Summary of all 4 phases:
✅ Phase 1: DB Migration (unified schema)
✅ Phase 2: Backend Executor (universal execution engine)
✅ Phase 3: Frontend UI (consolidated interface)
✅ Phase 4: Cleanup & Docs

Key improvements:
- Unlimited dynamic stages (no hardcoded limit)
- Multiple prompts per stage (parallel execution)
- Base prompts (reusable) + Pipeline prompts (workflows)
- Inline templates or references
- JSON output enforceable
- Cross-module correlations possible

Ready for testing on dev.mitai.jinkendo.de
2026-03-25 15:33:47 +01:00
Lars 31e2c24a8a feat: unified prompt UI - Phase 3 complete (Issue #28)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Failing after 35s
Build Test / lint-backend (push) Successful in 0s
Frontend Consolidation:
- UnifiedPromptModal: Single editor for base + pipeline prompts
  - Type selector (base/pipeline)
  - Base: Template editor with placeholders
  - Pipeline: Dynamic stage editor
  - Add/remove stages with drag/drop
  - Inline or reference prompts per stage
  - Output key + format per prompt

- AdminPromptsPage redesign:
  - Removed tab switcher (prompts/pipelines)
  - Added type filter (All/Base/Pipeline)
  - Type badge in table
  - Stage count column
  - Icon-based actions (Edit/Copy/Delete)
  - Category filter retained

Changes:
- Completely rewrote AdminPromptsPage (495 → 446 lines)
- Single modal for all prompt types
- Mobile-ready layout
- Simplified state management

Next: Phase 4 - Cleanup deprecated endpoints + docs
2026-03-25 14:55:25 +01:00
Lars 7be7266477 feat: unified prompt executor - Phase 2 complete (Issue #28)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 1s
Backend:
- prompt_executor.py: Universal executor for base + pipeline prompts
  - Dynamic placeholder resolution
  - JSON output validation
  - Multi-stage parallel execution (sequential impl)
  - Reference and inline prompt support
  - Data loading per module (körper, ernährung, training, schlaf, vitalwerte)

Endpoints:
- POST /api/prompts/execute - Execute unified prompts
- POST /api/prompts/unified - Create unified prompts
- PUT /api/prompts/unified/{id} - Update unified prompts

Frontend:
- api.js: executeUnifiedPrompt, createUnifiedPrompt, updateUnifiedPrompt

Next: Phase 3 - Frontend UI consolidation
2026-03-25 14:52:24 +01:00
Lars 33653fdfd4 fix: migration 020 - make template column nullable
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Issue: template has NOT NULL constraint but pipeline-type prompts
don't use template (they use stages JSONB instead).

Solution: ALTER COLUMN template DROP NOT NULL before inserting
pipeline configs into ai_prompts.
2026-03-25 14:45:53 +01:00
Lars 95dcf080e5 fix: migration 020 SQL syntax - correlated subquery issue
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 42s
Build Test / lint-backend (push) Successful in 0s
Fixed Step 3 pipeline_configs migration:
- Simplified JSONB aggregation logic
- Properly scope pc alias in subqueries
- Use UNNEST with FROM clause for array expansion

Previous version had correlation issues with nested subqueries.
2026-03-25 12:58:02 +01:00
Lars 2e0838ca08 feat: unified prompt system migration schema (Issue #28 Phase 1)
Deploy Development / deploy (push) Successful in 50s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
- Migration 020: Add type, stages, output_format columns to ai_prompts
- Migrate existing prompts to 1-stage pipeline format
- Migrate pipeline_configs into ai_prompts as multi-stage pipelines
- Add UnifiedPrompt Pydantic models for new API
- Backup pipeline_configs table (keep during transition)

Schema structure:
- type: 'base' (reusable) or 'pipeline' (multi-stage)
- stages: JSONB array [{stage:1, prompts:[{source, slug, template, output_key, output_format}]}]
- output_format: 'text' or 'json'
- output_schema: JSON validation schema (optional)

Next: Backend executor + Frontend UI consolidation
2026-03-25 10:43:10 +01:00
Lars 1b7fdb1739 chore: rollback point before unified prompt system refactoring (Issue #28)
Current state:
- Pipeline configs working (migration 019)
- PipelineConfigModal complete
- AdminPromptsPage with tabs
- All Phase 1+2 features deployed and tested

Next: Consolidate into unified prompt system
- Single ai_prompts table for all types
- Dynamic stages (unlimited)
- Basis prompts + pipeline prompts
2026-03-25 10:42:18 +01:00
LarsandClaude Opus 4.6 b23e361791 feat: Pipeline-System Frontend - Admin UI (Issue #28, Phase 2 Part 1)
Build Test / build-frontend (push) Successful in 15s
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
Implementiert Admin-UI für Pipeline-Konfigurationen:
- Pipeline-Config Dialog mit Module-Auswahl
- Stage-Konfiguration (Stage 1/2/3 Prompts)
- Admin-UI: Zwei Tabs (Prompts + Pipeline-Configs)
- CRUD-Operationen für Pipeline-Configs
- API-Integration: Pipeline-Config Endpoints

**Frontend:**
- components/PipelineConfigModal.jsx (neu): Dialog für Pipeline-Konfiguration
  - Module-Auswahl mit Zeiträumen (7 Module)
  - Stage 1: Multi-Select für parallele Prompts
  - Stage 2: Synthese-Prompt Auswahl
  - Stage 3: Optional (Goals)
  - Validierung (mind. 1 Modul, mind. 1 Stage-1-Prompt, Stage-2 erforderlich)

- pages/AdminPromptsPage.jsx (erweitert): Tab-Navigation
  - Tab 1: Prompts (bestehend)
  - Tab 2: Pipeline-Konfigurationen (neu)
  - Liste aller Configs mit Status (Aktiv, Standard)
  - Aktionen: Bearbeiten, Löschen, Als Standard setzen
  - Icons: Star, Edit, Trash2

- utils/api.js (erweitert):
  - listPipelineConfigs, createPipelineConfig, updatePipelineConfig
  - deletePipelineConfig, setDefaultPipelineConfig
  - executePipeline, resetPromptToDefault

**Nächste Schritte:**
- Pipeline-Auswahl in AnalysisPage (User-Seite)
- Mobile-Responsive Design

Issue #28 Progress: Frontend 2/3 (67%) | Design 0/3 | Testing 0/1

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-25 10:01:49 +01:00
Lars 053a9e18cf fix: use postgres container for psql commands
Deploy Development / deploy (push) Successful in 44s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
2026-03-25 09:54:44 +01:00
Lars 6f7303c0d5 fix: correct container name and DB credentials for dev environment
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
2026-03-25 09:52:26 +01:00
Lars 7f7edce62d chore: add pipeline system test scripts (Issue #28)
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
2026-03-25 09:47:58 +01:00
LarsandClaude Opus 4.6 6627b5eee7 feat: Pipeline-System - Backend Infrastructure (Issue #28, Phase 1)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 1s
Implementiert konfigurierbare mehrstufige Analysen. Admins können
mehrere Pipeline-Konfigurationen erstellen mit unterschiedlichen
Modulen, Zeiträumen und Prompts.

**Backend:**
- Migration 019: pipeline_configs Tabelle + ai_prompts erweitert
- Pipeline-Config Models: PipelineConfigCreate, PipelineConfigUpdate
- Pipeline-Executor: refactored für config-basierte Ausführung
- CRUD-Endpoints: /api/prompts/pipeline-configs (list, create, update, delete, set-default)
- Reset-to-Default: /api/prompts/{id}/reset-to-default für System-Prompts

**Features:**
- 3 Seed-Configs: "Alltags-Check" (default), "Schlaf & Erholung", "Wettkampf-Analyse"
- Dynamische Platzhalter: {{stage1_<slug>}} für alle Stage-1-Ergebnisse
- Backward-compatible: /api/insights/pipeline ohne config_id nutzt default

**Dateien:**
- backend/migrations/019_pipeline_system.sql
- backend/models.py (PipelineConfigCreate, PipelineConfigUpdate)
- backend/routers/insights.py (analyze_pipeline refactored)
- backend/routers/prompts.py (Pipeline-Config CRUD + Reset-to-Default)

**Nächste Schritte:**
- Frontend: Pipeline-Config Dialog + Admin-UI
- Design: Mobile-Responsive + Icons

Issue #28 Progress: Backend 3/3 ✅ | Frontend 0/3 🔲 | Design 0/3 🔲

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-25 09:42:28 +01:00
LarsandClaude Opus 4.6 5e7ef718e0 fix: placeholder picker improvements + insight display names (Issue #28)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Backend:
- get_placeholder_catalog(): grouped placeholders with descriptions
- Returns {category: [{key, description, example}]} format
- Categories: Profil, Körper, Ernährung, Training, Schlaf, Vitalwerte, Zeitraum

Frontend - Placeholder Picker:
- Grouped by category with visual separation
- Search/filter across keys and descriptions
- Hover effects for better UX
- Insert at cursor position (not at end)
- Shows: key + description + example value
- 'Keine Platzhalter gefunden' message when filtered

Frontend - Insight Display Names:
- InsightCard receives prompts array
- Finds matching prompt by scope/slug
- Shows prompt.display_name instead of hardcoded SLUG_LABELS
- History tab also shows display_name in group headers
- Fallback chain: display_name → SLUG_LABELS → scope

User-facing improvements:
✓ Platzhalter zeigen echte Daten statt Zahlen
✓ Durchsuchbar + filterbar
✓ Einfügen an Cursor-Position
✓ Insights zeigen custom Namen (z.B. '🍽️ Meine Ernährung')

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-25 06:44:22 +01:00
LarsandClaude Opus 4.6 0c4264de44 feat: display_name + placeholder picker for prompts (Issue #28)
Deploy Development / deploy (push) Successful in 51s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 1s
Migration 018:
- Add display_name column to ai_prompts
- Migrate existing prompts from hardcoded SLUG_LABELS
- Fallback: name if display_name is NULL

Backend:
- PromptCreate/Update models with display_name field
- create/update/duplicate endpoints handle display_name
- Fallback: use name if display_name not provided

Frontend:
- PromptEditModal: display_name input field
- Placeholder picker: button + dropdown with all placeholders
- Shows example values, inserts {{placeholder}} on click
- Analysis.jsx: use display_name instead of SLUG_LABELS

User-facing changes:
- Prompts now show custom display names (e.g. '🍽️ Ernährung')
- Admin can edit display names instead of hardcoded labels
- Template editor has 'Platzhalter einfügen' button
- No more hardcoded SLUG_LABELS in frontend

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-25 06:31:25 +01:00
LarsandClaude Opus 4.6 7a8a5aee98 fix: prompt editor layout - full-width inputs, left-aligned text (Issue #28)
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
- PromptEditModal: all inputs/textareas now full-width
- Labels positioned above fields (not inline)
- Text left-aligned (was right-aligned)
- Added resize:vertical for textareas
- Side-by-side comparison with word-wrap
- Follows app-wide form design pattern

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 20:53:15 +01:00
LarsandClaude Opus 4.6 c8cf375399 feat: AI-Prompts flexibilisierung - Frontend complete (Issue #28, Part 2)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Frontend components:
- PromptEditModal.jsx: Full editor with preview, generator, optimizer
- PromptGenerator.jsx: KI-assisted prompt creation from goal description
- Extended api.js with 10 new prompt endpoints

Navigation:
- Added /admin/prompts route to App.jsx
- Added KI-Prompts section to AdminPanel with navigation button

Features complete:
✅ Admin can create/edit/delete/duplicate prompts
✅ Category filtering and reordering
✅ Preview prompts with real user data
✅ KI generates prompts from goal + example data
✅ KI analyzes and optimizes existing prompts
✅ Side-by-side comparison original vs optimized

Ready for testing: http://dev.mitai.jinkendo.de/admin/prompts

Issue #28 Phase 2 complete - 13-18h estimated, ~14h actual

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 15:35:55 +01:00
LarsandClaude Opus 4.6 500de132b9 feat: AI-Prompts flexibilisierung - Backend & Admin UI (Issue #28, Part 1)
Backend complete:
- Migration 017: Add category column to ai_prompts
- placeholder_resolver.py: 20+ placeholders with resolver functions
- Extended routers/prompts.py with CRUD endpoints:
  * POST /api/prompts (create)
  * PUT /api/prompts/:id (update)
  * DELETE /api/prompts/:id (delete)
  * POST /api/prompts/:id/duplicate
  * PUT /api/prompts/reorder
  * POST /api/prompts/preview
  * GET /api/prompts/placeholders
  * POST /api/prompts/generate (KI-assisted generation)
  * POST /api/prompts/:id/optimize (KI analysis)
- Extended models.py with PromptCreate, PromptUpdate, PromptGenerateRequest

Frontend:
- AdminPromptsPage.jsx: Full CRUD UI with category filter, reordering

Meta-Features:
- KI generates prompts from goal description + example data
- KI analyzes and optimizes existing prompts

Next: PromptEditModal, PromptGenerator, api.js integration

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 15:32:25 +01:00
Lars ac4c6760d7 Merge pull request 'globaler Filter für Qualitätsgates von Trainings' (#41) from develop into main
Deploy Production / deploy (push) Successful in 52s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 1s
Reviewed-on: #41
2026-03-24 08:44:22 +01:00
LarsandClaude Opus 4.6 5796c6a21a refactor: replace local quality filter with info banner (Issue #31)
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Removed local quality filter UI from History page since backend now
handles filtering globally. Activities are already filtered when loaded.

Changes:
- Removed qualityLevel local state
- Simplified filtA to only filter by period
- Replaced filter buttons with info banner showing active global filter
- Added 'Hier ändern →' link to Settings

User can now only change quality filter in Settings (global), not per
page. History shows which filter is active with link to change it.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 08:06:20 +01:00
LarsandClaude Opus 4.6 302948a248 fix: add quality_filter_level to ProfileUpdate model (Issue #31)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 0s
The frontend was sending quality_filter_level to the backend, but the
Pydantic ProfileUpdate model didn't include this field, so it was
silently ignored. Profile updates never actually saved the filter.

This is why the charts didn't react to filter changes - the backend
database was never updated.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 06:44:05 +01:00
LarsandClaude Opus 4.6 e3819327a9 fix: reload TrainingTypeDistribution on quality filter change (Issue #31)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
The component was loading data from backend (which uses global filter)
but useEffect dependency didn't include quality_filter_level, so it
didn't reload when user changed the filter in Settings.

Added useProfile() context and activeProfile.quality_filter_level
to dependency array.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 06:30:39 +01:00
LarsandClaude Opus 4.6 04306a7fef feat: global quality filter setting (Issue #31)
Deploy Development / deploy (push) Successful in 44s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Implemented global quality_filter_level in user profiles for consistent
data filtering across all views (Dashboard, History, Charts, KI-Pipeline).

Backend changes:
- Migration 016: Add quality_filter_level column to profiles table
- quality_filter.py: Centralized helper functions for SQL filtering
- insights.py: Apply global filter in _get_profile_data()
- activity.py: Apply global filter in list_activity()

Frontend changes:
- SettingsPage.jsx: Add Datenqualität section with 4-level selector
- History.jsx: Use global quality filter from profile context

Filter levels: all, quality (good+excellent+acceptable), very_good
(good+excellent), excellent (only excellent)

Closes #31

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 22:29:49 +01:00
LarsandClaude Opus 4.6 b317246bcd docs: Quality-Level Parameter für KI-Analysen notiert (#28)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 45s
Build Test / lint-backend (push) Successful in 0s
Notiert an 3 Stellen:
1. insights.py: TODO-Kommentar im Code
2. ROADMAP.md: Deliverable bei M0.2 (lokal, nicht im Git)
3. Gitea Issue #28: Kommentar mit Spezifikation

Zukünftig:
- GET /api/insights/run/{slug}?quality_level=quality
- 4 Stufen: all, quality, very_good, excellent
- Frontend: Dropdown wie in History.jsx
- Pipeline-Configs können Standard-Level haben

User-Request: Quality-Level-Auswahl für KI-Analysen

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 22:06:30 +01:00
LarsandClaude Opus 4.6 848ba0a815 refactor: mehrstufiger Quality-Filter statt Toggle (#24)
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 1s
Statt einfachem On/Off Toggle jetzt 4 Qualitätsstufen:
- 📊 Alle (kein Filter)
- ✓ Hochwertig (excellent + good + acceptable)
- ✓✓ Sehr gut (excellent + good)
- ⭐ Exzellent (nur excellent)

UI:
- Button-Group (Segmented Control) mit 4 Stufen
- Beschreibung welche Labels inkludiert werden
- Anzeige: X von Y Aktivitäten (wenn gefiltert)

User-Feedback: Stufenweiser Filter ist flexibler als binärer Toggle

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 22:04:29 +01:00
LarsandClaude Opus 4.6 9ec774e956 feat: Quality-Filter für KI-Pipeline & History (#24)
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 1s
Backend:
- insights.py: KI-Pipeline filtert activity_log nach quality_label
- Nur 'excellent', 'good', 'acceptable' (poor wird ausgeschlossen)
- NULL-Werte erlaubt (für alte Einträge vor Migration 014)

Frontend:
- History.jsx: Toggle "Nur qualitativ hochwertige Aktivitäten"
- Filter wirkt auf Activity-Statistiken, Charts, Listen
- Anzeige: X von Y Activities (wenn gefiltert)

Dokumentation:
- CLAUDE.md: Feature-Roadmap aktualisiert (Phase 0-2)

Closes #24

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 21:59:02 +01:00
Lars 9210d051a8 docs: update CLAUDE.md - v9d Phase 2 deployed to production
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
2026-03-23 16:53:29 +01:00
Lars 5a6a140dfd Merge pull request 'Bugfixes: Vitals Import (German columns + decimal values)' (#23) from develop into main
Deploy Production / deploy (push) Successful in 56s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
2026-03-23 16:52:27 +01:00
LarsandClaude Opus 4.6 6f035e3706 fix: handle decimal values in Apple Health vitals import
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 1s
Problem: Import failed with "invalid literal for int() with base 10: '37.95'"
because Apple Health exports HRV and other vitals with decimal values.

Root cause: Code used int() directly on string values with decimals.

Fix:
- Added safe_int(): parses decimals as float first, then rounds to int
- Added safe_float(): robust float parsing with error handling
- Applied to all vital value parsing: RHR, HRV, VO2 Max, SpO2, resp rate

Example: '37.95' → float(37.95) → int(38) ✓

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 16:50:08 +01:00
LarsandClaude Opus 4.6 6b64cf31c4 fix: return error details in import response for debugging
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Problem: Errors during import were logged but not visible to user.

Changes:
- Backend: Collect error messages and return in response (first 10 errors)
- Frontend: Display error details in import result box
- UI: Red background when errors > 0, shows detailed error messages

Now users can see exactly which rows failed and why.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 16:47:36 +01:00
Lars 4b024e6d0f debug: add detailed error logging with traceback for import failures
Build Test / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 45s
Build Test / lint-backend (push) Successful in 0s
2026-03-23 16:44:16 +01:00
LarsandClaude Opus 4.6 f506a55d7b fix: support German column names in CSV imports
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Problem: Import expected English column names, but German Apple Health/Omron
exports use German names with units.

Fixed:
- Apple Health: Support both English and German column names
  - "Start" OR "Datum/Uhrzeit"
  - "Resting Heart Rate" OR "Ruhepuls (count/min)"
  - "Heart Rate Variability" OR "Herzfrequenzvariabilität (ms)"
  - "VO2 Max" OR "VO2 max (ml/(kg·min))"
  - "Oxygen Saturation" OR "Blutsauerstoffsättigung (%)"
  - "Respiratory Rate" OR "Atemfrequenz (count/min)"

- Omron: Support column names with/without units
  - "Systolisch (mmHg)" OR "Systolisch"
  - "Diastolisch (mmHg)" OR "Diastolisch"
  - "Puls (bpm)" OR "Puls"
  - "Unregelmäßiger Herzschlag festgestellt" OR "Unregelmäßiger Herzschlag"
  - "Mögliches AFib" OR "Vorhofflimmern"

Added debug logging for both imports to show detected columns.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 16:40:49 +01:00
LarsandClaude Opus 4.6 6a7b78c3eb debug: add logging to Apple Health import to diagnose skipped rows
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Logs:
- CSV column names from first row
- Rows skipped due to missing date
- Rows skipped due to no vitals data
- Shows which fields were found/missing

Helps diagnose CSV format mismatches.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 16:38:18 +01:00
LarsandClaude Opus 4.6 7dcab1d7a3 fix: correct import skipped count when manual entries exist
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 1s
Problem: Import reported all entries as "updated" even when skipped
due to WHERE clause (source != 'manual')

Root cause: RETURNING returns NULL when WHERE clause prevents update,
but code counted NULL as "updated" instead of "skipped"

Fix:
- Check if result is None → skipped (WHERE prevented update)
- Check if xmax = 0 → inserted (new row)
- Otherwise → updated (existing row modified)

Affects:
- vitals_baseline.py: Apple Health import
- blood_pressure.py: Omron import

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 16:35:07 +01:00
Lars 931012c16b Merge pull request 'v9d Phase 2d: Vitals Module Refactoring (Baseline + Blood Pressure)' (#22) from develop into main
Deploy Production / deploy (push) Successful in 54s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
2026-03-23 16:27:03 +01:00
LarsandClaude Opus 4.6 10772d1f80 feat: VitalsPage mobile-optimized with inline editing & smart upsert
Deploy Development / deploy (push) Successful in 44s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
- Full-width fields with section headers (mobile-friendly)
- Inline editing for all measurements (edit mode per row)
- Smart upsert: date change loads existing entry → update instead of duplicate
- Units integrated into labels (no overflow)
- Baseline: auto-detects existing entry and switches to update mode
- Blood Pressure: inline editing with all fields (date, time, BP, context, flags)
- Edit/Save/Cancel buttons with lucide-react icons

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 16:19:53 +01:00
LarsandClaude Opus 4.6 7f10286e02 feat: complete VitalsPage UI with 3-tab architecture (v9d Phase 2d)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 0s
- Tab 1: BaselineTab (once daily morning vitals: RHR, HRV, VO2 Max, SpO2, respiratory rate)
- Tab 2: BloodPressureTab (multiple daily with context tagging, WHO/ISH classification)
- Tab 3: ImportTab (drag & drop for Omron + Apple Health CSV)
- Stats display with 7d averages and trends
- Context-aware BP measurements (8 context options)
- Color-coded BP category classification
- Entry lists with delete functionality

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 16:10:42 +01:00
LarsandClaude Opus 4.6 1cc3b05705 temp: placeholder VitalsPage während Frontend-Refactoring
Deploy Development / deploy (push) Successful in 47s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Einfache 3-Tab-Struktur als Platzhalter:
- Morgenmessung (Baseline)
- Blutdruck (BP)
- Import

Verhindert Crash durch alte API-Calls.
Vollständige UI folgt nach Backend-Test.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 16:03:12 +01:00
LarsandClaude Opus 4.6 1866ff9ce6 refactor: vitals architecture - separate baseline vs blood pressure
Build Test / build-frontend (push) Waiting to run
Deploy Development / deploy (push) Has been cancelled
Build Test / lint-backend (push) Waiting to run
BREAKING CHANGE: vitals_log split into vitals_baseline + blood_pressure_log

**Architektur-Änderung:**
- Baseline-Vitals (langsam veränderlich, 1x täglich morgens)
  → vitals_baseline (RHR, HRV, VO2 Max, SpO2, Atemfrequenz)
- Kontext-abhängige Vitals (mehrfach täglich, situativ)
  → blood_pressure_log (Blutdruck + Kontext-Tagging)

**Migration 015:**
- CREATE TABLE vitals_baseline (once daily, morning measurements)
- CREATE TABLE blood_pressure_log (multiple daily, context-aware)
- Migrate data from vitals_log → new tables
- Rename vitals_log → vitals_log_backup_pre_015 (safety)
- Prepared for future: glucose_log, temperature_log (commented)

**Backend:**
- NEW: routers/vitals_baseline.py (CRUD + Apple Health import)
- NEW: routers/blood_pressure.py (CRUD + Omron import + context)
- UPDATED: main.py (register new routers, remove old vitals)
- UPDATED: insights.py (query new tables, split template vars)

**Frontend:**
- UPDATED: api.js (new endpoints für baseline + BP)
- UPDATED: Analysis.jsx (add {{bp_summary}} variable)

**Nächster Schritt:**
- Frontend: VitalsPage.jsx refactoren (3 Tabs: Morgenmessung, Blutdruck, Import)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 16:02:40 +01:00
LarsandClaude Opus 4.6 1619091640 fix: add python-dateutil dependency for vitals CSV import
Deploy Development / deploy (push) Successful in 50s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
ModuleNotFoundError: No module named 'dateutil' beim Server-Start.
Ursache: vitals.py importiert dateutil.parser für Omron-Datumsformatierung,
aber python-dateutil fehlte in requirements.txt.

Fix: python-dateutil==2.9.0 zu requirements.txt hinzugefügt.

Nach dem Update: Docker Container neu bauen auf dem Pi:
  cd /home/lars/docker/bodytrack-dev
  docker compose -f docker-compose.dev-env.yml build --no-cache backend
  docker compose -f docker-compose.dev-env.yml up -d

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 15:41:30 +01:00
LarsandClaude Opus 4.6 37fd28ec5a feat: add AI evaluation placeholders for v9d Phase 2 modules
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
**Backend (insights.py):**
- Extended _get_profile_data() to fetch sleep, rest_days, vitals
- Added template variables for Sleep Module:
  {{sleep_summary}}, {{sleep_detail}}, {{sleep_avg_duration}}, {{sleep_avg_quality}}
- Added template variables for Rest Days:
  {{rest_days_summary}}, {{rest_days_count}}, {{rest_days_types}}
- Added template variables for Vitals:
  {{vitals_summary}}, {{vitals_detail}}, {{vitals_avg_hr}}, {{vitals_avg_hrv}},
  {{vitals_avg_bp}}, {{vitals_vo2_max}}

**Frontend (Analysis.jsx):**
- Added 12 new template variables to VARS list in PromptEditor
- Enables AI prompt creation for Sleep, Rest Days, and Vitals analysis

All modules now have AI evaluation support for future prompt creation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 15:30:17 +01:00
LarsandClaude Opus 4.6 bf87e03100 docs: update CLAUDE.md with completed v9d Phase 2 modules
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
- Mark Sleep Module as complete (Phase 2b)
- Mark Rest Days as complete (Phase 2a)
- Mark Extended Vitals as complete (Phase 2d)
- Add migration details (010-014)
- HF-Zonen + Recovery Score marked as next (Phase 2e)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 15:27:55 +01:00
LarsandClaude Opus 4.6 548a5a481d feat: add CSV import for Vitals (Omron + Apple Health)
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
- Import endpoints for Omron blood pressure CSV (German date format)
- Import endpoints for Apple Health vitals CSV
- Import UI tab in VitalsPage with drag & drop for both sources
- German month mapping for Omron date parsing ("13 März 2026")
- Upsert logic preserves manual entries (source != 'manual')
- Import result feedback (inserted/updated/skipped/errors)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 15:26:51 +01:00
LarsandClaude Opus 4.6 a55f11bc96 feat: add blood pressure, VO2 max, and SpO2 to vitals stats
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
- Avg blood pressure (systolic/diastolic) 7d and 30d
- Latest VO2 Max value
- Avg SpO2 7d and 30d
- Backend now provides all metrics expected by frontend

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 15:18:13 +01:00
LarsandClaude Opus 4.6 9634ca8909 feat: extend VitalsPage with all new vital parameters
Build Test / build-frontend (push) Waiting to run
Deploy Development / deploy (push) Has been cancelled
Build Test / lint-backend (push) Waiting to run
Form sections:
- Morgenmessung: Ruhepuls, HRV
- Blutdruck (Omron): Systolisch, Diastolisch, Puls
- Fitness & Sauerstoff (Apple Watch): VO2 Max, SpO2, Atemfrequenz
- Warnungen: Unregelmäßiger Herzschlag, Mögliches AFib (checkboxes)

Display:
- All vitals shown in entry list with icons
- Blood pressure highlighted in red (🩸)
- VO2 Max in green (🏃)
- Warnings in orange (⚠️)

Stats overview:
- Dynamic grid showing available metrics
- Avg blood pressure 7d
- Latest VO2 Max
- Avg SpO2 7d

Save/Update:
- Only non-empty fields included in payload
- At least one vital must be provided

Ready for manual testing + import implementation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 15:17:36 +01:00
LarsandClaude Opus 4.6 4f53cfffab feat: extend vitals with blood pressure, VO2 max, SpO2, respiratory rate
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 42s
Build Test / lint-backend (push) Successful in 0s
Migration 014:
- blood_pressure_systolic/diastolic (mmHg)
- pulse (bpm) - during BP measurement
- vo2_max (ml/kg/min) - from Apple Watch
- spo2 (%) - blood oxygen saturation
- respiratory_rate (breaths/min)
- irregular_heartbeat, possible_afib (boolean flags from Omron)
- Added 'omron' to source enum

Backend:
- Updated Pydantic models (VitalsEntry, VitalsUpdate)
- Updated all SELECT queries to include new fields
- Updated INSERT/UPDATE with COALESCE for partial updates
- Validation: at least one vital must be provided

Preparation for Omron + Apple Health imports

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 15:14:34 +01:00
LarsandClaude Opus 4.6 7433b19b7e fix: handle empty HRV field in vitals form
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 45s
Build Test / lint-backend (push) Successful in 0s
- Only include fields in payload if they have values
- Prevents sending empty strings to backend (Pydantic validation error)
- Applies to both create and update operations

Error was: 'Input should be a valid integer, unable to parse string as an integer'

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 14:56:17 +01:00
LarsandClaude Opus 4.6 4191c52298 feat: implement Vitals module (Ruhepuls + HRV)
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Backend:
- New router: vitals.py with CRUD endpoints
- GET /api/vitals (list)
- GET /api/vitals/by-date/{date}
- POST /api/vitals (upsert)
- PUT /api/vitals/{id}
- DELETE /api/vitals/{id}
- GET /api/vitals/stats (7d/30d averages, trends)
- Registered in main.py

Frontend:
- VitalsPage.jsx with manual entry form
- List with inline editing
- Stats overview (averages, trend indicators)
- Added to CaptureHub (❤️ icon)
- Route /vitals in App.jsx

API:
- Added vitals methods to api.js

v9d Phase 2d - Vitals tracking complete

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 14:52:09 +01:00
LarsandClaude Opus 4.6 5bd1b33f5a docs: update ProfileBuilder placeholder for future dimensions
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
- Changed from 'folgt in nächster Iteration' to 'Analyse & Entwicklung, folgen später'
- Listed all 5 dimensions with clear purpose
- Clarifies that Minimum Requirements is sufficient for validation
- Other dimensions planned for v9e/v9f (ability development, AI prompts)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 14:40:56 +01:00
LarsandClaude Opus 4.6 b73c77d811 feat: improve ProfileBuilder mobile UX and clarity
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 42s
Build Test / lint-backend (push) Successful in 0s
Changes:
- Responsive layout: fields stack vertically, no more cramped grid
- Clear labels: 'WAS?', 'BEDINGUNG', 'WICHTIGKEIT'
- Weight field only shown when using 'weighted_score' strategy
- Weight explanation: '1 = unwichtig, 10 = sehr wichtig'
- Success message replaces alert() dialog (auto-dismiss after 2s)
- Delete button moved to rule header
- Better visual hierarchy with sections

User feedback:
- Felder lassen sich auf Handy nicht gut bearbeiten
- Überschriften nicht eindeutig
- Gewicht-Feld Verwirrung
- Keine OK-Dialoge

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 14:18:58 +01:00
LarsandClaude Opus 4.6 65846042e2 feat: improve ProfileBuilder UI clarity with field labels
Build Test / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 42s
Build Test / lint-backend (push) Successful in 1s
- Added label row: PARAMETER | OPERATOR | SCHWELLENWERT | GEWICHT
- Prevents confusion between threshold value and weight fields
- Better placeholder for value field (z.B. 90)
- Between operator: stacked vertical inputs with Min/Max labels
- User feedback: confusion between value and weight fields

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 13:35:52 +01:00
LarsandClaude Opus 4.6 2c73c3df52 fix: convert Decimal to float for JSON serialization in evaluation
Deploy Development / deploy (push) Successful in 50s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
- PostgreSQL returns numeric values as Decimal objects
- psycopg2.Json() cannot serialize Decimal to JSON
- Added convert_decimals() helper function
- Converts activity_data, context, and evaluation_result before saving

Fixes: Batch evaluation errors (31 errors 'Decimal is not JSON serializable')

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 13:28:07 +01:00
LarsandClaude Opus 4.6 4937ce4b05 feat: add visual evaluation status indicators to activity list
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 1s
- ✓ Green: Successfully evaluated (excellent/good/acceptable/poor)
- ⚠ Orange: Training type assigned but not evaluated (no profile)
- ✕ Gray: No training type assigned
- Tooltip shows evaluation details on hover

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 13:25:18 +01:00
LarsandClaude Opus 4.6 d07baa260c feat: display batch evaluation error details in UI
Build Test / build-frontend (push) Has been cancelled
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
- Shows first 10 errors with activity_id and error message
- Helps admin debug evaluation failures
- Errors shown in error box with details

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 13:24:29 +01:00
LarsandClaude Opus 4.6 33e27a4f3e feat: add error_details to batch evaluation response
Build Test / build-frontend (push) Waiting to run
Build Test / lint-backend (push) Waiting to run
Deploy Development / deploy (push) Has been cancelled
- Shows first 10 errors with activity_id, training_type_id, and error message
- Helps debug evaluation failures

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 13:24:14 +01:00
LarsandClaude Opus 4.6 41c7084159 fix: restore inline editing for training type profiles
Build Test / build-frontend (push) Successful in 12s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 1s
- ProfileBuilder now renders inline below training type row
- Type editor form also inline (not at top of page)
- Both forms appear at item position with marginTop: 8
- User feedback: 'Die Position bleibt die ganze Zeit gleich!'

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 13:23:00 +01:00
LarsandClaude Opus 4.6 6fa15f7f57 feat: Visual Profile Builder integrated into Training Types page (#15)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 45s
Build Test / lint-backend (push) Successful in 0s
MAJOR UX IMPROVEMENT - No more JSON editing required!

New Component: ProfileBuilder.jsx
- Visual form for configuring training type profiles
- Parameter dropdown (dynamically loaded from API)
- Operator dropdown (>=, <=, >, <, =, ≠, between)
- Value input (type-aware, between shows min/max)
- Weight slider (1-10)
- Add/remove rules visually
- Pass strategy selection
- Optional checkbox per rule
- Expandable sections

Integration: AdminTrainingTypesPage.jsx
- Added ProfileBuilder component
- ⚙️ Settings icon per training type
- Opens visual form when clicked
- ✓ Profil badge shows configured types
- Loads 16 parameters from API
- Save directly to training type

User Experience:
1. Go to /admin/training-types
2. Click ⚙️ icon on any type
3. Visual form opens
4. Add rules via dropdowns
5. Save → Profile configured!

NO JSON EDITING NEEDED! 🎉

Next: Add visual builders for other dimensions (Zones, Effects, etc.)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 13:01:35 +01:00
LarsandClaude Opus 4.6 2abaac22cf fix: correct API method calls in AdminTrainingProfiles (#15)
Deploy Development / deploy (push) Successful in 52s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
Fixed "U.get is not a function" error:
- Added missing API methods to api.js:
  - getProfileStats()
  - getProfileTemplates()
  - applyProfileTemplate()
  - getTrainingParameters()
  - batchEvaluateActivities()
- Updated AdminTrainingProfiles.jsx to use correct methods
- Replaced api.get/post/put with specific named methods

Error resolved. Page should now load correctly.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 12:36:39 +01:00
LarsandClaude Opus 4.6 1d252b5299 feat: Training Type Profiles Phase 2.2 - Frontend Admin-UI (#15)
Deploy Development / deploy (push) Successful in 48s
Build Test / build-frontend (push) Successful in 12s
Build Test / lint-backend (push) Successful in 1s
New admin page for profile configuration:
- AdminTrainingProfiles.jsx: Profile management interface
- Statistics dashboard (configured/unconfigured count)
- Training types list with profile status badges
- JSON-based profile editor (modal)
- One-click template application (Running, Meditation, Strength)
- Batch re-evaluation button for existing activities
- Link in AdminPanel under "Trainingstypen (v9d)"

Features:
- Apply templates with one click
- Edit profiles as JSON in modal
- Real-time validation
- Success/error messages
- Responsive layout

Route: /admin/training-profiles

Next: Test and iterate, then Phase 3 (User-UI for viewing results)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 11:53:58 +01:00
LarsandClaude Opus 4.6 d7145874cf feat: Training Type Profiles Phase 2.1 - Backend Profile Management (#15)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Admin endpoints for profile configuration:
- Extended TrainingTypeCreate/Update models with profile field
- Added profile column to all SELECT queries
- Profile templates for Running, Meditation, Strength Training
- Template endpoints: list, get, apply
- Profile stats endpoint (configured/unconfigured count)

New file: profile_templates.py
- TEMPLATE_RUNNING: Endurance-focused with HR zones
- TEMPLATE_MEDITATION: Mental-focused (low HR ≤ instead of ≥)
- TEMPLATE_STRENGTH: Strength-focused

API Endpoints:
- GET /api/admin/training-types/profiles/templates
- GET /api/admin/training-types/profiles/templates/{key}
- POST /api/admin/training-types/{id}/profile/apply-template
- GET /api/admin/training-types/profiles/stats

Next: Frontend Admin-UI (ProfileEditor component)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 11:50:40 +01:00
LarsandClaude Opus 4.6 ca7d9b2e3f fix: add missing validation_rules in migration 013 (#15)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 0s
SQL Error: VALUES lists must all be the same length (line 130)
Cause: kcal_per_km row was missing validation_rules JSONB value

Fixed: Added validation_rules '{"min": 0, "max": 1000}'::jsonb

All 16 parameter rows now have correct 10 columns:
key, name_de, name_en, category, data_type, unit, source_field,
validation_rules, description_de, description_en

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 11:01:53 +01:00
LarsandClaude Opus 4.6 edd15dd556 fix: defensive evaluation import to prevent startup crash (#15)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 1s
Problem: Backend crashed on startup due to evaluation import failure
Solution: Wrap evaluation_helper import in try/except

Changes:
- Import evaluation_helper with error handling
- Add EVALUATION_AVAILABLE flag
- All evaluation calls now check flag before executing
- System remains functional even if evaluation system unavailable

This prevents backend crashes if:
- Migrations haven't run yet
- Dependencies are missing
- Import errors occur

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 10:59:23 +01:00
LarsandClaude Opus 4.6 e11953736d feat: Training Type Profiles Phase 1.2 - Auto-evaluation (#15)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Automatic evaluation on activity INSERT/UPDATE:
- create_activity(): Evaluate after manual creation
- update_activity(): Re-evaluate after manual update
- import_activity_csv(): Evaluate after CSV import (INSERT + UPDATE)
- bulk_categorize_activities(): Evaluate after bulk training type assignment

All evaluation calls wrapped in try/except to prevent activity operations
from failing if evaluation encounters an error. Only activities with
training_type_id assigned are evaluated.

Phase 1.2 complete ✅

## Next Steps (Phase 2):
Admin-UI for training type profile configuration

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-23 10:53:13 +01:00
Lars 1b9cd6d5e6 feat: Training Type Profiles - Phase 1.1 Foundation (#15)
Deploy Development / deploy (push) Successful in 55s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
## Implemented

### DB-Schema (Migrations)
- Migration 013: training_parameters table (16 standard parameters)
- Migration 014: training_types.profile + activity_log.evaluation columns
- Performance metric calculations (avg_hr_percent, kcal_per_km)

### Backend - Rule Engine
- RuleEvaluator: Generic rule evaluation with 9 operators
  - gte, lte, gt, lt, eq, neq, between, in, not_in
  - Weighted scoring system
  - Pass strategies: all_must_pass, weighted_score, at_least_n

- IntensityZoneEvaluator: HR zone analysis
- TrainingEffectsEvaluator: Abilities development

### Backend - Master Evaluator
- TrainingProfileEvaluator: 7-dimensional evaluation
  1. Minimum Requirements (Quality Gates)
  2. Intensity Zones (HR zones)
  3. Training Effects (Abilities)
  4. Periodization (Frequency & Recovery)
  5. Performance Indicators (KPIs)
  6. Safety (Warnings)
  7. AI Context (simplified for MVP)

- evaluation_helper.py: Utilities for loading + saving
- routers/evaluation.py: API endpoints
  - POST /api/evaluation/activity/{id}
  - POST /api/evaluation/batch
  - GET /api/evaluation/parameters

### Integration
- main.py: Router registration

## TODO (Phase 1.2)
- Auto-evaluation on activity INSERT/UPDATE
- Admin-UI for profile editing
- User-UI for results display

## Testing
- ✅ Syntax checks passed
- 🔲 Runtime testing pending (after auto-evaluation)

Part of Issue #15 - Training Type Profiles System
2026-03-23 10:49:26 +01:00
Lars 03f4b871a9 Merge pull request 'Production Release: RestDays Widget + Trainingstyp Fix' (#16) from develop into main
Deploy Production / deploy (push) Successful in 52s
Build Test / build-frontend (push) Successful in 14s
Build Test / lint-backend (push) Successful in 0s
Merge pull request #16: Production Release
2026-03-23 09:24:17 +01:00
Lars 29770503bf fix: wrap abilities dict with Json() for JSONB insert (#13)
Deploy Development / deploy (push) Successful in 49s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Problem: Creating new training types via Admin UI resulted in
'Internal Server Error' because abilities dict was passed directly
to PostgreSQL JSONB column without Json() wrapper.

Solution:
- Import Json from psycopg2.extras
- Wrap abilities_json with Json() in INSERT
- Wrap data.abilities with Json() in UPDATE

Same issue as rest_days JSONB fix (commit 7d627cf).

Closes #13
2026-03-23 09:13:50 +01:00
Lars 7a0b2097ae feat: dashboard rest days widget + today highlighting
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
- Add RestDaysWidget component showing today's rest days with icons & colors
- Integrate widget into Dashboard (above training distribution)
- Highlight current day in RestDaysPage (accent border + HEUTE badge)
- Fix: Improve error handling in api.js (parse JSON detail field)

Part of v9d Phase 2 (Vitals & Recovery)
2026-03-23 08:38:57 +01:00
LarsandClaude Opus 4.6 f87b93ce2f feat: prevent duplicate rest day types per date (Migration 012)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Problem: User can create multiple rest days of same type per date
(e.g., 2x Mental Rest on 2026-03-23) - makes no sense.

Solution: UNIQUE constraint on (profile_id, date, focus)

## Migration 012:
- Add focus column (extracted from rest_config JSONB)
- Populate from existing data
- Add NOT NULL constraint
- Add CHECK constraint (valid focus values)
- Add UNIQUE constraint (profile_id, date, focus)
- Add index for performance

## Backend:
- Insert focus column alongside rest_config
- Handle UniqueViolation gracefully
- User-friendly error: "Du hast bereits einen Ruhetag 'Muskelregeneration' für 23.03."

## Benefits:
- DB-level enforcement (clean)
- Fast queries (no JSONB scan)
- Clear error messages
- Prevents: 2x muscle_recovery same day
- Allows: muscle_recovery + mental_rest same day ✓

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 17:36:49 +01:00
LarsandClaude Opus 4.6 f2e2aff17f fix: remove ON CONFLICT clause after constraint removal
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 0s
Migration 011 removed UNIQUE constraint (profile_id, date) to allow
multiple rest days per date, but INSERT still used ON CONFLICT.

Error: psycopg2.errors.InvalidColumnReference: there is no unique or
exclusion constraint matching the ON CONFLICT specification

Solution: Remove ON CONFLICT clause, use plain INSERT.
Multiple entries per date now allowed.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 17:05:06 +01:00
LarsandClaude Opus 4.6 6916e5b808 feat: multi-dimensional rest days + development routes architecture (v9d → v9e)
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
## Changes:

**Frontend:**
- Fix double icon in rest day list (removed icons from FOCUS_LABELS)
- Icon now shows once with proper styling

**Migration 011:**
- Remove UNIQUE constraint (profile_id, date) from rest_days
- Allow multiple rest day types per date
- Use case: Muscle recovery + Mental rest same day

**Architecture: Development Routes**
New document: `.claude/docs/functional/DEVELOPMENT_ROUTES.md`

6 Independent Development Routes:
- 💪 Kraft (Strength): Muscle, power, HIIT
- 🏃 Kondition (Conditioning): Cardio, endurance, VO2max
- 🧘 Mental: Stress, focus, competition readiness
- 🤸 Koordination (Coordination): Balance, agility, technique
- 🧘‍♂️ Mobilität (Mobility): Flexibility, ROM, fascia
- 🎯 Technik (Technique): Sport-specific skills

Each route has:
- Independent rest requirements
- Independent training plans
- Independent progress tracking
- Independent goals & habits

**Future (v9e):**
- Route-based weekly planning
- Multi-route conflict validation
- Auto-rest on poor recovery
- Route balance analysis (KI)

**Future (v9g):**
- Habits per route (route_habits table)
- Streak tracking per route
- Dashboard route-habits widget

**Backlog Updated:**
- v9d: Rest days ✅ (in testing)
- v9e: Development Routes & Weekly Planning (new)
- v9g: Habits per Route (extended)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 16:51:09 +01:00
LarsandClaude Opus 4.6 7d627cf128 fix: wrap rest_config dict with Json() for psycopg2 JSONB insert
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Error: psycopg2.ProgrammingError: can't adapt type 'dict'
Solution: Import psycopg2.extras.Json and wrap config_dict

Changes:
- Import Json from psycopg2.extras
- Wrap config_dict with Json() in INSERT
- Wrap config_dict with Json() in UPDATE

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 16:38:39 +01:00
LarsandClaude Opus 4.6 c265ab1245 feat: RestDaysPage UI with Quick Mode presets (v9d Phase 2a)
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 45s
Build Test / lint-backend (push) Successful in 0s
Quick Mode with 4 presets:
- 💪 Kraft-Ruhetag (strength/hiit pause, cardio allowed, max 60%)
- 🏃 Cardio-Ruhetag (cardio pause, strength/mobility allowed, max 70%)
- 🧘 Entspannungstag (all pause, only meditation/walk, max 40%)
- 📉 Deload (all allowed, max 70% intensity)

Features:
- Preset selection with visual cards
- Date picker
- Optional note field
- List view with inline editing
- Delete with confirmation
- Toast notifications
- Detail view (shows rest_from, allows, intensity_max)

Integration:
- Route: /rest-days
- CaptureHub entry: 🛌 Ruhetage

Next Phase:
- Custom Mode (full control)
- Activity conflict warnings
- Weekly planning integration

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 16:33:32 +01:00
LarsandClaude Opus 4.6 b63d15fd02 feat: flexible rest days system with JSONB config (v9d Phase 2a)
Build Test / build-frontend (push) Successful in 14s
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
PROBLEM: Simple full_rest/active_recovery model doesn't support
context-specific rest days (e.g., strength rest but cardio allowed).

SOLUTION: JSONB-based flexible rest day configuration.

## Changes:

**Migration 010:**
- Refactor rest_days.type → rest_config JSONB
- Schema: {focus, rest_from[], allows[], intensity_max}
- Validation function with check constraint
- GIN index for performant JSONB queries

**Backend (routers/rest_days.py):**
- CRUD: list, create (upsert by date), get, update, delete
- Stats: count per week, focus distribution
- Validation: check activity conflicts with rest day config

**Frontend (api.js):**
- 7 new methods: listRestDays, createRestDay, updateRestDay,
  deleteRestDay, getRestDaysStats, validateActivity

**Integration:**
- Router registered in main.py
- Ready for weekly planning validation rules

## Next Steps:
- Frontend UI (RestDaysPage with Quick/Custom mode)
- Activity conflict warnings
- Dashboard widget

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 16:20:52 +01:00
LarsandClaude Opus 4.6 0278a8e4a6 fix: photo upload date parameter parsing
Deploy Development / deploy (push) Successful in 50s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Problem: Photos were always getting NULL date instead of form date,
causing frontend to fallback to created timestamp (today).

Root cause: FastAPI requires Form() wrapper for form fields when
mixing with File() parameters. Without it, the date parameter was
treated as query parameter and always received empty string.

Solution:
- Import Form from fastapi
- Change date parameter from str="" to str=Form("")
- Return photo_date instead of date in response (consistency)

Now photos correctly use the date from the upload form and can be
backdated when uploading later.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 14:33:01 +01:00
LarsandClaude Opus 4.6 ef27660fc8 fix: photo upload with empty date string
Build Test / build-frontend (push) Successful in 13s
Deploy Development / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 0s
Problem:
- Photo upload with empty date parameter (date='')
- PostgreSQL rejects empty string for DATE field
- Error: "invalid input syntax for type date: ''"
- Occurred when saving circumference entry with only photo

Fix:
- Convert empty string to NULL before INSERT
- Check: date if date and date.strip() else None
- NULL is valid for optional date field

Test case:
- Circumference entry with only photo → should work now
- Photo without date → stored with date=NULL ✓

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 14:25:27 +01:00
84 changed files with 22842 additions and 444 deletions

No files matched your search

+382 -18
View File
@@ -7,6 +7,26 @@
> | Coding-Regeln | `.claude/rules/CODING_RULES.md` |
> | Lessons Learned | `.claude/rules/LESSONS_LEARNED.md` |
## Claude Code Verantwortlichkeiten
**Issue-Management (Gitea):**
- ✅ Neue Issues/Feature Requests in Gitea anlegen
- ✅ Issue-Dokumentation in `docs/issues/` pflegen
- ✅ Issues mit Labels, Priority, Aufwandsschätzung versehen
- ✅ Bestehende Issues aktualisieren (Status, Beschreibung)
- ✅ Issues bei Fertigstellung schließen
- 🎯 Gitea: http://192.168.2.144:3000/Lars/mitai-jinkendo/issues
**Dokumentation:**
- Code-Änderungen in CLAUDE.md dokumentieren
- Versions-Updates bei jedem Feature/Fix
- Library-Dateien bei größeren Änderungen aktualisieren
**Entwicklung:**
- Alle Änderungen auf `develop` Branch
- Production Deploy nur nach expliziter Freigabe
- Migration 001-999 Pattern einhalten
## Projekt-Übersicht
**Mitai Jinkendo** (身体 Jinkendo) – selbst-gehostete PWA für Körper-Tracking mit KI-Auswertung.
Teil der **Jinkendo**-App-Familie (人拳道). Domains: jinkendo.de / .com / .life
@@ -56,7 +76,46 @@ frontend/src/
└── technical/ # MEMBERSHIP_SYSTEM.md
```
## Aktuelle Version: v9c (komplett) 🚀 Production seit 21.03.2026
## Aktuelle Version: v9e+ (Phase 1 Goal System Fixes) 🎯 Ready for Phase 0b - 27.03.2026
### 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
- ✅ **VO2Max Fix:** Spaltenname vo2_max (statt vo2max) korrigiert
- ✅ **Keine Doppelarbeit:** Phase 0b Platzhalter (120+) müssen bei v2.0 nicht umgeschrieben werden
### Phase 0a Completion (26.03.2026) 🎯
- ✅ **Phase 0a: Minimal Goal System:** Strategic + Tactical Layers implementiert
- ✅ **Migration 022:** goal_mode, goals, training_phases, fitness_tests tables
- ✅ **Backend Router:** goals.py mit vollständigem CRUD (490 Zeilen)
- ✅ **Frontend:** GoalsPage mit mobile-friendly Design (570 Zeilen)
- ✅ **Navigation:** Goals Preview (Dashboard) + Ziele Button (Analysis)
- ✅ **Basis geschaffen:** Für 120+ goal-aware Platzhalter (Phase 0b)
- ✅ **Dokumentation:** issue-50, NEXT_STEPS_2026-03-26.md, GOALS_SYSTEM_UNIFIED_ANALYSIS.md
### Frühere Updates (26.03.2026 - Vormittag)
- ✅ **circ_summary erweitert:** Best-of-Each Strategie mit Altersangaben
- ✅ **Stage Outputs Fix:** Debug-Info für Experten-Modus
- ✅ **Collapsible JSON:** Stage-Rohdaten aufklappbar
- ✅ **Gitea #28 geschlossen:** AI-Prompts Flexibilisierung
- ✅ **Gitea #44 geschlossen:** Analysen löschen behoben
- ✅ **Gitea #47 erstellt:** Wertetabelle Optimierung
### Implementiert ✅
- Login (E-Mail + bcrypt), Auth-Middleware alle Endpoints, Rate Limiting
@@ -135,32 +194,326 @@ frontend/src/
- `.claude/docs/functional/AI_PROMPTS.md` (erweitert um Fähigkeiten-Mapping)
- `.claude/docs/technical/CENTRAL_SUBSCRIPTION_SYSTEM.md`
### v9d – Phase 2 🔲 (Nächster Schritt)
### v9d – Phase 2 ✅ (Deployed to Production 23.03.2026)
**Vitalwerte & Erholung:**
- 🔲 Ruhetage erfassen (rest_days Tabelle)
- 🔲 Ruhepuls erfassen (vitals_log Tabelle)
- 🔲 HF-Zonen + Erholungsstatus
- 🔲 Schlaf-Modul (Basis)
- ✅ **Schlaf-Modul (v9d Phase 2b):**
- Tabelle `sleep_log` mit JSONB sleep_segments
- Schlafphasen (Deep, REM, Light, Awake)
- Apple Health CSV Import
- Schlaf-Statistiken & Trends
- Schlafschuld-Berechnung
- ✅ **Ruhetage (v9d Phase 2a):**
- Tabelle `rest_days` (Multi-Dimensional Rest)
- 3 Typen: Kraft-Ruhe, Cardio-Ruhe, Entspannung
- Quick Mode Presets + Custom Entry
- Validierung gegen geplante Aktivitäten
- Dashboard Widget mit aktuellen Ruhetagen
- ✅ **Vitalwerte erweitert (v9d Phase 2d):**
- **3-Tab Architektur:** Baseline (morgens) / Blutdruck (mehrfach täglich) / Import
- **Baseline Vitals:** Ruhepuls, HRV, VO2 Max, SpO2, Atemfrequenz
- **Blutdruck:** Systolisch/Diastolisch + Puls, WHO/ISH-Klassifizierung
- **Context-Tagging:** 8 Kontexte (nüchtern, nach Essen, Training, Stress, etc.)
- **Inline-Editing:** Alle Messungen direkt in der Liste bearbeitbar
- **Smart Upsert:** Baseline lädt existierende Einträge automatisch
- **CSV Import:** Omron (Deutsch) + Apple Health (Deutsch/Englisch)
- **Mobile-optimiert:** Volle Breite Felder, Sektions-Überschriften
- Unregelmäßiger Herzschlag & AFib-Warnungen
- Trend-Analyse (7d/14d/30d)
**Bugfixes (23.03.2026):**
- ✅ Import-Zählung korrigiert (skipped vs. updated)
- ✅ Deutsche Spaltennamen für CSV-Imports (Ruhepuls, Herzfrequenzvariabilität, etc.)
- ✅ Dezimalwerte-Parsing (safe_int/safe_float für Apple Health Exports)
- ✅ Error-Details in Import-Response (erste 10 Fehler im Frontend sichtbar)
- 🔲 **HF-Zonen + Erholungsstatus (v9d Phase 2e):**
- HF-Zonen-Verteilung pro Training
- Recovery Score basierend auf Ruhepuls + HRV + Schlaf
- Übertraining-Warnung
**Migrations:**
- Migration 010: sleep_log Tabelle (JSONB segments)
- Migration 011: rest_days Tabelle (Kraft, Cardio, Entspannung)
- Migration 012: Unique constraint rest_days (profile_id, date, rest_type)
- Migration 013: vitals_log Tabelle (Ruhepuls, HRV) - deprecated
- Migration 014: Extended vitals (BP, VO2 Max, SpO2, respiratory_rate) - deprecated
- Migration 015: **Vitals Refactoring** - Trennung in vitals_baseline + blood_pressure_log
📚 Details: `.claude/docs/functional/TRAINING_TYPES.md`
📚 Details: `.claude/docs/technical/MEMBERSHIP_SYSTEM.md` · `.claude/docs/architecture/FEATURE_ENFORCEMENT.md`
### Feature: Unified Prompt System ✅ (Completed 26.03.2026)
> **Gitea:** Issue #28 (AI-Prompts Flexibilisierung) - CLOSED
**AI-Prompts Flexibilisierung - Komplett überarbeitet:**
- ✅ **Unified Prompt System (4 Phasen):**
- **Phase 1:** DB-Migration - Schema erweitert
- `ai_prompts` um `type`, `stages`, `output_format`, `output_schema` erweitert
- Alle Prompts zu 1-stage Pipelines migriert
- Pipeline-Configs in `ai_prompts` konsolidiert
- **Phase 2:** Backend Executor
- `prompt_executor.py` - universeller Executor für base + pipeline
- Dynamische Placeholder-Auflösung (`{{stage_N_key}}`)
- JSON-Output-Validierung
- Multi-stage parallele Ausführung
- Reference (Basis-Prompts) + Inline (Templates) Support
- **Phase 3:** Frontend UI Consolidation
- `UnifiedPromptModal` - ein Editor für beide Typen
- `AdminPromptsPage` - Tab-Switcher entfernt, Type-Filter hinzugefügt
- Stage-Editor mit Add/Remove/Reorder
- Mobile-ready Design
- **Phase 4:** Cleanup & Docs
- Deprecated Komponenten entfernt (PipelineConfigModal, PromptEditModal)
- Old endpoints behalten für Backward-Compatibility
**Features:**
- Unbegrenzte dynamische Stages (keine 3-Stage Limitierung mehr)
- Mehrere Prompts pro Stage (parallel)
- Zwei Prompt-Typen: `base` (wiederverwendbar) + `pipeline` (Workflows)
- Inline-Templates oder Referenzen zu Basis-Prompts
- JSON-Output erzwingbar pro Prompt
- Cross-Module Korrelationen möglich
**Debug & Development Tools (26.03.2026):**
- ✅ **Comprehensive Debug System:**
- Test-Button in Prompt-Editor mit Debug-Modus
- Shows resolved/unresolved placeholders
- Displays final prompts sent to AI
- Per-stage debug info for pipelines
- Export debug data as JSON
- ✅ **Placeholder Export (per Test):**
- Button in Debug-Viewer
- Exports all placeholders with values per execution
- ✅ **Global Placeholder Export:**
- Settings → "📊 Platzhalter exportieren"
- All 32 placeholders with current values
- Organized by category
- Includes metadata (description, example)
- ✅ **Batch Import/Export:**
- Admin → "📦 Alle exportieren" (all prompts as JSON)
- Admin → "📥 Importieren" (upload JSON, create/update)
- Dev→Prod sync in 2 clicks
**Placeholder System Enhancements:**
- ✅ **6 New Placeholder Functions:**
- `{{sleep_avg_duration}}` - Average sleep duration (7d)
- `{{sleep_avg_quality}}` - Deep+REM percentage (7d)
- `{{rest_days_count}}` - Rest days count (30d)
- `{{vitals_avg_hr}}` - Average resting heart rate (7d)
- `{{vitals_avg_hrv}}` - Average HRV (7d)
- `{{vitals_vo2_max}}` - Latest VO2 Max value
- ✅ **7 Reconstructed Placeholders:**
- `{{caliper_summary}}`, `{{circ_summary}}`
- `{{goal_weight}}`, `{{goal_bf_pct}}`
- `{{nutrition_days}}`
- `{{protein_ziel_low}}`, `{{protein_ziel_high}}`
- `{{activity_detail}}`
- **Total: 32 active placeholders** across 6 categories
**Bug Fixes (26.03.2026):**
- ✅ **PIPELINE_MASTER Response:** Analysis page now uses unified executor
- Fixed: Old `/insights/run` endpoint sent raw template to AI
- Now: `/prompts/execute` with proper stage processing
- ✅ **Age Calculation:** Handle PostgreSQL DATE objects
- Fixed: `calculate_age()` expected string, got date object
- Now: Handles both strings and date objects
- ✅ **Sleep Quality 0%:** Lowercase stage names
- Fixed: Checked ['Deep', 'REM'], but stored as ['deep', 'rem']
- Now: Correct case-sensitive matching
- ✅ **SQL Column Name Errors:**
- Fixed: `bf_jpl` → `body_fat_pct`
- Fixed: `brust` → `c_chest`, etc.
- Fixed: `protein` → `protein_g`
- ✅ **Decimal × Float Type Error:**
- Fixed: `protein_ziel_low/high` calculations
- Now: Convert Decimal to float before multiplication
**Migrations:**
- Migration 020: Unified Prompt System Schema
**Backend Endpoints:**
- `POST /api/prompts/execute` - Universeller Executor (with save=true param)
- `POST /api/prompts/unified` - Create unified prompt
- `PUT /api/prompts/unified/{id}` - Update unified prompt
- `GET /api/prompts/export-all` - Export all prompts as JSON
- `POST /api/prompts/import` - Import prompts from JSON (with overwrite option)
- `GET /api/prompts/placeholders/export-values` - Export all placeholder values
**UI:**
- Admin → KI-Prompts: Type-Filter (Alle/Basis/Pipeline)
- Neuer Prompt-Editor mit dynamischem Stage-Builder
- Inline editing von Stages + Prompts
- Test-Button mit Debug-Viewer (always visible)
- Export/Import Buttons (📦 Alle exportieren, 📥 Importieren)
- Settings → 📊 Platzhalter exportieren
📚 Details: `.claude/docs/functional/AI_PROMPTS.md`
**Related Gitea Issues:**
- Gitea #28: AI-Prompts Flexibilisierung - ✅ CLOSED (26.03.2026)
- Gitea #42, #43: Enhanced Debug UI - 🔲 OPEN (Future enhancement)
- Gitea #44: BUG - Analysen löschen - ✅ CLOSED (26.03.2026)
- Gitea #45: KI Prompt-Optimierer - 🔲 OPEN (Future feature)
- Gitea #46: KI Prompt-Ersteller - 🔲 OPEN (Future feature)
- Gitea #47: Wertetabelle Optimierung - 🔲 OPEN (Refinement, siehe docs/issues/issue-50)
### Feature: Comprehensive Value Table ✅ (Completed 26.03.2026)
> **Gitea:** Basis-Implementierung abgeschlossen. Issue #47 (Wertetabelle Optimierung) für Refinement offen.
**AI-Analyse Transparenz - Vollständige Platzhalter-Anzeige:**
- ✅ **Metadata Collection System:**
- Alle genutzten Platzhalter mit Werten während Ausführung gesammelt
- Vollständige (nicht gekürzte) Werte aus placeholder_resolver
- Kategorisierung nach Modul (Profil, Körper, Ernährung, Training, etc.)
- Speicherung in ai_insights.metadata (JSONB)
- ✅ **Expert Mode:**
- Toggle-Button "🔬 Experten-Modus" in Analysis-Seite
- Normal-Modus: Zeigt nur relevante, gefüllte Werte
- Experten-Modus: Zeigt alle Werte inkl. Rohdaten und Stage-Outputs
- ✅ **Stage Output Extraction:**
- Basis-Prompts mit JSON-Output: Einzelwerte extrahiert
- Jedes Feld aus Stage-JSON als eigene Zeile
- Visuelle Kennzeichnung: ↳ für extrahierte Werte
- Source-Tracking: Welche Stage, welcher Output
- ✅ **Category Grouping:**
- Gruppierung nach Kategorien (PROFIL, KÖRPER, ERNÄHRUNG, etc.)
- Stage-Outputs als eigene Kategorien ("Stage 1 - Body")
- Rohdaten-Sektion (nur im Experten-Modus)
- Sortierung: Reguläre → Stage-Outputs → Rohdaten
- ✅ **Value Table Features:**
- Drei Spalten: Platzhalter | Wert | Beschreibung
- Keine Kürzung langer Werte
- Kategorie-Header mit grauem Hintergrund
- Empty/nicht verfügbar Werte ausgeblendet (Normal-Modus)
**Migrations:**
- Migration 021: ai_insights.metadata JSONB column
**Backend Endpoints:**
- `POST /api/prompts/execute` - Erweitert um Metadata-Collection
- `GET /api/insights/placeholders/catalog` - Placeholder-Kategorien
**UI:**
- Analysis Page: Value Table mit Category-Grouping
- Expert-Mode Toggle (🔬 Symbol)
- Collapsible JSON für Rohdaten
- Delete-Button für Insights (🗑️)
📚 Details: `.claude/docs/functional/AI_PROMPTS.md`
### Phase 0a: Minimal Goal System ✅ (Completed 26.03.2026)
> **Gitea:** Issue #50 (zu erstellen) - COMPLETED
> **Dokumentation:** `docs/issues/issue-50-phase-0a-goal-system.md`, `docs/GOALS_SYSTEM_UNIFIED_ANALYSIS.md`
**Zwei-Ebenen-Ziel-Architektur für goal-aware KI-Analysen:**
- ✅ **Strategic Layer (Goal Modes):**
- `goal_mode` in profiles table (weight_loss, strength, endurance, recomposition, health)
- Bestimmt Score-Gewichtung für alle KI-Analysen
- UI: 5 Goal Mode Cards mit Icons und Beschreibungen
- ✅ **Tactical Layer (Concrete Goals):**
- `goals` table mit vollständigem Progress-Tracking
- 8 Goal-Typen: weight, body_fat, lean_mass, vo2max, strength, flexibility, bp, rhr
- Auto-calculated progress percentage
- Linear projection für target_date
- Primary/Secondary goal concept
- UI: Goal CRUD mit Fortschrittsbalken, mobile-friendly
- ✅ **Training Phases Framework:**
- `training_phases` table (Auto-Detection vorbereitet)
- 5 Phase-Typen: calorie_deficit, calorie_surplus, deload, maintenance, periodization
- Status-Flow: suggested → accepted → active → completed
- Confidence scoring für KI-basierte Erkennung
- ✅ **Fitness Tests:**
- `fitness_tests` table für standardisierte Tests
- 8 Test-Typen: Cooper, Step Test, Pushups, Plank, VO2Max, Strength (Squat/Bench)
- Norm-Kategorisierung vorbereitet
**Backend:**
- Migration 022: goal_mode, goals, training_phases, fitness_tests tables
- Router: `routers/goals.py` (490 Zeilen) - vollständiges CRUD
- API Endpoints: `/api/goals/*` (mode, list, create, update, delete, phases, tests)
**Frontend:**
- GoalsPage: `frontend/src/pages/GoalsPage.jsx` (570 Zeilen)
- Mobile-friendly Design (full-width inputs, labels above)
- Navigation: Dashboard (Goals Preview Card) + Analysis (🎯 Ziele Button)
- api.js: 15+ neue Goal-Funktionen
**Commits:**
- `337667f` - feat: Phase 0a - Minimal Goal System
- `906a3b7` - fix: Migration 022 tracking
- `75f0a5d` - refactor: mobile-friendly design
- `5be52bc` - feat: goals navigation + UX
**Basis für Phase 0b:**
- Foundation für 120+ goal-aware Platzhalter
- Score-Berechnungen abhängig von goal_mode
- Intelligente Coaching-Funktionen
- Automatische Trainingsphasen-Erkennung
**Nächste Schritte:**
- Option A: Issue #49 - Prompt Page Assignment (6-8h, Quick Win)
- Option B: Phase 0b - Goal-Aware Placeholders (16-20h, Strategic)
📚 Details: `docs/NEXT_STEPS_2026-03-26.md`
## Feature-Roadmap
> Vollständiges Backlog: `.claude/docs/BACKLOG.md`
> Beim Implementieren: verlinkte Dok-Datei zuerst lesen!
> 📋 **Detaillierte Roadmap:** `.claude/docs/ROADMAP.md` (Phasen 0-3, Timeline, Abhängigkeiten)
> 📚 **Vollständiges Backlog:** `.claude/docs/BACKLOG.md`
> 🎯 **Gitea Issues:** http://192.168.2.144:3000/Lars/mitai-jinkendo/issues
>
> **Beim Implementieren:** verlinkte Dok-Datei zuerst lesen!
| Version | Feature | Dokumentation |
|---------|---------|---------------|
| v9c | Membership (aktiv) | `technical/MEMBERSHIP_SYSTEM.md` ✅ |
| v9d | Schlaf-Modul | `functional/SLEEP_MODULE.md` (ausstehend) |
| v9d | Trainingstypen + HF | `functional/TRAINING_TYPES.md` ✅ |
| v9e | Ziele + Vitalwerte | `functional/GOALS_VITALS.md` (ausstehend) |
| v9f | KI-Prompt Flexibilisierung | `functional/AI_PROMPTS.md` ✅ |
| v9g | Meditation + Selbstwahrnehmung | `functional/MEDITATION.md` (ausstehend) |
| v9h | Connectoren + Stripe | ausstehend |
| — | Responsive UI | `functional/RESPONSIVE_UI.md` ✅ |
### Aktuelle Entwicklung (Phase 0-2, ~10-13 Wochen)
| Phase | Fokus | Dauer | Gitea Issues |
|-------|-------|-------|--------------|
| **Phase 0** | Infrastruktur (v9f) | 4-6 Wochen | #24, #28, #29, #30 |
| **Phase 1** | Foundation (Charts, Goals) | 2-3 Wochen | #26, #25 |
| **Phase 2** | Engagement (Korrelationen, KI) | 3-4 Wochen | #27, #25 |
| **Phase 3** | Begleitung (Development Routes) | später | - |
**Phase 0 Issues:**
- #24: Quality-Filter (3h, Quick Win) ← **Start hier**
- #28: AI-Prompts Flexibilisierung (16-20h, kritisch)
- #29: Abilities-Matrix UI (6-8h)
- #30: Responsive UI (8-10h, parallel)
**Phase 1 Issues:**
- #26: Charts erweitern (8-10h)
- #25: Ziele-System Basis (10-12h)
**Phase 2 Issues:**
- #27: Korrelationen (6-8h)
- #25: Goals KI-Integration (4h)
### Versions-Übersicht
| Version | Feature | Dokumentation | Status |
|---------|---------|---------------|--------|
| v9c | Membership (aktiv) | `technical/MEMBERSHIP_SYSTEM.md` | ✅ Production |
| v9d | Schlaf-Modul | `functional/SLEEP_MODULE.md` | ✅ Production |
| v9d | Trainingstypen + HF | `functional/TRAINING_TYPES.md` | ✅ Production |
| v9e | Ziele + Vitalwerte | `functional/GOALS_VITALS.md` | 🔲 Phase 1 |
| v9f | KI-Prompt Flexibilisierung | `functional/AI_PROMPTS.md` | 🔲 Phase 0 |
| v9g | Meditation + Selbstwahrnehmung | `functional/MEDITATION.md` | 🔲 Phase 3 |
| v9h | Connectoren + Stripe | ausstehend | 🔲 Später |
| — | Responsive UI | `functional/RESPONSIVE_UI.md` | 🔲 Phase 0 |
## Deployment
@@ -204,6 +557,17 @@ subscriptions · coupons · coupon_redemptions · features
tier_limits · user_feature_restrictions · user_feature_usage
access_grants · user_activity_log
v9d neu (Training & Vitals):
training_types – 29 Trainingstypen in 7 Kategorien
activity_type_mappings – Lernendes Mapping-System (Deutsch/Englisch)
sleep_log – Schlaf mit JSONB segments (Phasen)
rest_days – Multi-dimensionale Ruhetage (Kraft/Cardio/Entspannung)
vitals_baseline – Morgenmessung (RHR, HRV, VO2 Max, SpO2, resp_rate)
blood_pressure_log – Blutdruck mehrfach täglich mit Context-Tagging
Deprecated (v9d Phase 2d):
vitals_log → vitals_log_backup_pre_015 (nach Migration 015)
Infrastruktur:
schema_migrations – Tracking für automatische DB-Migrationen
+181
View File
@@ -0,0 +1,181 @@
#!/usr/bin/env python3
"""
Quick diagnostic: Check Migration 024 state
Run this inside the backend container:
docker exec bodytrack-dev-backend-1 python check_migration_024.py
"""
import psycopg2
import os
from psycopg2.extras import RealDictCursor
# Database connection
DB_HOST = os.getenv('DB_HOST', 'db')
DB_PORT = os.getenv('DB_PORT', '5432')
DB_NAME = os.getenv('DB_NAME', 'bodytrack')
DB_USER = os.getenv('DB_USER', 'bodytrack')
DB_PASS = os.getenv('DB_PASSWORD', '')
def main():
print("=" * 70)
print("Migration 024 Diagnostic")
print("=" * 70)
# Connect to database
conn = psycopg2.connect(
host=DB_HOST,
port=DB_PORT,
dbname=DB_NAME,
user=DB_USER,
password=DB_PASS
)
cur = conn.cursor(cursor_factory=RealDictCursor)
# 1. Check if table exists
print("\n1. Checking if goal_type_definitions table exists...")
cur.execute("""
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_name = 'goal_type_definitions'
)
""")
exists = cur.fetchone()['exists']
print(f" ✓ Table exists: {exists}")
if not exists:
print("\n❌ TABLE DOES NOT EXIST - Migration 024 did not run!")
print("\nRECOMMENDED ACTION:")
print(" 1. Restart backend container: docker restart bodytrack-dev-backend-1")
print(" 2. Check logs: docker logs bodytrack-dev-backend-1 | grep 'Migration'")
cur.close()
conn.close()
return
# 2. Check row count
print("\n2. Checking row count...")
cur.execute("SELECT COUNT(*) as count FROM goal_type_definitions")
count = cur.fetchone()['count']
print(f" Row count: {count}")
if count == 0:
print("\n❌ TABLE IS EMPTY - Seed data was not inserted!")
print("\nPOSSIBLE CAUSES:")
print(" - INSERT statements failed (constraint violation?)")
print(" - Migration ran partially")
print("\nRECOMMENDED ACTION:")
print(" Run the seed statements manually (see below)")
else:
print(f" ✓ Table has {count} entries")
# 3. Show all entries
print("\n3. Current goal type definitions:")
cur.execute("""
SELECT type_key, label_de, unit, is_system, is_active, created_at
FROM goal_type_definitions
ORDER BY is_system DESC, type_key
""")
entries = cur.fetchall()
if entries:
print(f"\n {'Type Key':<20} {'Label':<20} {'Unit':<10} {'System':<8} {'Active':<8}")
print(" " + "-" * 70)
for row in entries:
status = "SYSTEM" if row['is_system'] else "CUSTOM"
active = "YES" if row['is_active'] else "NO"
print(f" {row['type_key']:<20} {row['label_de']:<20} {row['unit']:<10} {status:<8} {active:<8}")
else:
print(" (empty)")
# 4. Check schema_migrations
print("\n4. Checking schema_migrations tracking...")
cur.execute("""
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_name = 'schema_migrations'
)
""")
sm_exists = cur.fetchone()['exists']
if sm_exists:
cur.execute("""
SELECT filename, executed_at
FROM schema_migrations
WHERE filename = '024_goal_type_registry.sql'
""")
tracked = cur.fetchone()
if tracked:
print(f" ✓ Migration 024 is tracked (executed: {tracked['executed_at']})")
else:
print(" ❌ Migration 024 is NOT tracked in schema_migrations")
else:
print(" ⚠️ schema_migrations table does not exist")
# 5. Check for errors
print("\n5. Potential issues:")
issues = []
if count == 0:
issues.append("No seed data - INSERTs failed")
if count > 0 and count < 6:
issues.append(f"Only {count} types (expected 8) - partial seed")
cur.execute("""
SELECT COUNT(*) as inactive_count
FROM goal_type_definitions
WHERE is_active = false
""")
inactive = cur.fetchone()['inactive_count']
if inactive > 2:
issues.append(f"{inactive} inactive types (expected 2)")
if not issues:
print(" ✓ No issues detected")
else:
for issue in issues:
print(f" ❌ {issue}")
# 6. Test query that frontend uses
print("\n6. Testing frontend query (WHERE is_active = true)...")
cur.execute("""
SELECT COUNT(*) as active_count
FROM goal_type_definitions
WHERE is_active = true
""")
active_count = cur.fetchone()['active_count']
print(f" Active types returned: {active_count}")
if active_count == 0:
print(" ❌ This is why frontend shows empty list!")
print("\n" + "=" * 70)
print("SUMMARY")
print("=" * 70)
if count == 0:
print("\n🔴 PROBLEM: Table exists but has no data")
print("\nQUICK FIX: Run these SQL commands manually:")
print("\n```sql")
print("-- Connect to database:")
print("docker exec -it bodytrack-dev-db-1 psql -U bodytrack -d bodytrack")
print("\n-- Then paste migration content:")
print("-- (copy from backend/migrations/024_goal_type_registry.sql)")
print("-- Skip CREATE TABLE (already exists), run INSERT statements only")
print("```")
elif active_count >= 6:
print("\n🟢 EVERYTHING LOOKS GOOD")
print(f" {active_count} active goal types available")
print("\nIf frontend still shows error, check:")
print(" 1. Backend logs: docker logs bodytrack-dev-backend-1 -f")
print(" 2. Network tab in browser DevTools")
print(" 3. API endpoint: curl -H 'X-Auth-Token: YOUR_TOKEN' http://localhost:8099/api/goals/goal-types")
else:
print(f"\n🟡 PARTIAL DATA: {active_count} active types (expected 6)")
print(" Some INSERTs might have failed")
cur.close()
conn.close()
if __name__ == '__main__':
main()
+287
View File
@@ -0,0 +1,287 @@
"""
Training Type Profiles - Helper Functions
Utilities for loading parameters, profiles, and running evaluations.
Issue: #15
Date: 2026-03-23
"""
from typing import Dict, Optional, List
from decimal import Decimal
import logging
from db import get_cursor
from profile_evaluator import TrainingProfileEvaluator
logger = logging.getLogger(__name__)
def convert_decimals(obj):
"""
Recursively converts Decimal objects to float for JSON serialization.
PostgreSQL returns numeric values as Decimal, but psycopg2.Json() can't serialize them.
"""
if isinstance(obj, Decimal):
return float(obj)
elif isinstance(obj, dict):
return {k: convert_decimals(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [convert_decimals(item) for item in obj]
return obj
def load_parameters_registry(cur) -> Dict[str, Dict]:
"""
Loads training parameters registry from database.
Returns:
Dict mapping parameter_key -> config
"""
cur.execute("""
SELECT key, name_de, name_en, category, data_type, unit,
description_de, source_field, validation_rules
FROM training_parameters
WHERE is_active = true
""")
registry = {}
for row in cur.fetchall():
registry[row['key']] = dict(row)
return registry
def load_training_type_profile(cur, training_type_id: int) -> Optional[Dict]:
"""
Loads training type profile for a given type ID.
Returns:
Profile JSONB or None if not configured
"""
cur.execute(
"SELECT profile FROM training_types WHERE id = %s",
(training_type_id,)
)
row = cur.fetchone()
if row and row['profile']:
return row['profile']
return None
def load_evaluation_context(
cur,
profile_id: str,
activity_date: str,
lookback_days: int = 30
) -> Dict:
"""
Loads context data for evaluation (user profile + recent activities).
Args:
cur: Database cursor
profile_id: User profile ID
activity_date: Date of activity being evaluated
lookback_days: How many days of history to load
Returns:
{
"user_profile": {...},
"recent_activities": [...],
"historical_activities": [...]
}
"""
# Load user profile
cur.execute(
"SELECT hf_max, sleep_goal_minutes FROM profiles WHERE id = %s",
(profile_id,)
)
user_row = cur.fetchone()
user_profile = dict(user_row) if user_row else {}
# Load recent activities (last N days)
cur.execute("""
SELECT id, date, training_type_id, duration_min, hr_avg, hr_max,
distance_km, kcal_active, rpe
FROM activity_log
WHERE profile_id = %s
AND date >= %s::date - INTERVAL '%s days'
AND date < %s::date
ORDER BY date DESC
LIMIT 50
""", (profile_id, activity_date, lookback_days, activity_date))
recent_activities = [dict(r) for r in cur.fetchall()]
# Historical activities (same for MVP)
historical_activities = recent_activities
return {
"user_profile": user_profile,
"recent_activities": recent_activities,
"historical_activities": historical_activities
}
def evaluate_and_save_activity(
cur,
activity_id: str,
activity_data: Dict,
training_type_id: int,
profile_id: str
) -> Optional[Dict]:
"""
Evaluates an activity and saves the result to the database.
Args:
cur: Database cursor
activity_id: Activity ID
activity_data: Activity data dict
training_type_id: Training type ID
profile_id: User profile ID
Returns:
Evaluation result or None if no profile configured
"""
# Load profile
profile = load_training_type_profile(cur, training_type_id)
if not profile:
logger.info(f"[EVALUATION] No profile for training_type {training_type_id}, skipping")
return None
# Load parameters registry
parameters = load_parameters_registry(cur)
# Load context
context = load_evaluation_context(
cur,
profile_id,
activity_data.get("date"),
lookback_days=30
)
# Convert Decimal values in activity_data and context
activity_data_clean = convert_decimals(activity_data)
context_clean = convert_decimals(context)
# Evaluate
evaluator = TrainingProfileEvaluator(parameters)
evaluation_result = evaluator.evaluate_activity(
activity_data_clean,
profile,
context_clean
)
# Save to database
from psycopg2.extras import Json
# Convert Decimal to float for JSON serialization
evaluation_result_clean = convert_decimals(evaluation_result)
cur.execute("""
UPDATE activity_log
SET evaluation = %s,
quality_label = %s,
overall_score = %s
WHERE id = %s
""", (
Json(evaluation_result_clean),
evaluation_result_clean.get("quality_label"),
evaluation_result_clean.get("overall_score"),
activity_id
))
logger.info(
f"[EVALUATION] Activity {activity_id}: "
f"{evaluation_result.get('quality_label')} "
f"(score: {evaluation_result.get('overall_score')})"
)
return evaluation_result
def batch_evaluate_activities(
cur,
profile_id: str,
limit: Optional[int] = None
) -> Dict:
"""
Re-evaluates all activities for a user.
Useful for:
- Initial setup after profiles are configured
- Re-evaluation after profile changes
Args:
cur: Database cursor
profile_id: User profile ID
limit: Optional limit for testing
Returns:
{
"total": int,
"evaluated": int,
"skipped": int,
"errors": int
}
"""
# Load all activities
query = """
SELECT id, profile_id, date, training_type_id, duration_min,
hr_avg, hr_max, distance_km, kcal_active, kcal_resting,
rpe, pace_min_per_km, cadence, elevation_gain
FROM activity_log
WHERE profile_id = %s
ORDER BY date DESC
"""
params = [profile_id]
if limit:
query += " LIMIT %s"
params.append(limit)
cur.execute(query, params)
activities = cur.fetchall()
stats = {
"total": len(activities),
"evaluated": 0,
"skipped": 0,
"errors": 0
}
# Track error details
error_details = []
for activity in activities:
activity_dict = dict(activity)
try:
result = evaluate_and_save_activity(
cur,
activity_dict["id"],
activity_dict,
activity_dict["training_type_id"],
profile_id
)
if result:
stats["evaluated"] += 1
else:
stats["skipped"] += 1
except Exception as e:
logger.error(f"[BATCH-EVAL] Error evaluating {activity_dict['id']}: {e}")
error_details.append({
"activity_id": activity_dict['id'],
"training_type_id": activity_dict.get('training_type_id'),
"error": str(e)
})
stats["errors"] += 1
# Add error details to stats (limit to first 10)
if error_details:
stats["error_details"] = error_details[:10]
logger.info(f"[BATCH-EVAL] Completed: {stats}")
return stats
+215
View File
@@ -0,0 +1,215 @@
#!/usr/bin/env python3
"""
Quick Fix: Insert seed data for goal_type_definitions
This script ONLY inserts the 8 standard goal types.
Safe to run multiple times (uses ON CONFLICT DO NOTHING).
Run inside backend container:
docker exec bodytrack-dev-backend-1 python fix_seed_goal_types.py
"""
import psycopg2
import os
from psycopg2.extras import RealDictCursor
# Database connection
DB_HOST = os.getenv('DB_HOST', 'db')
DB_PORT = os.getenv('DB_PORT', '5432')
DB_NAME = os.getenv('DB_NAME', 'bodytrack')
DB_USER = os.getenv('DB_USER', 'bodytrack')
DB_PASS = os.getenv('DB_PASSWORD', '')
SEED_DATA = [
{
'type_key': 'weight',
'label_de': 'Gewicht',
'label_en': 'Weight',
'unit': 'kg',
'icon': '⚖️',
'category': 'body',
'source_table': 'weight_log',
'source_column': 'weight',
'aggregation_method': 'latest',
'description': 'Aktuelles Körpergewicht',
'is_system': True
},
{
'type_key': 'body_fat',
'label_de': 'Körperfett',
'label_en': 'Body Fat',
'unit': '%',
'icon': '📊',
'category': 'body',
'source_table': 'caliper_log',
'source_column': 'body_fat_pct',
'aggregation_method': 'latest',
'description': 'Körperfettanteil aus Caliper-Messung',
'is_system': True
},
{
'type_key': 'lean_mass',
'label_de': 'Muskelmasse',
'label_en': 'Lean Mass',
'unit': 'kg',
'icon': '💪',
'category': 'body',
'calculation_formula': '{"type": "lean_mass", "dependencies": ["weight_log.weight", "caliper_log.body_fat_pct"], "formula": "weight - (weight * body_fat_pct / 100)"}',
'description': 'Fettfreie Körpermasse (berechnet aus Gewicht und Körperfett)',
'is_system': True
},
{
'type_key': 'vo2max',
'label_de': 'VO2Max',
'label_en': 'VO2Max',
'unit': 'ml/kg/min',
'icon': '🫁',
'category': 'recovery',
'source_table': 'vitals_baseline',
'source_column': 'vo2_max',
'aggregation_method': 'latest',
'description': 'Maximale Sauerstoffaufnahme (geschätzt oder gemessen)',
'is_system': True
},
{
'type_key': 'rhr',
'label_de': 'Ruhepuls',
'label_en': 'Resting Heart Rate',
'unit': 'bpm',
'icon': '💓',
'category': 'recovery',
'source_table': 'vitals_baseline',
'source_column': 'resting_hr',
'aggregation_method': 'latest',
'description': 'Ruhepuls morgens vor dem Aufstehen',
'is_system': True
},
{
'type_key': 'bp',
'label_de': 'Blutdruck',
'label_en': 'Blood Pressure',
'unit': 'mmHg',
'icon': '❤️',
'category': 'recovery',
'source_table': 'blood_pressure_log',
'source_column': 'systolic',
'aggregation_method': 'latest',
'description': 'Blutdruck (aktuell nur systolisch, v2.0: beide Werte)',
'is_system': True
},
{
'type_key': 'strength',
'label_de': 'Kraft',
'label_en': 'Strength',
'unit': 'kg',
'icon': '🏋️',
'category': 'activity',
'description': 'Maximalkraft (Platzhalter, Datenquelle in v2.0)',
'is_system': True,
'is_active': False
},
{
'type_key': 'flexibility',
'label_de': 'Beweglichkeit',
'label_en': 'Flexibility',
'unit': 'cm',
'icon': '🤸',
'category': 'activity',
'description': 'Beweglichkeit (Platzhalter, Datenquelle in v2.0)',
'is_system': True,
'is_active': False
}
]
def main():
print("=" * 70)
print("Goal Type Definitions - Seed Data Fix")
print("=" * 70)
# Connect to database
conn = psycopg2.connect(
host=DB_HOST,
port=DB_PORT,
dbname=DB_NAME,
user=DB_USER,
password=DB_PASS
)
conn.autocommit = False
cur = conn.cursor(cursor_factory=RealDictCursor)
try:
# Check current state
cur.execute("SELECT COUNT(*) as count FROM goal_type_definitions")
before_count = cur.fetchone()['count']
print(f"\nBefore: {before_count} goal types in database")
# Insert seed data
print(f"\nInserting {len(SEED_DATA)} standard goal types...")
inserted = 0
skipped = 0
for data in SEED_DATA:
columns = list(data.keys())
values = [data[col] for col in columns]
placeholders = ', '.join(['%s'] * len(values))
cols_str = ', '.join(columns)
sql = f"""
INSERT INTO goal_type_definitions ({cols_str})
VALUES ({placeholders})
ON CONFLICT (type_key) DO NOTHING
RETURNING id
"""
cur.execute(sql, values)
result = cur.fetchone()
if result:
inserted += 1
print(f" ✓ {data['type_key']}: {data['label_de']}")
else:
skipped += 1
print(f" - {data['type_key']}: already exists (skipped)")
conn.commit()
# Check final state
cur.execute("SELECT COUNT(*) as count FROM goal_type_definitions")
after_count = cur.fetchone()['count']
print(f"\nAfter: {after_count} goal types in database")
print(f" Inserted: {inserted}")
print(f" Skipped: {skipped}")
# Show summary
cur.execute("""
SELECT type_key, label_de, is_active, is_system
FROM goal_type_definitions
ORDER BY is_system DESC, type_key
""")
print("\n" + "=" * 70)
print("Current Goal Types:")
print("=" * 70)
print(f"\n{'Type Key':<20} {'Label':<20} {'System':<8} {'Active':<8}")
print("-" * 70)
for row in cur.fetchall():
status = "YES" if row['is_system'] else "NO"
active = "YES" if row['is_active'] else "NO"
print(f"{row['type_key']:<20} {row['label_de']:<20} {status:<8} {active:<8}")
print("\n✅ DONE! Goal types seeded successfully.")
print("\nNext step: Reload frontend to see the changes.")
except Exception as e:
conn.rollback()
print(f"\n❌ Error: {e}")
import traceback
traceback.print_exc()
finally:
cur.close()
conn.close()
if __name__ == '__main__':
main()
+504
View File
@@ -0,0 +1,504 @@
"""
Goal Utilities - Abstraction Layer for Focus Weights & Universal Value Fetcher
This module provides:
1. Abstraction layer between goal modes and focus weights (Phase 1)
2. Universal value fetcher for dynamic goal types (Phase 1.5)
Version History:
- V1 (Phase 1): Maps goal_mode to predefined weights
- V1.5 (Phase 1.5): Universal value fetcher for DB-registry goal types
- V2 (future): Reads from focus_areas table with custom user weights
Part of Phase 1 + Phase 1.5: Flexible Goal System
"""
from typing import Dict, Optional, Any
from datetime import date, timedelta
from decimal import Decimal
import json
from db import get_cursor
def get_focus_weights(conn, profile_id: str) -> Dict[str, float]:
"""
Get focus area weights for a profile.
V2 (Goal System v2.0): Reads from focus_areas table with custom user weights.
Falls back to goal_mode mapping if focus_areas not set.
Args:
conn: Database connection
profile_id: User's profile ID
Returns:
Dict with focus weights (sum = 1.0):
{
'weight_loss': 0.3, # Fat loss priority
'muscle_gain': 0.2, # Muscle gain priority
'strength': 0.25, # Strength training priority
'endurance': 0.25, # Cardio/endurance priority
'flexibility': 0.0, # Mobility priority
'health': 0.0 # General health maintenance
}
Example Usage in Phase 0b:
weights = get_focus_weights(conn, profile_id)
# Score calculation considers user's focus
overall_score = (
body_score * weights['weight_loss'] +
strength_score * weights['strength'] +
cardio_score * weights['endurance']
)
"""
cur = get_cursor(conn)
# V2: Try to fetch from focus_areas table
cur.execute("""
SELECT weight_loss_pct, muscle_gain_pct, strength_pct,
endurance_pct, flexibility_pct, health_pct
FROM focus_areas
WHERE profile_id = %s AND active = true
LIMIT 1
""", (profile_id,))
row = cur.fetchone()
if row:
# Convert percentages to weights (0-1 range)
return {
'weight_loss': row['weight_loss_pct'] / 100.0,
'muscle_gain': row['muscle_gain_pct'] / 100.0,
'strength': row['strength_pct'] / 100.0,
'endurance': row['endurance_pct'] / 100.0,
'flexibility': row['flexibility_pct'] / 100.0,
'health': row['health_pct'] / 100.0
}
# V1 Fallback: Use goal_mode if focus_areas not set
cur.execute(
"SELECT goal_mode FROM profiles WHERE id = %s",
(profile_id,)
)
row = cur.fetchone()
if not row:
# Ultimate fallback: balanced health focus
return {
'weight_loss': 0.0,
'muscle_gain': 0.0,
'strength': 0.10,
'endurance': 0.20,
'flexibility': 0.15,
'health': 0.55
}
goal_mode = row['goal_mode']
if not goal_mode:
return {
'weight_loss': 0.0,
'muscle_gain': 0.0,
'strength': 0.10,
'endurance': 0.20,
'flexibility': 0.15,
'health': 0.55
}
# V1: Predefined weight mappings per goal_mode (fallback)
WEIGHT_MAPPINGS = {
'weight_loss': {
'weight_loss': 0.60,
'endurance': 0.20,
'muscle_gain': 0.0,
'strength': 0.10,
'flexibility': 0.05,
'health': 0.05
},
'strength': {
'strength': 0.50,
'muscle_gain': 0.40,
'endurance': 0.10,
'weight_loss': 0.0,
'flexibility': 0.0,
'health': 0.0
},
'endurance': {
'endurance': 0.70,
'health': 0.20,
'flexibility': 0.10,
'weight_loss': 0.0,
'muscle_gain': 0.0,
'strength': 0.0
},
'recomposition': {
'weight_loss': 0.30,
'muscle_gain': 0.30,
'strength': 0.25,
'endurance': 0.10,
'flexibility': 0.05,
'health': 0.0
},
'health': {
'health': 0.50,
'endurance': 0.20,
'flexibility': 0.15,
'strength': 0.10,
'weight_loss': 0.05,
'muscle_gain': 0.0
}
}
return WEIGHT_MAPPINGS.get(goal_mode, WEIGHT_MAPPINGS['health'])
def get_primary_focus(conn, profile_id: str) -> str:
"""
Get the primary focus area for a profile.
Returns the focus area with the highest weight.
Useful for UI labels and simple decision logic.
Args:
conn: Database connection
profile_id: User's profile ID
Returns:
Primary focus area name (e.g., 'weight_loss', 'strength')
"""
weights = get_focus_weights(conn, profile_id)
return max(weights.items(), key=lambda x: x[1])[0]
def get_focus_description(focus_area: str) -> str:
"""
Get human-readable description for a focus area.
Args:
focus_area: Focus area key (e.g., 'weight_loss')
Returns:
German description for UI display
"""
descriptions = {
'weight_loss': 'Gewichtsreduktion & Fettabbau',
'muscle_gain': 'Muskelaufbau & Hypertrophie',
'strength': 'Kraftsteigerung & Performance',
'endurance': 'Ausdauer & aerobe Kapazität',
'flexibility': 'Beweglichkeit & Mobilität',
'health': 'Allgemeine Gesundheit & Erhaltung'
}
return descriptions.get(focus_area, focus_area)
# ============================================================================
# Phase 1.5: Universal Value Fetcher for Dynamic Goal Types
# ============================================================================
def get_goal_type_config(conn, type_key: str) -> Optional[Dict[str, Any]]:
"""
Get goal type configuration from database registry.
Args:
conn: Database connection
type_key: Goal type key (e.g., 'weight', 'meditation_minutes')
Returns:
Dict with config or None if not found/inactive
"""
cur = get_cursor(conn)
cur.execute("""
SELECT type_key, source_table, source_column, aggregation_method,
calculation_formula, filter_conditions, label_de, unit, icon, category
FROM goal_type_definitions
WHERE type_key = %s AND is_active = true
LIMIT 1
""", (type_key,))
return cur.fetchone()
def get_current_value_for_goal(conn, profile_id: str, goal_type: str) -> Optional[float]:
"""
Universal value fetcher for any goal type.
Reads configuration from goal_type_definitions table and executes
appropriate query based on aggregation_method or calculation_formula.
Args:
conn: Database connection
profile_id: User's profile ID
goal_type: Goal type key (e.g., 'weight', 'meditation_minutes')
Returns:
Current value as float or None if not available
"""
config = get_goal_type_config(conn, goal_type)
if not config:
print(f"[WARNING] Goal type '{goal_type}' not found or inactive")
return None
# Complex calculation (e.g., lean_mass)
if config['calculation_formula']:
return _execute_calculation_formula(conn, profile_id, config['calculation_formula'])
# Simple aggregation
return _fetch_by_aggregation_method(
conn,
profile_id,
config['source_table'],
config['source_column'],
config['aggregation_method'],
config.get('filter_conditions')
)
def _fetch_by_aggregation_method(
conn,
profile_id: str,
table: str,
column: str,
method: str,
filter_conditions: Optional[Any] = None
) -> Optional[float]:
"""
Fetch value using specified aggregation method.
Supported methods:
- latest: Most recent value
- avg_7d: 7-day average
- avg_30d: 30-day average
- sum_30d: 30-day sum
- count_7d: Count of entries in last 7 days
- count_30d: Count of entries in last 30 days
- min_30d: Minimum value in last 30 days
- max_30d: Maximum value in last 30 days
Args:
filter_conditions: Optional JSON filters (e.g., {"training_type": "strength"})
"""
# Guard: source_table/column required for simple aggregation
if not table or not column:
print(f"[WARNING] Missing source_table or source_column for aggregation")
return None
# Table-specific date column mapping (some tables use different column names)
DATE_COLUMN_MAP = {
'blood_pressure_log': 'measured_at',
'activity_log': 'date',
'weight_log': 'date',
'circumference_log': 'date',
'caliper_log': 'date',
'nutrition_log': 'date',
'sleep_log': 'date',
'vitals_baseline': 'date',
'rest_days': 'date',
'fitness_tests': 'test_date'
}
date_col = DATE_COLUMN_MAP.get(table, 'date')
# Build filter SQL from JSON conditions
filter_sql = ""
filter_params = []
if filter_conditions:
try:
if isinstance(filter_conditions, str):
filters = json.loads(filter_conditions)
else:
filters = filter_conditions
for filter_col, filter_val in filters.items():
if isinstance(filter_val, list):
# IN clause for multiple values
placeholders = ', '.join(['%s'] * len(filter_val))
filter_sql += f" AND {filter_col} IN ({placeholders})"
filter_params.extend(filter_val)
else:
# Single value equality
filter_sql += f" AND {filter_col} = %s"
filter_params.append(filter_val)
except (json.JSONDecodeError, TypeError, AttributeError) as e:
print(f"[WARNING] Invalid filter_conditions: {e}, ignoring filters")
cur = get_cursor(conn)
try:
if method == 'latest':
params = [profile_id] + filter_params
cur.execute(f"""
SELECT {column} FROM {table}
WHERE profile_id = %s AND {column} IS NOT NULL{filter_sql}
ORDER BY {date_col} DESC LIMIT 1
""", params)
row = cur.fetchone()
return float(row[column]) if row else None
elif method == 'avg_7d':
days_ago = date.today() - timedelta(days=7)
params = [profile_id, days_ago] + filter_params
cur.execute(f"""
SELECT AVG({column}) as avg_value FROM {table}
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
elif method == 'avg_30d':
days_ago = date.today() - timedelta(days=30)
params = [profile_id, days_ago] + filter_params
cur.execute(f"""
SELECT AVG({column}) as avg_value FROM {table}
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
elif method == 'sum_30d':
days_ago = date.today() - timedelta(days=30)
params = [profile_id, days_ago] + filter_params
cur.execute(f"""
SELECT SUM({column}) as sum_value FROM {table}
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
elif method == 'count_7d':
days_ago = date.today() - timedelta(days=7)
params = [profile_id, days_ago] + filter_params
cur.execute(f"""
SELECT COUNT(*) as count_value FROM {table}
WHERE profile_id = %s AND {date_col} >= %s{filter_sql}
""", params)
row = cur.fetchone()
return float(row['count_value']) if row else 0.0
elif method == 'count_30d':
days_ago = date.today() - timedelta(days=30)
params = [profile_id, days_ago] + filter_params
cur.execute(f"""
SELECT COUNT(*) as count_value FROM {table}
WHERE profile_id = %s AND {date_col} >= %s{filter_sql}
""", params)
row = cur.fetchone()
return float(row['count_value']) if row else 0.0
elif method == 'min_30d':
days_ago = date.today() - timedelta(days=30)
params = [profile_id, days_ago] + filter_params
cur.execute(f"""
SELECT MIN({column}) as min_value FROM {table}
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
elif method == 'max_30d':
days_ago = date.today() - timedelta(days=30)
params = [profile_id, days_ago] + filter_params
cur.execute(f"""
SELECT MAX({column}) as max_value FROM {table}
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
else:
print(f"[WARNING] Unknown aggregation method: {method}")
return None
except Exception as e:
print(f"[ERROR] Failed to fetch value from {table}.{column} using {method}: {e}")
return None
def _execute_calculation_formula(conn, profile_id: str, formula_json: str) -> Optional[float]:
"""
Execute complex calculation formula.
Currently supports:
- lean_mass: weight - (weight * body_fat_pct / 100)
Future: Parse JSON formula and execute dynamically.
Args:
conn: Database connection
profile_id: User's profile ID
formula_json: JSON string with calculation config
Returns:
Calculated value or None
"""
try:
formula = json.loads(formula_json)
calc_type = formula.get('type')
if calc_type == 'lean_mass':
# Get dependencies
cur = get_cursor(conn)
cur.execute("""
SELECT weight FROM weight_log
WHERE profile_id = %s
ORDER BY date DESC LIMIT 1
""", (profile_id,))
weight_row = cur.fetchone()
cur.execute("""
SELECT body_fat_pct FROM caliper_log
WHERE profile_id = %s
ORDER BY date DESC LIMIT 1
""", (profile_id,))
bf_row = cur.fetchone()
if weight_row and bf_row:
weight = float(weight_row['weight'])
bf_pct = float(bf_row['body_fat_pct'])
lean_mass = weight - (weight * bf_pct / 100.0)
return round(lean_mass, 2)
return None
else:
print(f"[WARNING] Unknown calculation type: {calc_type}")
return None
except (json.JSONDecodeError, KeyError, ValueError, TypeError) as e:
print(f"[ERROR] Formula execution failed: {e}, formula={formula_json}")
return None
# Future V2 Implementation (commented out for reference):
"""
def get_focus_weights_v2(conn, profile_id: str) -> Dict[str, float]:
'''V2: Read from focus_areas table with custom user weights'''
cur = get_cursor(conn)
cur.execute('''
SELECT weight_loss_pct, muscle_gain_pct, endurance_pct,
strength_pct, flexibility_pct, health_pct
FROM focus_areas
WHERE profile_id = %s AND active = true
LIMIT 1
''', (profile_id,))
row = cur.fetchone()
if not row:
# Fallback to V1 behavior
return get_focus_weights(conn, profile_id)
# Convert percentages to weights (0-1 range)
return {
'weight_loss': row['weight_loss_pct'] / 100.0,
'muscle_gain': row['muscle_gain_pct'] / 100.0,
'endurance': row['endurance_pct'] / 100.0,
'strength': row['strength_pct'] / 100.0,
'flexibility': row['flexibility_pct'] / 100.0,
'health': row['health_pct'] / 100.0
}
"""
+10 -2
View File
@@ -20,7 +20,10 @@ from routers import activity, nutrition, photos, insights, prompts
from routers import admin, stats, exportdata, importdata
from routers import subscription, coupons, features, tiers_mgmt, tier_limits
from routers import user_restrictions, access_grants, training_types, admin_training_types
from routers import admin_activity_mappings, sleep
from routers import admin_activity_mappings, sleep, rest_days
from routers import vitals_baseline, blood_pressure # v9d Phase 2d Refactored
from routers import evaluation # v9d/v9e Training Type Profiles (#15)
from routers import goals # v9e Goal System (Strategic + Tactical)
# ── App Configuration ─────────────────────────────────────────────────────────
DATA_DIR = Path(os.getenv("DATA_DIR", "./data"))
@@ -86,11 +89,16 @@ app.include_router(tier_limits.router) # /api/tier-limits (admin)
app.include_router(user_restrictions.router) # /api/user-restrictions (admin)
app.include_router(access_grants.router) # /api/access-grants (admin)
# v9d Training Types & Sleep Module
# v9d Training Types & Sleep Module & Rest Days & Vitals
app.include_router(training_types.router) # /api/training-types/*
app.include_router(admin_training_types.router) # /api/admin/training-types/*
app.include_router(admin_activity_mappings.router) # /api/admin/activity-mappings/*
app.include_router(sleep.router) # /api/sleep/* (v9d Phase 2b)
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(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(goals.router) # /api/goals/* (v9e Goal System Strategic + Tactical)
# ── Health Check ──────────────────────────────────────────────────────────────
@app.get("/")
@@ -0,0 +1,62 @@
-- Migration 010: Rest Days Refactoring zu JSONB
-- v9d Phase 2a: Flexible, context-specific rest days
-- Date: 2026-03-22
-- Refactor rest_days to JSONB config for flexible rest day types
-- OLD: type VARCHAR(20) CHECK (type IN ('full_rest', 'active_recovery'))
-- NEW: rest_config JSONB with {focus, rest_from[], allows[], intensity_max}
-- Drop old type column
ALTER TABLE rest_days
DROP COLUMN IF EXISTS type;
-- Add new JSONB config column
ALTER TABLE rest_days
ADD COLUMN IF NOT EXISTS rest_config JSONB NOT NULL DEFAULT '{"focus": "mental_rest", "rest_from": [], "allows": []}'::jsonb;
-- Validation function for rest_config
CREATE OR REPLACE FUNCTION validate_rest_config(config JSONB) RETURNS BOOLEAN AS $$
BEGIN
-- Must have focus field
IF NOT (config ? 'focus') THEN
RETURN FALSE;
END IF;
-- focus must be one of the allowed values
IF NOT (config->>'focus' IN ('muscle_recovery', 'cardio_recovery', 'mental_rest', 'deload', 'injury')) THEN
RETURN FALSE;
END IF;
-- rest_from must be array if present
IF (config ? 'rest_from') AND jsonb_typeof(config->'rest_from') != 'array' THEN
RETURN FALSE;
END IF;
-- allows must be array if present
IF (config ? 'allows') AND jsonb_typeof(config->'allows') != 'array' THEN
RETURN FALSE;
END IF;
-- intensity_max must be number between 1-100 if present
IF (config ? 'intensity_max') AND (
jsonb_typeof(config->'intensity_max') != 'number' OR
(config->>'intensity_max')::int < 1 OR
(config->>'intensity_max')::int > 100
) THEN
RETURN FALSE;
END IF;
RETURN TRUE;
END;
$$ LANGUAGE plpgsql;
-- Add check constraint
ALTER TABLE rest_days
ADD CONSTRAINT valid_rest_config CHECK (validate_rest_config(rest_config));
-- Add comment for documentation
COMMENT ON COLUMN rest_days.rest_config IS 'JSONB: {focus: string, rest_from: string[], allows: string[], intensity_max?: number (1-100), note?: string}';
COMMENT ON TABLE rest_days IS 'v9d Phase 2a: Context-specific rest days (strength rest but cardio allowed, etc.)';
-- Create GIN index on rest_config for faster JSONB queries
CREATE INDEX IF NOT EXISTS idx_rest_days_config ON rest_days USING GIN (rest_config);
@@ -0,0 +1,17 @@
-- Migration 011: Allow Multiple Rest Days per Date
-- v9d Phase 2a: Support for multi-dimensional rest (development routes)
-- Date: 2026-03-22
-- Remove UNIQUE constraint to allow multiple rest day types per date
-- Use Case: Muscle recovery + Mental rest on same day
-- Future: Development routes (Conditioning, Strength, Coordination, Mental, Mobility, Technique)
ALTER TABLE rest_days
DROP CONSTRAINT IF EXISTS unique_rest_day_per_profile;
-- Add index for efficient queries (profile_id, date)
CREATE INDEX IF NOT EXISTS idx_rest_days_profile_date_multi
ON rest_days(profile_id, date DESC);
-- Comment for documentation
COMMENT ON TABLE rest_days IS 'v9d Phase 2a: Multi-dimensional rest days - multiple entries per date allowed for different development routes (muscle, cardio, mental, coordination, technique)';
@@ -0,0 +1,34 @@
-- Migration 012: Unique constraint on (profile_id, date, focus)
-- v9d Phase 2a: Prevent duplicate rest day types per date
-- Date: 2026-03-22
-- Add focus column (extracted from rest_config for performance + constraints)
ALTER TABLE rest_days
ADD COLUMN IF NOT EXISTS focus VARCHAR(20);
-- Populate from existing JSONB data
UPDATE rest_days
SET focus = rest_config->>'focus'
WHERE focus IS NULL;
-- Make NOT NULL (safe because we just populated all rows)
ALTER TABLE rest_days
ALTER COLUMN focus SET NOT NULL;
-- Add CHECK constraint for valid focus values
ALTER TABLE rest_days
ADD CONSTRAINT valid_focus CHECK (
focus IN ('muscle_recovery', 'cardio_recovery', 'mental_rest', 'deload', 'injury')
);
-- Add UNIQUE constraint: Same profile + date + focus = duplicate
ALTER TABLE rest_days
ADD CONSTRAINT unique_rest_day_per_focus
UNIQUE (profile_id, date, focus);
-- Add index for efficient queries by focus
CREATE INDEX IF NOT EXISTS idx_rest_days_focus
ON rest_days(focus);
-- Comment for documentation
COMMENT ON COLUMN rest_days.focus IS 'Extracted from rest_config.focus for performance and constraints. Prevents duplicate rest day types per date.';
@@ -0,0 +1,145 @@
-- Migration 013: Training Parameters Registry
-- Training Type Profiles System - Foundation
-- Date: 2026-03-23
-- Issue: #15
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-- TRAINING PARAMETERS REGISTRY
-- Zentrale Definition aller messbaren Parameter für Aktivitäten
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CREATE TABLE IF NOT EXISTS training_parameters (
id SERIAL PRIMARY KEY,
key VARCHAR(50) UNIQUE NOT NULL,
name_de VARCHAR(100) NOT NULL,
name_en VARCHAR(100) NOT NULL,
category VARCHAR(50) NOT NULL,
data_type VARCHAR(20) NOT NULL,
unit VARCHAR(20),
description_de TEXT,
description_en TEXT,
source_field VARCHAR(100),
validation_rules JSONB DEFAULT '{}'::jsonb,
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMP DEFAULT NOW(),
CONSTRAINT chk_category CHECK (category IN (
'physical', 'physiological', 'subjective', 'environmental', 'performance'
)),
CONSTRAINT chk_data_type CHECK (data_type IN (
'integer', 'float', 'string', 'boolean'
))
);
CREATE INDEX idx_training_parameters_category ON training_parameters(category) WHERE is_active = true;
CREATE INDEX idx_training_parameters_key ON training_parameters(key) WHERE is_active = true;
COMMENT ON TABLE training_parameters IS 'Registry of all measurable activity parameters (Training Type Profiles System)';
COMMENT ON COLUMN training_parameters.key IS 'Unique identifier (e.g. "avg_hr", "duration_min")';
COMMENT ON COLUMN training_parameters.category IS 'Parameter category: physical, physiological, subjective, environmental, performance';
COMMENT ON COLUMN training_parameters.data_type IS 'Data type: integer, float, string, boolean';
COMMENT ON COLUMN training_parameters.source_field IS 'Mapping to activity_log column name';
COMMENT ON COLUMN training_parameters.validation_rules IS 'Min/Max/Enum for validation (JSONB)';
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-- STANDARD PARAMETERS
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
INSERT INTO training_parameters (key, name_de, name_en, category, data_type, unit, source_field, validation_rules, description_de, description_en) VALUES
-- Physical Parameters
('duration_min', 'Dauer', 'Duration', 'physical', 'integer', 'min', 'duration_min',
'{"min": 0, "max": 600}'::jsonb,
'Trainingsdauer in Minuten',
'Training duration in minutes'),
('distance_km', 'Distanz', 'Distance', 'physical', 'float', 'km', 'distance_km',
'{"min": 0, "max": 200}'::jsonb,
'Zurückgelegte Distanz in Kilometern',
'Distance covered in kilometers'),
('kcal_active', 'Aktive Kalorien', 'Active Calories', 'physical', 'integer', 'kcal', 'kcal_active',
'{"min": 0, "max": 5000}'::jsonb,
'Aktiver Kalorienverbrauch',
'Active calorie burn'),
('kcal_resting', 'Ruhekalorien', 'Resting Calories', 'physical', 'integer', 'kcal', 'kcal_resting',
'{"min": 0, "max": 2000}'::jsonb,
'Ruheumsatz während Training',
'Resting calorie burn during training'),
('elevation_gain', 'Höhenmeter', 'Elevation Gain', 'physical', 'integer', 'm', 'elevation_gain',
'{"min": 0, "max": 5000}'::jsonb,
'Überwundene Höhenmeter',
'Elevation gain in meters'),
('pace_min_per_km', 'Pace', 'Pace', 'physical', 'float', 'min/km', 'pace_min_per_km',
'{"min": 2, "max": 20}'::jsonb,
'Durchschnittstempo in Minuten pro Kilometer',
'Average pace in minutes per kilometer'),
('cadence', 'Trittfrequenz', 'Cadence', 'physical', 'integer', 'spm', 'cadence',
'{"min": 0, "max": 220}'::jsonb,
'Schrittfrequenz (Schritte pro Minute)',
'Step frequency (steps per minute)'),
-- Physiological Parameters
('avg_hr', 'Durchschnittspuls', 'Average Heart Rate', 'physiological', 'integer', 'bpm', 'hr_avg',
'{"min": 30, "max": 220}'::jsonb,
'Durchschnittliche Herzfrequenz',
'Average heart rate'),
('max_hr', 'Maximalpuls', 'Max Heart Rate', 'physiological', 'integer', 'bpm', 'hr_max',
'{"min": 40, "max": 220}'::jsonb,
'Maximale Herzfrequenz',
'Maximum heart rate'),
('min_hr', 'Minimalpuls', 'Min Heart Rate', 'physiological', 'integer', 'bpm', 'hr_min',
'{"min": 30, "max": 200}'::jsonb,
'Minimale Herzfrequenz',
'Minimum heart rate'),
('avg_power', 'Durchschnittsleistung', 'Average Power', 'physiological', 'integer', 'W', 'avg_power',
'{"min": 0, "max": 1000}'::jsonb,
'Durchschnittliche Leistung in Watt',
'Average power output in watts'),
-- Subjective Parameters
('rpe', 'RPE (Anstrengung)', 'RPE (Perceived Exertion)', 'subjective', 'integer', 'scale', 'rpe',
'{"min": 1, "max": 10}'::jsonb,
'Subjektive Anstrengung (Rate of Perceived Exertion)',
'Rate of Perceived Exertion'),
-- Environmental Parameters
('temperature_celsius', 'Temperatur', 'Temperature', 'environmental', 'float', '°C', 'temperature_celsius',
'{"min": -30, "max": 50}'::jsonb,
'Umgebungstemperatur in Celsius',
'Ambient temperature in Celsius'),
('humidity_percent', 'Luftfeuchtigkeit', 'Humidity', 'environmental', 'integer', '%', 'humidity_percent',
'{"min": 0, "max": 100}'::jsonb,
'Relative Luftfeuchtigkeit in Prozent',
'Relative humidity in percent'),
-- Performance Parameters (calculated)
('avg_hr_percent', '% Max-HF', '% Max HR', 'performance', 'float', '%', 'avg_hr_percent',
'{"min": 0, "max": 100}'::jsonb,
'Durchschnittspuls als Prozent der maximalen Herzfrequenz',
'Average heart rate as percentage of max heart rate'),
('kcal_per_km', 'Kalorien pro km', 'Calories per km', 'performance', 'float', 'kcal/km', 'kcal_per_km',
'{"min": 0, "max": 1000}'::jsonb,
'Kalorienverbrauch pro Kilometer',
'Calorie burn per kilometer');
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-- SUMMARY
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-- Display inserted parameters
DO $$
BEGIN
RAISE NOTICE '✓ Migration 013 completed';
RAISE NOTICE ' - Created training_parameters table';
RAISE NOTICE ' - Inserted % standard parameters', (SELECT COUNT(*) FROM training_parameters);
END $$;
@@ -0,0 +1,114 @@
-- Migration 014: Training Type Profiles & Activity Evaluation
-- Training Type Profiles System - Schema Extensions
-- Date: 2026-03-23
-- Issue: #15
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-- EXTEND TRAINING TYPES
-- Add profile column for comprehensive training type configuration
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ALTER TABLE training_types ADD COLUMN IF NOT EXISTS profile JSONB DEFAULT NULL;
CREATE INDEX idx_training_types_profile_enabled ON training_types
((profile->'rule_sets'->'minimum_requirements'->>'enabled'))
WHERE profile IS NOT NULL;
COMMENT ON COLUMN training_types.profile IS 'Comprehensive training type profile with 7 dimensions (rule_sets, intensity_zones, training_effects, periodization, performance_indicators, safety, ai_context)';
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-- EXTEND ACTIVITY LOG
-- Add evaluation results and quality labels
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS evaluation JSONB DEFAULT NULL;
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS quality_label VARCHAR(20);
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS overall_score FLOAT;
CREATE INDEX idx_activity_quality_label ON activity_log(quality_label)
WHERE quality_label IS NOT NULL;
CREATE INDEX idx_activity_overall_score ON activity_log(overall_score DESC)
WHERE overall_score IS NOT NULL;
CREATE INDEX idx_activity_evaluation_passed ON activity_log
((evaluation->'rule_set_results'->'minimum_requirements'->>'passed'))
WHERE evaluation IS NOT NULL;
COMMENT ON COLUMN activity_log.evaluation IS 'Complete evaluation result (7 dimensions, scores, recommendations, warnings)';
COMMENT ON COLUMN activity_log.quality_label IS 'Quality label: excellent, good, acceptable, poor (for quick filtering)';
COMMENT ON COLUMN activity_log.overall_score IS 'Overall quality score 0.0-1.0 (for sorting)';
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-- ADD MISSING COLUMNS (if not already added by previous migrations)
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-- Add HR columns if not exist (might be in Migration 008)
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_name='activity_log' AND column_name='hr_min') THEN
ALTER TABLE activity_log ADD COLUMN hr_min INTEGER CHECK (hr_min > 0 AND hr_min < 200);
END IF;
END $$;
-- Add performance columns for calculated values
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS avg_hr_percent FLOAT;
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS kcal_per_km FLOAT;
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS pace_min_per_km FLOAT;
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS cadence INTEGER;
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS avg_power INTEGER;
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS elevation_gain INTEGER;
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS temperature_celsius FLOAT;
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS humidity_percent INTEGER;
COMMENT ON COLUMN activity_log.avg_hr_percent IS 'Average HR as percentage of user max HR (calculated)';
COMMENT ON COLUMN activity_log.kcal_per_km IS 'Calories burned per kilometer (calculated)';
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-- HELPER FUNCTION: Calculate avg_hr_percent
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CREATE OR REPLACE FUNCTION calculate_avg_hr_percent()
RETURNS TRIGGER AS $$
DECLARE
user_max_hr INTEGER;
BEGIN
-- Get user's max HR from profile
SELECT hf_max INTO user_max_hr
FROM profiles
WHERE id = NEW.profile_id;
-- Calculate percentage if both values exist
IF NEW.hr_avg IS NOT NULL AND user_max_hr IS NOT NULL AND user_max_hr > 0 THEN
NEW.avg_hr_percent := (NEW.hr_avg::float / user_max_hr::float) * 100;
END IF;
-- Calculate kcal per km
IF NEW.kcal_active IS NOT NULL AND NEW.distance_km IS NOT NULL AND NEW.distance_km > 0 THEN
NEW.kcal_per_km := NEW.kcal_active::float / NEW.distance_km;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Trigger for automatic calculation
DROP TRIGGER IF EXISTS trg_calculate_performance_metrics ON activity_log;
CREATE TRIGGER trg_calculate_performance_metrics
BEFORE INSERT OR UPDATE ON activity_log
FOR EACH ROW
EXECUTE FUNCTION calculate_avg_hr_percent();
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-- SUMMARY
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
DO $$
BEGIN
RAISE NOTICE '✓ Migration 014 completed';
RAISE NOTICE ' - Extended training_types with profile column';
RAISE NOTICE ' - Extended activity_log with evaluation columns';
RAISE NOTICE ' - Added performance metric calculations';
RAISE NOTICE ' - Created indexes for fast queries';
END $$;
@@ -0,0 +1,29 @@
-- Migration 014: Extended Vitals (Blood Pressure, VO2 Max, SpO2, Respiratory Rate)
-- v9d Phase 2d: Complete vitals tracking
-- Date: 2026-03-23
-- Add new vitals fields
ALTER TABLE vitals_log
ADD COLUMN IF NOT EXISTS blood_pressure_systolic INTEGER CHECK (blood_pressure_systolic > 0 AND blood_pressure_systolic < 300),
ADD COLUMN IF NOT EXISTS blood_pressure_diastolic INTEGER CHECK (blood_pressure_diastolic > 0 AND blood_pressure_diastolic < 200),
ADD COLUMN IF NOT EXISTS pulse INTEGER CHECK (pulse > 0 AND pulse < 250),
ADD COLUMN IF NOT EXISTS vo2_max DECIMAL(4,1) CHECK (vo2_max > 0 AND vo2_max < 100),
ADD COLUMN IF NOT EXISTS spo2 INTEGER CHECK (spo2 >= 70 AND spo2 <= 100),
ADD COLUMN IF NOT EXISTS respiratory_rate DECIMAL(4,1) CHECK (respiratory_rate > 0 AND respiratory_rate < 60),
ADD COLUMN IF NOT EXISTS irregular_heartbeat BOOLEAN DEFAULT false,
ADD COLUMN IF NOT EXISTS possible_afib BOOLEAN DEFAULT false;
-- Update source check to include omron
ALTER TABLE vitals_log DROP CONSTRAINT IF EXISTS vitals_log_source_check;
ALTER TABLE vitals_log ADD CONSTRAINT vitals_log_source_check
CHECK (source IN ('manual', 'apple_health', 'garmin', 'omron'));
-- Comments
COMMENT ON COLUMN vitals_log.blood_pressure_systolic IS 'Systolic blood pressure (mmHg) from Omron or manual entry';
COMMENT ON COLUMN vitals_log.blood_pressure_diastolic IS 'Diastolic blood pressure (mmHg) from Omron or manual entry';
COMMENT ON COLUMN vitals_log.pulse IS 'Pulse during blood pressure measurement (bpm)';
COMMENT ON COLUMN vitals_log.vo2_max IS 'VO2 Max from Apple Watch (ml/kg/min)';
COMMENT ON COLUMN vitals_log.spo2 IS 'Blood oxygen saturation (%) from Apple Watch';
COMMENT ON COLUMN vitals_log.respiratory_rate IS 'Respiratory rate (breaths/min) from Apple Watch';
COMMENT ON COLUMN vitals_log.irregular_heartbeat IS 'Irregular heartbeat detected (Omron)';
COMMENT ON COLUMN vitals_log.possible_afib IS 'Possible atrial fibrillation (Omron)';
@@ -0,0 +1,184 @@
-- Migration 015: Vitals Refactoring - Trennung Baseline vs. Context-Dependent
-- v9d Phase 2d: Architektur-Verbesserung für bessere Datenqualität
-- Date: 2026-03-23
-- ══════════════════════════════════════════════════════════════════════════════
-- STEP 1: Create new tables
-- ══════════════════════════════════════════════════════════════════════════════
-- Baseline Vitals (slow-changing, once daily, morning measurement)
CREATE TABLE IF NOT EXISTS vitals_baseline (
id SERIAL PRIMARY KEY,
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
date DATE NOT NULL,
-- Core baseline vitals
resting_hr INTEGER CHECK (resting_hr > 0 AND resting_hr < 120),
hrv INTEGER CHECK (hrv > 0 AND hrv < 300),
vo2_max DECIMAL(4,1) CHECK (vo2_max > 0 AND vo2_max < 100),
spo2 INTEGER CHECK (spo2 >= 70 AND spo2 <= 100),
respiratory_rate DECIMAL(4,1) CHECK (respiratory_rate > 0 AND respiratory_rate < 60),
-- Future baseline vitals (prepared for expansion)
body_temperature DECIMAL(3,1) CHECK (body_temperature > 30 AND body_temperature < 45),
resting_metabolic_rate INTEGER CHECK (resting_metabolic_rate > 0),
-- Metadata
note TEXT,
source VARCHAR(20) DEFAULT 'manual' CHECK (source IN ('manual', 'apple_health', 'garmin', 'withings')),
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
CONSTRAINT unique_baseline_per_day UNIQUE(profile_id, date)
);
CREATE INDEX idx_vitals_baseline_profile_date ON vitals_baseline(profile_id, date DESC);
COMMENT ON TABLE vitals_baseline IS 'v9d Phase 2d: Baseline vitals measured once daily (morning, fasted)';
COMMENT ON COLUMN vitals_baseline.resting_hr IS 'Resting heart rate (bpm) - measured in the morning before getting up';
COMMENT ON COLUMN vitals_baseline.hrv IS 'Heart rate variability (ms) - higher is better';
COMMENT ON COLUMN vitals_baseline.vo2_max IS 'VO2 Max (ml/kg/min) - estimated by Apple Watch or lab test';
COMMENT ON COLUMN vitals_baseline.spo2 IS 'Blood oxygen saturation (%) - baseline measurement';
COMMENT ON COLUMN vitals_baseline.respiratory_rate IS 'Respiratory rate (breaths/min) - baseline measurement';
-- ══════════════════════════════════════════════════════════════════════════════
-- Blood Pressure Log (context-dependent, multiple times per day)
CREATE TABLE IF NOT EXISTS blood_pressure_log (
id SERIAL PRIMARY KEY,
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
measured_at TIMESTAMP NOT NULL,
-- Blood pressure measurements
systolic INTEGER NOT NULL CHECK (systolic > 0 AND systolic < 300),
diastolic INTEGER NOT NULL CHECK (diastolic > 0 AND diastolic < 200),
pulse INTEGER CHECK (pulse > 0 AND pulse < 250),
-- Context tagging for correlation analysis
context VARCHAR(30) CHECK (context IN (
'morning_fasted', -- Morgens nüchtern
'after_meal', -- Nach dem Essen
'before_training', -- Vor dem Training
'after_training', -- Nach dem Training
'evening', -- Abends
'stress', -- Bei Stress
'resting', -- Ruhemessung
'other' -- Sonstiges
)),
-- Warning flags (Omron)
irregular_heartbeat BOOLEAN DEFAULT false,
possible_afib BOOLEAN DEFAULT false,
-- Metadata
note TEXT,
source VARCHAR(20) DEFAULT 'manual' CHECK (source IN ('manual', 'omron', 'apple_health', 'withings')),
created_at TIMESTAMP DEFAULT NOW(),
CONSTRAINT unique_bp_measurement UNIQUE(profile_id, measured_at)
);
CREATE INDEX idx_blood_pressure_profile_datetime ON blood_pressure_log(profile_id, measured_at DESC);
CREATE INDEX idx_blood_pressure_context ON blood_pressure_log(context) WHERE context IS NOT NULL;
COMMENT ON TABLE blood_pressure_log IS 'v9d Phase 2d: Blood pressure measurements (multiple per day, context-aware)';
COMMENT ON COLUMN blood_pressure_log.context IS 'Measurement context for correlation analysis';
COMMENT ON COLUMN blood_pressure_log.irregular_heartbeat IS 'Irregular heartbeat detected (Omron device)';
COMMENT ON COLUMN blood_pressure_log.possible_afib IS 'Possible atrial fibrillation (Omron device)';
-- ══════════════════════════════════════════════════════════════════════════════
-- STEP 2: Migrate existing data from vitals_log
-- ══════════════════════════════════════════════════════════════════════════════
-- Migrate baseline vitals (RHR, HRV, VO2 Max, SpO2, Respiratory Rate)
INSERT INTO vitals_baseline (
profile_id, date,
resting_hr, hrv, vo2_max, spo2, respiratory_rate,
note, source, created_at, updated_at
)
SELECT
profile_id, date,
resting_hr, hrv, vo2_max, spo2, respiratory_rate,
note, source, created_at, updated_at
FROM vitals_log
WHERE resting_hr IS NOT NULL
OR hrv IS NOT NULL
OR vo2_max IS NOT NULL
OR spo2 IS NOT NULL
OR respiratory_rate IS NOT NULL
ON CONFLICT (profile_id, date) DO NOTHING;
-- Migrate blood pressure measurements
-- Note: Use date + 08:00 as default timestamp (morning measurement)
INSERT INTO blood_pressure_log (
profile_id, measured_at,
systolic, diastolic, pulse,
irregular_heartbeat, possible_afib,
note, source, created_at
)
SELECT
profile_id,
(date + TIME '08:00:00')::timestamp AS measured_at,
blood_pressure_systolic,
blood_pressure_diastolic,
pulse,
irregular_heartbeat,
possible_afib,
note,
CASE
WHEN source = 'manual' THEN 'manual'
WHEN source = 'omron' THEN 'omron'
ELSE 'manual'
END AS source,
created_at
FROM vitals_log
WHERE blood_pressure_systolic IS NOT NULL
AND blood_pressure_diastolic IS NOT NULL
ON CONFLICT (profile_id, measured_at) DO NOTHING;
-- ══════════════════════════════════════════════════════════════════════════════
-- STEP 3: Drop old vitals_log table (backup first)
-- ══════════════════════════════════════════════════════════════════════════════
-- Rename old table as backup (keep for safety, can be dropped later)
ALTER TABLE vitals_log RENAME TO vitals_log_backup_pre_015;
-- Drop old index (it's on the renamed table now)
DROP INDEX IF EXISTS idx_vitals_profile_date;
-- ══════════════════════════════════════════════════════════════════════════════
-- STEP 4: Prepared for future vitals types
-- ══════════════════════════════════════════════════════════════════════════════
-- Future tables (commented out, create when needed):
-- Glucose Log (for blood sugar tracking)
-- CREATE TABLE glucose_log (
-- id SERIAL PRIMARY KEY,
-- profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
-- measured_at TIMESTAMP NOT NULL,
-- glucose_mg_dl INTEGER NOT NULL CHECK (glucose_mg_dl > 0 AND glucose_mg_dl < 500),
-- context VARCHAR(30) CHECK (context IN (
-- 'fasted', 'before_meal', 'after_meal_1h', 'after_meal_2h', 'before_training', 'after_training', 'other'
-- )),
-- note TEXT,
-- source VARCHAR(20) DEFAULT 'manual',
-- created_at TIMESTAMP DEFAULT NOW(),
-- CONSTRAINT unique_glucose_measurement UNIQUE(profile_id, measured_at)
-- );
-- Temperature Log (for illness tracking)
-- CREATE TABLE temperature_log (
-- id SERIAL PRIMARY KEY,
-- profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
-- measured_at TIMESTAMP NOT NULL,
-- temperature_celsius DECIMAL(3,1) NOT NULL CHECK (temperature_celsius > 30 AND temperature_celsius < 45),
-- measurement_location VARCHAR(20) CHECK (measurement_location IN ('oral', 'ear', 'forehead', 'armpit')),
-- note TEXT,
-- created_at TIMESTAMP DEFAULT NOW(),
-- CONSTRAINT unique_temperature_measurement UNIQUE(profile_id, measured_at)
-- );
-- ══════════════════════════════════════════════════════════════════════════════
-- Migration complete
-- ══════════════════════════════════════════════════════════════════════════════
@@ -0,0 +1,21 @@
-- Migration 016: Global Quality Filter Setting
-- Issue: #31
-- Date: 2026-03-23
-- Description: Add quality_filter_level to profiles for consistent data views
-- Add quality_filter_level column to profiles
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS quality_filter_level VARCHAR(20) DEFAULT 'all';
COMMENT ON COLUMN profiles.quality_filter_level IS 'Global quality filter for all activity views: all, quality, very_good, excellent';
-- Create index for performance (if filtering becomes common)
CREATE INDEX IF NOT EXISTS idx_profiles_quality_filter ON profiles(quality_filter_level);
-- Migration tracking
DO $$
BEGIN
RAISE NOTICE '✓ Migration 016: Added global quality filter setting';
RAISE NOTICE ' - Added profiles.quality_filter_level column';
RAISE NOTICE ' - Default: all (no filter)';
RAISE NOTICE ' - Values: all, quality, very_good, excellent';
END $$;
@@ -0,0 +1,22 @@
-- Migration 017: AI Prompts Flexibilisierung (Issue #28)
-- Add category column to ai_prompts for better organization and filtering
-- Add category column
ALTER TABLE ai_prompts ADD COLUMN IF NOT EXISTS category VARCHAR(20) DEFAULT 'ganzheitlich';
-- Create index for category filtering
CREATE INDEX IF NOT EXISTS idx_ai_prompts_category ON ai_prompts(category);
-- Add comment
COMMENT ON COLUMN ai_prompts.category IS 'Prompt category: körper, ernährung, training, schlaf, vitalwerte, ziele, ganzheitlich';
-- Update existing prompts with appropriate categories
-- Based on slug patterns and content
UPDATE ai_prompts SET category = 'körper' WHERE slug IN ('koerperkomposition', 'gewichtstrend', 'umfaenge', 'caliper');
UPDATE ai_prompts SET category = 'ernährung' WHERE slug IN ('ernaehrung', 'kalorienbilanz', 'protein', 'makros');
UPDATE ai_prompts SET category = 'training' WHERE slug IN ('aktivitaet', 'trainingsanalyse', 'erholung', 'leistung');
UPDATE ai_prompts SET category = 'schlaf' WHERE slug LIKE '%schlaf%';
UPDATE ai_prompts SET category = 'vitalwerte' WHERE slug IN ('vitalwerte', 'herzfrequenz', 'ruhepuls', 'hrv');
UPDATE ai_prompts SET category = 'ziele' WHERE slug LIKE '%ziel%' OR slug LIKE '%goal%';
-- Pipeline prompts remain 'ganzheitlich' (default)
@@ -0,0 +1,20 @@
-- Migration 018: Add display_name to ai_prompts for user-facing labels
ALTER TABLE ai_prompts ADD COLUMN IF NOT EXISTS display_name VARCHAR(100);
-- Migrate existing prompts from hardcoded SLUG_LABELS
UPDATE ai_prompts SET display_name = '🔍 Gesamtanalyse' WHERE slug = 'gesamt' AND display_name IS NULL;
UPDATE ai_prompts SET display_name = '🫧 Körperkomposition' WHERE slug = 'koerper' AND display_name IS NULL;
UPDATE ai_prompts SET display_name = '🍽️ Ernährung' WHERE slug = 'ernaehrung' AND display_name IS NULL;
UPDATE ai_prompts SET display_name = '🏋️ Aktivität' WHERE slug = 'aktivitaet' AND display_name IS NULL;
UPDATE ai_prompts SET display_name = '❤️ Gesundheitsindikatoren' WHERE slug = 'gesundheit' AND display_name IS NULL;
UPDATE ai_prompts SET display_name = '🎯 Zielfortschritt' WHERE slug = 'ziele' AND display_name IS NULL;
UPDATE ai_prompts SET display_name = '🔬 Mehrstufige Gesamtanalyse' WHERE slug = 'pipeline' AND display_name IS NULL;
UPDATE ai_prompts SET display_name = '🔬 Pipeline: Körper-Analyse (JSON)' WHERE slug = 'pipeline_body' AND display_name IS NULL;
UPDATE ai_prompts SET display_name = '🔬 Pipeline: Ernährungs-Analyse (JSON)' WHERE slug = 'pipeline_nutrition' AND display_name IS NULL;
UPDATE ai_prompts SET display_name = '🔬 Pipeline: Aktivitäts-Analyse (JSON)' WHERE slug = 'pipeline_activity' AND display_name IS NULL;
UPDATE ai_prompts SET display_name = '🔬 Pipeline: Synthese' WHERE slug = 'pipeline_synthesis' AND display_name IS NULL;
UPDATE ai_prompts SET display_name = '🔬 Pipeline: Zielabgleich' WHERE slug = 'pipeline_goals' AND display_name IS NULL;
-- Fallback: use name as display_name if still NULL
UPDATE ai_prompts SET display_name = name WHERE display_name IS NULL;
+157
View File
@@ -0,0 +1,157 @@
-- Migration 019: Pipeline-System - Konfigurierbare mehrstufige Analysen
-- Ermöglicht Admin-Verwaltung von Pipeline-Konfigurationen (Issue #28)
-- Created: 2026-03-25
-- ========================================
-- 1. Erweitere ai_prompts für Reset-Feature
-- ========================================
ALTER TABLE ai_prompts
ADD COLUMN IF NOT EXISTS is_system_default BOOLEAN DEFAULT FALSE,
ADD COLUMN IF NOT EXISTS default_template TEXT;
COMMENT ON COLUMN ai_prompts.is_system_default IS 'true = System-Prompt mit Reset-Funktion';
COMMENT ON COLUMN ai_prompts.default_template IS 'Original-Template für Reset-to-Default';
-- Markiere bestehende Pipeline-Prompts als System-Defaults
UPDATE ai_prompts
SET
is_system_default = true,
default_template = template
WHERE slug LIKE 'pipeline_%';
-- ========================================
-- 2. Create pipeline_configs table
-- ========================================
CREATE TABLE IF NOT EXISTS pipeline_configs (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
name VARCHAR(255) NOT NULL UNIQUE,
description TEXT,
is_default BOOLEAN DEFAULT FALSE,
active BOOLEAN DEFAULT TRUE,
-- Module configuration: which data sources to include
modules JSONB NOT NULL DEFAULT '{}'::jsonb,
-- Example: {"körper": true, "ernährung": true, "training": true, "schlaf": false}
-- Timeframes per module (days)
timeframes JSONB NOT NULL DEFAULT '{}'::jsonb,
-- Example: {"körper": 30, "ernährung": 30, "training": 14}
-- Stage 1 prompts (parallel execution)
stage1_prompts TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[],
-- Example: ARRAY['pipeline_body', 'pipeline_nutrition', 'pipeline_activity']
-- Stage 2 prompt (synthesis)
stage2_prompt VARCHAR(100) NOT NULL,
-- Example: 'pipeline_synthesis'
-- Stage 3 prompt (optional, e.g., goals)
stage3_prompt VARCHAR(100),
-- Example: 'pipeline_goals'
created TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- ========================================
-- 3. Create indexes
-- ========================================
CREATE INDEX IF NOT EXISTS idx_pipeline_configs_default ON pipeline_configs(is_default) WHERE is_default = true;
CREATE INDEX IF NOT EXISTS idx_pipeline_configs_active ON pipeline_configs(active);
-- ========================================
-- 4. Seed: Standard-Pipeline "Alltags-Check"
-- ========================================
INSERT INTO pipeline_configs (
name,
description,
is_default,
modules,
timeframes,
stage1_prompts,
stage2_prompt,
stage3_prompt
) VALUES (
'Alltags-Check',
'Standard-Analyse: Körper, Ernährung, Training über die letzten 2-4 Wochen',
true,
'{"körper": true, "ernährung": true, "training": true, "schlaf": false, "vitalwerte": false, "mentales": false, "ziele": false}'::jsonb,
'{"körper": 30, "ernährung": 30, "training": 14}'::jsonb,
ARRAY['pipeline_body', 'pipeline_nutrition', 'pipeline_activity'],
'pipeline_synthesis',
'pipeline_goals'
) ON CONFLICT (name) DO NOTHING;
-- ========================================
-- 5. Seed: Erweiterte Pipelines (optional)
-- ========================================
-- Schlaf-Fokus Pipeline (wenn Schlaf-Prompts existieren)
INSERT INTO pipeline_configs (
name,
description,
is_default,
modules,
timeframes,
stage1_prompts,
stage2_prompt,
stage3_prompt
) VALUES (
'Schlaf & Erholung',
'Analyse von Schlaf, Vitalwerten und Erholungsstatus',
false,
'{"schlaf": true, "vitalwerte": true, "training": true, "körper": false, "ernährung": false, "mentales": false, "ziele": false}'::jsonb,
'{"schlaf": 14, "vitalwerte": 7, "training": 14}'::jsonb,
ARRAY['pipeline_sleep', 'pipeline_vitals', 'pipeline_activity'],
'pipeline_synthesis',
NULL
) ON CONFLICT (name) DO NOTHING;
-- Wettkampf-Analyse (langfristiger Trend)
INSERT INTO pipeline_configs (
name,
description,
is_default,
modules,
timeframes,
stage1_prompts,
stage2_prompt,
stage3_prompt
) VALUES (
'Wettkampf-Analyse',
'Langfristige Analyse für Wettkampfvorbereitung (90 Tage)',
false,
'{"körper": true, "training": true, "vitalwerte": true, "ernährung": true, "schlaf": false, "mentales": false, "ziele": true}'::jsonb,
'{"körper": 90, "training": 90, "vitalwerte": 30, "ernährung": 60}'::jsonb,
ARRAY['pipeline_body', 'pipeline_activity', 'pipeline_vitals', 'pipeline_nutrition'],
'pipeline_synthesis',
'pipeline_goals'
) ON CONFLICT (name) DO NOTHING;
-- ========================================
-- 6. Trigger für updated timestamp
-- ========================================
DROP TRIGGER IF EXISTS trigger_pipeline_configs_updated ON pipeline_configs;
CREATE TRIGGER trigger_pipeline_configs_updated
BEFORE UPDATE ON pipeline_configs
FOR EACH ROW
EXECUTE FUNCTION update_updated_timestamp();
-- ========================================
-- 7. Constraints & Validation
-- ========================================
-- Only one default config allowed (enforced via partial unique index)
CREATE UNIQUE INDEX IF NOT EXISTS idx_pipeline_configs_single_default
ON pipeline_configs(is_default)
WHERE is_default = true;
-- ========================================
-- 8. Comments (Documentation)
-- ========================================
COMMENT ON TABLE pipeline_configs IS 'v9f Issue #28: Konfigurierbare Pipeline-Analysen. Admins können mehrere Pipeline-Configs erstellen mit unterschiedlichen Modulen und Zeiträumen.';
COMMENT ON COLUMN pipeline_configs.modules IS 'JSONB: Welche Module aktiv sind (boolean flags)';
COMMENT ON COLUMN pipeline_configs.timeframes IS 'JSONB: Zeiträume pro Modul in Tagen';
COMMENT ON COLUMN pipeline_configs.stage1_prompts IS 'Array von slug-Werten für parallele Stage-1-Prompts';
COMMENT ON COLUMN pipeline_configs.stage2_prompt IS 'Slug des Synthese-Prompts (kombiniert Stage-1-Ergebnisse)';
COMMENT ON COLUMN pipeline_configs.stage3_prompt IS 'Optionaler Slug für Stage-3-Prompt (z.B. Zielabgleich)';
@@ -0,0 +1,128 @@
-- Migration 020: Unified Prompt System (Issue #28)
-- Consolidate ai_prompts and pipeline_configs into single system
-- Type: 'base' (reusable building blocks) or 'pipeline' (workflows)
-- Step 1: Add new columns to ai_prompts and make template nullable
ALTER TABLE ai_prompts
ADD COLUMN IF NOT EXISTS type VARCHAR(20) DEFAULT 'pipeline',
ADD COLUMN IF NOT EXISTS stages JSONB,
ADD COLUMN IF NOT EXISTS output_format VARCHAR(10) DEFAULT 'text',
ADD COLUMN IF NOT EXISTS output_schema JSONB;
-- Make template nullable (pipeline-type prompts use stages instead)
ALTER TABLE ai_prompts
ALTER COLUMN template DROP NOT NULL;
-- Step 2: Migrate existing single-prompts to 1-stage pipeline format
-- All existing prompts become single-stage pipelines with inline source
UPDATE ai_prompts
SET
type = 'pipeline',
stages = jsonb_build_array(
jsonb_build_object(
'stage', 1,
'prompts', jsonb_build_array(
jsonb_build_object(
'source', 'inline',
'template', template,
'output_key', REPLACE(slug, 'pipeline_', ''),
'output_format', 'text'
)
)
)
),
output_format = 'text'
WHERE stages IS NULL;
-- Step 3: Migrate pipeline_configs into ai_prompts as multi-stage pipelines
-- Each pipeline_config becomes a pipeline-type prompt with multiple stages
INSERT INTO ai_prompts (
slug,
name,
description,
type,
stages,
output_format,
active,
is_system_default,
category
)
SELECT
'pipeline_config_' || LOWER(REPLACE(pc.name, ' ', '_')) || '_' || SUBSTRING(pc.id::TEXT FROM 1 FOR 8) as slug,
pc.name,
pc.description,
'pipeline' as type,
-- Build stages JSONB: combine stage1_prompts, stage2_prompt, stage3_prompt
(
-- Stage 1: Convert array to prompts
SELECT jsonb_agg(stage_obj ORDER BY stage_num)
FROM (
SELECT 1 as stage_num,
jsonb_build_object(
'stage', 1,
'prompts', (
SELECT jsonb_agg(
jsonb_build_object(
'source', 'reference',
'slug', s1.slug_val,
'output_key', REPLACE(s1.slug_val, 'pipeline_', 'stage1_'),
'output_format', 'json'
)
)
FROM UNNEST(pc.stage1_prompts) AS s1(slug_val)
)
) as stage_obj
WHERE array_length(pc.stage1_prompts, 1) > 0
UNION ALL
SELECT 2 as stage_num,
jsonb_build_object(
'stage', 2,
'prompts', jsonb_build_array(
jsonb_build_object(
'source', 'reference',
'slug', pc.stage2_prompt,
'output_key', 'synthesis',
'output_format', 'text'
)
)
) as stage_obj
WHERE pc.stage2_prompt IS NOT NULL
UNION ALL
SELECT 3 as stage_num,
jsonb_build_object(
'stage', 3,
'prompts', jsonb_build_array(
jsonb_build_object(
'source', 'reference',
'slug', pc.stage3_prompt,
'output_key', 'goals',
'output_format', 'text'
)
)
) as stage_obj
WHERE pc.stage3_prompt IS NOT NULL
) all_stages
) as stages,
'text' as output_format,
pc.active,
pc.is_default as is_system_default,
'pipeline' as category
FROM pipeline_configs pc;
-- Step 4: Add indices for performance
CREATE INDEX IF NOT EXISTS idx_ai_prompts_type ON ai_prompts(type);
CREATE INDEX IF NOT EXISTS idx_ai_prompts_stages ON ai_prompts USING GIN (stages);
-- Step 5: Add comment explaining stages structure
COMMENT ON COLUMN ai_prompts.stages IS 'JSONB array of stages, each with prompts array. Structure: [{"stage":1,"prompts":[{"source":"reference|inline","slug":"...","template":"...","output_key":"key","output_format":"text|json"}]}]';
-- Step 6: Backup pipeline_configs before eventual deletion
CREATE TABLE IF NOT EXISTS pipeline_configs_backup_pre_020 AS
SELECT * FROM pipeline_configs;
-- Note: We keep pipeline_configs table for now during transition period
-- It can be dropped in a later migration once all code is migrated
@@ -0,0 +1,7 @@
-- Migration 021: Add metadata column to ai_insights for storing debug info
-- Date: 2026-03-26
-- Purpose: Store resolved placeholder values with descriptions for transparency
ALTER TABLE ai_insights ADD COLUMN IF NOT EXISTS metadata JSONB DEFAULT NULL;
COMMENT ON COLUMN ai_insights.metadata IS 'Debug info: resolved placeholders, descriptions, etc.';
+135
View File
@@ -0,0 +1,135 @@
-- Migration 022: Goal System (Strategic + Tactical)
-- Date: 2026-03-26
-- Purpose: Two-level goal architecture for AI-driven coaching
-- ============================================================================
-- STRATEGIC LAYER: Goal Modes
-- ============================================================================
-- Add goal_mode to profiles (strategic training direction)
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS goal_mode VARCHAR(50) DEFAULT 'health';
COMMENT ON COLUMN profiles.goal_mode IS
'Strategic goal mode: weight_loss, strength, endurance, recomposition, health.
Determines score weights and interpretation context for all analyses.';
-- ============================================================================
-- TACTICAL LAYER: Concrete Goal Targets
-- ============================================================================
CREATE TABLE IF NOT EXISTS goals (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
-- Goal Classification
goal_type VARCHAR(50) NOT NULL, -- weight, body_fat, lean_mass, vo2max, strength, flexibility, bp, rhr
is_primary BOOLEAN DEFAULT false,
status VARCHAR(20) DEFAULT 'active', -- draft, active, reached, abandoned, expired
-- Target Values
target_value DECIMAL(10,2),
current_value DECIMAL(10,2),
start_value DECIMAL(10,2),
unit VARCHAR(20), -- kg, %, ml/kg/min, bpm, mmHg, cm, reps
-- Timeline
start_date DATE DEFAULT CURRENT_DATE,
target_date DATE,
reached_date DATE,
-- Metadata
name VARCHAR(100), -- e.g., "Sommerfigur 2026"
description TEXT,
-- Progress Tracking
progress_pct DECIMAL(5,2), -- Auto-calculated: (current - start) / (target - start) * 100
projection_date DATE, -- Prognose wann Ziel erreicht wird
on_track BOOLEAN, -- true wenn Prognose <= target_date
-- Timestamps
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_goals_profile ON goals(profile_id);
CREATE INDEX IF NOT EXISTS idx_goals_status ON goals(profile_id, status);
CREATE INDEX IF NOT EXISTS idx_goals_primary ON goals(profile_id, is_primary) WHERE is_primary = true;
COMMENT ON TABLE goals IS 'Concrete user goals (tactical targets)';
COMMENT ON COLUMN goals.goal_type IS 'Type of goal: weight, body_fat, lean_mass, vo2max, strength, flexibility, bp, rhr';
COMMENT ON COLUMN goals.is_primary IS 'Primary goal gets highest priority in scoring and charts';
COMMENT ON COLUMN goals.status IS 'draft = not yet started, active = in progress, reached = successfully completed, abandoned = given up, expired = deadline passed';
COMMENT ON COLUMN goals.progress_pct IS 'Percentage progress: (current_value - start_value) / (target_value - start_value) * 100';
COMMENT ON COLUMN goals.projection_date IS 'Projected date when goal will be reached based on current trend';
COMMENT ON COLUMN goals.on_track IS 'true if projection_date <= target_date (goal reachable on time)';
-- ============================================================================
-- TRAINING PHASES (Auto-Detection)
-- ============================================================================
CREATE TABLE IF NOT EXISTS training_phases (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
-- Phase Classification
phase_type VARCHAR(50) NOT NULL, -- calorie_deficit, calorie_surplus, deload, maintenance, periodization
detected_automatically BOOLEAN DEFAULT false,
confidence_score DECIMAL(3,2), -- 0.00 - 1.00 (Wie sicher ist die Erkennung?)
status VARCHAR(20) DEFAULT 'suggested', -- suggested, accepted, active, completed, rejected
-- Timeframe
start_date DATE NOT NULL,
end_date DATE,
duration_days INT,
-- Detection Criteria (JSONB für Flexibilität)
detection_params JSONB, -- { "avg_calories": 1800, "weight_trend": -0.3, ... }
-- User Notes
notes TEXT,
-- Timestamps
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_training_phases_profile ON training_phases(profile_id);
CREATE INDEX IF NOT EXISTS idx_training_phases_status ON training_phases(profile_id, status);
CREATE INDEX IF NOT EXISTS idx_training_phases_dates ON training_phases(profile_id, start_date, end_date);
COMMENT ON TABLE training_phases IS 'Training phases detected from data patterns or manually defined';
COMMENT ON COLUMN training_phases.phase_type IS 'calorie_deficit, calorie_surplus, deload, maintenance, periodization';
COMMENT ON COLUMN training_phases.detected_automatically IS 'true if AI detected this phase from data patterns';
COMMENT ON COLUMN training_phases.confidence_score IS 'AI confidence in detection (0.0 - 1.0)';
COMMENT ON COLUMN training_phases.status IS 'suggested = AI proposed, accepted = user confirmed, active = currently running, completed = finished, rejected = user dismissed';
COMMENT ON COLUMN training_phases.detection_params IS 'JSON with detection criteria: avg_calories, weight_trend, activity_volume, etc.';
-- ============================================================================
-- FITNESS TESTS (Standardized Performance Tests)
-- ============================================================================
CREATE TABLE IF NOT EXISTS fitness_tests (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
-- Test Type
test_type VARCHAR(50) NOT NULL, -- cooper_12min, step_test, pushups_max, plank_max, flexibility_sit_reach, vo2max_est, strength_1rm_squat, strength_1rm_bench
result_value DECIMAL(10,2) NOT NULL,
result_unit VARCHAR(20) NOT NULL, -- meters, bpm, reps, seconds, cm, ml/kg/min, kg
-- Test Metadata
test_date DATE NOT NULL,
test_conditions TEXT, -- Optional: Notizen zu Bedingungen
norm_category VARCHAR(30), -- sehr gut, gut, durchschnitt, unterdurchschnitt, schlecht
-- Timestamps
created_at TIMESTAMP DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_fitness_tests_profile ON fitness_tests(profile_id);
CREATE INDEX IF NOT EXISTS idx_fitness_tests_type ON fitness_tests(profile_id, test_type);
CREATE INDEX IF NOT EXISTS idx_fitness_tests_date ON fitness_tests(profile_id, test_date);
COMMENT ON TABLE fitness_tests IS 'Standardized fitness tests (Cooper, step test, strength tests, etc.)';
COMMENT ON COLUMN fitness_tests.test_type IS 'cooper_12min, step_test, pushups_max, plank_max, flexibility_sit_reach, vo2max_est, strength_1rm_squat, strength_1rm_bench';
COMMENT ON COLUMN fitness_tests.norm_category IS 'Performance category based on age/gender norms';
@@ -0,0 +1,185 @@
-- Migration 024: Goal Type Registry (Flexible Goal System)
-- Date: 2026-03-27
-- Purpose: Enable dynamic goal types without code changes
-- ============================================================================
-- Goal Type Definitions
-- ============================================================================
CREATE TABLE IF NOT EXISTS goal_type_definitions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
-- Unique identifier (used in code)
type_key VARCHAR(50) UNIQUE NOT NULL,
-- Display metadata
label_de VARCHAR(100) NOT NULL,
label_en VARCHAR(100),
unit VARCHAR(20) NOT NULL,
icon VARCHAR(10),
category VARCHAR(50), -- body, mind, activity, nutrition, recovery, custom
-- Data source configuration
source_table VARCHAR(50), -- Which table to query
source_column VARCHAR(50), -- Which column to fetch
aggregation_method VARCHAR(20), -- How to aggregate: latest, avg_7d, avg_30d, sum_30d, count_7d, count_30d, min_30d, max_30d
-- Complex calculations (optional)
-- For types like lean_mass that need custom logic
-- JSON format: {"type": "formula", "dependencies": ["weight", "body_fat"], "expression": "..."}
calculation_formula TEXT,
-- Metadata
description TEXT,
is_active BOOLEAN DEFAULT true,
is_system BOOLEAN DEFAULT false, -- System types cannot be deleted
-- Audit
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_goal_type_definitions_active ON goal_type_definitions(is_active) WHERE is_active = true;
CREATE INDEX IF NOT EXISTS idx_goal_type_definitions_category ON goal_type_definitions(category);
COMMENT ON TABLE goal_type_definitions IS 'Registry of available goal types - allows dynamic goal creation without code changes';
COMMENT ON COLUMN goal_type_definitions.type_key IS 'Unique key used in code (e.g., weight, meditation_minutes)';
COMMENT ON COLUMN goal_type_definitions.aggregation_method IS 'latest = most recent value, avg_7d = 7-day average, count_7d = count in last 7 days, etc.';
COMMENT ON COLUMN goal_type_definitions.calculation_formula IS 'JSON for complex calculations like lean_mass = weight - (weight * bf_pct / 100)';
COMMENT ON COLUMN goal_type_definitions.is_system IS 'System types are protected from deletion (core functionality)';
-- ============================================================================
-- Seed Data: Migrate existing 8 goal types
-- ============================================================================
-- 1. Weight (simple - latest value)
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
source_table, source_column, aggregation_method,
description, is_system
) VALUES (
'weight', 'Gewicht', 'Weight', 'kg', '⚖️', 'body',
'weight_log', 'weight', 'latest',
'Aktuelles Körpergewicht', true
)
ON CONFLICT (type_key) DO NOTHING;
-- 2. Body Fat (simple - latest value)
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
source_table, source_column, aggregation_method,
description, is_system
) VALUES (
'body_fat', 'Körperfett', 'Body Fat', '%', '📊', 'body',
'caliper_log', 'body_fat_pct', 'latest',
'Körperfettanteil aus Caliper-Messung', true
)
ON CONFLICT (type_key) DO NOTHING;
-- 3. Lean Mass (complex - calculation formula)
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
calculation_formula,
description, is_system
) VALUES (
'lean_mass', 'Muskelmasse', 'Lean Mass', 'kg', '💪', 'body',
'{"type": "lean_mass", "dependencies": ["weight_log.weight", "caliper_log.body_fat_pct"], "formula": "weight - (weight * body_fat_pct / 100)"}',
'Fettfreie Körpermasse (berechnet aus Gewicht und Körperfett)', true
)
ON CONFLICT (type_key) DO NOTHING;
-- 4. VO2 Max (simple - latest value)
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
source_table, source_column, aggregation_method,
description, is_system
) VALUES (
'vo2max', 'VO2Max', 'VO2Max', 'ml/kg/min', '🫁', 'recovery',
'vitals_baseline', 'vo2_max', 'latest',
'Maximale Sauerstoffaufnahme (geschätzt oder gemessen)', true
)
ON CONFLICT (type_key) DO NOTHING;
-- 5. Resting Heart Rate (simple - latest value)
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
source_table, source_column, aggregation_method,
description, is_system
) VALUES (
'rhr', 'Ruhepuls', 'Resting Heart Rate', 'bpm', '💓', 'recovery',
'vitals_baseline', 'resting_hr', 'latest',
'Ruhepuls morgens vor dem Aufstehen', true
)
ON CONFLICT (type_key) DO NOTHING;
-- 6. Blood Pressure (placeholder - compound goal for v2.0)
-- Currently limited to single value, v2.0 will support systolic/diastolic
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
source_table, source_column, aggregation_method,
description, is_system
) VALUES (
'bp', 'Blutdruck', 'Blood Pressure', 'mmHg', '❤️', 'recovery',
'blood_pressure_log', 'systolic', 'latest',
'Blutdruck (aktuell nur systolisch, v2.0: beide Werte)', true
)
ON CONFLICT (type_key) DO NOTHING;
-- 7. Strength (placeholder - no data source yet)
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
description, is_system, is_active
) VALUES (
'strength', 'Kraft', 'Strength', 'kg', '🏋️', 'activity',
'Maximalkraft (Platzhalter, Datenquelle in v2.0)', true, false
)
ON CONFLICT (type_key) DO NOTHING;
-- 8. Flexibility (placeholder - no data source yet)
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
description, is_system, is_active
) VALUES (
'flexibility', 'Beweglichkeit', 'Flexibility', 'cm', '🤸', 'activity',
'Beweglichkeit (Platzhalter, Datenquelle in v2.0)', true, false
)
ON CONFLICT (type_key) DO NOTHING;
-- ============================================================================
-- Example: Future custom goal types (commented out, for reference)
-- ============================================================================
/*
-- Meditation Minutes (avg last 7 days)
INSERT INTO goal_type_definitions (
type_key, label_de, unit, icon, category,
source_table, source_column, aggregation_method,
description, is_system
) VALUES (
'meditation_minutes', 'Meditation', 'min/Tag', '🧘', 'mind',
'meditation_log', 'duration_minutes', 'avg_7d',
'Durchschnittliche Meditationsdauer pro Tag (7 Tage)', false
);
-- Training Frequency (count last 7 days)
INSERT INTO goal_type_definitions (
type_key, label_de, unit, icon, category,
source_table, source_column, aggregation_method,
description, is_system
) VALUES (
'training_frequency', 'Trainingshäufigkeit', 'x/Woche', '📅', 'activity',
'activity_log', 'id', 'count_7d',
'Anzahl Trainingseinheiten pro Woche', false
);
-- Sleep Quality (avg last 7 days)
INSERT INTO goal_type_definitions (
type_key, label_de, unit, icon, category,
source_table, source_column, aggregation_method,
description, is_system
) VALUES (
'sleep_quality', 'Schlafqualität', '%', '💤', 'recovery',
'sleep_log', 'quality_score', 'avg_7d',
'Durchschnittliche Schlafqualität (Deep+REM Anteil)', false
);
*/
@@ -0,0 +1,103 @@
-- Migration 025: Cleanup goal_type_definitions
-- Date: 2026-03-27
-- Purpose: Remove problematic FK columns and ensure seed data
-- Remove created_by/updated_by columns if they exist
-- (May have been created by failed Migration 024)
ALTER TABLE goal_type_definitions DROP COLUMN IF EXISTS created_by;
ALTER TABLE goal_type_definitions DROP COLUMN IF EXISTS updated_by;
-- Re-insert seed data (ON CONFLICT ensures idempotency)
-- This fixes cases where Migration 024 created table but failed to seed
-- 1. Weight
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
source_table, source_column, aggregation_method,
description, is_system
) VALUES (
'weight', 'Gewicht', 'Weight', 'kg', '⚖️', 'body',
'weight_log', 'weight', 'latest',
'Aktuelles Körpergewicht', true
)
ON CONFLICT (type_key) DO NOTHING;
-- 2. Body Fat
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
source_table, source_column, aggregation_method,
description, is_system
) VALUES (
'body_fat', 'Körperfett', 'Body Fat', '%', '📊', 'body',
'caliper_log', 'body_fat_pct', 'latest',
'Körperfettanteil aus Caliper-Messung', true
)
ON CONFLICT (type_key) DO NOTHING;
-- 3. Lean Mass
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
calculation_formula,
description, is_system
) VALUES (
'lean_mass', 'Muskelmasse', 'Lean Mass', 'kg', '💪', 'body',
'{"type": "lean_mass", "dependencies": ["weight_log.weight", "caliper_log.body_fat_pct"], "formula": "weight - (weight * body_fat_pct / 100)"}',
'Fettfreie Körpermasse (berechnet aus Gewicht und Körperfett)', true
)
ON CONFLICT (type_key) DO NOTHING;
-- 4. VO2 Max
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
source_table, source_column, aggregation_method,
description, is_system
) VALUES (
'vo2max', 'VO2Max', 'VO2Max', 'ml/kg/min', '🫁', 'recovery',
'vitals_baseline', 'vo2_max', 'latest',
'Maximale Sauerstoffaufnahme (geschätzt oder gemessen)', true
)
ON CONFLICT (type_key) DO NOTHING;
-- 5. Resting Heart Rate
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
source_table, source_column, aggregation_method,
description, is_system
) VALUES (
'rhr', 'Ruhepuls', 'Resting Heart Rate', 'bpm', '💓', 'recovery',
'vitals_baseline', 'resting_hr', 'latest',
'Ruhepuls morgens vor dem Aufstehen', true
)
ON CONFLICT (type_key) DO NOTHING;
-- 6. Blood Pressure
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
source_table, source_column, aggregation_method,
description, is_system
) VALUES (
'bp', 'Blutdruck', 'Blood Pressure', 'mmHg', '❤️', 'recovery',
'blood_pressure_log', 'systolic', 'latest',
'Blutdruck (aktuell nur systolisch, v2.0: beide Werte)', true
)
ON CONFLICT (type_key) DO NOTHING;
-- 7. Strength (inactive placeholder)
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
description, is_system, is_active
) VALUES (
'strength', 'Kraft', 'Strength', 'kg', '🏋️', 'activity',
'Maximalkraft (Platzhalter, Datenquelle in v2.0)', true, false
)
ON CONFLICT (type_key) DO NOTHING;
-- 8. Flexibility (inactive placeholder)
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
description, is_system, is_active
) VALUES (
'flexibility', 'Beweglichkeit', 'Flexibility', 'cm', '🤸', 'activity',
'Beweglichkeit (Platzhalter, Datenquelle in v2.0)', true, false
)
ON CONFLICT (type_key) DO NOTHING;
@@ -0,0 +1,40 @@
-- Migration 026: Goal Type Filters
-- Date: 2026-03-27
-- Purpose: Enable filtered counting/aggregation (e.g., count only strength training)
-- Add filter_conditions column for flexible filtering
ALTER TABLE goal_type_definitions
ADD COLUMN IF NOT EXISTS filter_conditions JSONB;
COMMENT ON COLUMN goal_type_definitions.filter_conditions IS
'Optional filter conditions as JSON. Example: {"training_type": "strength"} to count only strength training sessions.
Supports any column in the source table. Format: {"column_name": "value"} or {"column_name": ["value1", "value2"]} for IN clause.';
-- Example usage (commented out):
/*
-- Count only strength training sessions per week
INSERT INTO goal_type_definitions (
type_key, label_de, unit, icon, category,
source_table, source_column, aggregation_method,
filter_conditions,
description, is_system
) VALUES (
'strength_frequency', 'Krafttraining Häufigkeit', 'x/Woche', '🏋️', 'activity',
'activity_log', 'id', 'count_7d',
'{"training_type": "strength"}',
'Anzahl Krafttraining-Einheiten pro Woche', false
) ON CONFLICT (type_key) DO NOTHING;
-- Count only cardio sessions per week
INSERT INTO goal_type_definitions (
type_key, label_de, unit, icon, category,
source_table, source_column, aggregation_method,
filter_conditions,
description, is_system
) VALUES (
'cardio_frequency', 'Cardio Häufigkeit', 'x/Woche', '🏃', 'activity',
'activity_log', 'id', 'count_7d',
'{"training_type": "cardio"}',
'Anzahl Cardio-Einheiten pro Woche', false
) ON CONFLICT (type_key) DO NOTHING;
*/
@@ -0,0 +1,125 @@
-- Migration 027: Focus Areas System (Goal System v2.0)
-- Date: 2026-03-27
-- Purpose: Replace single primary goal with weighted multi-goal system
-- ============================================================================
-- Focus Areas Table
-- ============================================================================
CREATE TABLE IF NOT EXISTS focus_areas (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
-- Six focus dimensions (percentages, sum = 100)
weight_loss_pct INTEGER DEFAULT 0 CHECK (weight_loss_pct >= 0 AND weight_loss_pct <= 100),
muscle_gain_pct INTEGER DEFAULT 0 CHECK (muscle_gain_pct >= 0 AND muscle_gain_pct <= 100),
strength_pct INTEGER DEFAULT 0 CHECK (strength_pct >= 0 AND strength_pct <= 100),
endurance_pct INTEGER DEFAULT 0 CHECK (endurance_pct >= 0 AND endurance_pct <= 100),
flexibility_pct INTEGER DEFAULT 0 CHECK (flexibility_pct >= 0 AND flexibility_pct <= 100),
health_pct INTEGER DEFAULT 0 CHECK (health_pct >= 0 AND health_pct <= 100),
-- Status
active BOOLEAN DEFAULT true,
-- Audit
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
-- Constraints
CONSTRAINT sum_equals_100 CHECK (
weight_loss_pct + muscle_gain_pct + strength_pct +
endurance_pct + flexibility_pct + health_pct = 100
)
);
-- Only one active focus_areas per profile
CREATE UNIQUE INDEX IF NOT EXISTS idx_focus_areas_profile_active
ON focus_areas(profile_id) WHERE active = true;
COMMENT ON TABLE focus_areas IS 'User-defined focus area weights (replaces simple goal_mode). Enables multi-goal prioritization with custom percentages.';
COMMENT ON COLUMN focus_areas.weight_loss_pct IS 'Focus on fat loss (0-100%)';
COMMENT ON COLUMN focus_areas.muscle_gain_pct IS 'Focus on muscle growth (0-100%)';
COMMENT ON COLUMN focus_areas.strength_pct IS 'Focus on strength gains (0-100%)';
COMMENT ON COLUMN focus_areas.endurance_pct IS 'Focus on aerobic capacity (0-100%)';
COMMENT ON COLUMN focus_areas.flexibility_pct IS 'Focus on mobility/flexibility (0-100%)';
COMMENT ON COLUMN focus_areas.health_pct IS 'Focus on general health (0-100%)';
-- ============================================================================
-- Migrate existing goal_mode to focus_areas
-- ============================================================================
-- For each profile with a goal_mode, create initial focus_areas
INSERT INTO focus_areas (
profile_id,
weight_loss_pct, muscle_gain_pct, strength_pct,
endurance_pct, flexibility_pct, health_pct
)
SELECT
id AS profile_id,
CASE goal_mode
WHEN 'weight_loss' THEN 60
WHEN 'recomposition' THEN 30
WHEN 'health' THEN 5
ELSE 0
END AS weight_loss_pct,
CASE goal_mode
WHEN 'strength' THEN 40 ELSE 0
END +
CASE goal_mode
WHEN 'recomposition' THEN 30 ELSE 0
END AS muscle_gain_pct,
CASE goal_mode
WHEN 'strength' THEN 50
WHEN 'recomposition' THEN 25
WHEN 'weight_loss' THEN 10
WHEN 'health' THEN 10
ELSE 0
END AS strength_pct,
CASE goal_mode
WHEN 'endurance' THEN 70
WHEN 'recomposition' THEN 10
WHEN 'weight_loss' THEN 20
WHEN 'health' THEN 20
ELSE 0
END AS endurance_pct,
CASE goal_mode
WHEN 'endurance' THEN 10 ELSE 0
END +
CASE goal_mode
WHEN 'health' THEN 15 ELSE 0
END +
CASE goal_mode
WHEN 'recomposition' THEN 5 ELSE 0
END +
CASE goal_mode
WHEN 'weight_loss' THEN 5 ELSE 0
END AS flexibility_pct,
CASE goal_mode
WHEN 'health' THEN 50
WHEN 'endurance' THEN 20
WHEN 'strength' THEN 10
WHEN 'weight_loss' THEN 5
ELSE 0
END AS health_pct
FROM profiles
WHERE goal_mode IS NOT NULL
ON CONFLICT DO NOTHING;
-- For profiles without goal_mode, use balanced health focus
INSERT INTO focus_areas (
profile_id,
weight_loss_pct, muscle_gain_pct, strength_pct,
endurance_pct, flexibility_pct, health_pct
)
SELECT
id AS profile_id,
0, 0, 10, 20, 15, 55
FROM profiles
WHERE goal_mode IS NULL
AND id NOT IN (SELECT profile_id FROM focus_areas WHERE active = true)
ON CONFLICT DO NOTHING;
@@ -0,0 +1,57 @@
-- Migration 028: Goal Categories and Priorities
-- Date: 2026-03-27
-- Purpose: Multi-dimensional goal priorities (one primary goal per category)
-- ============================================================================
-- Add category and priority columns
-- ============================================================================
ALTER TABLE goals
ADD COLUMN category VARCHAR(50),
ADD COLUMN priority INTEGER DEFAULT 2 CHECK (priority >= 1 AND priority <= 3);
COMMENT ON COLUMN goals.category IS 'Goal category: body, training, nutrition, recovery, health, other';
COMMENT ON COLUMN goals.priority IS 'Priority level: 1=high, 2=medium, 3=low';
-- ============================================================================
-- Migrate existing goals to categories based on goal_type
-- ============================================================================
UPDATE goals SET category = CASE
-- Body composition goals
WHEN goal_type IN ('weight', 'body_fat', 'lean_mass') THEN 'body'
-- Training goals
WHEN goal_type IN ('strength', 'flexibility', 'training_frequency') THEN 'training'
-- Health/cardio goals
WHEN goal_type IN ('vo2max', 'rhr', 'bp', 'hrv') THEN 'health'
-- Recovery goals
WHEN goal_type IN ('sleep_quality', 'sleep_duration', 'rest_days') THEN 'recovery'
-- Nutrition goals
WHEN goal_type IN ('calories', 'protein', 'healthy_eating') THEN 'nutrition'
-- Default
ELSE 'other'
END
WHERE category IS NULL;
-- ============================================================================
-- Set priority based on is_primary
-- ============================================================================
UPDATE goals SET priority = CASE
WHEN is_primary = true THEN 1 -- Primary goals get priority 1
ELSE 2 -- Others get priority 2 (medium)
END;
-- ============================================================================
-- Create index for category-based queries
-- ============================================================================
CREATE INDEX IF NOT EXISTS idx_goals_category_priority
ON goals(profile_id, category, priority);
COMMENT ON INDEX idx_goals_category_priority IS 'Fast lookup for category-grouped goals sorted by priority';
@@ -0,0 +1,74 @@
-- Migration 029: Fix Missing Goal Types (flexibility, strength)
-- Date: 2026-03-27
-- Purpose: Ensure flexibility and strength goal types are active and properly configured
-- These types were created earlier but are inactive or misconfigured
-- This migration fixes them without breaking if they don't exist
-- ============================================================================
-- Upsert flexibility goal type
-- ============================================================================
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
source_table, source_column, aggregation_method,
calculation_formula, filter_conditions, description, is_active
) VALUES (
'flexibility',
'Beweglichkeit',
'Flexibility',
'cm',
'🤸',
'training',
NULL, -- No automatic data source
NULL,
'latest',
NULL,
NULL,
'Beweglichkeit und Mobilität - manuelle Erfassung',
true
)
ON CONFLICT (type_key)
DO UPDATE SET
label_de = 'Beweglichkeit',
label_en = 'Flexibility',
unit = 'cm',
icon = '🤸',
category = 'training',
is_active = true,
description = 'Beweglichkeit und Mobilität - manuelle Erfassung';
-- ============================================================================
-- Upsert strength goal type
-- ============================================================================
INSERT INTO goal_type_definitions (
type_key, label_de, label_en, unit, icon, category,
source_table, source_column, aggregation_method,
calculation_formula, filter_conditions, description, is_active
) VALUES (
'strength',
'Kraftniveau',
'Strength',
'Punkte',
'💪',
'training',
NULL, -- No automatic data source
NULL,
'latest',
NULL,
NULL,
'Allgemeines Kraftniveau - manuelle Erfassung',
true
)
ON CONFLICT (type_key)
DO UPDATE SET
label_de = 'Kraftniveau',
label_en = 'Strength',
unit = 'Punkte',
icon = '💪',
category = 'training',
is_active = true,
description = 'Allgemeines Kraftniveau - manuelle Erfassung';
COMMENT ON TABLE goal_type_definitions IS 'Goal type registry - defines all available goal types (v1.5: DB-driven, flexible system)';
@@ -0,0 +1,64 @@
-- Migration 030: Goal Progress Log
-- Date: 2026-03-27
-- Purpose: Track progress history for all goals (especially custom goals without data source)
-- ============================================================================
-- Goal Progress Log Table
-- ============================================================================
CREATE TABLE IF NOT EXISTS goal_progress_log (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
goal_id UUID NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
-- Progress data
date DATE NOT NULL,
value DECIMAL(10,2) NOT NULL,
note TEXT,
-- Metadata
source VARCHAR(20) DEFAULT 'manual' CHECK (source IN ('manual', 'automatic', 'import')),
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
-- Constraints
CONSTRAINT unique_progress_per_day UNIQUE(goal_id, date)
);
CREATE INDEX idx_goal_progress_goal_date ON goal_progress_log(goal_id, date DESC);
CREATE INDEX idx_goal_progress_profile ON goal_progress_log(profile_id);
COMMENT ON TABLE goal_progress_log IS 'Progress history for goals - enables manual tracking for custom goals and charts';
COMMENT ON COLUMN goal_progress_log.value IS 'Progress value in goal unit (e.g., kg, cm, points)';
COMMENT ON COLUMN goal_progress_log.source IS 'manual: user entered, automatic: computed from data source, import: CSV/API';
-- ============================================================================
-- Function: Update goal current_value from latest progress
-- ============================================================================
CREATE OR REPLACE FUNCTION update_goal_current_value()
RETURNS TRIGGER AS $$
BEGIN
-- Update current_value in goals table with latest progress entry
UPDATE goals
SET current_value = (
SELECT value
FROM goal_progress_log
WHERE goal_id = NEW.goal_id
ORDER BY date DESC
LIMIT 1
),
updated_at = NOW()
WHERE id = NEW.goal_id;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Trigger: Auto-update current_value when progress is added/updated
CREATE TRIGGER trigger_update_goal_current_value
AFTER INSERT OR UPDATE ON goal_progress_log
FOR EACH ROW
EXECUTE FUNCTION update_goal_current_value();
COMMENT ON FUNCTION update_goal_current_value IS 'Auto-update goal.current_value when new progress is logged';
+114
View File
@@ -27,6 +27,7 @@ class ProfileUpdate(BaseModel):
height: Optional[float] = None
goal_weight: Optional[float] = None
goal_bf_pct: Optional[float] = None
quality_filter_level: Optional[str] = None # Issue #31: Global quality filter
# ── Tracking Models ───────────────────────────────────────────────────────────
@@ -126,3 +127,116 @@ class AdminProfileUpdate(BaseModel):
ai_enabled: Optional[int] = None
ai_limit_day: Optional[int] = None
export_enabled: Optional[int] = None
# ── Prompt Models (Issue #28) ────────────────────────────────────────────────
class PromptCreate(BaseModel):
name: str
slug: str
display_name: Optional[str] = None
description: Optional[str] = None
template: str
category: str = 'ganzheitlich'
active: bool = True
sort_order: int = 0
class PromptUpdate(BaseModel):
name: Optional[str] = None
display_name: Optional[str] = None
description: Optional[str] = None
template: Optional[str] = None
category: Optional[str] = None
active: Optional[bool] = None
sort_order: Optional[int] = None
class PromptGenerateRequest(BaseModel):
goal: str
data_categories: list[str]
example_output: Optional[str] = None
# ── Unified Prompt System Models (Issue #28 Phase 2) ───────────────────────
class StagePromptCreate(BaseModel):
"""Single prompt within a stage"""
source: str # 'inline' or 'reference'
slug: Optional[str] = None # Required if source='reference'
template: Optional[str] = None # Required if source='inline'
output_key: str # Key for storing result (e.g., 'nutrition', 'stage1_body')
output_format: str = 'text' # 'text' or 'json'
output_schema: Optional[dict] = None # JSON schema if output_format='json'
class StageCreate(BaseModel):
"""Single stage with multiple prompts"""
stage: int # Stage number (1, 2, 3, ...)
prompts: list[StagePromptCreate]
class UnifiedPromptCreate(BaseModel):
"""Create a new unified prompt (base or pipeline type)"""
name: str
slug: str
display_name: Optional[str] = None
description: Optional[str] = None
type: str # 'base' or 'pipeline'
category: str = 'ganzheitlich'
active: bool = True
sort_order: int = 0
# For base prompts (single reusable template)
template: Optional[str] = None # Required if type='base'
output_format: str = 'text'
output_schema: Optional[dict] = None
# For pipeline prompts (multi-stage workflow)
stages: Optional[list[StageCreate]] = None # Required if type='pipeline'
class UnifiedPromptUpdate(BaseModel):
"""Update an existing unified prompt"""
name: Optional[str] = None
display_name: Optional[str] = None
description: Optional[str] = None
type: Optional[str] = None
category: Optional[str] = None
active: Optional[bool] = None
sort_order: Optional[int] = None
template: Optional[str] = None
output_format: Optional[str] = None
output_schema: Optional[dict] = None
stages: Optional[list[StageCreate]] = None
# ── Pipeline Config Models (Issue #28) ─────────────────────────────────────
# NOTE: These will be deprecated in favor of UnifiedPrompt models above
class PipelineConfigCreate(BaseModel):
name: str
description: Optional[str] = None
is_default: bool = False
active: bool = True
modules: dict # {"körper": true, "ernährung": true, ...}
timeframes: dict # {"körper": 30, "ernährung": 30, ...}
stage1_prompts: list[str] # Array of slugs
stage2_prompt: str # slug
stage3_prompt: Optional[str] = None # slug
class PipelineConfigUpdate(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
is_default: Optional[bool] = None
active: Optional[bool] = None
modules: Optional[dict] = None
timeframes: Optional[dict] = None
stage1_prompts: Optional[list[str]] = None
stage2_prompt: Optional[str] = None
stage3_prompt: Optional[str] = None
class PipelineExecuteRequest(BaseModel):
config_id: Optional[str] = None # None = use default config
+715
View File
@@ -0,0 +1,715 @@
"""
Placeholder Resolver for AI Prompts
Provides a registry of placeholder functions that resolve to actual user data.
Used for prompt templates and preview functionality.
"""
import re
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Callable
from db import get_db, get_cursor, r2d
# ── Helper Functions ──────────────────────────────────────────────────────────
def get_profile_data(profile_id: str) -> Dict:
"""Load profile data for a user."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (profile_id,))
return r2d(cur.fetchone()) if cur.rowcount > 0 else {}
def get_latest_weight(profile_id: str) -> Optional[str]:
"""Get latest weight entry."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT weight FROM weight_log WHERE profile_id=%s ORDER BY date DESC LIMIT 1",
(profile_id,)
)
row = cur.fetchone()
return f"{row['weight']:.1f} kg" if row else "nicht verfügbar"
def get_weight_trend(profile_id: str, days: int = 28) -> str:
"""Calculate weight trend description."""
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT weight, date FROM weight_log
WHERE profile_id=%s AND date >= %s
ORDER BY date""",
(profile_id, cutoff)
)
rows = [r2d(r) for r in cur.fetchall()]
if len(rows) < 2:
return "nicht genug Daten"
first = rows[0]['weight']
last = rows[-1]['weight']
delta = last - first
if abs(delta) < 0.3:
return "stabil"
elif delta > 0:
return f"steigend (+{delta:.1f} kg in {days} Tagen)"
else:
return f"sinkend ({delta:.1f} kg in {days} Tagen)"
def get_latest_bf(profile_id: str) -> Optional[str]:
"""Get latest body fat percentage from caliper."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""SELECT body_fat_pct FROM caliper_log
WHERE profile_id=%s AND body_fat_pct IS NOT NULL
ORDER BY date DESC LIMIT 1""",
(profile_id,)
)
row = cur.fetchone()
return f"{row['body_fat_pct']:.1f}%" if row else "nicht verfügbar"
def get_nutrition_avg(profile_id: str, field: str, days: int = 30) -> str:
"""Calculate average nutrition value."""
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
# Map field names to actual column names
field_map = {
'protein': 'protein_g',
'fat': 'fat_g',
'carb': 'carbs_g',
'kcal': 'kcal'
}
db_field = field_map.get(field, field)
cur.execute(
f"""SELECT AVG({db_field}) as avg FROM nutrition_log
WHERE profile_id=%s AND date >= %s AND {db_field} IS NOT NULL""",
(profile_id, cutoff)
)
row = cur.fetchone()
if row and row['avg']:
if field == 'kcal':
return f"{int(row['avg'])} kcal/Tag (Ø {days} Tage)"
else:
return f"{int(row['avg'])}g/Tag (Ø {days} Tage)"
return "nicht verfügbar"
def get_caliper_summary(profile_id: str) -> str:
"""Get latest caliper measurements summary."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""SELECT body_fat_pct, sf_method, date FROM caliper_log
WHERE profile_id=%s AND body_fat_pct IS NOT NULL
ORDER BY date DESC LIMIT 1""",
(profile_id,)
)
row = r2d(cur.fetchone()) if cur.rowcount > 0 else None
if not row:
return "keine Caliper-Messungen"
method = row.get('sf_method', 'unbekannt')
return f"{row['body_fat_pct']:.1f}% ({method} am {row['date']})"
def get_circ_summary(profile_id: str) -> str:
"""Get latest circumference measurements summary with age annotations.
For each measurement point, fetches the most recent value (even if from different dates).
Annotates each value with measurement age for AI context.
"""
with get_db() as conn:
cur = get_cursor(conn)
# Define all circumference points with their labels
fields = [
('c_neck', 'Nacken'),
('c_chest', 'Brust'),
('c_waist', 'Taille'),
('c_belly', 'Bauch'),
('c_hip', 'Hüfte'),
('c_thigh', 'Oberschenkel'),
('c_calf', 'Wade'),
('c_arm', 'Arm')
]
parts = []
today = datetime.now().date()
# Get latest value for each field individually
for field_name, label in fields:
cur.execute(
f"""SELECT {field_name}, date,
CURRENT_DATE - date AS age_days
FROM circumference_log
WHERE profile_id=%s AND {field_name} IS NOT NULL
ORDER BY date DESC LIMIT 1""",
(profile_id,)
)
row = r2d(cur.fetchone()) if cur.rowcount > 0 else None
if row:
value = row[field_name]
age_days = row['age_days']
# Format age annotation
if age_days == 0:
age_str = "heute"
elif age_days == 1:
age_str = "gestern"
elif age_days <= 7:
age_str = f"vor {age_days} Tagen"
elif age_days <= 30:
weeks = age_days // 7
age_str = f"vor {weeks} Woche{'n' if weeks > 1 else ''}"
else:
months = age_days // 30
age_str = f"vor {months} Monat{'en' if months > 1 else ''}"
parts.append(f"{label} {value:.1f}cm ({age_str})")
return ', '.join(parts) if parts else "keine Umfangsmessungen"
def get_goal_weight(profile_id: str) -> str:
"""Get goal weight from profile."""
profile = get_profile_data(profile_id)
goal = profile.get('goal_weight')
return f"{goal:.1f}" if goal else "nicht gesetzt"
def get_goal_bf_pct(profile_id: str) -> str:
"""Get goal body fat percentage from profile."""
profile = get_profile_data(profile_id)
goal = profile.get('goal_bf_pct')
return f"{goal:.1f}" if goal else "nicht gesetzt"
def get_nutrition_days(profile_id: str, days: int = 30) -> str:
"""Get number of days with nutrition data."""
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT COUNT(DISTINCT date) as days FROM nutrition_log
WHERE profile_id=%s AND date >= %s""",
(profile_id, cutoff)
)
row = cur.fetchone()
return str(row['days']) if row else "0"
def get_protein_ziel_low(profile_id: str) -> str:
"""Calculate lower protein target based on current weight (1.6g/kg)."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""SELECT weight FROM weight_log
WHERE profile_id=%s ORDER BY date DESC LIMIT 1""",
(profile_id,)
)
row = cur.fetchone()
if row:
return f"{int(float(row['weight']) * 1.6)}"
return "nicht verfügbar"
def get_protein_ziel_high(profile_id: str) -> str:
"""Calculate upper protein target based on current weight (2.2g/kg)."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""SELECT weight FROM weight_log
WHERE profile_id=%s ORDER BY date DESC LIMIT 1""",
(profile_id,)
)
row = cur.fetchone()
if row:
return f"{int(float(row['weight']) * 2.2)}"
return "nicht verfügbar"
def get_activity_summary(profile_id: str, days: int = 14) -> str:
"""Get activity summary for recent period."""
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT COUNT(*) as count,
SUM(duration_min) as total_min,
SUM(kcal_active) as total_kcal
FROM activity_log
WHERE profile_id=%s AND date >= %s""",
(profile_id, cutoff)
)
row = r2d(cur.fetchone())
if row['count'] == 0:
return f"Keine Aktivitäten in den letzten {days} Tagen"
avg_min = int(row['total_min'] / row['count']) if row['total_min'] else 0
return f"{row['count']} Einheiten in {days} Tagen (Ø {avg_min} min/Einheit, {int(row['total_kcal'] or 0)} kcal gesamt)"
def calculate_age(dob) -> str:
"""Calculate age from date of birth (accepts date object or string)."""
if not dob:
return "unbekannt"
try:
# Handle both datetime.date objects and strings
if isinstance(dob, str):
birth = datetime.strptime(dob, '%Y-%m-%d').date()
else:
birth = dob # Already a date object from PostgreSQL
today = datetime.now().date()
age = today.year - birth.year - ((today.month, today.day) < (birth.month, birth.day))
return str(age)
except Exception as e:
return "unbekannt"
def get_activity_detail(profile_id: str, days: int = 14) -> str:
"""Get detailed activity log for analysis."""
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT date, activity_type, duration_min, kcal_active, hr_avg
FROM activity_log
WHERE profile_id=%s AND date >= %s
ORDER BY date DESC
LIMIT 50""",
(profile_id, cutoff)
)
rows = [r2d(r) for r in cur.fetchall()]
if not rows:
return f"Keine Aktivitäten in den letzten {days} Tagen"
# Format as readable list
lines = []
for r in rows:
hr_str = f" HF={r['hr_avg']}" if r.get('hr_avg') else ""
lines.append(
f"{r['date']}: {r['activity_type']} ({r['duration_min']}min, {r.get('kcal_active', 0)}kcal{hr_str})"
)
return '\n'.join(lines[:20]) # Max 20 entries to avoid token bloat
def get_trainingstyp_verteilung(profile_id: str, days: int = 14) -> str:
"""Get training type distribution."""
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT training_category, COUNT(*) as count
FROM activity_log
WHERE profile_id=%s AND date >= %s AND training_category IS NOT NULL
GROUP BY training_category
ORDER BY count DESC""",
(profile_id, cutoff)
)
rows = [r2d(r) for r in cur.fetchall()]
if not rows:
return "Keine kategorisierten Trainings"
total = sum(r['count'] for r in rows)
parts = [f"{r['training_category']}: {int(r['count']/total*100)}%" for r in rows[:3]]
return ", ".join(parts)
def get_sleep_avg_duration(profile_id: str, days: int = 7) -> str:
"""Calculate average sleep duration in hours."""
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT sleep_segments FROM sleep_log
WHERE profile_id=%s AND date >= %s
ORDER BY date DESC""",
(profile_id, cutoff)
)
rows = cur.fetchall()
if not rows:
return "nicht verfügbar"
total_minutes = 0
for row in rows:
segments = row['sleep_segments']
if segments:
# Sum duration_min from all segments
for seg in segments:
total_minutes += seg.get('duration_min', 0)
if total_minutes == 0:
return "nicht verfügbar"
avg_hours = total_minutes / len(rows) / 60
return f"{avg_hours:.1f}h"
def get_sleep_avg_quality(profile_id: str, days: int = 7) -> str:
"""Calculate average sleep quality (Deep+REM %)."""
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT sleep_segments FROM sleep_log
WHERE profile_id=%s AND date >= %s
ORDER BY date DESC""",
(profile_id, cutoff)
)
rows = cur.fetchall()
if not rows:
return "nicht verfügbar"
total_quality = 0
count = 0
for row in rows:
segments = row['sleep_segments']
if segments:
# Note: segments use 'phase' key (not 'stage'), stored lowercase (deep, rem, light, awake)
deep_rem_min = sum(s.get('duration_min', 0) for s in segments if s.get('phase') in ['deep', 'rem'])
total_min = sum(s.get('duration_min', 0) for s in segments)
if total_min > 0:
quality_pct = (deep_rem_min / total_min) * 100
total_quality += quality_pct
count += 1
if count == 0:
return "nicht verfügbar"
avg_quality = total_quality / count
return f"{avg_quality:.0f}% (Deep+REM)"
def get_rest_days_count(profile_id: str, days: int = 30) -> str:
"""Count rest days in the given period."""
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT COUNT(DISTINCT date) as count FROM rest_days
WHERE profile_id=%s AND date >= %s""",
(profile_id, cutoff)
)
row = cur.fetchone()
count = row['count'] if row else 0
return f"{count} Ruhetage"
def get_vitals_avg_hr(profile_id: str, days: int = 7) -> str:
"""Calculate average resting heart rate."""
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT AVG(resting_hr) as avg FROM vitals_baseline
WHERE profile_id=%s AND date >= %s AND resting_hr IS NOT NULL""",
(profile_id, cutoff)
)
row = cur.fetchone()
if row and row['avg']:
return f"{int(row['avg'])} bpm"
return "nicht verfügbar"
def get_vitals_avg_hrv(profile_id: str, days: int = 7) -> str:
"""Calculate average heart rate variability."""
with get_db() as conn:
cur = get_cursor(conn)
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT AVG(hrv) as avg FROM vitals_baseline
WHERE profile_id=%s AND date >= %s AND hrv IS NOT NULL""",
(profile_id, cutoff)
)
row = cur.fetchone()
if row and row['avg']:
return f"{int(row['avg'])} ms"
return "nicht verfügbar"
def get_vitals_vo2_max(profile_id: str) -> str:
"""Get latest VO2 Max value."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""SELECT vo2_max FROM vitals_baseline
WHERE profile_id=%s AND vo2_max IS NOT NULL
ORDER BY date DESC LIMIT 1""",
(profile_id,)
)
row = cur.fetchone()
if row and row['vo2_max']:
return f"{row['vo2_max']:.1f} ml/kg/min"
return "nicht verfügbar"
# ── Placeholder Registry ──────────────────────────────────────────────────────
PLACEHOLDER_MAP: Dict[str, Callable[[str], str]] = {
# Profil
'{{name}}': lambda pid: get_profile_data(pid).get('name', 'Nutzer'),
'{{age}}': lambda pid: calculate_age(get_profile_data(pid).get('dob')),
'{{height}}': lambda pid: str(get_profile_data(pid).get('height', 'unbekannt')),
'{{geschlecht}}': lambda pid: 'männlich' if get_profile_data(pid).get('sex') == 'm' else 'weiblich',
# Körper
'{{weight_aktuell}}': get_latest_weight,
'{{weight_trend}}': get_weight_trend,
'{{kf_aktuell}}': get_latest_bf,
'{{bmi}}': lambda pid: calculate_bmi(pid),
'{{caliper_summary}}': get_caliper_summary,
'{{circ_summary}}': get_circ_summary,
'{{goal_weight}}': get_goal_weight,
'{{goal_bf_pct}}': get_goal_bf_pct,
# Ernährung
'{{kcal_avg}}': lambda pid: get_nutrition_avg(pid, 'kcal', 30),
'{{protein_avg}}': lambda pid: get_nutrition_avg(pid, 'protein', 30),
'{{carb_avg}}': lambda pid: get_nutrition_avg(pid, 'carb', 30),
'{{fat_avg}}': lambda pid: get_nutrition_avg(pid, 'fat', 30),
'{{nutrition_days}}': lambda pid: get_nutrition_days(pid, 30),
'{{protein_ziel_low}}': get_protein_ziel_low,
'{{protein_ziel_high}}': get_protein_ziel_high,
# Training
'{{activity_summary}}': get_activity_summary,
'{{activity_detail}}': get_activity_detail,
'{{trainingstyp_verteilung}}': get_trainingstyp_verteilung,
# Schlaf & Erholung
'{{sleep_avg_duration}}': lambda pid: get_sleep_avg_duration(pid, 7),
'{{sleep_avg_quality}}': lambda pid: get_sleep_avg_quality(pid, 7),
'{{rest_days_count}}': lambda pid: get_rest_days_count(pid, 30),
# Vitalwerte
'{{vitals_avg_hr}}': lambda pid: get_vitals_avg_hr(pid, 7),
'{{vitals_avg_hrv}}': lambda pid: get_vitals_avg_hrv(pid, 7),
'{{vitals_vo2_max}}': get_vitals_vo2_max,
# Zeitraum
'{{datum_heute}}': lambda pid: datetime.now().strftime('%d.%m.%Y'),
'{{zeitraum_7d}}': lambda pid: 'letzte 7 Tage',
'{{zeitraum_30d}}': lambda pid: 'letzte 30 Tage',
'{{zeitraum_90d}}': lambda pid: 'letzte 90 Tage',
}
def calculate_bmi(profile_id: str) -> str:
"""Calculate BMI from latest weight and profile height."""
profile = get_profile_data(profile_id)
if not profile.get('height'):
return "nicht verfügbar"
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT weight FROM weight_log WHERE profile_id=%s ORDER BY date DESC LIMIT 1",
(profile_id,)
)
row = cur.fetchone()
if not row:
return "nicht verfügbar"
height_m = profile['height'] / 100
bmi = row['weight'] / (height_m ** 2)
return f"{bmi:.1f}"
# ── Public API ────────────────────────────────────────────────────────────────
def resolve_placeholders(template: str, profile_id: str) -> str:
"""
Replace all {{placeholders}} in template with actual user data.
Args:
template: Prompt template with placeholders
profile_id: User profile ID
Returns:
Resolved template with placeholders replaced by values
"""
result = template
for placeholder, resolver in PLACEHOLDER_MAP.items():
if placeholder in result:
try:
value = resolver(profile_id)
result = result.replace(placeholder, str(value))
except Exception as e:
# On error, replace with error message
result = result.replace(placeholder, f"[Fehler: {placeholder}]")
return result
def get_unknown_placeholders(template: str) -> List[str]:
"""
Find all placeholders in template that are not in PLACEHOLDER_MAP.
Args:
template: Prompt template
Returns:
List of unknown placeholder names (without {{}})
"""
# Find all {{...}} patterns
found = re.findall(r'\{\{(\w+)\}\}', template)
# Filter to only unknown ones
known_names = {p.strip('{}') for p in PLACEHOLDER_MAP.keys()}
unknown = [p for p in found if p not in known_names]
return list(set(unknown)) # Remove duplicates
def get_available_placeholders(categories: Optional[List[str]] = None) -> Dict[str, List[str]]:
"""
Get available placeholders, optionally filtered by categories.
Args:
categories: Optional list of categories to filter (körper, ernährung, training, etc.)
Returns:
Dict mapping category to list of placeholders
"""
placeholder_categories = {
'profil': [
'{{name}}', '{{age}}', '{{height}}', '{{geschlecht}}'
],
'körper': [
'{{weight_aktuell}}', '{{weight_trend}}', '{{kf_aktuell}}', '{{bmi}}'
],
'ernährung': [
'{{kcal_avg}}', '{{protein_avg}}', '{{carb_avg}}', '{{fat_avg}}'
],
'training': [
'{{activity_summary}}', '{{trainingstyp_verteilung}}'
],
'zeitraum': [
'{{datum_heute}}', '{{zeitraum_7d}}', '{{zeitraum_30d}}', '{{zeitraum_90d}}'
]
}
if not categories:
return placeholder_categories
# Filter to requested categories
return {k: v for k, v in placeholder_categories.items() if k in categories}
def get_placeholder_example_values(profile_id: str) -> Dict[str, str]:
"""
Get example values for all placeholders using real user data.
Args:
profile_id: User profile ID
Returns:
Dict mapping placeholder to example value
"""
examples = {}
for placeholder, resolver in PLACEHOLDER_MAP.items():
try:
examples[placeholder] = resolver(profile_id)
except Exception as e:
examples[placeholder] = f"[Fehler: {str(e)}]"
return examples
def get_placeholder_catalog(profile_id: str) -> Dict[str, List[Dict[str, str]]]:
"""
Get grouped placeholder catalog with descriptions and example values.
Args:
profile_id: User profile ID
Returns:
Dict mapping category to list of {key, description, example}
"""
# Placeholder definitions with descriptions
placeholders = {
'Profil': [
('name', 'Name des Nutzers'),
('age', 'Alter in Jahren'),
('height', 'Körpergröße in cm'),
('geschlecht', 'Geschlecht'),
],
'Körper': [
('weight_aktuell', 'Aktuelles Gewicht in kg'),
('weight_trend', 'Gewichtstrend (7d/30d)'),
('kf_aktuell', 'Aktueller Körperfettanteil in %'),
('bmi', 'Body Mass Index'),
],
'Ernährung': [
('kcal_avg', 'Durchschn. Kalorien (30d)'),
('protein_avg', 'Durchschn. Protein in g (30d)'),
('carb_avg', 'Durchschn. Kohlenhydrate in g (30d)'),
('fat_avg', 'Durchschn. Fett in g (30d)'),
],
'Training': [
('activity_summary', 'Aktivitäts-Zusammenfassung (7d)'),
('trainingstyp_verteilung', 'Verteilung nach Trainingstypen'),
],
'Schlaf & Erholung': [
('sleep_avg_duration', 'Durchschn. Schlafdauer (7d)'),
('sleep_avg_quality', 'Durchschn. Schlafqualität (7d)'),
('rest_days_count', 'Anzahl Ruhetage (30d)'),
],
'Vitalwerte': [
('vitals_avg_hr', 'Durchschn. Ruhepuls (7d)'),
('vitals_avg_hrv', 'Durchschn. HRV (7d)'),
('vitals_vo2_max', 'Aktueller VO2 Max'),
],
'Zeitraum': [
('datum_heute', 'Heutiges Datum'),
('zeitraum_7d', '7-Tage-Zeitraum'),
('zeitraum_30d', '30-Tage-Zeitraum'),
],
}
catalog = {}
for category, items in placeholders.items():
catalog[category] = []
for key, description in items:
placeholder = f'{{{{{key}}}}}'
# Get example value if resolver exists
resolver = PLACEHOLDER_MAP.get(placeholder)
if resolver:
try:
example = resolver(profile_id)
except Exception:
example = '[Nicht verfügbar]'
else:
example = '[Nicht implementiert]'
catalog[category].append({
'key': key,
'description': description,
'example': str(example)
})
return catalog
+349
View File
@@ -0,0 +1,349 @@
"""
Training Type Profiles - Master Evaluator
Comprehensive activity evaluation across all 7 dimensions.
Issue: #15
Date: 2026-03-23
"""
from typing import Dict, Optional, List
from datetime import datetime
import logging
from rule_engine import RuleEvaluator, IntensityZoneEvaluator, TrainingEffectsEvaluator
logger = logging.getLogger(__name__)
class TrainingProfileEvaluator:
"""
Master class for comprehensive activity evaluation.
Evaluates an activity against a training type profile across 7 dimensions:
1. Minimum Requirements (Quality Gates)
2. Intensity Zones (HR zones)
3. Training Effects (Abilities)
4. Periodization (Frequency & Recovery)
5. Performance Indicators (KPIs)
6. Safety (Warnings)
7. AI Context
"""
def __init__(self, parameters_registry: Dict[str, Dict]):
"""
Initialize evaluator with parameter registry.
Args:
parameters_registry: Dict mapping parameter_key -> config
"""
self.parameters_registry = parameters_registry
self.rule_evaluator = RuleEvaluator()
self.zone_evaluator = IntensityZoneEvaluator()
self.effects_evaluator = TrainingEffectsEvaluator()
def evaluate_activity(
self,
activity: Dict,
training_type_profile: Optional[Dict],
context: Optional[Dict] = None
) -> Dict:
"""
Complete evaluation of an activity against its training type profile.
Args:
activity: Activity data dictionary
training_type_profile: Training type profile (JSONB)
context: {
"user_profile": {...},
"recent_activities": [...],
"historical_activities": [...]
}
Returns:
{
"evaluated_at": ISO timestamp,
"profile_version": str,
"rule_set_results": {
"minimum_requirements": {...},
"intensity_zones": {...},
"training_effects": {...},
"periodization": {...},
"performance_indicators": {...},
"safety": {...}
},
"overall_score": float (0-1),
"quality_label": str,
"recommendations": [str],
"warnings": [str]
}
"""
# No profile? Return unvalidated result
if not training_type_profile:
return self._create_unvalidated_result()
rule_sets = training_type_profile.get("rule_sets", {})
context = context or {}
results = {
"evaluated_at": datetime.now().isoformat(),
"profile_version": training_type_profile.get("version", "unknown"),
"rule_set_results": {}
}
# ━━━ 1. MINIMUM REQUIREMENTS ━━━
if "minimum_requirements" in rule_sets:
results["rule_set_results"]["minimum_requirements"] = \
self.rule_evaluator.evaluate_rule_set(
rule_sets["minimum_requirements"],
activity,
self.parameters_registry
)
# ━━━ 2. INTENSITY ZONES ━━━
if "intensity_zones" in rule_sets:
results["rule_set_results"]["intensity_zones"] = \
self.zone_evaluator.evaluate(
rule_sets["intensity_zones"],
activity,
context.get("user_profile", {})
)
# ━━━ 3. TRAINING EFFECTS ━━━
if "training_effects" in rule_sets:
results["rule_set_results"]["training_effects"] = \
self.effects_evaluator.evaluate(
rule_sets["training_effects"],
activity,
results["rule_set_results"].get("intensity_zones")
)
# ━━━ 4. PERIODIZATION ━━━
if "periodization" in rule_sets:
results["rule_set_results"]["periodization"] = \
self._evaluate_periodization(
rule_sets["periodization"],
activity,
context.get("recent_activities", [])
)
# ━━━ 5. PERFORMANCE INDICATORS ━━━
if "performance_indicators" in rule_sets:
results["rule_set_results"]["performance_indicators"] = \
self._evaluate_performance(
rule_sets["performance_indicators"],
activity,
context.get("historical_activities", [])
)
# ━━━ 6. SAFETY WARNINGS ━━━
if "safety" in rule_sets:
results["rule_set_results"]["safety"] = \
self._evaluate_safety(
rule_sets["safety"],
activity
)
# ━━━ OVERALL SCORE & QUALITY LABEL ━━━
overall_score = self._calculate_overall_score(results["rule_set_results"])
results["overall_score"] = overall_score
results["quality_label"] = self._get_quality_label(overall_score)
# ━━━ RECOMMENDATIONS & WARNINGS ━━━
results["recommendations"] = self._generate_recommendations(results)
results["warnings"] = self._collect_warnings(results)
return results
def _create_unvalidated_result(self) -> Dict:
"""Creates result for activities without profile."""
return {
"evaluated_at": datetime.now().isoformat(),
"profile_version": None,
"rule_set_results": {},
"overall_score": None,
"quality_label": None,
"recommendations": ["Kein Trainingsprofil konfiguriert"],
"warnings": []
}
def _evaluate_periodization(
self,
config: Dict,
activity: Dict,
recent_activities: List[Dict]
) -> Dict:
"""
Evaluates periodization compliance (frequency & recovery).
Simplified for MVP - full implementation later.
"""
if not config.get("enabled", False):
return {"enabled": False}
# Basic frequency check
training_type_id = activity.get("training_type_id")
same_type_this_week = sum(
1 for a in recent_activities
if a.get("training_type_id") == training_type_id
)
frequency_config = config.get("frequency", {})
optimal = frequency_config.get("per_week_optimal", 3)
return {
"enabled": True,
"weekly_count": same_type_this_week,
"optimal_count": optimal,
"frequency_status": "optimal" if same_type_this_week <= optimal else "over_optimal",
"recovery_adequate": True, # Simplified for MVP
"warning": None
}
def _evaluate_performance(
self,
config: Dict,
activity: Dict,
historical_activities: List[Dict]
) -> Dict:
"""
Evaluates performance development.
Simplified for MVP - full implementation later.
"""
if not config.get("enabled", False):
return {"enabled": False}
return {
"enabled": True,
"trend": "stable", # Simplified
"metrics_comparison": {},
"benchmark_level": "intermediate"
}
def _evaluate_safety(self, config: Dict, activity: Dict) -> Dict:
"""
Evaluates safety warnings.
"""
if not config.get("enabled", False):
return {"enabled": False, "warnings": []}
warnings_config = config.get("warnings", [])
triggered_warnings = []
for warning_rule in warnings_config:
param_key = warning_rule.get("parameter")
operator = warning_rule.get("operator")
threshold = warning_rule.get("value")
severity = warning_rule.get("severity", "medium")
message = warning_rule.get("message", "")
actual_value = activity.get(param_key)
if actual_value is not None:
operator_func = RuleEvaluator.OPERATORS.get(operator)
if operator_func and operator_func(actual_value, threshold):
triggered_warnings.append({
"severity": severity,
"message": message,
"parameter": param_key,
"actual_value": actual_value,
"threshold": threshold
})
return {
"enabled": True,
"warnings": triggered_warnings
}
def _calculate_overall_score(self, rule_set_results: Dict) -> float:
"""
Calculates weighted overall score.
Weights:
- Minimum Requirements: 40%
- Intensity Zones: 20%
- Periodization: 20%
- Performance: 10%
- Training Effects: 10%
"""
weights = {
"minimum_requirements": 0.4,
"intensity_zones": 0.2,
"periodization": 0.2,
"performance_indicators": 0.1,
"training_effects": 0.1
}
total_score = 0.0
total_weight = 0.0
for rule_set_name, weight in weights.items():
result = rule_set_results.get(rule_set_name)
if result and result.get("enabled"):
score = result.get("score", 0.5)
# Special handling for different result types
if rule_set_name == "intensity_zones":
score = result.get("duration_quality", 0.5)
elif rule_set_name == "periodization":
score = 1.0 if result.get("recovery_adequate", False) else 0.5
total_score += score * weight
total_weight += weight
return round(total_score / total_weight, 2) if total_weight > 0 else 0.5
def _get_quality_label(self, score: Optional[float]) -> Optional[str]:
"""Converts score to quality label."""
if score is None:
return None
if score >= 0.9:
return "excellent"
elif score >= 0.7:
return "good"
elif score >= 0.5:
return "acceptable"
else:
return "poor"
def _generate_recommendations(self, results: Dict) -> List[str]:
"""Generates actionable recommendations."""
recommendations = []
# Check minimum requirements
min_req = results["rule_set_results"].get("minimum_requirements", {})
if min_req.get("enabled") and not min_req.get("passed"):
for failed in min_req.get("failed_rules", []):
param = failed.get("parameter")
actual = failed.get("actual_value")
expected = failed.get("expected_value")
reason = failed.get("reason", "")
symbol = failed.get("operator_symbol", "")
recommendations.append(
f"{param}: {actual} {symbol} {expected} - {reason}"
)
# Check intensity zones
zone_result = results["rule_set_results"].get("intensity_zones", {})
if zone_result.get("enabled") and zone_result.get("recommendation"):
recommendations.append(zone_result["recommendation"])
# Default recommendation if excellent
if results.get("quality_label") == "excellent" and not recommendations:
recommendations.append("Hervorragendes Training! Weiter so.")
return recommendations
def _collect_warnings(self, results: Dict) -> List[str]:
"""Collects all warnings from safety checks."""
safety_result = results["rule_set_results"].get("safety", {})
if not safety_result.get("enabled"):
return []
warnings = []
for warning in safety_result.get("warnings", []):
severity_icon = "🔴" if warning["severity"] == "high" else "⚠️"
warnings.append(f"{severity_icon} {warning['message']}")
return warnings
+450
View File
@@ -0,0 +1,450 @@
"""
Training Type Profile Templates
Pre-configured profiles for common training types.
Issue: #15
Date: 2026-03-23
"""
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# TEMPLATE: LAUFEN (Running) - Ausdauer-fokussiert
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
TEMPLATE_RUNNING = {
"version": "1.0",
"name": "Laufen (Standard)",
"description": "Ausdauerlauf mit Herzfrequenz-Zonen",
"rule_sets": {
"minimum_requirements": {
"enabled": True,
"pass_strategy": "weighted_score",
"pass_threshold": 0.6,
"rules": [
{
"parameter": "duration_min",
"operator": "gte",
"value": 15,
"weight": 5,
"optional": False,
"reason": "Mindestens 15 Minuten für Trainingseffekt"
},
{
"parameter": "avg_hr",
"operator": "gte",
"value": 100,
"weight": 3,
"optional": False,
"reason": "Puls muss für Ausdauerreiz erhöht sein"
},
{
"parameter": "distance_km",
"operator": "gte",
"value": 1.0,
"weight": 2,
"optional": False,
"reason": "Mindestens 1 km Distanz"
}
]
},
"intensity_zones": {
"enabled": True,
"zones": [
{
"id": "regeneration",
"name": "Regeneration",
"color": "#4CAF50",
"effect": "Aktive Erholung",
"target_duration_min": 30,
"rules": [
{
"parameter": "avg_hr_percent",
"operator": "between",
"value": [50, 60]
}
]
},
{
"id": "grundlagenausdauer",
"name": "Grundlagenausdauer",
"color": "#2196F3",
"effect": "Fettverbrennung, aerobe Basis",
"target_duration_min": 45,
"rules": [
{
"parameter": "avg_hr_percent",
"operator": "between",
"value": [60, 70]
}
]
},
{
"id": "entwicklungsbereich",
"name": "Entwicklungsbereich",
"color": "#FF9800",
"effect": "VO2max-Training, Laktattoleranz",
"target_duration_min": 30,
"rules": [
{
"parameter": "avg_hr_percent",
"operator": "between",
"value": [70, 80]
}
]
},
{
"id": "schwellentraining",
"name": "Schwellentraining",
"color": "#F44336",
"effect": "Anaerobe Schwelle, Wettkampftempo",
"target_duration_min": 20,
"rules": [
{
"parameter": "avg_hr_percent",
"operator": "between",
"value": [80, 90]
}
]
}
]
},
"training_effects": {
"enabled": True,
"default_effects": {
"primary_abilities": [
{
"category": "konditionell",
"ability": "ausdauer",
"intensity": 5
}
],
"secondary_abilities": [
{
"category": "konditionell",
"ability": "schnelligkeit",
"intensity": 2
},
{
"category": "koordinativ",
"ability": "rhythmus",
"intensity": 3
},
{
"category": "psychisch",
"ability": "willenskraft",
"intensity": 4
}
]
},
"metabolic_focus": ["aerobic", "fat_oxidation"],
"muscle_groups": ["legs", "core", "cardiovascular"]
},
"periodization": {
"enabled": True,
"frequency": {
"per_week_optimal": 3,
"per_week_max": 5
},
"recovery": {
"min_hours_between": 24
}
},
"performance_indicators": {
"enabled": False
},
"safety": {
"enabled": True,
"warnings": [
{
"parameter": "avg_hr_percent",
"operator": "gt",
"value": 95,
"severity": "high",
"message": "Herzfrequenz zu hoch - Überbelastungsrisiko"
},
{
"parameter": "duration_min",
"operator": "gt",
"value": 180,
"severity": "medium",
"message": "Sehr lange Einheit - achte auf Regeneration"
}
]
}
}
}
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# TEMPLATE: MEDITATION - Mental-fokussiert (≤ statt ≥ bei HR!)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
TEMPLATE_MEDITATION = {
"version": "1.0",
"name": "Meditation (Standard)",
"description": "Mentales Training mit niedrigem Puls",
"rule_sets": {
"minimum_requirements": {
"enabled": True,
"pass_strategy": "weighted_score",
"pass_threshold": 0.6,
"rules": [
{
"parameter": "duration_min",
"operator": "gte",
"value": 5,
"weight": 5,
"optional": False,
"reason": "Mindestens 5 Minuten für Entspannungseffekt"
},
{
"parameter": "avg_hr",
"operator": "lte",
"value": 80,
"weight": 4,
"optional": False,
"reason": "Niedriger Puls zeigt Entspannung an"
}
]
},
"intensity_zones": {
"enabled": True,
"zones": [
{
"id": "deep_relaxation",
"name": "Tiefenentspannung",
"color": "#4CAF50",
"effect": "Parasympathikus-Aktivierung",
"target_duration_min": 10,
"rules": [
{
"parameter": "avg_hr_percent",
"operator": "between",
"value": [35, 45]
}
]
},
{
"id": "light_meditation",
"name": "Leichte Meditation",
"color": "#2196F3",
"effect": "Achtsamkeit, Fokus",
"target_duration_min": 15,
"rules": [
{
"parameter": "avg_hr_percent",
"operator": "between",
"value": [45, 55]
}
]
}
]
},
"training_effects": {
"enabled": True,
"default_effects": {
"primary_abilities": [
{
"category": "kognitiv",
"ability": "konzentration",
"intensity": 5
},
{
"category": "psychisch",
"ability": "stressresistenz",
"intensity": 5
}
],
"secondary_abilities": [
{
"category": "kognitiv",
"ability": "wahrnehmung",
"intensity": 4
},
{
"category": "psychisch",
"ability": "selbstvertrauen",
"intensity": 3
}
]
},
"metabolic_focus": ["parasympathetic_activation"],
"muscle_groups": []
},
"periodization": {
"enabled": True,
"frequency": {
"per_week_optimal": 5,
"per_week_max": 7
},
"recovery": {
"min_hours_between": 0
}
},
"performance_indicators": {
"enabled": False
},
"safety": {
"enabled": True,
"warnings": [
{
"parameter": "avg_hr",
"operator": "gt",
"value": 100,
"severity": "medium",
"message": "Herzfrequenz zu hoch für Meditation - bist du wirklich entspannt?"
}
]
}
}
}
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# TEMPLATE: KRAFTTRAINING - Kraft-fokussiert
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
TEMPLATE_STRENGTH = {
"version": "1.0",
"name": "Krafttraining (Standard)",
"description": "Krafttraining mit moderater Herzfrequenz",
"rule_sets": {
"minimum_requirements": {
"enabled": True,
"pass_strategy": "weighted_score",
"pass_threshold": 0.5,
"rules": [
{
"parameter": "duration_min",
"operator": "gte",
"value": 20,
"weight": 5,
"optional": False,
"reason": "Mindestens 20 Minuten für Muskelreiz"
},
{
"parameter": "kcal_active",
"operator": "gte",
"value": 100,
"weight": 2,
"optional": True,
"reason": "Mindest-Kalorienverbrauch"
}
]
},
"intensity_zones": {
"enabled": False
},
"training_effects": {
"enabled": True,
"default_effects": {
"primary_abilities": [
{
"category": "konditionell",
"ability": "kraft",
"intensity": 5
}
],
"secondary_abilities": [
{
"category": "koordinativ",
"ability": "differenzierung",
"intensity": 3
},
{
"category": "psychisch",
"ability": "willenskraft",
"intensity": 4
}
]
},
"metabolic_focus": ["anaerobic", "muscle_growth"],
"muscle_groups": ["full_body"]
},
"periodization": {
"enabled": True,
"frequency": {
"per_week_optimal": 3,
"per_week_max": 5
},
"recovery": {
"min_hours_between": 48
}
},
"performance_indicators": {
"enabled": False
},
"safety": {
"enabled": True,
"warnings": []
}
}
}
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# TEMPLATE REGISTRY
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
TEMPLATES = {
"running": {
"name_de": "Laufen",
"name_en": "Running",
"icon": "🏃",
"categories": ["cardio", "running"],
"template": TEMPLATE_RUNNING
},
"meditation": {
"name_de": "Meditation",
"name_en": "Meditation",
"icon": "🧘",
"categories": ["geist", "meditation"],
"template": TEMPLATE_MEDITATION
},
"strength": {
"name_de": "Krafttraining",
"name_en": "Strength Training",
"icon": "💪",
"categories": ["kraft", "krafttraining"],
"template": TEMPLATE_STRENGTH
}
}
def get_template(template_key: str) -> dict:
"""Get profile template by key."""
template_info = TEMPLATES.get(template_key)
if not template_info:
return None
return template_info["template"]
def list_templates() -> list:
"""List all available templates."""
return [
{
"key": key,
"name_de": info["name_de"],
"name_en": info["name_en"],
"icon": info["icon"],
"categories": info["categories"]
}
for key, info in TEMPLATES.items()
]
+526
View File
@@ -0,0 +1,526 @@
"""
Unified Prompt Executor (Issue #28 Phase 2)
Executes both base and pipeline-type prompts with:
- Dynamic placeholder resolution
- JSON output validation
- Multi-stage parallel execution
- Reference and inline prompt support
"""
import json
import re
from typing import Dict, Any, Optional
from db import get_db, get_cursor, r2d
from fastapi import HTTPException
def resolve_placeholders(template: str, variables: Dict[str, Any], debug_info: Optional[Dict] = None, catalog: Optional[Dict] = None) -> str:
"""
Replace {{placeholder}} with values from variables dict.
Supports modifiers:
- {{key|d}} - Include description in parentheses (requires catalog)
Args:
template: String with {{key}} or {{key|modifiers}} placeholders
variables: Dict of key -> value mappings
debug_info: Optional dict to collect debug information
catalog: Optional placeholder catalog for descriptions (from get_placeholder_catalog)
Returns:
Template with placeholders replaced
"""
resolved = {}
unresolved = []
def replacer(match):
full_placeholder = match.group(1).strip()
# Parse key and modifiers (e.g., "weight_aktuell|d" -> key="weight_aktuell", modifiers="d")
parts = full_placeholder.split('|')
key = parts[0].strip()
modifiers = parts[1].strip() if len(parts) > 1 else ''
if key in variables:
value = variables[key]
# Convert dict/list to JSON string
if isinstance(value, (dict, list)):
resolved_value = json.dumps(value, ensure_ascii=False)
else:
resolved_value = str(value)
# Apply modifiers
if 'd' in modifiers:
if catalog:
# Add description from catalog
description = None
for cat_items in catalog.values():
matching = [item for item in cat_items if item['key'] == key]
if matching:
description = matching[0].get('description', '')
break
if description:
resolved_value = f"{resolved_value} ({description})"
else:
# Catalog not available - log warning in debug
if debug_info is not None:
if 'warnings' not in debug_info:
debug_info['warnings'] = []
debug_info['warnings'].append(f"Modifier |d used but catalog not available for {key}")
# Track resolution for debug
if debug_info is not None:
resolved[key] = resolved_value[:100] + ('...' if len(resolved_value) > 100 else '')
return resolved_value
else:
# Keep placeholder if no value found
if debug_info is not None:
unresolved.append(key)
return match.group(0)
result = re.sub(r'\{\{([^}]+)\}\}', replacer, template)
# Store debug info
if debug_info is not None:
debug_info['resolved_placeholders'] = resolved
debug_info['unresolved_placeholders'] = unresolved
return result
def validate_json_output(output: str, schema: Optional[Dict] = None, debug_info: Optional[Dict] = None) -> Dict:
"""
Validate that output is valid JSON.
Unwraps Markdown-wrapped JSON (```json ... ```) if present.
Args:
output: String to validate
schema: Optional JSON schema to validate against (TODO: jsonschema library)
debug_info: Optional dict to attach to error for debugging
Returns:
Parsed JSON dict
Raises:
HTTPException: If output is not valid JSON (with debug info attached)
"""
# Try to unwrap Markdown code blocks (common AI pattern)
unwrapped = output.strip()
if unwrapped.startswith('```json'):
# Extract content between ```json and ```
lines = unwrapped.split('\n')
if len(lines) > 2 and lines[-1].strip() == '```':
unwrapped = '\n'.join(lines[1:-1])
elif unwrapped.startswith('```'):
# Generic code block
lines = unwrapped.split('\n')
if len(lines) > 2 and lines[-1].strip() == '```':
unwrapped = '\n'.join(lines[1:-1])
try:
parsed = json.loads(unwrapped)
# TODO: Add jsonschema validation if schema provided
return parsed
except json.JSONDecodeError as e:
error_detail = {
"error": f"AI returned invalid JSON: {str(e)}",
"raw_output": output[:500] + ('...' if len(output) > 500 else ''),
"unwrapped": unwrapped[:500] if unwrapped != output else None,
"output_length": len(output)
}
if debug_info:
error_detail["debug"] = debug_info
raise HTTPException(
status_code=500,
detail=error_detail
)
async def execute_prompt(
prompt_slug: str,
variables: Dict[str, Any],
openrouter_call_func,
enable_debug: bool = False
) -> Dict[str, Any]:
"""
Execute a single prompt (base or pipeline type).
Args:
prompt_slug: Slug of prompt to execute
variables: Dict of variables for placeholder replacement
openrouter_call_func: Async function(prompt_text) -> response_text
enable_debug: If True, include debug information in response
Returns:
Dict with execution results:
{
"type": "base" | "pipeline",
"slug": "...",
"output": "..." | {...}, # String or parsed JSON
"stages": [...] # Only for pipeline type
"debug": {...} # Only if enable_debug=True
}
"""
# Load prompt from database
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""SELECT * FROM ai_prompts
WHERE slug = %s AND active = true""",
(prompt_slug,)
)
row = cur.fetchone()
if not row:
raise HTTPException(404, f"Prompt nicht gefunden: {prompt_slug}")
prompt = r2d(row)
prompt_type = prompt.get('type', 'pipeline')
# Get catalog from variables if available (passed from execute_prompt_with_data)
catalog = variables.pop('_catalog', None) if '_catalog' in variables else None
if prompt_type == 'base':
# Base prompt: single execution with template
return await execute_base_prompt(prompt, variables, openrouter_call_func, enable_debug, catalog)
elif prompt_type == 'pipeline':
# Pipeline prompt: multi-stage execution
return await execute_pipeline_prompt(prompt, variables, openrouter_call_func, enable_debug, catalog)
else:
raise HTTPException(400, f"Unknown prompt type: {prompt_type}")
async def execute_base_prompt(
prompt: Dict,
variables: Dict[str, Any],
openrouter_call_func,
enable_debug: bool = False,
catalog: Optional[Dict] = None
) -> Dict[str, Any]:
"""Execute a base-type prompt (single template)."""
template = prompt.get('template')
if not template:
raise HTTPException(400, f"Base prompt missing template: {prompt['slug']}")
debug_info = {} if enable_debug else None
# Resolve placeholders (with optional catalog for |d modifier)
prompt_text = resolve_placeholders(template, variables, debug_info, catalog)
if enable_debug:
debug_info['template'] = template
debug_info['final_prompt'] = prompt_text[:500] + ('...' if len(prompt_text) > 500 else '')
debug_info['available_variables'] = list(variables.keys())
# Call AI
response = await openrouter_call_func(prompt_text)
if enable_debug:
debug_info['ai_response_length'] = len(response)
debug_info['ai_response_preview'] = response[:200] + ('...' if len(response) > 200 else '')
# Validate JSON if required
output_format = prompt.get('output_format', 'text')
if output_format == 'json':
output = validate_json_output(response, prompt.get('output_schema'), debug_info if enable_debug else None)
else:
output = response
result = {
"type": "base",
"slug": prompt['slug'],
"output": output,
"output_format": output_format
}
if enable_debug:
result['debug'] = debug_info
return result
async def execute_pipeline_prompt(
prompt: Dict,
variables: Dict[str, Any],
openrouter_call_func,
enable_debug: bool = False,
catalog: Optional[Dict] = None
) -> Dict[str, Any]:
"""
Execute a pipeline-type prompt (multi-stage).
Each stage's results are added to variables for next stage.
"""
stages = prompt.get('stages')
if not stages:
raise HTTPException(400, f"Pipeline prompt missing stages: {prompt['slug']}")
# Parse stages if stored as JSON string
if isinstance(stages, str):
stages = json.loads(stages)
stage_results = []
context_vars = variables.copy()
pipeline_debug = [] if enable_debug else None
# Execute stages in order
for stage_def in sorted(stages, key=lambda s: s['stage']):
stage_num = stage_def['stage']
stage_prompts = stage_def.get('prompts', [])
if not stage_prompts:
continue
stage_debug = {} if enable_debug else None
if enable_debug:
stage_debug['stage'] = stage_num
stage_debug['available_variables'] = list(context_vars.keys())
stage_debug['prompts'] = []
# Execute all prompts in this stage (parallel concept, sequential impl for now)
stage_outputs = {}
for prompt_def in stage_prompts:
source = prompt_def.get('source')
output_key = prompt_def.get('output_key', f'stage{stage_num}')
output_format = prompt_def.get('output_format', 'text')
prompt_debug = {} if enable_debug else None
if source == 'reference':
# Reference to another prompt
ref_slug = prompt_def.get('slug')
if not ref_slug:
raise HTTPException(400, f"Reference prompt missing slug in stage {stage_num}")
if enable_debug:
prompt_debug['source'] = 'reference'
prompt_debug['ref_slug'] = ref_slug
# Load referenced prompt
result = await execute_prompt(ref_slug, context_vars, openrouter_call_func, enable_debug)
output = result['output']
if enable_debug and 'debug' in result:
prompt_debug['ref_debug'] = result['debug']
elif source == 'inline':
# Inline template
template = prompt_def.get('template')
if not template:
raise HTTPException(400, f"Inline prompt missing template in stage {stage_num}")
placeholder_debug = {} if enable_debug else None
prompt_text = resolve_placeholders(template, context_vars, placeholder_debug, catalog)
if enable_debug:
prompt_debug['source'] = 'inline'
prompt_debug['template'] = template
prompt_debug['final_prompt'] = prompt_text[:500] + ('...' if len(prompt_text) > 500 else '')
prompt_debug.update(placeholder_debug)
response = await openrouter_call_func(prompt_text)
if enable_debug:
prompt_debug['ai_response_length'] = len(response)
prompt_debug['ai_response_preview'] = response[:200] + ('...' if len(response) > 200 else '')
# Validate JSON if required
if output_format == 'json':
output = validate_json_output(response, prompt_def.get('output_schema'), prompt_debug if enable_debug else None)
else:
output = response
else:
raise HTTPException(400, f"Unknown prompt source: {source}")
# Store output with key
stage_outputs[output_key] = output
# Add to context for next stage
context_var_key = f'stage_{stage_num}_{output_key}'
context_vars[context_var_key] = output
if enable_debug:
prompt_debug['output_key'] = output_key
prompt_debug['context_var_key'] = context_var_key
stage_debug['prompts'].append(prompt_debug)
stage_results.append({
"stage": stage_num,
"outputs": stage_outputs
})
if enable_debug:
stage_debug['output'] = stage_outputs # Add outputs to debug info for value table
pipeline_debug.append(stage_debug)
# Final output is last stage's first output
final_output = stage_results[-1]['outputs'] if stage_results else {}
result = {
"type": "pipeline",
"slug": prompt['slug'],
"stages": stage_results,
"output": final_output,
"output_format": prompt.get('output_format', 'text')
}
if enable_debug:
result['debug'] = {
'initial_variables': list(variables.keys()),
'stages': pipeline_debug
}
return result
async def execute_prompt_with_data(
prompt_slug: str,
profile_id: str,
modules: Optional[Dict[str, bool]] = None,
timeframes: Optional[Dict[str, int]] = None,
openrouter_call_func = None,
enable_debug: bool = False
) -> Dict[str, Any]:
"""
Execute prompt with data loaded from database.
Args:
prompt_slug: Slug of prompt to execute
profile_id: User profile ID
modules: Dict of module -> enabled (e.g., {"körper": true})
timeframes: Dict of module -> days (e.g., {"körper": 30})
openrouter_call_func: Async function for AI calls
enable_debug: If True, include debug information in response
Returns:
Execution result dict
"""
from datetime import datetime, timedelta
from placeholder_resolver import get_placeholder_example_values, get_placeholder_catalog
# Build variables from data modules
variables = {
'profile_id': profile_id,
'today': datetime.now().strftime('%Y-%m-%d')
}
# Load placeholder catalog for |d modifier support
try:
catalog = get_placeholder_catalog(profile_id)
except Exception as e:
catalog = None
print(f"Warning: Could not load placeholder catalog: {e}")
variables['_catalog'] = catalog # Will be popped in execute_prompt (can be None)
# Add PROCESSED placeholders (name, weight_trend, caliper_summary, etc.)
# This makes old-style prompts work with the new executor
try:
processed_placeholders = get_placeholder_example_values(profile_id)
# Remove {{ }} from keys (placeholder_resolver returns them with wrappers)
cleaned_placeholders = {
key.replace('{{', '').replace('}}', ''): value
for key, value in processed_placeholders.items()
}
variables.update(cleaned_placeholders)
except Exception as e:
# Continue even if placeholder resolution fails
if enable_debug:
variables['_placeholder_error'] = str(e)
# Load data for enabled modules
if modules:
with get_db() as conn:
cur = get_cursor(conn)
# Weight data
if modules.get('körper'):
days = timeframes.get('körper', 30)
since = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT date, weight FROM weight_log
WHERE profile_id = %s AND date >= %s
ORDER BY date DESC""",
(profile_id, since)
)
variables['weight_data'] = [r2d(r) for r in cur.fetchall()]
# Nutrition data
if modules.get('ernährung'):
days = timeframes.get('ernährung', 30)
since = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT date, kcal, protein_g, fat_g, carbs_g
FROM nutrition_log
WHERE profile_id = %s AND date >= %s
ORDER BY date DESC""",
(profile_id, since)
)
variables['nutrition_data'] = [r2d(r) for r in cur.fetchall()]
# Activity data
if modules.get('training'):
days = timeframes.get('training', 14)
since = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT date, activity_type, duration_min, kcal_active, hr_avg
FROM activity_log
WHERE profile_id = %s AND date >= %s
ORDER BY date DESC""",
(profile_id, since)
)
variables['activity_data'] = [r2d(r) for r in cur.fetchall()]
# Sleep data
if modules.get('schlaf'):
days = timeframes.get('schlaf', 14)
since = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
cur.execute(
"""SELECT date, sleep_segments, source
FROM sleep_log
WHERE profile_id = %s AND date >= %s
ORDER BY date DESC""",
(profile_id, since)
)
variables['sleep_data'] = [r2d(r) for r in cur.fetchall()]
# Vitals data
if modules.get('vitalwerte'):
days = timeframes.get('vitalwerte', 7)
since = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
# Baseline vitals
cur.execute(
"""SELECT date, resting_hr, hrv, vo2_max, spo2, respiratory_rate
FROM vitals_baseline
WHERE profile_id = %s AND date >= %s
ORDER BY date DESC""",
(profile_id, since)
)
variables['vitals_baseline'] = [r2d(r) for r in cur.fetchall()]
# Blood pressure
cur.execute(
"""SELECT measured_at, systolic, diastolic, pulse
FROM blood_pressure_log
WHERE profile_id = %s AND measured_at >= %s
ORDER BY measured_at DESC""",
(profile_id, since + ' 00:00:00')
)
variables['blood_pressure'] = [r2d(r) for r in cur.fetchall()]
# Mental/Goals (no timeframe, just current state)
if modules.get('mentales') or modules.get('ziele'):
# TODO: Add mental state / goals data when implemented
variables['goals_data'] = []
# Execute prompt
return await execute_prompt(prompt_slug, variables, openrouter_call_func, enable_debug)
+125
View File
@@ -0,0 +1,125 @@
"""
Quality Filter Helper - Data Access Layer
Provides consistent quality filtering across all activity queries.
Issue: #31
"""
from typing import Optional, Dict
def get_quality_filter_sql(profile: Dict, table_alias: str = "") -> str:
"""
Returns SQL WHERE clause fragment for quality filtering.
Args:
profile: User profile dict with quality_filter_level
table_alias: Optional table alias (e.g., "a." for "a.quality_label")
Returns:
SQL fragment (e.g., "AND quality_label IN (...)") or empty string
Examples:
>>> get_quality_filter_sql({'quality_filter_level': 'all'})
''
>>> get_quality_filter_sql({'quality_filter_level': 'quality'})
"AND quality_label IN ('excellent', 'good', 'acceptable')"
>>> get_quality_filter_sql({'quality_filter_level': 'excellent'}, 'a.')
"AND a.quality_label = 'excellent'"
"""
level = profile.get('quality_filter_level', 'all')
prefix = table_alias if table_alias else ""
if level == 'all':
return '' # No filter
elif level == 'quality':
return f"AND {prefix}quality_label IN ('excellent', 'good', 'acceptable')"
elif level == 'very_good':
return f"AND {prefix}quality_label IN ('excellent', 'good')"
elif level == 'excellent':
return f"AND {prefix}quality_label = 'excellent'"
else:
# Unknown level → no filter (safe fallback)
return ''
def get_quality_filter_tuple(profile: Dict) -> tuple:
"""
Returns tuple of allowed quality labels for Python filtering.
Args:
profile: User profile dict with quality_filter_level
Returns:
Tuple of allowed quality labels or None (no filter)
Examples:
>>> get_quality_filter_tuple({'quality_filter_level': 'all'})
None
>>> get_quality_filter_tuple({'quality_filter_level': 'quality'})
('excellent', 'good', 'acceptable')
"""
level = profile.get('quality_filter_level', 'all')
if level == 'all':
return None # No filter
elif level == 'quality':
return ('excellent', 'good', 'acceptable')
elif level == 'very_good':
return ('excellent', 'good')
elif level == 'excellent':
return ('excellent',)
else:
return None # Unknown level → no filter
def filter_activities_by_quality(activities: list, profile: Dict) -> list:
"""
Filters a list of activity dicts by quality_label.
Useful for post-query filtering (e.g., when data already loaded).
Args:
activities: List of activity dicts with quality_label field
profile: User profile dict with quality_filter_level
Returns:
Filtered list of activities
"""
allowed_labels = get_quality_filter_tuple(profile)
if allowed_labels is None:
return activities # No filter
return [
act for act in activities
if act.get('quality_label') in allowed_labels
]
# Constants for frontend/documentation
QUALITY_LEVELS = {
'all': {
'label': 'Alle',
'icon': '📊',
'description': 'Alle Activities (kein Filter)',
'includes': None
},
'quality': {
'label': 'Hochwertig',
'icon': '✓',
'description': 'Hochwertige Activities',
'includes': ['excellent', 'good', 'acceptable']
},
'very_good': {
'label': 'Sehr gut',
'icon': '✓✓',
'description': 'Sehr gute Activities',
'includes': ['excellent', 'good']
},
'excellent': {
'label': 'Exzellent',
'icon': '⭐',
'description': 'Nur exzellente Activities',
'includes': ['excellent']
}
}
+1
View File
@@ -8,3 +8,4 @@ pydantic==2.7.1
bcrypt==4.1.3
slowapi==0.1.9
psycopg2-binary==2.9.9
python-dateutil==2.9.0
+145 -4
View File
@@ -16,6 +16,16 @@ from auth import require_auth, check_feature_access, increment_feature_usage
from models import ActivityEntry
from routers.profiles import get_pid
from feature_logger import log_feature_usage
from quality_filter import get_quality_filter_sql
# Evaluation import with error handling (Phase 1.2)
try:
from evaluation_helper import evaluate_and_save_activity
EVALUATION_AVAILABLE = True
except Exception as e:
logger.warning(f"[AUTO-EVAL] Evaluation system not available: {e}")
EVALUATION_AVAILABLE = False
evaluate_and_save_activity = None
router = APIRouter(prefix="/api/activity", tags=["activity"])
logger = logging.getLogger(__name__)
@@ -27,8 +37,19 @@ def list_activity(limit: int=200, x_profile_id: Optional[str]=Header(default=Non
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT * FROM activity_log WHERE profile_id=%s ORDER BY date DESC, start_time DESC LIMIT %s", (pid,limit))
# Issue #31: Apply global quality filter
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
profile = r2d(cur.fetchone())
quality_filter = get_quality_filter_sql(profile)
cur.execute(f"""
SELECT * FROM activity_log
WHERE profile_id=%s
{quality_filter}
ORDER BY date DESC, start_time DESC
LIMIT %s
""", (pid, limit))
return [r2d(r) for r in cur.fetchall()]
@@ -64,6 +85,27 @@ def create_activity(e: ActivityEntry, x_profile_id: Optional[str]=Header(default
d['kcal_active'],d['kcal_resting'],d['hr_avg'],d['hr_max'],d['distance_km'],
d['rpe'],d['source'],d['notes']))
# Phase 1.2: Auto-evaluation after INSERT
if EVALUATION_AVAILABLE:
# Load the activity data to evaluate
cur.execute("""
SELECT id, profile_id, date, training_type_id, duration_min,
hr_avg, hr_max, distance_km, kcal_active, kcal_resting,
rpe, pace_min_per_km, cadence, elevation_gain
FROM activity_log
WHERE id = %s
""", (eid,))
activity_row = cur.fetchone()
if activity_row:
activity_dict = dict(activity_row)
training_type_id = activity_dict.get("training_type_id")
if training_type_id:
try:
evaluate_and_save_activity(cur, eid, activity_dict, training_type_id, pid)
logger.info(f"[AUTO-EVAL] Evaluated activity {eid} on INSERT")
except Exception as eval_error:
logger.error(f"[AUTO-EVAL] Failed to evaluate activity {eid}: {eval_error}")
# Phase 2: Increment usage counter (always for new entries)
increment_feature_usage(pid, 'activity_entries')
@@ -79,6 +121,28 @@ def update_activity(eid: str, e: ActivityEntry, x_profile_id: Optional[str]=Head
cur = get_cursor(conn)
cur.execute(f"UPDATE activity_log SET {', '.join(f'{k}=%s' for k in d)} WHERE id=%s AND profile_id=%s",
list(d.values())+[eid,pid])
# Phase 1.2: Auto-evaluation after UPDATE
if EVALUATION_AVAILABLE:
# Load the updated activity data to evaluate
cur.execute("""
SELECT id, profile_id, date, training_type_id, duration_min,
hr_avg, hr_max, distance_km, kcal_active, kcal_resting,
rpe, pace_min_per_km, cadence, elevation_gain
FROM activity_log
WHERE id = %s
""", (eid,))
activity_row = cur.fetchone()
if activity_row:
activity_dict = dict(activity_row)
training_type_id = activity_dict.get("training_type_id")
if training_type_id:
try:
evaluate_and_save_activity(cur, eid, activity_dict, training_type_id, pid)
logger.info(f"[AUTO-EVAL] Re-evaluated activity {eid} on UPDATE")
except Exception as eval_error:
logger.error(f"[AUTO-EVAL] Failed to re-evaluate activity {eid}: {eval_error}")
return {"id":eid}
@@ -214,6 +278,31 @@ def bulk_categorize_activities(
""", (training_type_id, training_category, training_subcategory, pid, activity_type))
updated_count = cur.rowcount
# Phase 1.2: Auto-evaluation after bulk categorization
if EVALUATION_AVAILABLE:
# Load all activities that were just updated and evaluate them
cur.execute("""
SELECT id, profile_id, date, training_type_id, duration_min,
hr_avg, hr_max, distance_km, kcal_active, kcal_resting,
rpe, pace_min_per_km, cadence, elevation_gain
FROM activity_log
WHERE profile_id = %s
AND activity_type = %s
AND training_type_id = %s
""", (pid, activity_type, training_type_id))
activities_to_evaluate = cur.fetchall()
evaluated_count = 0
for activity_row in activities_to_evaluate:
activity_dict = dict(activity_row)
try:
evaluate_and_save_activity(cur, activity_dict["id"], activity_dict, training_type_id, pid)
evaluated_count += 1
except Exception as eval_error:
logger.warning(f"[AUTO-EVAL] Failed to evaluate bulk-categorized activity {activity_dict['id']}: {eval_error}")
logger.info(f"[AUTO-EVAL] Evaluated {evaluated_count}/{updated_count} bulk-categorized activities")
# Save mapping for future imports (upsert)
cur.execute("""
INSERT INTO activity_type_mappings (activity_type, training_type_id, profile_id, source, updated_at)
@@ -275,6 +364,7 @@ async def import_activity_csv(file: UploadFile=File(...), x_profile_id: Optional
if existing:
# Update existing entry (e.g., to add training type mapping)
existing_id = existing['id']
cur.execute("""
UPDATE activity_log
SET end_time = %s,
@@ -297,22 +387,73 @@ async def import_activity_csv(file: UploadFile=File(...), x_profile_id: Optional
tf(row.get('Max. Herzfrequenz (count/min)','')),
tf(row.get('Distanz (km)','')),
training_type_id, training_category, training_subcategory,
existing['id']
existing_id
))
skipped += 1 # Count as skipped (not newly inserted)
# Phase 1.2: Auto-evaluation after CSV import UPDATE
if EVALUATION_AVAILABLE and training_type_id:
try:
# Build activity dict for evaluation
activity_dict = {
"id": existing_id,
"profile_id": pid,
"date": date,
"training_type_id": training_type_id,
"duration_min": duration_min,
"hr_avg": tf(row.get('Durchschn. Herzfrequenz (count/min)','')),
"hr_max": tf(row.get('Max. Herzfrequenz (count/min)','')),
"distance_km": tf(row.get('Distanz (km)','')),
"kcal_active": kj(row.get('Aktive Energie (kJ)','')),
"kcal_resting": kj(row.get('Ruheeinträge (kJ)','')),
"rpe": None,
"pace_min_per_km": None,
"cadence": None,
"elevation_gain": None
}
evaluate_and_save_activity(cur, existing_id, activity_dict, training_type_id, pid)
logger.debug(f"[AUTO-EVAL] Re-evaluated updated activity {existing_id}")
except Exception as eval_error:
logger.warning(f"[AUTO-EVAL] Failed to re-evaluate updated activity {existing_id}: {eval_error}")
else:
# Insert new entry
new_id = str(uuid.uuid4())
cur.execute("""INSERT INTO activity_log
(id,profile_id,date,start_time,end_time,activity_type,duration_min,kcal_active,kcal_resting,
hr_avg,hr_max,distance_km,source,training_type_id,training_category,training_subcategory,created)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,'apple_health',%s,%s,%s,CURRENT_TIMESTAMP)""",
(str(uuid.uuid4()),pid,date,start,row.get('End',''),wtype,duration_min,
(new_id,pid,date,start,row.get('End',''),wtype,duration_min,
kj(row.get('Aktive Energie (kJ)','')),kj(row.get('Ruheeinträge (kJ)','')),
tf(row.get('Durchschn. Herzfrequenz (count/min)','')),
tf(row.get('Max. Herzfrequenz (count/min)','')),
tf(row.get('Distanz (km)','')),
training_type_id,training_category,training_subcategory))
inserted+=1
# Phase 1.2: Auto-evaluation after CSV import INSERT
if EVALUATION_AVAILABLE and training_type_id:
try:
# Build activity dict for evaluation
activity_dict = {
"id": new_id,
"profile_id": pid,
"date": date,
"training_type_id": training_type_id,
"duration_min": duration_min,
"hr_avg": tf(row.get('Durchschn. Herzfrequenz (count/min)','')),
"hr_max": tf(row.get('Max. Herzfrequenz (count/min)','')),
"distance_km": tf(row.get('Distanz (km)','')),
"kcal_active": kj(row.get('Aktive Energie (kJ)','')),
"kcal_resting": kj(row.get('Ruheeinträge (kJ)','')),
"rpe": None,
"pace_min_per_km": None,
"cadence": None,
"elevation_gain": None
}
evaluate_and_save_activity(cur, new_id, activity_dict, training_type_id, pid)
logger.debug(f"[AUTO-EVAL] Evaluated imported activity {new_id}")
except Exception as eval_error:
logger.warning(f"[AUTO-EVAL] Failed to evaluate imported activity {new_id}: {eval_error}")
except Exception as e:
logger.warning(f"Import row failed: {e}")
skipped+=1
+135 -7
View File
@@ -7,9 +7,11 @@ import logging
from typing import Optional
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
from psycopg2.extras import Json
from db import get_db, get_cursor, r2d
from auth import require_auth, require_admin
from profile_templates import list_templates, get_template
router = APIRouter(prefix="/api/admin/training-types", tags=["admin", "training-types"])
logger = logging.getLogger(__name__)
@@ -25,6 +27,7 @@ class TrainingTypeCreate(BaseModel):
description_en: Optional[str] = None
sort_order: int = 0
abilities: Optional[dict] = None
profile: Optional[dict] = None # Training Type Profile (Phase 2 #15)
class TrainingTypeUpdate(BaseModel):
@@ -37,6 +40,7 @@ class TrainingTypeUpdate(BaseModel):
description_en: Optional[str] = None
sort_order: Optional[int] = None
abilities: Optional[dict] = None
profile: Optional[dict] = None # Training Type Profile (Phase 2 #15)
@router.get("")
@@ -50,7 +54,7 @@ def list_training_types_admin(session: dict = Depends(require_admin)):
cur.execute("""
SELECT id, category, subcategory, name_de, name_en, icon,
description_de, description_en, sort_order, abilities,
created_at
profile, created_at
FROM training_types
ORDER BY sort_order, category, subcategory
""")
@@ -67,7 +71,7 @@ def get_training_type(type_id: int, session: dict = Depends(require_admin)):
cur.execute("""
SELECT id, category, subcategory, name_de, name_en, icon,
description_de, description_en, sort_order, abilities,
created_at
profile, created_at
FROM training_types
WHERE id = %s
""", (type_id,))
@@ -85,14 +89,15 @@ def create_training_type(data: TrainingTypeCreate, session: dict = Depends(requi
with get_db() as conn:
cur = get_cursor(conn)
# Convert abilities dict to JSONB
# Convert abilities and profile dict to JSONB
abilities_json = data.abilities if data.abilities else {}
profile_json = data.profile if data.profile else None
cur.execute("""
INSERT INTO training_types
(category, subcategory, name_de, name_en, icon,
description_de, description_en, sort_order, abilities)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
description_de, description_en, sort_order, abilities, profile)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""", (
data.category,
@@ -103,7 +108,8 @@ def create_training_type(data: TrainingTypeCreate, session: dict = Depends(requi
data.description_de,
data.description_en,
data.sort_order,
abilities_json
Json(abilities_json),
Json(profile_json) if profile_json else None
))
new_id = cur.fetchone()['id']
@@ -153,7 +159,10 @@ def update_training_type(
values.append(data.sort_order)
if data.abilities is not None:
updates.append("abilities = %s")
values.append(data.abilities)
values.append(Json(data.abilities))
if data.profile is not None:
updates.append("profile = %s")
values.append(Json(data.profile))
if not updates:
raise HTTPException(400, "No fields to update")
@@ -279,3 +288,122 @@ def get_abilities_taxonomy(session: dict = Depends(require_auth)):
}
return taxonomy
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# TRAINING TYPE PROFILES - Phase 2 (#15)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
@router.get("/profiles/templates")
def list_profile_templates(session: dict = Depends(require_admin)):
"""
List all available profile templates.
Returns templates for common training types (Running, Meditation, Strength, etc.)
"""
return list_templates()
@router.get("/profiles/templates/{template_key}")
def get_profile_template(template_key: str, session: dict = Depends(require_admin)):
"""
Get a specific profile template by key.
Keys: running, meditation, strength
"""
template = get_template(template_key)
if not template:
raise HTTPException(404, f"Template '{template_key}' not found")
return template
@router.post("/{type_id}/profile/apply-template")
def apply_profile_template(
type_id: int,
data: dict,
session: dict = Depends(require_admin)
):
"""
Apply a profile template to a training type.
Body: { "template_key": "running" }
"""
template_key = data.get("template_key")
if not template_key:
raise HTTPException(400, "template_key required")
template = get_template(template_key)
if not template:
raise HTTPException(404, f"Template '{template_key}' not found")
# Apply template to training type
with get_db() as conn:
cur = get_cursor(conn)
# Check if training type exists
cur.execute("SELECT id, name_de FROM training_types WHERE id = %s", (type_id,))
training_type = cur.fetchone()
if not training_type:
raise HTTPException(404, "Training type not found")
# Update profile
cur.execute("""
UPDATE training_types
SET profile = %s
WHERE id = %s
""", (Json(template), type_id))
logger.info(f"[ADMIN] Applied template '{template_key}' to training type {type_id} ({training_type['name_de']})")
return {
"message": f"Template '{template_key}' applied successfully",
"training_type_id": type_id,
"training_type_name": training_type['name_de'],
"template_key": template_key
}
@router.get("/profiles/stats")
def get_profile_stats(session: dict = Depends(require_admin)):
"""
Get statistics about configured profiles.
Returns count of training types with/without profiles.
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT
COUNT(*) as total,
COUNT(profile) as configured,
COUNT(*) - COUNT(profile) as unconfigured
FROM training_types
""")
stats = cur.fetchone()
# Get list of types with profiles
cur.execute("""
SELECT id, name_de, category, subcategory
FROM training_types
WHERE profile IS NOT NULL
ORDER BY name_de
""")
configured_types = [r2d(r) for r in cur.fetchall()]
# Get list of types without profiles
cur.execute("""
SELECT id, name_de, category, subcategory
FROM training_types
WHERE profile IS NULL
ORDER BY name_de
""")
unconfigured_types = [r2d(r) for r in cur.fetchall()]
return {
"total": stats['total'],
"configured": stats['configured'],
"unconfigured": stats['unconfigured'],
"configured_types": configured_types,
"unconfigured_types": unconfigured_types
}
+412
View File
@@ -0,0 +1,412 @@
"""
Blood Pressure Router - v9d Phase 2d Refactored
Context-dependent blood pressure measurements (multiple times per day):
- Systolic/Diastolic Blood Pressure
- Pulse during measurement
- Context tagging (morning_fasted, after_meal, before_training, etc.)
- Warning flags (irregular heartbeat, AFib)
Endpoints:
- GET /api/blood-pressure List BP measurements
- GET /api/blood-pressure/by-date/{date} Get measurements for specific date
- POST /api/blood-pressure Create BP measurement
- PUT /api/blood-pressure/{id} Update BP measurement
- DELETE /api/blood-pressure/{id} Delete BP measurement
- GET /api/blood-pressure/stats Statistics and trends
- POST /api/blood-pressure/import/omron Import Omron CSV
"""
from fastapi import APIRouter, HTTPException, Depends, Header, UploadFile, File
from pydantic import BaseModel
from typing import Optional
from datetime import datetime, timedelta
import logging
import csv
import io
from db import get_db, get_cursor, r2d
from auth import require_auth
from routers.profiles import get_pid
router = APIRouter(prefix="/api/blood-pressure", tags=["blood_pressure"])
logger = logging.getLogger(__name__)
# German month mapping for Omron dates
GERMAN_MONTHS = {
'Januar': '01', 'Jan.': '01', 'Jan': '01',
'Februar': '02', 'Feb.': '02', 'Feb': '02',
'März': '03', 'Mär.': '03', 'Mär': '03',
'April': '04', 'Apr.': '04', 'Apr': '04',
'Mai': '05',
'Juni': '06', 'Jun.': '06', 'Jun': '06',
'Juli': '07', 'Jul.': '07', 'Jul': '07',
'August': '08', 'Aug.': '08', 'Aug': '08',
'September': '09', 'Sep.': '09', 'Sep': '09',
'Oktober': '10', 'Okt.': '10', 'Okt': '10',
'November': '11', 'Nov.': '11', 'Nov': '11',
'Dezember': '12', 'Dez.': '12', 'Dez': '12',
}
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Pydantic Models
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
class BPEntry(BaseModel):
measured_at: str # ISO format datetime
systolic: int
diastolic: int
pulse: Optional[int] = None
context: Optional[str] = None # morning_fasted, after_meal, etc.
irregular_heartbeat: Optional[bool] = False
possible_afib: Optional[bool] = False
note: Optional[str] = None
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Helper Functions
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
def parse_omron_date(date_str: str, time_str: str) -> str:
"""
Parse Omron German date/time format to ISO datetime.
Input: "13 März 2026", "08:30"
Output: "2026-03-13 08:30:00"
"""
try:
parts = date_str.strip().split()
if len(parts) != 3:
return None
day = parts[0]
month_name = parts[1]
year = parts[2]
month = GERMAN_MONTHS.get(month_name)
if not month:
return None
iso_date = f"{year}-{month}-{day.zfill(2)}"
iso_datetime = f"{iso_date} {time_str}:00"
# Validate
datetime.fromisoformat(iso_datetime)
return iso_datetime
except Exception as e:
logger.error(f"Error parsing Omron date: {date_str} {time_str} - {e}")
return None
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# CRUD Endpoints
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
@router.get("")
def list_bp_measurements(
limit: int = 90,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Get blood pressure measurements (last N entries)."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT * FROM blood_pressure_log
WHERE profile_id = %s
ORDER BY measured_at DESC
LIMIT %s
""", (pid, limit))
return [r2d(r) for r in cur.fetchall()]
@router.get("/by-date/{date}")
def get_bp_by_date(
date: str,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Get all BP measurements for a specific date."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT * FROM blood_pressure_log
WHERE profile_id = %s
AND DATE(measured_at) = %s
ORDER BY measured_at ASC
""", (pid, date))
return [r2d(r) for r in cur.fetchall()]
@router.post("")
def create_bp_measurement(
entry: BPEntry,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Create new BP measurement."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
INSERT INTO blood_pressure_log (
profile_id, measured_at,
systolic, diastolic, pulse,
context, irregular_heartbeat, possible_afib,
note, source
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, 'manual')
RETURNING *
""", (
pid, entry.measured_at,
entry.systolic, entry.diastolic, entry.pulse,
entry.context, entry.irregular_heartbeat, entry.possible_afib,
entry.note
))
return r2d(cur.fetchone())
@router.put("/{entry_id}")
def update_bp_measurement(
entry_id: int,
entry: BPEntry,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Update existing BP measurement."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
UPDATE blood_pressure_log
SET measured_at = %s,
systolic = %s,
diastolic = %s,
pulse = %s,
context = %s,
irregular_heartbeat = %s,
possible_afib = %s,
note = %s
WHERE id = %s AND profile_id = %s
RETURNING *
""", (
entry.measured_at,
entry.systolic, entry.diastolic, entry.pulse,
entry.context, entry.irregular_heartbeat, entry.possible_afib,
entry.note,
entry_id, pid
))
row = cur.fetchone()
if not row:
raise HTTPException(404, "Entry not found")
return r2d(row)
@router.delete("/{entry_id}")
def delete_bp_measurement(
entry_id: int,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Delete BP measurement."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
DELETE FROM blood_pressure_log
WHERE id = %s AND profile_id = %s
""", (entry_id, pid))
if cur.rowcount == 0:
raise HTTPException(404, "Entry not found")
return {"ok": True}
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Statistics & Trends
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
@router.get("/stats")
def get_bp_stats(
days: int = 30,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Get blood pressure statistics and trends."""
pid = get_pid(x_profile_id)
cutoff_date = datetime.now() - timedelta(days=days)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT
COUNT(*) as total_measurements,
-- Overall averages
AVG(systolic) as avg_systolic,
AVG(diastolic) as avg_diastolic,
AVG(pulse) FILTER (WHERE pulse IS NOT NULL) as avg_pulse,
-- 7-day averages
AVG(systolic) FILTER (WHERE measured_at >= NOW() - INTERVAL '7 days') as avg_systolic_7d,
AVG(diastolic) FILTER (WHERE measured_at >= NOW() - INTERVAL '7 days') as avg_diastolic_7d,
-- Context-specific averages
AVG(systolic) FILTER (WHERE context = 'morning_fasted') as avg_systolic_morning,
AVG(diastolic) FILTER (WHERE context = 'morning_fasted') as avg_diastolic_morning,
AVG(systolic) FILTER (WHERE context = 'evening') as avg_systolic_evening,
AVG(diastolic) FILTER (WHERE context = 'evening') as avg_diastolic_evening,
-- Warning flags
COUNT(*) FILTER (WHERE irregular_heartbeat = true) as irregular_count,
COUNT(*) FILTER (WHERE possible_afib = true) as afib_count
FROM blood_pressure_log
WHERE profile_id = %s AND measured_at >= %s
""", (pid, cutoff_date))
stats = r2d(cur.fetchone())
# Classify BP ranges (WHO/ISH guidelines)
if stats['avg_systolic'] and stats['avg_diastolic']:
if stats['avg_systolic'] < 120 and stats['avg_diastolic'] < 80:
stats['bp_category'] = 'optimal'
elif stats['avg_systolic'] < 130 and stats['avg_diastolic'] < 85:
stats['bp_category'] = 'normal'
elif stats['avg_systolic'] < 140 and stats['avg_diastolic'] < 90:
stats['bp_category'] = 'high_normal'
elif stats['avg_systolic'] < 160 and stats['avg_diastolic'] < 100:
stats['bp_category'] = 'grade_1_hypertension'
elif stats['avg_systolic'] < 180 and stats['avg_diastolic'] < 110:
stats['bp_category'] = 'grade_2_hypertension'
else:
stats['bp_category'] = 'grade_3_hypertension'
else:
stats['bp_category'] = None
return stats
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Import: Omron CSV
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
@router.post("/import/omron")
async def import_omron_csv(
file: UploadFile = File(...),
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Import blood pressure measurements from Omron CSV export."""
pid = get_pid(x_profile_id)
content = await file.read()
decoded = content.decode('utf-8')
reader = csv.DictReader(io.StringIO(decoded))
inserted = 0
updated = 0
skipped = 0
errors = 0
with get_db() as conn:
cur = get_cursor(conn)
# Log available columns for debugging
first_row = True
for row in reader:
try:
if first_row:
logger.info(f"Omron CSV Columns: {list(row.keys())}")
first_row = False
# Parse Omron German date format
date_str = row.get('Datum', row.get('Date'))
time_str = row.get('Zeit', row.get('Time', '08:00'))
if not date_str:
skipped += 1
continue
measured_at = parse_omron_date(date_str, time_str)
if not measured_at:
errors += 1
continue
# Extract measurements (support column names with/without units)
systolic = (row.get('Systolisch (mmHg)') or row.get('Systolisch') or
row.get('Systolic (mmHg)') or row.get('Systolic'))
diastolic = (row.get('Diastolisch (mmHg)') or row.get('Diastolisch') or
row.get('Diastolic (mmHg)') or row.get('Diastolic'))
pulse = (row.get('Puls (bpm)') or row.get('Puls') or
row.get('Pulse (bpm)') or row.get('Pulse'))
if not systolic or not diastolic:
logger.warning(f"Skipped row {date_str} {time_str}: Missing BP values (sys={systolic}, dia={diastolic})")
skipped += 1
continue
# Parse warning flags (support various column names)
irregular = (row.get('Unregelmäßiger Herzschlag festgestellt') or
row.get('Unregelmäßiger Herzschlag') or
row.get('Irregular Heartbeat') or '')
afib = (row.get('Mögliches AFib') or
row.get('Vorhofflimmern') or
row.get('Possible AFib') or
row.get('AFib') or '')
irregular_heartbeat = irregular.lower() in ['ja', 'yes', 'true', '1']
possible_afib = afib.lower() in ['ja', 'yes', 'true', '1']
# Determine context based on time
hour = int(time_str.split(':')[0])
if 5 <= hour < 10:
context = 'morning_fasted'
elif 18 <= hour < 23:
context = 'evening'
else:
context = 'other'
# Upsert
cur.execute("""
INSERT INTO blood_pressure_log (
profile_id, measured_at,
systolic, diastolic, pulse,
context, irregular_heartbeat, possible_afib,
source
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'omron')
ON CONFLICT (profile_id, measured_at)
DO UPDATE SET
systolic = EXCLUDED.systolic,
diastolic = EXCLUDED.diastolic,
pulse = EXCLUDED.pulse,
context = EXCLUDED.context,
irregular_heartbeat = EXCLUDED.irregular_heartbeat,
possible_afib = EXCLUDED.possible_afib
WHERE blood_pressure_log.source != 'manual'
RETURNING (xmax = 0) AS inserted
""", (
pid, measured_at,
int(systolic), int(diastolic),
int(pulse) if pulse else None,
context, irregular_heartbeat, possible_afib
))
result = cur.fetchone()
if result is None:
# WHERE clause prevented update (manual entry exists)
skipped += 1
elif result['inserted']:
inserted += 1
else:
updated += 1
except Exception as e:
logger.error(f"Error importing Omron row: {e}")
errors += 1
return {
"inserted": inserted,
"updated": updated,
"skipped": skipped,
"errors": errors
}
+146
View File
@@ -0,0 +1,146 @@
"""
Evaluation Endpoints - Training Type Profiles
Endpoints for activity evaluation and re-evaluation.
Issue: #15
Date: 2026-03-23
"""
import logging
from typing import Optional
from fastapi import APIRouter, HTTPException, Depends
from db import get_db, get_cursor, r2d
from auth import require_auth, require_admin
from evaluation_helper import (
evaluate_and_save_activity,
batch_evaluate_activities,
load_parameters_registry
)
router = APIRouter(prefix="/api/evaluation", tags=["evaluation"])
logger = logging.getLogger(__name__)
@router.get("/parameters")
def list_parameters(session: dict = Depends(require_auth)):
"""
List all available training parameters.
"""
with get_db() as conn:
cur = get_cursor(conn)
parameters = load_parameters_registry(cur)
return {
"parameters": list(parameters.values()),
"count": len(parameters)
}
@router.post("/activity/{activity_id}")
def evaluate_activity(
activity_id: str,
session: dict = Depends(require_auth)
):
"""
Evaluates or re-evaluates a single activity.
Returns the evaluation result.
"""
profile_id = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
# Load activity
cur.execute("""
SELECT id, profile_id, date, training_type_id, duration_min,
hr_avg, hr_max, distance_km, kcal_active, kcal_resting,
rpe, pace_min_per_km, cadence, elevation_gain
FROM activity_log
WHERE id = %s AND profile_id = %s
""", (activity_id, profile_id))
activity = cur.fetchone()
if not activity:
raise HTTPException(404, "Activity not found")
activity_dict = dict(activity)
# Evaluate
result = evaluate_and_save_activity(
cur,
activity_dict["id"],
activity_dict,
activity_dict["training_type_id"],
profile_id
)
if not result:
return {
"message": "No profile configured for this training type",
"evaluation": None
}
return {
"message": "Activity evaluated",
"evaluation": result
}
@router.post("/batch")
def batch_evaluate(
limit: Optional[int] = None,
session: dict = Depends(require_auth)
):
"""
Re-evaluates all activities for the current user.
Optional limit parameter for testing.
"""
profile_id = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
stats = batch_evaluate_activities(cur, profile_id, limit)
return {
"message": "Batch evaluation completed",
"stats": stats
}
@router.post("/batch/all")
def batch_evaluate_all(session: dict = Depends(require_admin)):
"""
Admin-only: Re-evaluates all activities for all users.
Use with caution on large databases!
"""
with get_db() as conn:
cur = get_cursor(conn)
# Get all profiles
cur.execute("SELECT id FROM profiles")
profiles = cur.fetchall()
total_stats = {
"profiles": len(profiles),
"total": 0,
"evaluated": 0,
"skipped": 0,
"errors": 0
}
for profile in profiles:
profile_id = profile['id']
stats = batch_evaluate_activities(cur, profile_id)
total_stats["total"] += stats["total"]
total_stats["evaluated"] += stats["evaluated"]
total_stats["skipped"] += stats["skipped"]
total_stats["errors"] += stats["errors"]
return {
"message": "Batch evaluation for all users completed",
"stats": total_stats
}
File diff suppressed because it is too large. Load diff
+183 -26
View File
@@ -17,6 +17,7 @@ from db import get_db, get_cursor, r2d
from auth import require_auth, require_admin, check_feature_access, increment_feature_usage
from routers.profiles import get_pid
from feature_logger import log_feature_usage
from quality_filter import get_quality_filter_sql
router = APIRouter(prefix="/api", tags=["insights"])
logger = logging.getLogger(__name__)
@@ -67,6 +68,9 @@ def _get_profile_data(pid: str):
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
prof = r2d(cur.fetchone())
# Issue #31: Get global quality filter setting
quality_filter = get_quality_filter_sql(prof)
cur.execute("SELECT * FROM weight_log WHERE profile_id=%s ORDER BY date DESC LIMIT 90", (pid,))
weight = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM circumference_log WHERE profile_id=%s ORDER BY date DESC LIMIT 30", (pid,))
@@ -75,15 +79,36 @@ def _get_profile_data(pid: str):
caliper = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM nutrition_log WHERE profile_id=%s ORDER BY date DESC LIMIT 90", (pid,))
nutrition = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM activity_log WHERE profile_id=%s ORDER BY date DESC LIMIT 90", (pid,))
# Issue #31: Global quality filter (from user profile setting)
cur.execute(f"""
SELECT * FROM activity_log
WHERE profile_id=%s
{quality_filter}
ORDER BY date DESC LIMIT 90
""", (pid,))
activity = [r2d(r) for r in cur.fetchall()]
# v9d Phase 2: Sleep, Rest Days, Vitals
cur.execute("SELECT * FROM sleep_log WHERE profile_id=%s ORDER BY date DESC LIMIT 30", (pid,))
sleep = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM rest_days WHERE profile_id=%s ORDER BY date DESC LIMIT 30", (pid,))
rest_days = [r2d(r) for r in cur.fetchall()]
# v9d Phase 2d Refactored: separate baseline and BP tables
cur.execute("SELECT * FROM vitals_baseline WHERE profile_id=%s ORDER BY date DESC LIMIT 30", (pid,))
vitals_baseline = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM blood_pressure_log WHERE profile_id=%s ORDER BY measured_at DESC LIMIT 90", (pid,))
blood_pressure = [r2d(r) for r in cur.fetchall()]
return {
"profile": prof,
"weight": weight,
"circumference": circ,
"caliper": caliper,
"nutrition": nutrition,
"activity": activity
"activity": activity,
"sleep": sleep,
"rest_days": rest_days,
"vitals_baseline": vitals_baseline,
"blood_pressure": blood_pressure
}
@@ -103,6 +128,10 @@ def _prepare_template_vars(data: dict) -> dict:
caliper = data['caliper']
nutrition = data['nutrition']
activity = data['activity']
sleep = data.get('sleep', [])
rest_days = data.get('rest_days', [])
vitals_baseline = data.get('vitals_baseline', [])
blood_pressure = data.get('blood_pressure', [])
vars = {
"name": prof.get('name', 'Nutzer'),
@@ -192,6 +221,83 @@ def _prepare_template_vars(data: dict) -> dict:
vars['activity_detail'] = "keine Daten"
vars['activity_kcal_summary'] = "keine Daten"
# Sleep summary (v9d Phase 2b)
if sleep:
n = len(sleep)
avg_duration = sum(float(s.get('duration_minutes',0) or 0) for s in sleep) / n
avg_quality = sum(int(s.get('quality',0) or 0) for s in sleep if s.get('quality')) / max(sum(1 for s in sleep if s.get('quality')), 1)
deep_data = [s for s in sleep if s.get('deep_minutes')]
avg_deep = sum(float(s.get('deep_minutes',0)) for s in deep_data) / len(deep_data) if deep_data else 0
vars['sleep_summary'] = f"{n} Nächte, Ø {avg_duration/60:.1f}h Schlafdauer, Qualität {avg_quality:.1f}/5"
vars['sleep_detail'] = f"Ø {avg_duration:.0f}min gesamt, {avg_deep:.0f}min Tiefschlaf"
vars['sleep_avg_duration'] = round(avg_duration)
vars['sleep_avg_quality'] = round(avg_quality, 1)
vars['sleep_nights'] = n
else:
vars['sleep_summary'] = "keine Daten"
vars['sleep_detail'] = "keine Daten"
vars['sleep_avg_duration'] = 0
vars['sleep_avg_quality'] = 0
vars['sleep_nights'] = 0
# Rest Days summary (v9d Phase 2a)
if rest_days:
n = len(rest_days)
types = {}
for rd in rest_days:
rt = rd.get('rest_type', 'unknown')
types[rt] = types.get(rt, 0) + 1
type_summary = ", ".join([f"{k}: {v}x" for k, v in types.items()])
vars['rest_days_summary'] = f"{n} Ruhetage (letzte 30d): {type_summary}"
vars['rest_days_count'] = n
vars['rest_days_types'] = type_summary
else:
vars['rest_days_summary'] = "keine Daten"
vars['rest_days_count'] = 0
vars['rest_days_types'] = "keine"
# Vitals Baseline summary (v9d Phase 2d Refactored)
if vitals_baseline:
n = len(vitals_baseline)
hr_data = [v for v in vitals_baseline if v.get('resting_hr')]
hrv_data = [v for v in vitals_baseline if v.get('hrv')]
vo2_data = [v for v in vitals_baseline if v.get('vo2_max')]
avg_hr = sum(int(v.get('resting_hr')) for v in hr_data) / len(hr_data) if hr_data else 0
avg_hrv = sum(int(v.get('hrv')) for v in hrv_data) / len(hrv_data) if hrv_data else 0
latest_vo2 = float(vo2_data[0].get('vo2_max')) if vo2_data else 0
parts = []
if avg_hr: parts.append(f"Ruhepuls Ø {avg_hr:.0f}bpm")
if avg_hrv: parts.append(f"HRV Ø {avg_hrv:.0f}ms")
if latest_vo2: parts.append(f"VO2 Max {latest_vo2:.1f}")
vars['vitals_summary'] = f"{n} Messungen: " + ", ".join(parts) if parts else "keine verwertbaren Daten"
vars['vitals_detail'] = vars['vitals_summary']
vars['vitals_avg_hr'] = round(avg_hr)
vars['vitals_avg_hrv'] = round(avg_hrv)
vars['vitals_vo2_max'] = round(latest_vo2, 1) if latest_vo2 else "k.A."
else:
vars['vitals_summary'] = "keine Daten"
vars['vitals_detail'] = "keine Daten"
vars['vitals_avg_hr'] = 0
vars['vitals_avg_hrv'] = 0
vars['vitals_vo2_max'] = "k.A."
# Blood Pressure summary (v9d Phase 2d Refactored)
if blood_pressure:
n = len(blood_pressure)
bp_data = [bp for bp in blood_pressure if bp.get('systolic') and bp.get('diastolic')]
avg_bp_sys = sum(int(bp.get('systolic')) for bp in bp_data) / len(bp_data) if bp_data else 0
avg_bp_dia = sum(int(bp.get('diastolic')) for bp in bp_data) / len(bp_data) if bp_data else 0
vars['vitals_avg_bp'] = f"{round(avg_bp_sys)}/{round(avg_bp_dia)}" if avg_bp_sys else "k.A."
vars['bp_summary'] = f"{n} Messungen, Ø {avg_bp_sys:.0f}/{avg_bp_dia:.0f} mmHg" if avg_bp_sys else "keine Daten"
else:
vars['vitals_avg_bp'] = "k.A."
vars['bp_summary'] = "keine Daten"
return vars
@@ -327,8 +433,17 @@ async def analyze_with_prompt(slug: str, x_profile_id: Optional[str]=Header(defa
@router.post("/insights/pipeline")
async def analyze_pipeline(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Run 3-stage pipeline analysis."""
async def analyze_pipeline(
config_id: Optional[str] = None,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""
Run configurable multi-stage pipeline analysis.
Args:
config_id: Pipeline config ID (optional, uses default if not specified)
"""
pid = get_pid(x_profile_id)
# Phase 4: Check pipeline feature access (boolean - enabled/disabled)
@@ -360,14 +475,34 @@ async def analyze_pipeline(x_profile_id: Optional[str]=Header(default=None), ses
f"Bitte kontaktiere den Admin oder warte bis zum nächsten Reset."
)
# Load pipeline config
with get_db() as conn:
cur = get_cursor(conn)
if config_id:
cur.execute("SELECT * FROM pipeline_configs WHERE id=%s AND active=true", (config_id,))
else:
cur.execute("SELECT * FROM pipeline_configs WHERE is_default=true AND active=true")
config = r2d(cur.fetchone())
if not config:
raise HTTPException(404, "Pipeline-Konfiguration nicht gefunden")
logger.info(f"[PIPELINE] Using config '{config['name']}' (id={config['id']})")
data = _get_profile_data(pid)
vars = _prepare_template_vars(data)
# Stage 1: Parallel JSON analyses
# Stage 1: Load and execute prompts from config
stage1_prompts = []
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT slug, template FROM ai_prompts WHERE slug LIKE 'pipeline_%' AND slug NOT IN ('pipeline_synthesis','pipeline_goals') AND active=true")
stage1_prompts = [r2d(r) for r in cur.fetchall()]
for slug in config['stage1_prompts']:
cur.execute("SELECT slug, template FROM ai_prompts WHERE slug=%s AND active=true", (slug,))
prompt = r2d(cur.fetchone())
if prompt:
stage1_prompts.append(prompt)
else:
logger.warning(f"[PIPELINE] Stage 1 prompt '{slug}' not found or inactive")
stage1_results = {}
for p in stage1_prompts:
@@ -404,17 +539,20 @@ async def analyze_pipeline(x_profile_id: Optional[str]=Header(default=None), ses
except:
stage1_results[slug] = content
# Stage 2: Synthesis
vars['stage1_body'] = json.dumps(stage1_results.get('pipeline_body', {}), ensure_ascii=False)
vars['stage1_nutrition'] = json.dumps(stage1_results.get('pipeline_nutrition', {}), ensure_ascii=False)
vars['stage1_activity'] = json.dumps(stage1_results.get('pipeline_activity', {}), ensure_ascii=False)
# Stage 2: Synthesis with dynamic placeholders
# Inject all stage1 results as {{stage1_<slug>}} placeholders
for slug, result in stage1_results.items():
# Convert slug like "pipeline_body" to placeholder name "stage1_body"
placeholder_name = slug.replace('pipeline_', 'stage1_')
vars[placeholder_name] = json.dumps(result, ensure_ascii=False) if isinstance(result, dict) else str(result)
# Load stage 2 prompt from config
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT template FROM ai_prompts WHERE slug='pipeline_synthesis' AND active=true")
cur.execute("SELECT template FROM ai_prompts WHERE slug=%s AND active=true", (config['stage2_prompt'],))
synth_row = cur.fetchone()
if not synth_row:
raise HTTPException(500, "Pipeline synthesis prompt not found")
raise HTTPException(500, f"Pipeline synthesis prompt '{config['stage2_prompt']}' not found")
synth_prompt = _render_template(synth_row['template'], vars)
@@ -442,16 +580,24 @@ async def analyze_pipeline(x_profile_id: Optional[str]=Header(default=None), ses
else:
raise HTTPException(500, "Keine KI-API konfiguriert")
# Stage 3: Goals (only if goals are set)
# Stage 3: Optional (e.g., Goals)
goals_text = None
prof = data['profile']
if prof.get('goal_weight') or prof.get('goal_bf_pct'):
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT template FROM ai_prompts WHERE slug='pipeline_goals' AND active=true")
goals_row = cur.fetchone()
if goals_row:
goals_prompt = _render_template(goals_row['template'], vars)
if config.get('stage3_prompt'):
# Check if conditions are met (for backwards compatibility with goals check)
prof = data['profile']
should_run_stage3 = True
# Special case: goals prompt only runs if goals are set
if config['stage3_prompt'] == 'pipeline_goals':
should_run_stage3 = bool(prof.get('goal_weight') or prof.get('goal_bf_pct'))
if should_run_stage3:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT template FROM ai_prompts WHERE slug=%s AND active=true", (config['stage3_prompt'],))
goals_row = cur.fetchone()
if goals_row:
goals_prompt = _render_template(goals_row['template'], vars)
if ANTHROPIC_KEY:
import anthropic
@@ -480,11 +626,14 @@ async def analyze_pipeline(x_profile_id: Optional[str]=Header(default=None), ses
if goals_text:
final_content += "\n\n" + goals_text
# Save as 'pipeline' scope (with history - no DELETE)
# Save with config-specific scope (with history - no DELETE)
scope = f"pipeline_{config['name'].lower().replace(' ', '_')}"
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("INSERT INTO ai_insights (id, profile_id, scope, content, created) VALUES (%s,%s,'pipeline',%s,CURRENT_TIMESTAMP)",
(str(uuid.uuid4()), pid, final_content))
cur.execute("INSERT INTO ai_insights (id, profile_id, scope, content, created) VALUES (%s,%s,%s,%s,CURRENT_TIMESTAMP)",
(str(uuid.uuid4()), pid, scope, final_content))
logger.info(f"[PIPELINE] Completed '{config['name']}' - saved as scope='{scope}'")
# Phase 2: Increment ai_calls usage (pipeline uses multiple API calls)
# Note: We increment once per pipeline run, not per individual call
@@ -493,7 +642,15 @@ async def analyze_pipeline(x_profile_id: Optional[str]=Header(default=None), ses
# Old usage tracking (keep for now)
inc_ai_usage(pid)
return {"scope": "pipeline", "content": final_content, "stage1": stage1_results}
return {
"scope": scope,
"content": final_content,
"stage1": stage1_results,
"config": {
"id": config['id'],
"name": config['name']
}
}
@router.get("/ai/usage")
+8 -4
View File
@@ -9,7 +9,7 @@ import logging
from pathlib import Path
from typing import Optional
from fastapi import APIRouter, UploadFile, File, Header, HTTPException, Depends
from fastapi import APIRouter, UploadFile, File, Form, Header, HTTPException, Depends
from fastapi.responses import FileResponse
import aiofiles
@@ -26,7 +26,7 @@ PHOTOS_DIR.mkdir(parents=True, exist_ok=True)
@router.post("")
async def upload_photo(file: UploadFile=File(...), date: str="",
async def upload_photo(file: UploadFile=File(...), date: str=Form(""),
x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Upload progress photo."""
pid = get_pid(x_profile_id)
@@ -50,15 +50,19 @@ async def upload_photo(file: UploadFile=File(...), date: str="",
ext = Path(file.filename).suffix or '.jpg'
path = PHOTOS_DIR / f"{fid}{ext}"
async with aiofiles.open(path,'wb') as f: await f.write(await file.read())
# Convert empty string to NULL for date field
photo_date = date if date and date.strip() else None
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("INSERT INTO photos (id,profile_id,date,path,created) VALUES (%s,%s,%s,%s,CURRENT_TIMESTAMP)",
(fid,pid,date,str(path)))
(fid,pid,photo_date,str(path)))
# Phase 2: Increment usage counter
increment_feature_usage(pid, 'photos')
return {"id":fid,"date":date}
return {"id":fid,"date":photo_date}
@router.get("/{fid}")
+1193 -18
View File
File diff suppressed because it is too large. Load diff
+368
View File
@@ -0,0 +1,368 @@
"""
Rest Days Endpoints for Mitai Jinkendo
Context-specific rest days with flexible JSONB configuration.
"""
import logging
from typing import Optional, Literal
from datetime import datetime, timedelta
from fastapi import APIRouter, HTTPException, Depends, Header
from pydantic import BaseModel, Field
from psycopg2.extras import Json
from psycopg2.errors import UniqueViolation
from db import get_db, get_cursor, r2d
from auth import require_auth
from routers.profiles import get_pid
router = APIRouter(prefix="/api/rest-days", tags=["rest-days"])
logger = logging.getLogger(__name__)
# ── Models ────────────────────────────────────────────────────────────────────
class RestConfig(BaseModel):
focus: Literal['muscle_recovery', 'cardio_recovery', 'mental_rest', 'deload', 'injury']
rest_from: list[str] = Field(default_factory=list, description="Training type IDs to avoid")
allows: list[str] = Field(default_factory=list, description="Allowed activity type IDs")
intensity_max: Optional[int] = Field(None, ge=1, le=100, description="Max HR% for allowed activities")
note: str = ""
class RestDayCreate(BaseModel):
date: str # YYYY-MM-DD
rest_config: RestConfig
note: str = ""
class RestDayUpdate(BaseModel):
date: Optional[str] = None
rest_config: Optional[RestConfig] = None
note: Optional[str] = None
class ActivityConflictCheck(BaseModel):
date: str
activity_type: str
# ── CRUD Endpoints ────────────────────────────────────────────────────────────
@router.get("")
def list_rest_days(
limit: int = 90,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""List rest days for current profile (last N days)."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT id, profile_id, date, rest_config, note, created_at
FROM rest_days
WHERE profile_id = %s
ORDER BY date DESC
LIMIT %s
""",
(pid, limit)
)
return [r2d(r) for r in cur.fetchall()]
@router.post("")
def create_rest_day(
data: RestDayCreate,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Create rest day with JSONB config. Upserts by date."""
pid = get_pid(x_profile_id)
# Validate date format
try:
datetime.strptime(data.date, '%Y-%m-%d')
except ValueError:
raise HTTPException(400, "Invalid date format. Use YYYY-MM-DD")
# Convert RestConfig to dict for JSONB storage
config_dict = data.rest_config.model_dump()
focus = data.rest_config.focus
try:
with get_db() as conn:
cur = get_cursor(conn)
# Insert (multiple entries per date allowed, but not same focus)
cur.execute(
"""
INSERT INTO rest_days (profile_id, date, focus, rest_config, note, created_at)
VALUES (%s, %s, %s, %s, %s, CURRENT_TIMESTAMP)
RETURNING id, profile_id, date, focus, rest_config, note, created_at
""",
(pid, data.date, focus, Json(config_dict), data.note)
)
result = cur.fetchone()
return r2d(result)
except UniqueViolation:
# User-friendly error for duplicate focus
focus_labels = {
'muscle_recovery': 'Muskelregeneration',
'cardio_recovery': 'Cardio-Erholung',
'mental_rest': 'Mentale Erholung',
'deload': 'Deload',
'injury': 'Verletzungspause',
}
focus_label = focus_labels.get(focus, focus)
raise HTTPException(
400,
f"Du hast bereits einen Ruhetag '{focus_label}' für {data.date}. Bitte wähle einen anderen Typ oder lösche den bestehenden Eintrag."
)
@router.get("/{rest_day_id}")
def get_rest_day(
rest_day_id: int,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Get single rest day by ID."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT id, profile_id, date, rest_config, note, created_at
FROM rest_days
WHERE id = %s AND profile_id = %s
""",
(rest_day_id, pid)
)
row = cur.fetchone()
if not row:
raise HTTPException(404, "Rest day not found")
return r2d(row)
@router.put("/{rest_day_id}")
def update_rest_day(
rest_day_id: int,
data: RestDayUpdate,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Update rest day."""
pid = get_pid(x_profile_id)
# Build update fields dynamically
updates = []
values = []
if data.date:
try:
datetime.strptime(data.date, '%Y-%m-%d')
except ValueError:
raise HTTPException(400, "Invalid date format. Use YYYY-MM-DD")
updates.append("date = %s")
values.append(data.date)
if data.rest_config:
updates.append("rest_config = %s")
values.append(Json(data.rest_config.model_dump()))
# Also update focus column if config changed
updates.append("focus = %s")
values.append(data.rest_config.focus)
if data.note is not None:
updates.append("note = %s")
values.append(data.note)
if not updates:
raise HTTPException(400, "No fields to update")
values.extend([rest_day_id, pid])
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
f"""
UPDATE rest_days
SET {', '.join(updates)}
WHERE id = %s AND profile_id = %s
RETURNING id, profile_id, date, rest_config, note, created_at
""",
values
)
result = cur.fetchone()
if not result:
raise HTTPException(404, "Rest day not found")
return r2d(result)
@router.delete("/{rest_day_id}")
def delete_rest_day(
rest_day_id: int,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Delete rest day."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"DELETE FROM rest_days WHERE id = %s AND profile_id = %s RETURNING id",
(rest_day_id, pid)
)
result = cur.fetchone()
if not result:
raise HTTPException(404, "Rest day not found")
return {"deleted": True, "id": result['id']}
# ── Stats & Validation ────────────────────────────────────────────────────────
@router.get("/stats")
def get_rest_days_stats(
weeks: int = 4,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Get rest day statistics (count per week, focus distribution)."""
pid = get_pid(x_profile_id)
cutoff_date = (datetime.now() - timedelta(weeks=weeks)).strftime('%Y-%m-%d')
with get_db() as conn:
cur = get_cursor(conn)
# Total count
cur.execute(
"""
SELECT COUNT(*) as total
FROM rest_days
WHERE profile_id = %s AND date >= %s
""",
(pid, cutoff_date)
)
total = cur.fetchone()['total']
# Count by focus type
cur.execute(
"""
SELECT
rest_config->>'focus' as focus,
COUNT(*) as count
FROM rest_days
WHERE profile_id = %s AND date >= %s
GROUP BY rest_config->>'focus'
ORDER BY count DESC
""",
(pid, cutoff_date)
)
by_focus = [r2d(r) for r in cur.fetchall()]
# Count by week (ISO week number)
cur.execute(
"""
SELECT
EXTRACT(YEAR FROM date) as year,
EXTRACT(WEEK FROM date) as week,
COUNT(*) as count
FROM rest_days
WHERE profile_id = %s AND date >= %s
GROUP BY year, week
ORDER BY year DESC, week DESC
""",
(pid, cutoff_date)
)
by_week = [r2d(r) for r in cur.fetchall()]
return {
"total_rest_days": total,
"weeks_analyzed": weeks,
"by_focus": by_focus,
"by_week": by_week
}
@router.post("/validate-activity")
def validate_activity(
data: ActivityConflictCheck,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""
Check if activity conflicts with rest day configuration.
Returns:
- conflict: bool
- severity: 'warning' | 'info' | 'none'
- message: str
"""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT rest_config
FROM rest_days
WHERE profile_id = %s AND date = %s
""",
(pid, data.date)
)
row = cur.fetchone()
if not row:
return {"conflict": False, "severity": "none", "message": ""}
config = row['rest_config']
# Check if activity is in rest_from
if data.activity_type in config.get('rest_from', []):
focus_labels = {
'muscle_recovery': 'Muskelregeneration',
'cardio_recovery': 'Cardio-Erholung',
'mental_rest': 'Mentale Erholung',
'deload': 'Deload',
'injury': 'Verletzungspause'
}
focus_label = focus_labels.get(config.get('focus'), 'Ruhetag')
return {
"conflict": True,
"severity": "warning",
"message": f"Ruhetag ({focus_label}) – {data.activity_type} sollte pausiert werden. Trotzdem erfassen?"
}
# Check if activity is allowed
allows_list = config.get('allows', [])
if allows_list and data.activity_type not in allows_list:
return {
"conflict": True,
"severity": "info",
"message": f"Aktivität nicht in erlaubten Aktivitäten. Heute: {', '.join(allows_list) or 'Keine'}."
}
# Check intensity_max (if provided in request)
intensity_max = config.get('intensity_max')
if intensity_max:
return {
"conflict": False,
"severity": "info",
"message": f"Erlaubt bei max. {intensity_max}% HFmax."
}
return {"conflict": False, "severity": "none", "message": ""}
+681
View File
@@ -0,0 +1,681 @@
"""
Vitals Router - Resting HR + HRV Tracking
v9d Phase 2: Vitals Module
Endpoints:
- GET /api/vitals List vitals (with limit)
- GET /api/vitals/by-date/{date} Get vitals for specific date
- POST /api/vitals Create/update vitals (upsert)
- PUT /api/vitals/{id} Update vitals
- DELETE /api/vitals/{id} Delete vitals
- GET /api/vitals/stats Get vitals statistics
- POST /api/vitals/import/omron Import Omron CSV
- POST /api/vitals/import/apple-health Import Apple Health CSV
"""
from fastapi import APIRouter, HTTPException, Depends, Header, UploadFile, File
from pydantic import BaseModel
from typing import Optional
from datetime import datetime, timedelta
import logging
import csv
import io
from dateutil import parser as date_parser
from db import get_db, get_cursor, r2d
from auth import require_auth
router = APIRouter(prefix="/api/vitals", tags=["vitals"])
logger = logging.getLogger(__name__)
# German month mapping for Omron dates
GERMAN_MONTHS = {
'Januar': '01', 'Jan.': '01',
'Februar': '02', 'Feb.': '02',
'März': '03',
'April': '04', 'Apr.': '04',
'Mai': '05',
'Juni': '06',
'Juli': '07',
'August': '08', 'Aug.': '08',
'September': '09', 'Sep.': '09',
'Oktober': '10', 'Okt.': '10',
'November': '11', 'Nov.': '11',
'Dezember': '12', 'Dez.': '12'
}
class VitalsEntry(BaseModel):
date: str
resting_hr: Optional[int] = None
hrv: Optional[int] = None
blood_pressure_systolic: Optional[int] = None
blood_pressure_diastolic: Optional[int] = None
pulse: Optional[int] = None
vo2_max: Optional[float] = None
spo2: Optional[int] = None
respiratory_rate: Optional[float] = None
irregular_heartbeat: Optional[bool] = None
possible_afib: Optional[bool] = None
note: Optional[str] = None
class VitalsUpdate(BaseModel):
date: Optional[str] = None
resting_hr: Optional[int] = None
hrv: Optional[int] = None
blood_pressure_systolic: Optional[int] = None
blood_pressure_diastolic: Optional[int] = None
pulse: Optional[int] = None
vo2_max: Optional[float] = None
spo2: Optional[int] = None
respiratory_rate: Optional[float] = None
irregular_heartbeat: Optional[bool] = None
possible_afib: Optional[bool] = None
note: Optional[str] = None
def get_pid(x_profile_id: Optional[str], session: dict) -> str:
"""Extract profile_id from session (never from header for security)."""
return session['profile_id']
@router.get("")
def list_vitals(
limit: int = 90,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Get vitals entries for current profile."""
pid = get_pid(x_profile_id, session)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT id, profile_id, date, resting_hr, hrv,
blood_pressure_systolic, blood_pressure_diastolic, pulse,
vo2_max, spo2, respiratory_rate,
irregular_heartbeat, possible_afib,
note, source, created_at, updated_at
FROM vitals_log
WHERE profile_id = %s
ORDER BY date DESC
LIMIT %s
""",
(pid, limit)
)
return [r2d(r) for r in cur.fetchall()]
@router.get("/by-date/{date}")
def get_vitals_by_date(
date: str,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Get vitals entry for a specific date."""
pid = get_pid(x_profile_id, session)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT id, profile_id, date, resting_hr, hrv,
blood_pressure_systolic, blood_pressure_diastolic, pulse,
vo2_max, spo2, respiratory_rate,
irregular_heartbeat, possible_afib,
note, source, created_at, updated_at
FROM vitals_log
WHERE profile_id = %s AND date = %s
""",
(pid, date)
)
row = cur.fetchone()
if not row:
raise HTTPException(404, "Keine Vitalwerte für dieses Datum gefunden")
return r2d(row)
@router.post("")
def create_vitals(
entry: VitalsEntry,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Create or update vitals entry (upsert)."""
pid = get_pid(x_profile_id, session)
# Validation: at least one vital must be provided
has_data = any([
entry.resting_hr, entry.hrv, entry.blood_pressure_systolic,
entry.blood_pressure_diastolic, entry.vo2_max, entry.spo2,
entry.respiratory_rate
])
if not has_data:
raise HTTPException(400, "Mindestens ein Vitalwert muss angegeben werden")
with get_db() as conn:
cur = get_cursor(conn)
# Upsert: insert or update if date already exists
cur.execute(
"""
INSERT INTO vitals_log (
profile_id, date, resting_hr, hrv,
blood_pressure_systolic, blood_pressure_diastolic, pulse,
vo2_max, spo2, respiratory_rate,
irregular_heartbeat, possible_afib,
note, source
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'manual')
ON CONFLICT (profile_id, date)
DO UPDATE SET
resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_log.resting_hr),
hrv = COALESCE(EXCLUDED.hrv, vitals_log.hrv),
blood_pressure_systolic = COALESCE(EXCLUDED.blood_pressure_systolic, vitals_log.blood_pressure_systolic),
blood_pressure_diastolic = COALESCE(EXCLUDED.blood_pressure_diastolic, vitals_log.blood_pressure_diastolic),
pulse = COALESCE(EXCLUDED.pulse, vitals_log.pulse),
vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_log.vo2_max),
spo2 = COALESCE(EXCLUDED.spo2, vitals_log.spo2),
respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_log.respiratory_rate),
irregular_heartbeat = COALESCE(EXCLUDED.irregular_heartbeat, vitals_log.irregular_heartbeat),
possible_afib = COALESCE(EXCLUDED.possible_afib, vitals_log.possible_afib),
note = COALESCE(EXCLUDED.note, vitals_log.note),
updated_at = CURRENT_TIMESTAMP
RETURNING id, profile_id, date, resting_hr, hrv,
blood_pressure_systolic, blood_pressure_diastolic, pulse,
vo2_max, spo2, respiratory_rate,
irregular_heartbeat, possible_afib,
note, source, created_at, updated_at
""",
(pid, entry.date, entry.resting_hr, entry.hrv,
entry.blood_pressure_systolic, entry.blood_pressure_diastolic, entry.pulse,
entry.vo2_max, entry.spo2, entry.respiratory_rate,
entry.irregular_heartbeat, entry.possible_afib,
entry.note)
)
row = cur.fetchone()
conn.commit()
logger.info(f"[VITALS] Upserted vitals for {pid} on {entry.date}")
return r2d(row)
@router.put("/{vitals_id}")
def update_vitals(
vitals_id: int,
updates: VitalsUpdate,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Update existing vitals entry."""
pid = get_pid(x_profile_id, session)
with get_db() as conn:
cur = get_cursor(conn)
# Check ownership
cur.execute(
"SELECT id FROM vitals_log WHERE id = %s AND profile_id = %s",
(vitals_id, pid)
)
if not cur.fetchone():
raise HTTPException(404, "Eintrag nicht gefunden")
# Build update query dynamically
fields = []
values = []
if updates.date is not None:
fields.append("date = %s")
values.append(updates.date)
if updates.resting_hr is not None:
fields.append("resting_hr = %s")
values.append(updates.resting_hr)
if updates.hrv is not None:
fields.append("hrv = %s")
values.append(updates.hrv)
if updates.blood_pressure_systolic is not None:
fields.append("blood_pressure_systolic = %s")
values.append(updates.blood_pressure_systolic)
if updates.blood_pressure_diastolic is not None:
fields.append("blood_pressure_diastolic = %s")
values.append(updates.blood_pressure_diastolic)
if updates.pulse is not None:
fields.append("pulse = %s")
values.append(updates.pulse)
if updates.vo2_max is not None:
fields.append("vo2_max = %s")
values.append(updates.vo2_max)
if updates.spo2 is not None:
fields.append("spo2 = %s")
values.append(updates.spo2)
if updates.respiratory_rate is not None:
fields.append("respiratory_rate = %s")
values.append(updates.respiratory_rate)
if updates.irregular_heartbeat is not None:
fields.append("irregular_heartbeat = %s")
values.append(updates.irregular_heartbeat)
if updates.possible_afib is not None:
fields.append("possible_afib = %s")
values.append(updates.possible_afib)
if updates.note is not None:
fields.append("note = %s")
values.append(updates.note)
if not fields:
raise HTTPException(400, "Keine Änderungen angegeben")
fields.append("updated_at = CURRENT_TIMESTAMP")
values.append(vitals_id)
query = f"""
UPDATE vitals_log
SET {', '.join(fields)}
WHERE id = %s
RETURNING id, profile_id, date, resting_hr, hrv,
blood_pressure_systolic, blood_pressure_diastolic, pulse,
vo2_max, spo2, respiratory_rate,
irregular_heartbeat, possible_afib,
note, source, created_at, updated_at
"""
cur.execute(query, values)
row = cur.fetchone()
conn.commit()
return r2d(row)
@router.delete("/{vitals_id}")
def delete_vitals(
vitals_id: int,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Delete vitals entry."""
pid = get_pid(x_profile_id, session)
with get_db() as conn:
cur = get_cursor(conn)
# Check ownership and delete
cur.execute(
"DELETE FROM vitals_log WHERE id = %s AND profile_id = %s RETURNING id",
(vitals_id, pid)
)
if not cur.fetchone():
raise HTTPException(404, "Eintrag nicht gefunden")
conn.commit()
logger.info(f"[VITALS] Deleted vitals {vitals_id} for {pid}")
return {"message": "Eintrag gelöscht"}
@router.get("/stats")
def get_vitals_stats(
days: int = 30,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""
Get vitals statistics over the last N days.
Returns:
- avg_resting_hr (7d and 30d)
- avg_hrv (7d and 30d)
- trend (increasing/decreasing/stable)
- latest values
"""
pid = get_pid(x_profile_id, session)
with get_db() as conn:
cur = get_cursor(conn)
# Get latest entry
cur.execute(
"""
SELECT date, resting_hr, hrv
FROM vitals_log
WHERE profile_id = %s AND date >= CURRENT_DATE - INTERVAL '%s days'
ORDER BY date DESC
LIMIT 1
""",
(pid, days)
)
latest = cur.fetchone()
# Get averages (7d and 30d)
cur.execute(
"""
SELECT
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '7 days' THEN resting_hr END) as avg_hr_7d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '30 days' THEN resting_hr END) as avg_hr_30d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '7 days' THEN hrv END) as avg_hrv_7d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '30 days' THEN hrv END) as avg_hrv_30d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '7 days' THEN blood_pressure_systolic END) as avg_bp_sys_7d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '30 days' THEN blood_pressure_systolic END) as avg_bp_sys_30d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '7 days' THEN blood_pressure_diastolic END) as avg_bp_dia_7d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '30 days' THEN blood_pressure_diastolic END) as avg_bp_dia_30d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '7 days' THEN spo2 END) as avg_spo2_7d,
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '30 days' THEN spo2 END) as avg_spo2_30d,
COUNT(*) as total_entries
FROM vitals_log
WHERE profile_id = %s AND date >= CURRENT_DATE - INTERVAL '%s days'
""",
(pid, max(days, 30))
)
stats_row = cur.fetchone()
# Get latest VO2 Max
cur.execute(
"""
SELECT vo2_max
FROM vitals_log
WHERE profile_id = %s AND vo2_max IS NOT NULL
ORDER BY date DESC
LIMIT 1
""",
(pid,)
)
vo2_row = cur.fetchone()
latest_vo2 = vo2_row['vo2_max'] if vo2_row else None
# Get entries for trend calculation (last 14 days)
cur.execute(
"""
SELECT date, resting_hr, hrv
FROM vitals_log
WHERE profile_id = %s AND date >= CURRENT_DATE - INTERVAL '14 days'
ORDER BY date ASC
""",
(pid,)
)
entries = [r2d(r) for r in cur.fetchall()]
# Simple trend calculation (compare first half vs second half)
trend_hr = "stable"
trend_hrv = "stable"
if len(entries) >= 4:
mid = len(entries) // 2
first_half_hr = [e['resting_hr'] for e in entries[:mid] if e['resting_hr']]
second_half_hr = [e['resting_hr'] for e in entries[mid:] if e['resting_hr']]
if first_half_hr and second_half_hr:
avg_first = sum(first_half_hr) / len(first_half_hr)
avg_second = sum(second_half_hr) / len(second_half_hr)
diff = avg_second - avg_first
if diff > 2:
trend_hr = "increasing"
elif diff < -2:
trend_hr = "decreasing"
first_half_hrv = [e['hrv'] for e in entries[:mid] if e['hrv']]
second_half_hrv = [e['hrv'] for e in entries[mid:] if e['hrv']]
if first_half_hrv and second_half_hrv:
avg_first_hrv = sum(first_half_hrv) / len(first_half_hrv)
avg_second_hrv = sum(second_half_hrv) / len(second_half_hrv)
diff_hrv = avg_second_hrv - avg_first_hrv
if diff_hrv > 5:
trend_hrv = "increasing"
elif diff_hrv < -5:
trend_hrv = "decreasing"
return {
"latest": r2d(latest) if latest else None,
"avg_resting_hr_7d": round(stats_row['avg_hr_7d'], 1) if stats_row['avg_hr_7d'] else None,
"avg_resting_hr_30d": round(stats_row['avg_hr_30d'], 1) if stats_row['avg_hr_30d'] else None,
"avg_hrv_7d": round(stats_row['avg_hrv_7d'], 1) if stats_row['avg_hrv_7d'] else None,
"avg_hrv_30d": round(stats_row['avg_hrv_30d'], 1) if stats_row['avg_hrv_30d'] else None,
"avg_bp_systolic_7d": round(stats_row['avg_bp_sys_7d'], 1) if stats_row['avg_bp_sys_7d'] else None,
"avg_bp_systolic_30d": round(stats_row['avg_bp_sys_30d'], 1) if stats_row['avg_bp_sys_30d'] else None,
"avg_bp_diastolic_7d": round(stats_row['avg_bp_dia_7d'], 1) if stats_row['avg_bp_dia_7d'] else None,
"avg_bp_diastolic_30d": round(stats_row['avg_bp_dia_30d'], 1) if stats_row['avg_bp_dia_30d'] else None,
"avg_spo2_7d": round(stats_row['avg_spo2_7d'], 1) if stats_row['avg_spo2_7d'] else None,
"avg_spo2_30d": round(stats_row['avg_spo2_30d'], 1) if stats_row['avg_spo2_30d'] else None,
"latest_vo2_max": float(latest_vo2) if latest_vo2 else None,
"total_entries": stats_row['total_entries'],
"trend_resting_hr": trend_hr,
"trend_hrv": trend_hrv,
"period_days": days
}
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Import Endpoints
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
def parse_omron_date(date_str: str) -> str:
"""
Parse Omron German date format to YYYY-MM-DD.
Examples:
- "13 März 2026" -> "2026-03-13"
- "28 Feb. 2026" -> "2026-02-28"
"""
parts = date_str.strip().split()
if len(parts) != 3:
raise ValueError(f"Invalid date format: {date_str}")
day = parts[0].zfill(2)
month_str = parts[1]
year = parts[2]
# Map German month to number
month = GERMAN_MONTHS.get(month_str)
if not month:
raise ValueError(f"Unknown month: {month_str}")
return f"{year}-{month}-{day}"
@router.post("/import/omron")
async def import_omron_csv(
file: UploadFile = File(...),
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""
Import Omron blood pressure CSV export.
Expected format:
Datum,Zeit,Systolisch (mmHg),Diastolisch (mmHg),Puls (bpm),...
"""
pid = get_pid(x_profile_id, session)
# Read file
content = await file.read()
content_str = content.decode('utf-8')
# Parse CSV
reader = csv.DictReader(io.StringIO(content_str))
inserted = 0
updated = 0
skipped = 0
errors = []
with get_db() as conn:
cur = get_cursor(conn)
for row_num, row in enumerate(reader, start=2):
try:
# Parse date
date_str = parse_omron_date(row['Datum'])
# Parse values
systolic = int(row['Systolisch (mmHg)']) if row['Systolisch (mmHg)'] and row['Systolisch (mmHg)'] != '-' else None
diastolic = int(row['Diastolisch (mmHg)']) if row['Diastolisch (mmHg)'] and row['Diastolisch (mmHg)'] != '-' else None
pulse = int(row['Puls (bpm)']) if row['Puls (bpm)'] and row['Puls (bpm)'] != '-' else None
# Skip if no data
if not systolic and not diastolic and not pulse:
skipped += 1
continue
# Parse flags (optional columns)
irregular = row.get('Unregelmäßiger Herzschlag festgestellt', '').strip() not in ('', '-', ' ')
afib = row.get('Mögliches AFib', '').strip() not in ('', '-', ' ')
# Upsert
cur.execute(
"""
INSERT INTO vitals_log (
profile_id, date, blood_pressure_systolic, blood_pressure_diastolic,
pulse, irregular_heartbeat, possible_afib, source
)
VALUES (%s, %s, %s, %s, %s, %s, %s, 'omron')
ON CONFLICT (profile_id, date)
DO UPDATE SET
blood_pressure_systolic = COALESCE(EXCLUDED.blood_pressure_systolic, vitals_log.blood_pressure_systolic),
blood_pressure_diastolic = COALESCE(EXCLUDED.blood_pressure_diastolic, vitals_log.blood_pressure_diastolic),
pulse = COALESCE(EXCLUDED.pulse, vitals_log.pulse),
irregular_heartbeat = COALESCE(EXCLUDED.irregular_heartbeat, vitals_log.irregular_heartbeat),
possible_afib = COALESCE(EXCLUDED.possible_afib, vitals_log.possible_afib),
source = CASE WHEN vitals_log.source = 'manual' THEN vitals_log.source ELSE 'omron' END,
updated_at = CURRENT_TIMESTAMP
RETURNING (xmax = 0) AS inserted
""",
(pid, date_str, systolic, diastolic, pulse, irregular, afib)
)
result = cur.fetchone()
if result['inserted']:
inserted += 1
else:
updated += 1
except Exception as e:
errors.append(f"Zeile {row_num}: {str(e)}")
logger.error(f"[OMRON-IMPORT] Error at row {row_num}: {e}")
continue
conn.commit()
logger.info(f"[OMRON-IMPORT] {pid}: {inserted} inserted, {updated} updated, {skipped} skipped, {len(errors)} errors")
return {
"message": "Omron CSV Import abgeschlossen",
"inserted": inserted,
"updated": updated,
"skipped": skipped,
"errors": errors[:10] # Limit to first 10 errors
}
@router.post("/import/apple-health")
async def import_apple_health_csv(
file: UploadFile = File(...),
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""
Import Apple Health vitals CSV export.
Expected columns:
- Datum/Uhrzeit
- Ruhepuls (count/min)
- Herzfrequenzvariabilität (ms)
- VO2 max (ml/(kg·min))
- Blutsauerstoffsättigung (%)
- Atemfrequenz (count/min)
"""
pid = get_pid(x_profile_id, session)
# Read file
content = await file.read()
content_str = content.decode('utf-8')
# Parse CSV
reader = csv.DictReader(io.StringIO(content_str))
inserted = 0
updated = 0
skipped = 0
errors = []
with get_db() as conn:
cur = get_cursor(conn)
for row_num, row in enumerate(reader, start=2):
try:
# Parse date (format: "2026-02-21 00:00:00")
date_str = row.get('Datum/Uhrzeit', '').split()[0] # Extract date part
if not date_str:
skipped += 1
continue
# Parse values (columns might be empty)
resting_hr = None
hrv = None
vo2_max = None
spo2 = None
respiratory_rate = None
if 'Ruhepuls (count/min)' in row and row['Ruhepuls (count/min)']:
resting_hr = int(float(row['Ruhepuls (count/min)']))
if 'Herzfrequenzvariabilität (ms)' in row and row['Herzfrequenzvariabilität (ms)']:
hrv = int(float(row['Herzfrequenzvariabilität (ms)']))
if 'VO2 max (ml/(kg·min))' in row and row['VO2 max (ml/(kg·min))']:
vo2_max = float(row['VO2 max (ml/(kg·min))'])
if 'Blutsauerstoffsättigung (%)' in row and row['Blutsauerstoffsättigung (%)']:
spo2 = int(float(row['Blutsauerstoffsättigung (%)']))
if 'Atemfrequenz (count/min)' in row and row['Atemfrequenz (count/min)']:
respiratory_rate = float(row['Atemfrequenz (count/min)'])
# Skip if no vitals data
if not any([resting_hr, hrv, vo2_max, spo2, respiratory_rate]):
skipped += 1
continue
# Upsert
cur.execute(
"""
INSERT INTO vitals_log (
profile_id, date, resting_hr, hrv, vo2_max, spo2,
respiratory_rate, source
)
VALUES (%s, %s, %s, %s, %s, %s, %s, 'apple_health')
ON CONFLICT (profile_id, date)
DO UPDATE SET
resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_log.resting_hr),
hrv = COALESCE(EXCLUDED.hrv, vitals_log.hrv),
vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_log.vo2_max),
spo2 = COALESCE(EXCLUDED.spo2, vitals_log.spo2),
respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_log.respiratory_rate),
source = CASE WHEN vitals_log.source = 'manual' THEN vitals_log.source ELSE 'apple_health' END,
updated_at = CURRENT_TIMESTAMP
RETURNING (xmax = 0) AS inserted
""",
(pid, date_str, resting_hr, hrv, vo2_max, spo2, respiratory_rate)
)
result = cur.fetchone()
if result['inserted']:
inserted += 1
else:
updated += 1
except Exception as e:
errors.append(f"Zeile {row_num}: {str(e)}")
logger.error(f"[APPLE-HEALTH-IMPORT] Error at row {row_num}: {e}")
continue
conn.commit()
logger.info(f"[APPLE-HEALTH-IMPORT] {pid}: {inserted} inserted, {updated} updated, {skipped} skipped, {len(errors)} errors")
return {
"message": "Apple Health CSV Import abgeschlossen",
"inserted": inserted,
"updated": updated,
"skipped": skipped,
"errors": errors[:10] # Limit to first 10 errors
}
+414
View File
@@ -0,0 +1,414 @@
"""
Vitals Baseline Router - v9d Phase 2d Refactored
Baseline vitals measured once daily (morning, fasted):
- Resting Heart Rate (RHR)
- Heart Rate Variability (HRV)
- VO2 Max
- SpO2 (Blood Oxygen Saturation)
- Respiratory Rate
Endpoints:
- GET /api/vitals/baseline List baseline vitals
- GET /api/vitals/baseline/by-date/{date} Get entry for specific date
- POST /api/vitals/baseline Create/update baseline entry (upsert)
- PUT /api/vitals/baseline/{id} Update baseline entry
- DELETE /api/vitals/baseline/{id} Delete baseline entry
- GET /api/vitals/baseline/stats Statistics and trends
- POST /api/vitals/baseline/import/apple-health Import Apple Health CSV
"""
from fastapi import APIRouter, HTTPException, Depends, Header, UploadFile, File
from pydantic import BaseModel
from typing import Optional
from datetime import datetime, timedelta
import logging
import csv
import io
from db import get_db, get_cursor, r2d
from auth import require_auth
from routers.profiles import get_pid
router = APIRouter(prefix="/api/vitals/baseline", tags=["vitals_baseline"])
logger = logging.getLogger(__name__)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Pydantic Models
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
class BaselineEntry(BaseModel):
date: str
resting_hr: Optional[int] = None
hrv: Optional[int] = None
vo2_max: Optional[float] = None
spo2: Optional[int] = None
respiratory_rate: Optional[float] = None
body_temperature: Optional[float] = None
resting_metabolic_rate: Optional[int] = None
note: Optional[str] = None
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# CRUD Endpoints
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
@router.get("")
def list_baseline_vitals(
limit: int = 90,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Get baseline vitals (last N days)."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT * FROM vitals_baseline
WHERE profile_id = %s
ORDER BY date DESC
LIMIT %s
""", (pid, limit))
return [r2d(r) for r in cur.fetchall()]
@router.get("/by-date/{date}")
def get_baseline_by_date(
date: str,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Get baseline entry for specific date."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT * FROM vitals_baseline
WHERE profile_id = %s AND date = %s
""", (pid, date))
row = cur.fetchone()
return r2d(row) if row else None
@router.post("")
def create_or_update_baseline(
entry: BaselineEntry,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Create or update baseline entry (upsert on date)."""
pid = get_pid(x_profile_id)
# Build dynamic update columns (only non-None fields)
fields = []
values = [pid, entry.date]
if entry.resting_hr is not None:
fields.append("resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_baseline.resting_hr)")
values.append(entry.resting_hr)
if entry.hrv is not None:
fields.append("hrv = COALESCE(EXCLUDED.hrv, vitals_baseline.hrv)")
values.append(entry.hrv)
if entry.vo2_max is not None:
fields.append("vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_baseline.vo2_max)")
values.append(entry.vo2_max)
if entry.spo2 is not None:
fields.append("spo2 = COALESCE(EXCLUDED.spo2, vitals_baseline.spo2)")
values.append(entry.spo2)
if entry.respiratory_rate is not None:
fields.append("respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_baseline.respiratory_rate)")
values.append(entry.respiratory_rate)
if entry.body_temperature is not None:
fields.append("body_temperature = COALESCE(EXCLUDED.body_temperature, vitals_baseline.body_temperature)")
values.append(entry.body_temperature)
if entry.resting_metabolic_rate is not None:
fields.append("resting_metabolic_rate = COALESCE(EXCLUDED.resting_metabolic_rate, vitals_baseline.resting_metabolic_rate)")
values.append(entry.resting_metabolic_rate)
if entry.note:
fields.append("note = COALESCE(EXCLUDED.note, vitals_baseline.note)")
values.append(entry.note)
# At least one field must be provided
if not fields:
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:
cur = get_cursor(conn)
query = f"""
INSERT INTO vitals_baseline (profile_id, date, {', '.join([f.split('=')[0].strip() for f in fields])})
VALUES ($1, $2, {', '.join([f'${i}' for i in range(3, len(values) + 1)])})
ON CONFLICT (profile_id, date)
DO UPDATE SET {', '.join(fields)}, updated_at = NOW()
RETURNING *
"""
cur.execute(query, values)
return r2d(cur.fetchone())
@router.put("/{entry_id}")
def update_baseline(
entry_id: int,
entry: BaselineEntry,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Update existing baseline entry."""
pid = get_pid(x_profile_id)
# Build SET clause dynamically
updates = []
values = []
idx = 1
if entry.resting_hr is not None:
updates.append(f"resting_hr = ${idx}")
values.append(entry.resting_hr)
idx += 1
if entry.hrv is not None:
updates.append(f"hrv = ${idx}")
values.append(entry.hrv)
idx += 1
if entry.vo2_max is not None:
updates.append(f"vo2_max = ${idx}")
values.append(entry.vo2_max)
idx += 1
if entry.spo2 is not None:
updates.append(f"spo2 = ${idx}")
values.append(entry.spo2)
idx += 1
if entry.respiratory_rate is not None:
updates.append(f"respiratory_rate = ${idx}")
values.append(entry.respiratory_rate)
idx += 1
if entry.note:
updates.append(f"note = ${idx}")
values.append(entry.note)
idx += 1
if not updates:
raise HTTPException(400, "No fields to update")
updates.append("updated_at = NOW()")
values.extend([entry_id, pid])
with get_db() as conn:
cur = get_cursor(conn)
query = f"""
UPDATE vitals_baseline
SET {', '.join(updates)}
WHERE id = ${idx} AND profile_id = ${idx + 1}
RETURNING *
"""
cur.execute(query, values)
row = cur.fetchone()
if not row:
raise HTTPException(404, "Entry not found")
return r2d(row)
@router.delete("/{entry_id}")
def delete_baseline(
entry_id: int,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Delete baseline entry."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
DELETE FROM vitals_baseline
WHERE id = %s AND profile_id = %s
""", (entry_id, pid))
if cur.rowcount == 0:
raise HTTPException(404, "Entry not found")
return {"ok": True}
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Statistics & Trends
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
@router.get("/stats")
def get_baseline_stats(
days: int = 30,
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Get baseline vitals statistics and trends."""
pid = get_pid(x_profile_id)
cutoff_date = (datetime.now() - timedelta(days=days)).date()
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT
COUNT(*) as total_entries,
-- Resting HR
AVG(resting_hr) FILTER (WHERE date >= %s - INTERVAL '7 days') as avg_rhr_7d,
AVG(resting_hr) FILTER (WHERE date >= %s - INTERVAL '30 days') as avg_rhr_30d,
-- HRV
AVG(hrv) FILTER (WHERE date >= %s - INTERVAL '7 days') as avg_hrv_7d,
AVG(hrv) FILTER (WHERE date >= %s - INTERVAL '30 days') as avg_hrv_30d,
-- Latest values
(SELECT vo2_max FROM vitals_baseline WHERE profile_id = %s AND vo2_max IS NOT NULL ORDER BY date DESC LIMIT 1) as latest_vo2_max,
AVG(spo2) FILTER (WHERE date >= %s - INTERVAL '7 days') as avg_spo2_7d
FROM vitals_baseline
WHERE profile_id = %s AND date >= %s
""", (cutoff_date, cutoff_date, cutoff_date, cutoff_date, pid, cutoff_date, pid, cutoff_date))
stats = r2d(cur.fetchone())
# Calculate trends (7d vs 30d)
if stats['avg_rhr_7d'] and stats['avg_rhr_30d']:
if stats['avg_rhr_7d'] < stats['avg_rhr_30d'] - 2:
stats['trend_rhr'] = 'decreasing' # Good!
elif stats['avg_rhr_7d'] > stats['avg_rhr_30d'] + 2:
stats['trend_rhr'] = 'increasing' # Warning
else:
stats['trend_rhr'] = 'stable'
else:
stats['trend_rhr'] = None
if stats['avg_hrv_7d'] and stats['avg_hrv_30d']:
if stats['avg_hrv_7d'] > stats['avg_hrv_30d'] + 5:
stats['trend_hrv'] = 'increasing' # Good!
elif stats['avg_hrv_7d'] < stats['avg_hrv_30d'] - 5:
stats['trend_hrv'] = 'decreasing' # Warning
else:
stats['trend_hrv'] = 'stable'
else:
stats['trend_hrv'] = None
return stats
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Import: Apple Health CSV
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
def safe_int(value):
"""Safely parse string to int, handling decimals."""
if not value or value == '':
return None
try:
# If it has a decimal point, parse as float first then round to int
if '.' in str(value):
return int(float(value))
return int(value)
except (ValueError, TypeError):
return None
def safe_float(value):
"""Safely parse string to float."""
if not value or value == '':
return None
try:
return float(value)
except (ValueError, TypeError):
return None
@router.post("/import/apple-health")
async def import_apple_health_baseline(
file: UploadFile = File(...),
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""Import baseline vitals from Apple Health CSV export."""
pid = get_pid(x_profile_id)
content = await file.read()
decoded = content.decode('utf-8')
reader = csv.DictReader(io.StringIO(decoded))
inserted = 0
updated = 0
skipped = 0
errors = 0
error_details = [] # Collect error messages
with get_db() as conn:
cur = get_cursor(conn)
# Log available columns for debugging
first_row = True
for row in reader:
try:
if first_row:
logger.info(f"CSV Columns: {list(row.keys())}")
first_row = False
# Support both English and German column names
date_raw = row.get('Start') or row.get('Datum/Uhrzeit')
date = date_raw[:10] if date_raw else None
if not date:
logger.warning(f"Skipped row (no date): Start='{row.get('Start')}', Datum/Uhrzeit='{row.get('Datum/Uhrzeit')}'")
skipped += 1
continue
# Extract baseline vitals (support English + German column names)
rhr = row.get('Resting Heart Rate') or row.get('Ruhepuls (count/min)')
hrv = row.get('Heart Rate Variability') or row.get('Herzfrequenzvariabilität (ms)')
vo2 = row.get('VO2 Max') or row.get('VO2 max (ml/(kg·min))')
spo2 = row.get('Oxygen Saturation') or row.get('Blutsauerstoffsättigung (%)')
resp_rate = row.get('Respiratory Rate') or row.get('Atemfrequenz (count/min)')
# Skip if no baseline vitals
if not any([rhr, hrv, vo2, spo2, resp_rate]):
logger.warning(f"Skipped row {date} (no vitals): RHR={rhr}, HRV={hrv}, VO2={vo2}, SpO2={spo2}, RespRate={resp_rate}")
skipped += 1
continue
# Upsert
cur.execute("""
INSERT INTO vitals_baseline (
profile_id, date,
resting_hr, hrv, vo2_max, spo2, respiratory_rate,
source
) VALUES (%s, %s, %s, %s, %s, %s, %s, 'apple_health')
ON CONFLICT (profile_id, date)
DO UPDATE SET
resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_baseline.resting_hr),
hrv = COALESCE(EXCLUDED.hrv, vitals_baseline.hrv),
vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_baseline.vo2_max),
spo2 = COALESCE(EXCLUDED.spo2, vitals_baseline.spo2),
respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_baseline.respiratory_rate),
updated_at = NOW()
WHERE vitals_baseline.source != 'manual'
RETURNING (xmax = 0) AS inserted
""", (
pid, date,
safe_int(rhr),
safe_int(hrv),
safe_float(vo2),
safe_int(spo2),
safe_float(resp_rate)
))
result = cur.fetchone()
if result is None:
# WHERE clause prevented update (manual entry exists)
skipped += 1
elif result['inserted']:
inserted += 1
else:
updated += 1
except Exception as e:
import traceback
error_msg = f"Row {date if 'date' in locals() else 'unknown'}: {str(e)}"
error_details.append(error_msg)
logger.error(f"{error_msg}\n{traceback.format_exc()}")
errors += 1
return {
"inserted": inserted,
"updated": updated,
"skipped": skipped,
"errors": errors,
"error_details": error_details[:10] # Return first 10 errors
}
+427
View File
@@ -0,0 +1,427 @@
"""
Training Type Profiles - Rule Engine
Flexible rule evaluation system for activity quality assessment.
Issue: #15
Date: 2026-03-23
"""
from typing import Any, Dict, List, Optional, Callable
from datetime import datetime
import logging
logger = logging.getLogger(__name__)
class RuleEvaluator:
"""
Generic rule evaluator for arbitrary parameters and operators.
Supports flexible rule definitions with various operators:
- gte, lte, gt, lt: Comparison operators
- eq, neq: Equality operators
- between: Range checks
- in, not_in: Set membership
"""
# Operator definitions
OPERATORS: Dict[str, Callable[[Any, Any], bool]] = {
"gte": lambda actual, expected: actual is not None and actual >= expected,
"lte": lambda actual, expected: actual is not None and actual <= expected,
"gt": lambda actual, expected: actual is not None and actual > expected,
"lt": lambda actual, expected: actual is not None and actual < expected,
"eq": lambda actual, expected: actual == expected,
"neq": lambda actual, expected: actual != expected,
"between": lambda actual, expected: actual is not None and expected[0] <= actual <= expected[1],
"in": lambda actual, expected: actual in expected,
"not_in": lambda actual, expected: actual not in expected,
}
OPERATOR_SYMBOLS = {
"gte": "≥",
"lte": "≤",
"gt": ">",
"lt": "<",
"eq": "=",
"neq": "≠",
"between": "⟷",
"in": "∈",
"not_in": "∉",
}
@classmethod
def evaluate_rule(
cls,
rule: Dict,
activity: Dict,
parameters_registry: Dict[str, Dict]
) -> Dict:
"""
Evaluates a single rule against an activity.
Args:
rule: {
"parameter": str,
"operator": str,
"value": Any,
"weight": int,
"optional": bool,
"reason": str
}
activity: Activity data dictionary
parameters_registry: Mapping parameter_key -> config
Returns:
{
"passed": bool,
"actual_value": Any,
"expected_value": Any,
"parameter": str,
"operator": str,
"operator_symbol": str,
"reason": str,
"weight": int,
"skipped": bool (optional),
"error": str (optional)
}
"""
param_key = rule.get("parameter")
operator = rule.get("operator")
expected_value = rule.get("value")
weight = rule.get("weight", 1)
reason = rule.get("reason", "")
optional = rule.get("optional", False)
# Get parameter configuration
param_config = parameters_registry.get(param_key)
if not param_config:
return {
"passed": False,
"parameter": param_key,
"error": f"Unknown parameter: {param_key}"
}
# Extract value from activity
source_field = param_config.get("source_field", param_key)
actual_value = activity.get(source_field)
# Optional and not provided? → Pass
if optional and actual_value is None:
return {
"passed": True,
"actual_value": None,
"expected_value": expected_value,
"parameter": param_key,
"operator": operator,
"operator_symbol": cls.OPERATOR_SYMBOLS.get(operator, operator),
"reason": "Optional parameter not provided",
"weight": weight,
"skipped": True
}
# Required but not provided? → Fail
if actual_value is None:
return {
"passed": False,
"actual_value": None,
"expected_value": expected_value,
"parameter": param_key,
"operator": operator,
"operator_symbol": cls.OPERATOR_SYMBOLS.get(operator, operator),
"reason": reason or "Required parameter missing",
"weight": weight
}
# Apply operator
operator_func = cls.OPERATORS.get(operator)
if not operator_func:
return {
"passed": False,
"parameter": param_key,
"error": f"Unknown operator: {operator}"
}
try:
passed = operator_func(actual_value, expected_value)
except Exception as e:
logger.error(f"[RULE-ENGINE] Error evaluating rule {param_key}: {e}")
return {
"passed": False,
"parameter": param_key,
"error": f"Evaluation error: {str(e)}"
}
return {
"passed": passed,
"actual_value": actual_value,
"expected_value": expected_value,
"parameter": param_key,
"operator": operator,
"operator_symbol": cls.OPERATOR_SYMBOLS.get(operator, operator),
"reason": reason,
"weight": weight
}
@classmethod
def evaluate_rule_set(
cls,
rule_set: Dict,
activity: Dict,
parameters_registry: Dict[str, Dict]
) -> Dict:
"""
Evaluates a complete rule set (e.g., minimum_requirements).
Args:
rule_set: {
"enabled": bool,
"pass_strategy": str,
"pass_threshold": float,
"rules": [...]
}
activity: Activity data
parameters_registry: Parameter configurations
Returns:
{
"enabled": bool,
"passed": bool,
"score": float (0-1),
"rule_results": [...],
"pass_strategy": str,
"pass_threshold": float,
"failed_rules": [...]
}
"""
if not rule_set.get("enabled", False):
return {
"enabled": False,
"passed": True,
"score": 1.0,
"rule_results": [],
"failed_rules": []
}
rules = rule_set.get("rules", [])
pass_strategy = rule_set.get("pass_strategy", "weighted_score")
pass_threshold = rule_set.get("pass_threshold", 0.6)
rule_results = []
failed_rules = []
total_weight = 0
passed_weight = 0
# Evaluate each rule
for rule in rules:
result = cls.evaluate_rule(rule, activity, parameters_registry)
rule_results.append(result)
if result.get("skipped"):
continue
if result.get("error"):
logger.warning(f"[RULE-ENGINE] Rule error: {result['error']}")
continue
weight = result.get("weight", 1)
total_weight += weight
if result["passed"]:
passed_weight += weight
else:
failed_rules.append(result)
# Calculate score
score = passed_weight / total_weight if total_weight > 0 else 1.0
# Apply pass strategy
if pass_strategy == "all_must_pass":
passed = all(
r["passed"] for r in rule_results
if not r.get("skipped") and not r.get("error")
)
elif pass_strategy == "weighted_score":
passed = score >= pass_threshold
elif pass_strategy == "at_least_n":
n = rule_set.get("at_least_n", 1)
passed_count = sum(
1 for r in rule_results
if r["passed"] and not r.get("skipped")
)
passed = passed_count >= n
else:
passed = False
logger.warning(f"[RULE-ENGINE] Unknown pass strategy: {pass_strategy}")
return {
"enabled": True,
"passed": passed,
"score": round(score, 2),
"rule_results": rule_results,
"failed_rules": failed_rules,
"pass_strategy": pass_strategy,
"pass_threshold": pass_threshold
}
class IntensityZoneEvaluator:
"""
Evaluates heart rate zones and time distribution.
"""
@staticmethod
def evaluate(
zone_config: Dict,
activity: Dict,
user_profile: Dict
) -> Dict:
"""
Evaluates which HR zone the activity was in.
Args:
zone_config: intensity_zones configuration
activity: Activity data (with hr_avg)
user_profile: User profile (with hf_max)
Returns:
{
"enabled": bool,
"dominant_zone": str,
"avg_hr_percent": float,
"zone_color": str,
"zone_effect": str,
"duration_quality": float (0-1),
"recommendation": str
}
"""
if not zone_config.get("enabled", False):
return {"enabled": False}
avg_hr = activity.get("hr_avg")
user_max_hr = user_profile.get("hf_max", 180) # Default 180 if not set
if not avg_hr or not user_max_hr:
return {
"enabled": True,
"dominant_zone": "unknown",
"avg_hr_percent": None,
"recommendation": "Herzfrequenz-Daten fehlen"
}
avg_hr_percent = (avg_hr / user_max_hr) * 100
# Find matching zone
zones = zone_config.get("zones", [])
dominant_zone = None
for zone in zones:
zone_rules = zone.get("rules", [])
for rule in zone_rules:
if rule["parameter"] == "avg_hr_percent":
min_percent, max_percent = rule["value"]
if min_percent <= avg_hr_percent <= max_percent:
dominant_zone = zone
break
if dominant_zone:
break
if not dominant_zone:
return {
"enabled": True,
"dominant_zone": "out_of_range",
"avg_hr_percent": round(avg_hr_percent, 1),
"recommendation": "Herzfrequenz außerhalb definierter Zonen"
}
# Check duration quality
duration = activity.get("duration_min", 0)
target_duration = dominant_zone.get("target_duration_min", 30)
duration_quality = min(duration / target_duration, 1.0) if target_duration > 0 else 1.0
recommendation = f"Training in Zone '{dominant_zone['name']}' (Effekt: {dominant_zone['effect']})."
if duration < target_duration:
recommendation += f" Für optimale Wirkung: {target_duration}min empfohlen."
return {
"enabled": True,
"dominant_zone": dominant_zone.get("id"),
"dominant_zone_name": dominant_zone.get("name"),
"avg_hr_percent": round(avg_hr_percent, 1),
"zone_color": dominant_zone.get("color"),
"zone_effect": dominant_zone.get("effect"),
"duration_quality": round(duration_quality, 2),
"target_duration_min": target_duration,
"actual_duration_min": duration,
"recommendation": recommendation
}
class TrainingEffectsEvaluator:
"""
Evaluates which abilities are trained by the activity.
"""
@staticmethod
def evaluate(
effects_config: Dict,
activity: Dict,
intensity_zone_result: Optional[Dict] = None
) -> Dict:
"""
Evaluates training effects (abilities trained).
Args:
effects_config: training_effects configuration
activity: Activity data
intensity_zone_result: Result from intensity zone evaluation
Returns:
{
"enabled": bool,
"abilities_trained": [...],
"total_training_load": float
}
"""
if not effects_config.get("enabled", False):
return {"enabled": False}
abilities_trained = []
# Use default effects if no conditional matching
default_effects = effects_config.get("default_effects", {})
primary_abilities = default_effects.get("primary_abilities", [])
secondary_abilities = default_effects.get("secondary_abilities", [])
# Calculate quality factor (simplified for now)
quality_factor = 1.0
# Primary abilities
for ability in primary_abilities:
abilities_trained.append({
"category": ability["category"],
"ability": ability["ability"],
"intensity": ability["intensity"],
"quality": quality_factor,
"contribution": ability["intensity"] * quality_factor,
"type": "primary"
})
# Secondary abilities
for ability in secondary_abilities:
abilities_trained.append({
"category": ability["category"],
"ability": ability["ability"],
"intensity": ability["intensity"],
"quality": quality_factor * 0.7, # Secondary = 70%
"contribution": ability["intensity"] * quality_factor * 0.7,
"type": "secondary"
})
total_training_load = sum(a["contribution"] for a in abilities_trained)
return {
"enabled": True,
"abilities_trained": abilities_trained,
"total_training_load": round(total_training_load, 2),
"metabolic_focus": effects_config.get("metabolic_focus", []),
"muscle_groups": effects_config.get("muscle_groups", [])
}
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env python3
"""
Manual Migration 024 Runner
Run this to manually execute Migration 024 if it didn't run automatically.
"""
import psycopg2
import os
from psycopg2.extras import RealDictCursor
# Database connection
DB_HOST = os.getenv('DB_HOST', 'localhost')
DB_PORT = os.getenv('DB_PORT', '5432')
DB_NAME = os.getenv('DB_NAME', 'bodytrack')
DB_USER = os.getenv('DB_USER', 'bodytrack')
DB_PASS = os.getenv('DB_PASSWORD', '')
def main():
print("🔧 Manual Migration 024 Runner")
print("=" * 60)
# Connect to database
conn = psycopg2.connect(
host=DB_HOST,
port=DB_PORT,
dbname=DB_NAME,
user=DB_USER,
password=DB_PASS
)
conn.autocommit = False
cur = conn.cursor(cursor_factory=RealDictCursor)
try:
# Check if table exists
cur.execute("""
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_name = 'goal_type_definitions'
)
""")
exists = cur.fetchone()['exists']
if exists:
print("✓ goal_type_definitions table already exists")
# Check if it has data
cur.execute("SELECT COUNT(*) as count FROM goal_type_definitions")
count = cur.fetchone()['count']
print(f"✓ Table has {count} entries")
if count > 0:
print("\n📊 Existing Goal Types:")
cur.execute("""
SELECT type_key, label_de, unit, is_system, is_active
FROM goal_type_definitions
ORDER BY is_system DESC, label_de
""")
for row in cur.fetchall():
status = "SYSTEM" if row['is_system'] else "CUSTOM"
active = "ACTIVE" if row['is_active'] else "INACTIVE"
print(f" - {row['type_key']}: {row['label_de']} ({row['unit']}) [{status}] [{active}]")
print("\n✅ Migration 024 is already complete!")
return
# Run migration
print("\n🚀 Running Migration 024...")
with open('migrations/024_goal_type_registry.sql', 'r', encoding='utf-8') as f:
migration_sql = f.read()
cur.execute(migration_sql)
conn.commit()
print("✅ Migration 024 executed successfully!")
# Verify
cur.execute("SELECT COUNT(*) as count FROM goal_type_definitions")
count = cur.fetchone()['count']
print(f"✓ {count} goal types seeded")
# Show created types
cur.execute("""
SELECT type_key, label_de, unit, is_system
FROM goal_type_definitions
WHERE is_active = true
ORDER BY is_system DESC, label_de
""")
print("\n📊 Created Goal Types:")
for row in cur.fetchall():
status = "SYSTEM" if row['is_system'] else "CUSTOM"
print(f" - {row['type_key']}: {row['label_de']} ({row['unit']}) [{status}]")
# Update schema_migrations
cur.execute("""
INSERT INTO schema_migrations (filename, executed_at)
VALUES ('024_goal_type_registry.sql', NOW())
ON CONFLICT (filename) DO NOTHING
""")
conn.commit()
print("\n✅ Migration 024 complete!")
except Exception as e:
conn.rollback()
print(f"\n❌ Error: {e}")
import traceback
traceback.print_exc()
finally:
cur.close()
conn.close()
if __name__ == '__main__':
main()
+595
View File
@@ -0,0 +1,595 @@
# Zielesystem: Vereinheitlichte Analyse beider Fachkonzepte
**Datum:** 26. März 2026
**Basis:**
- `.claude/docs/functional/GOALS_VITALS.md` (v9e Spec)
- `.claude/docs/functional/mitai_jinkendo_konzept_diagramme_auswertungen_v2.md`
---
## 1. Wichtige Erkenntnis: BEIDE Konzepte sind komplementär!
### GOALS_VITALS.md definiert:
- **Konkrete Zielwerte** (z.B. "82kg bis 30.06.2026")
- 8 Zieltypen (Gewicht, KF%, VO2Max, etc.)
- Primär-/Nebenziel-Konzept
- Trainingsphasen (automatische Erkennung)
- Aktive Tests (Cooper, Liegestütze, etc.)
- 13 neue KI-Platzhalter
### Konzept v2 definiert:
- **Goal Modes** (strategische Ausrichtung: weight_loss, strength, etc.)
- Score-Gewichtung je Goal Mode
- Chart-Priorisierung je Goal Mode
- Regelbasierte Interpretationen
### Zusammenspiel:
```
Goal MODE (v2) → "weight_loss" (strategische Ausrichtung)
↓
Primary GOAL (v9e) → "82kg bis 30.06.2026" (konkretes Ziel)
Secondary GOAL → "16% Körperfett"
↓
Training PHASE (v9e) → "Kaloriendefizit" (automatisch erkannt)
↓
Score Weights (v2) → body_progress: 0.30, nutrition: 0.25, ...
↓
Charts (v2) → Zeigen gewichtete Scores + Fortschritt zu Zielen
```
---
## 2. Zwei-Ebenen-Architektur
### Ebene 1: STRATEGIC (Goal Modes aus v2)
**Was:** Grundsätzliche Trainingsausrichtung
**Werte:** weight_loss, strength, endurance, recomposition, health
**Zweck:** Bestimmt Score-Gewichtung und Interpretations-Kontext
**Beispiel:** "Ich will Kraft aufbauen" → mode: strength
### Ebene 2: TACTICAL (Goal Targets aus v9e)
**Was:** Konkrete messbare Ziele
**Werte:** "82kg bis 30.06.2026", "VO2Max 55 ml/kg/min", "50 Liegestütze"
**Zweck:** Fortschritts-Tracking, Prognosen, Motivation
**Beispiel:** "Ich will 82kg wiegen" → target: Gewichtsziel
### Beide zusammen = Vollständiges Zielesystem
---
## 3. Überarbeitetes Datenmodell
### Tabelle: `profiles` (erweitern)
```sql
-- Strategic Goal Mode (aus v2)
ALTER TABLE profiles ADD COLUMN goal_mode VARCHAR(50) DEFAULT 'health';
COMMENT ON COLUMN profiles.goal_mode IS
'Strategic goal mode: weight_loss, strength, endurance, recomposition, health.
Determines score weights and interpretation context.';
```
### Tabelle: `goals` (NEU, aus v9e)
```sql
CREATE TABLE goals (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
-- Goal Classification
goal_type VARCHAR(50) NOT NULL, -- weight, body_fat, lean_mass, vo2max, strength, flexibility, bp, rhr
is_primary BOOLEAN DEFAULT false,
status VARCHAR(20) DEFAULT 'active', -- draft, active, reached, abandoned, expired
-- Target Values
target_value DECIMAL(10,2),
current_value DECIMAL(10,2),
start_value DECIMAL(10,2),
unit VARCHAR(20), -- kg, %, ml/kg/min, bpm, mmHg, cm, reps
-- Timeline
start_date DATE DEFAULT CURRENT_DATE,
target_date DATE,
reached_date DATE,
-- Metadata
name VARCHAR(100), -- z.B. "Sommerfigur 2026"
description TEXT,
-- Progress Tracking
progress_pct DECIMAL(5,2), -- Auto-calculated: (current - start) / (target - start) * 100
-- Timestamps
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
-- Constraints
CHECK (progress_pct >= 0 AND progress_pct <= 100),
CHECK (status IN ('draft', 'active', 'reached', 'abandoned', 'expired'))
);
-- Only one primary goal per profile
CREATE UNIQUE INDEX idx_goals_primary ON goals(profile_id, is_primary) WHERE is_primary = true;
-- Index for active goals lookup
CREATE INDEX idx_goals_active ON goals(profile_id, status) WHERE status = 'active';
```
### Tabelle: `training_phases` (NEU, aus v9e)
```sql
CREATE TABLE training_phases (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
-- Phase Type
phase_type VARCHAR(50) NOT NULL,
-- Werte: calorie_deficit, calorie_maintenance, calorie_surplus,
-- conditioning, hiit, max_strength, regeneration, competition_prep
-- Detection
detected_automatically BOOLEAN DEFAULT false,
confidence_score DECIMAL(3,2), -- 0.00-1.00
-- Status
status VARCHAR(20) DEFAULT 'suggested', -- suggested, confirmed, active, ended
-- Timeline
start_date DATE,
end_date DATE,
-- Metadata
detection_reason TEXT, -- Why was this phase detected?
user_notes TEXT,
-- Timestamps
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
-- Only one active phase per profile
CREATE UNIQUE INDEX idx_phases_active ON training_phases(profile_id, status) WHERE status = 'active';
```
### Tabelle: `fitness_tests` (NEU, aus v9e)
```sql
CREATE TABLE fitness_tests (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
-- Test Type
test_type VARCHAR(50) NOT NULL,
-- Standard: cooper, step_test, pushups, squats, sit_reach, balance, grip_strength
-- Custom: user_defined
-- Result
result_value DECIMAL(10,2) NOT NULL,
result_unit VARCHAR(20) NOT NULL, -- meters, bpm, reps, cm, seconds, kg
-- Test Date
test_date DATE NOT NULL,
-- Evaluation
norm_category VARCHAR(30), -- very_good, good, average, needs_improvement
percentile DECIMAL(5,2), -- Where user ranks vs. norm (0-100)
-- Trend
improvement_vs_last DECIMAL(10,2), -- % change from previous test
-- Metadata
notes TEXT,
conditions TEXT, -- e.g., "Nach 3h Schlaf, erkältet"
-- Next Test Recommendation
recommended_retest_date DATE,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE INDEX idx_fitness_tests_profile_type ON fitness_tests(profile_id, test_type, test_date DESC);
```
---
## 4. Vereinheitlichte API-Struktur
### Goal Modes (Strategic)
```python
# routers/goals.py
@router.get("/modes")
def get_goal_modes():
"""Get all strategic goal modes with score weights."""
return GOAL_MODES # From v2 concept
@router.post("/set-mode")
def set_goal_mode(goal_mode: str, session=Depends(require_auth)):
"""Set user's strategic goal mode."""
# Updates profiles.goal_mode
```
### Goal Targets (Tactical)
```python
@router.get("/targets")
def get_goal_targets(session=Depends(require_auth)):
"""Get all active goal targets."""
profile_id = session['profile_id']
# Returns list from goals table
# Includes: primary + all secondary goals
@router.post("/targets")
def create_goal_target(goal: GoalCreate, session=Depends(require_auth)):
"""Create a new goal target."""
# Inserts into goals table
# Auto-calculates progress_pct
@router.get("/targets/{goal_id}")
def get_goal_detail(goal_id: str, session=Depends(require_auth)):
"""Get detailed goal info with history."""
# Returns goal + progress history + prognosis
@router.put("/targets/{goal_id}/progress")
def update_goal_progress(goal_id: str, session=Depends(require_auth)):
"""Recalculate goal progress."""
# Auto-called after new measurements
# Updates current_value, progress_pct
@router.post("/targets/{goal_id}/reach")
def mark_goal_reached(goal_id: str, session=Depends(require_auth)):
"""Mark goal as reached."""
# Sets status='reached', reached_date=today
```
### Training Phases
```python
@router.get("/phases/current")
def get_current_phase(session=Depends(require_auth)):
"""Get active training phase."""
@router.get("/phases/detect")
def detect_phase(session=Depends(require_auth)):
"""Run phase detection algorithm."""
# Analyzes last 14 days
# Returns suggested phase + confidence + reasoning
@router.post("/phases/confirm")
def confirm_phase(phase_id: str, session=Depends(require_auth)):
"""Confirm detected phase."""
# Sets status='active'
```
### Fitness Tests
```python
@router.get("/tests/types")
def get_test_types():
"""Get all available fitness tests."""
@router.post("/tests/{test_type}/execute")
def record_test_result(
test_type: str,
result_value: float,
result_unit: str,
session=Depends(require_auth)
):
"""Record a fitness test result."""
# Inserts into fitness_tests
# Auto-calculates norm_category, percentile, improvement
@router.get("/tests/due")
def get_due_tests(session=Depends(require_auth)):
"""Get tests that are due for retesting."""
```
---
## 5. Neue KI-Platzhalter (kombiniert aus beiden Konzepten)
### Strategic (aus v2)
```python
{{goal_mode}} # "weight_loss"
{{goal_mode_label}} # "Gewichtsreduktion"
{{goal_mode_description}} # "Fettabbau bei Erhalt der Magermasse"
```
### Tactical - Primary Goal (aus v9e)
```python
{{primary_goal_type}} # "weight"
{{primary_goal_name}} # "Sommerfigur 2026"
{{primary_goal_target}} # "82 kg bis 30.06.2026"
{{primary_goal_current}} # "85.2 kg"
{{primary_goal_start}} # "86.1 kg"
{{primary_goal_progress_pct}} # "72%"
{{primary_goal_progress_text}} # "72% erreicht (4 kg von 5,5 kg)"
{{primary_goal_days_remaining}} # "45 Tage"
{{primary_goal_prognosis}} # "Ziel voraussichtlich in 6 Wochen erreicht (3 Wochen früher!)"
{{primary_goal_on_track}} # "true"
```
### Tactical - Secondary Goals (aus v9e)
```python
{{secondary_goals_count}} # "2"
{{secondary_goals_list}} # "16% Körperfett, VO2Max 55 ml/kg/min"
{{secondary_goal_1_type}} # "body_fat"
{{secondary_goal_1_progress}} # "45%"
```
### Training Phase (aus v9e)
```python
{{current_phase}} # "calorie_deficit"
{{current_phase_label}} # "Kaloriendefizit"
{{phase_since}} # "seit 14 Tagen"
{{phase_confidence}} # "0.92"
{{phase_recommendation}} # "Krafttraining erhalten, Cardio moderat, Proteinzufuhr 2g/kg"
{{phase_detected_automatically}} # "true"
```
### Fitness Tests (aus v9e)
```python
{{test_last_cooper}} # "2.800m (VO2Max ~52) vor 3 Wochen"
{{test_last_cooper_date}} # "2026-03-05"
{{test_last_cooper_result}} # "2800"
{{test_last_cooper_vo2max}} # "52.3"
{{test_last_cooper_category}} # "good"
{{test_due_list}} # "Sit & Reach (seit 5 Wochen), Liegestütze (seit 4 Wochen)"
{{test_next_recommended}} # "Cooper-Test (in 2 Wochen fällig)"
{{fitness_score_overall}} # "72/100"
{{fitness_score_endurance}} # "good"
{{fitness_score_strength}} # "average"
{{fitness_score_flexibility}} # "needs_improvement"
```
### GESAMT: 35+ neue Platzhalter aus v9e
Plus die 84 aus v2 = **120+ neue Platzhalter total**
---
## 6. Überarbeitete Implementierungs-Roadmap
### Phase 0a: Minimal Goal System (3-4h) ⭐ **JETZT**
**Strategic Layer:**
- DB: `goal_mode` in profiles
- Backend: GOAL_MODES aus v2
- API: GET/SET goal mode
- UI: Goal Mode Selector (5 Modi)
**Tactical Layer:**
- DB: `goals` table
- API: CRUD für goal targets
- UI: Goal Management Page (minimal)
- Liste aktiver Ziele
- Fortschrittsbalken
- "+ Neues Ziel" Button
**Aufwand:** 3-4h (erweitert wegen Tactical Layer)
---
### Phase 0b: Goal-Aware Placeholders (16-20h)
**Strategic Placeholders:**
```python
{{goal_mode}} # Aus profiles.goal_mode
{{goal_mode_label}} # Aus GOAL_MODES mapping
```
**Tactical Placeholders:**
```python
{{primary_goal_type}} # Aus goals WHERE is_primary=true
{{primary_goal_target}}
{{primary_goal_progress_pct}}
{{primary_goal_prognosis}} # Berechnet aus Trend
```
**Score Calculations (goal-aware):**
```python
def get_body_progress_score(profile_id: str) -> str:
profile = get_profile_data(profile_id)
goal_mode = profile.get('goal_mode', 'health')
# Get weights from v2 concept
weights = GOAL_MODES[goal_mode]['score_weights']
# Calculate sub-scores
fm_score = calculate_fm_progress(profile_id)
lbm_score = calculate_lbm_progress(profile_id)
# Weight according to goal mode
if goal_mode == 'weight_loss':
total = 0.50 * fm_score + 0.30 * weight_score + 0.20 * lbm_score
elif goal_mode == 'strength':
total = 0.60 * lbm_score + 0.30 * fm_score + 0.10 * weight_score
# ...
return f"{int(total)}/100"
```
---
### Phase 0c: Training Phases (4-6h) **PARALLEL**
**DB:**
- `training_phases` table
**Detection Algorithm:**
```python
def detect_current_phase(profile_id: str) -> dict:
"""Detects training phase from last 14 days of data."""
# Analyze data
kcal_balance = get_kcal_balance_14d(profile_id)
training_dist = get_training_distribution_14d(profile_id)
weight_trend = get_weight_trend_14d(profile_id)
hrv_avg = get_hrv_avg_14d(profile_id)
volume_change = get_volume_change_14d(profile_id)
# Phase Detection Rules
if kcal_balance < -300 and weight_trend < 0:
return {
'phase': 'calorie_deficit',
'confidence': 0.85,
'reason': f'Avg kcal balance {kcal_balance}/day, weight -0.5kg/week'
}
if training_dist['endurance'] > 60 and vo2max_trend > 0:
return {
'phase': 'conditioning',
'confidence': 0.78,
'reason': f'{training_dist["endurance"]}% cardio, VO2max improving'
}
if volume_change < -40 and hrv_avg < hrv_baseline * 0.85:
return {
'phase': 'regeneration',
'confidence': 0.92,
'reason': f'Volume -40%, HRV below baseline, recovery needed'
}
# Default
return {
'phase': 'maintenance',
'confidence': 0.50,
'reason': 'No clear pattern detected'
}
```
**API:**
- GET /phases/current
- GET /phases/detect
- POST /phases/confirm
**UI:**
- Dashboard Badge: "📊 Phase: Kaloriendefizit"
- Phase Detection Banner: "Wir haben erkannt: Kaloriendefizit-Phase. Stimmt das?"
---
### Phase 0d: Fitness Tests (4-6h) **SPÄTER**
**DB:**
- `fitness_tests` table
**Test Definitions:**
```python
FITNESS_TESTS = {
'cooper': {
'name': 'Cooper-Test',
'description': '12 Minuten laufen, maximale Distanz',
'unit': 'meters',
'interval_weeks': 6,
'norm_tables': { # Simplified
'male_30-39': {'very_good': 2800, 'good': 2500, 'average': 2200},
'female_30-39': {'very_good': 2500, 'good': 2200, 'average': 1900}
},
'calculate_vo2max': lambda distance: (distance - 504.9) / 44.73
},
'pushups': {
'name': 'Liegestütze-Test',
'description': 'Maximale Anzahl ohne Pause',
'unit': 'reps',
'interval_weeks': 4,
'norm_tables': { ... }
},
# ... weitere Tests
}
```
**UI:**
- Tests Page mit Testliste
- Test Execution Flow (Anleitung → Eingabe → Auswertung)
- Test History mit Trend-Chart
---
## 7. Priorisierte Reihenfolge
### SOFORT (3-4h)
**Phase 0a:** Minimal Goal System (Strategic + Tactical)
- Basis für alles andere
- User kann Ziele setzen
- Score-Berechnungen können goal_mode nutzen
### DIESE WOCHE (16-20h)
**Phase 0b:** Goal-Aware Placeholders
- 84 Platzhalter aus v2
- 35+ Platzhalter aus v9e
- **TOTAL: 120+ Platzhalter**
### PARALLEL (4-6h)
**Phase 0c:** Training Phases
- Automatische Erkennung
- Phase-aware Recommendations
### SPÄTER (4-6h)
**Phase 0d:** Fitness Tests
- Enhancement, nicht kritisch für Charts
---
## 8. Kritische Erkenntnisse
### 1. GOALS_VITALS.md ist detaillierter
- Konkrete Implementierungs-Specs
- DB-Schema-Vorschläge
- 13 definierte KI-Platzhalter
- **ABER:** Fehlt Score-Gewichtung (das hat v2)
### 2. Konzept v2 ist strategischer
- Goal Modes mit Score-Gewichtung
- Chart-Interpretationen
- Regelbasierte Logik
- **ABER:** Fehlt konkrete Ziel-Tracking (das hat v9e)
### 3. Beide zusammen = Vollständig
- v2 (Goal Modes) + v9e (Goal Targets) = Komplettes Zielesystem
- v2 (Scores) + v9e (Tests) = Vollständiges Assessment
- v2 (Charts) + v9e (Phases) = Kontext-aware Visualisierung
### 4. Meine ursprüngliche Analyse war incomplete
- Ich hatte nur v2 betrachtet
- v9e fügt kritische Details hinzu
- **Neue Gesamt-Schätzung:** 120+ Platzhalter (statt 84)
---
## 9. Aktualisierte Empfehlung
**JA zu Phase 0a (Minimal Goal System), ABER erweitert:**
### Was Phase 0a umfassen muss (3-4h):
1. **Strategic Layer (aus v2):**
- goal_mode in profiles
- GOAL_MODES Definition
- GET/SET endpoints
2. **Tactical Layer (aus v9e):**
- goals Tabelle
- CRUD für Ziele
- Fortschritts-Berechnung
3. **UI:**
- Goal Mode Selector (Settings)
- Goal Management Page (Basic)
- Dashboard Goal Widget
### Was kann warten:
- Training Phases → Phase 0c (parallel)
- Fitness Tests → Phase 0d (später)
- Vollständige Test-Integration → v9f
---
## 10. Nächste Schritte
**JETZT:**
1. Phase 0a implementieren (3-4h)
- Strategic + Tactical Goal System
2. Dann Phase 0b (Goal-Aware Placeholders, 16-20h)
3. Parallel Phase 0c (Training Phases, 4-6h)
**Soll ich mit Phase 0a (erweitert) starten?**
- Beide Goal-Konzepte integriert
- Ready für 120+ Platzhalter
- Basis für intelligentes Coach-System
**Commit:** ae93b9d (muss aktualisiert werden)
**Neue Analyse:** GOALS_SYSTEM_UNIFIED_ANALYSIS.md
+538
View File
@@ -0,0 +1,538 @@
# Zielesystem: Prioritäts-Analyse
**Datum:** 26. März 2026
**Frage:** Zielesystem vor oder nach Platzhaltern/Charts?
**Antwort:** **Minimales Zielesystem VOR Platzhaltern, volles System parallel**
---
## 1. Kritische Erkenntnis aus Fachkonzept
### Zitat Fachkonzept (Zeile 20-28):
> **Wichtig ist, dass das System zielabhängig interpretiert:**
> - Gewichtsreduktion
> - Muskel-/Kraftaufbau
> - Konditions-/Ausdaueraufbau
> - Körperrekomposition
> - allgemeine Gesundheit
>
> **Dasselbe Rohsignal kann je nach Ziel anders bewertet werden.**
> Ein Kaloriendefizit ist z. B. bei Gewichtsreduktion oft positiv,
> bei Kraftaufbau aber potenziell hinderlich.
### Konsequenz
❌ **Charts OHNE Zielesystem = falsche Interpretationen**
✅ **Charts MIT Zielesystem = korrekte, zielspezifische Aussagen**
---
## 2. Abhängigkeits-Matrix
### Was hängt vom Zielesystem ab?
| Komponente | Zielabhängig? | Beispiel |
|------------|---------------|----------|
| **Rohdaten-Charts** | ❌ Nein | Gewichtsverlauf, Umfänge-Trend |
| **Score-Gewichtung** | ✅ JA | Body Progress Score: 30% bei weight_loss, 20% bei strength |
| **Interpretationen** | ✅ JA | Kaloriendefizit: "gut" bei weight_loss, "kritisch" bei strength |
| **Hinweise** | ✅ JA | "Gewicht stagniert" → bei weight_loss: Warnung, bei strength: egal |
| **Platzhalter (Berechnungen)** | ⚠️ TEILWEISE | Trends: Nein, Scores: JA |
| **KI-Prompts** | ✅ JA | Analyse-Kontext ändert sich komplett |
### Fachkonzept: Score-Gewichtung (Zeile 185-216)
```yaml
score_weights:
weight_loss:
body_progress: 0.30 # Körper wichtig
nutrition: 0.25
activity: 0.20
recovery: 0.15
health_risk: 0.10
strength:
body_progress: 0.20
nutrition: 0.25
activity: 0.30 # Training wichtiger
recovery: 0.20
health_risk: 0.05 # Weniger kritisch
endurance:
body_progress: 0.10 # Körper unwichtiger
activity: 0.35 # Training am wichtigsten
recovery: 0.25 # Recovery sehr wichtig
```
### Beispiel: Body Progress Score
**OHNE Zielesystem:**
```python
def calculate_body_progress_score():
# Generisch, für niemanden wirklich passend
fm_delta_score = calculate_fm_change() # -5kg
lbm_delta_score = calculate_lbm_change() # -2kg
return (fm_delta_score + lbm_delta_score) / 2
# Score: 50/100 (FM gut runter, aber LBM auch runter)
```
**MIT Zielesystem:**
```python
def calculate_body_progress_score(goal_mode):
fm_delta_score = calculate_fm_change() # -5kg
lbm_delta_score = calculate_lbm_change() # -2kg
if goal_mode == "weight_loss":
# FM runter: sehr gut, LBM runter: tolerierbar wenn nicht zu viel
return 0.70 * fm_delta_score + 0.30 * lbm_delta_score
# Score: 78/100 (FM wichtiger, LBM-Verlust weniger kritisch)
elif goal_mode == "strength":
# FM runter: ok, LBM runter: SEHR SCHLECHT
return 0.30 * fm_delta_score + 0.70 * lbm_delta_score
# Score: 32/100 (LBM-Verlust ist Hauptproblem!)
elif goal_mode == "recomposition":
# FM runter: gut, LBM runter: schlecht
return 0.50 * fm_delta_score + 0.50 * lbm_delta_score
# Score: 50/100 (ausgewogen bewertet)
```
**Ergebnis:**
- Gleiche Daten (-5kg FM, -2kg LBM)
- ABER: 78/100 bei weight_loss, 32/100 bei strength
- **Ohne Ziel: völlig falsche Bewertung!**
---
## 3. Ziel-Erkennung aus Daten
### Fachkonzept erwähnt dies NICHT explizit, aber logisch ableitbar:
**Pattern-Erkennung:**
```python
def suggest_goal_from_data(profile_id):
"""Schlägt Ziel basierend auf Daten-Mustern vor."""
# Analyse der letzten 28 Tage
training_types = get_training_distribution_28d(profile_id)
nutrition = get_nutrition_pattern_28d(profile_id)
body_changes = get_body_changes_28d(profile_id)
# Pattern 1: Viel Kraft + viel Protein + LBM steigt
if (training_types['strength'] > 60% and
nutrition['protein_g_per_kg'] > 1.8 and
body_changes['lbm_trend'] > 0):
return {
'suggested_goal': 'strength',
'confidence': 'high',
'reasoning': 'Krafttraining dominant + hohe Proteinzufuhr + Muskelaufbau erkennbar'
}
# Pattern 2: Viel Cardio + Kaloriendefizit + Gewicht sinkt
if (training_types['endurance'] > 50% and
nutrition['kcal_balance_avg'] < -300 and
body_changes['weight_trend'] < 0):
return {
'suggested_goal': 'weight_loss',
'confidence': 'high',
'reasoning': 'Ausdauertraining + Kaloriendefizit + Gewichtsverlust'
}
# Pattern 3: Mixed Training + Protein hoch + Gewicht stabil + Rekomposition
if (training_types['mixed'] == True and
nutrition['protein_g_per_kg'] > 1.6 and
abs(body_changes['weight_trend']) < 0.05 and
body_changes['fm_trend'] < 0 and
body_changes['lbm_trend'] > 0):
return {
'suggested_goal': 'recomposition',
'confidence': 'medium',
'reasoning': 'Gemischtes Training + Rekomposition sichtbar (FM↓, LBM↑)'
}
# Default: Nicht genug Muster erkennbar
return {
'suggested_goal': 'health',
'confidence': 'low',
'reasoning': 'Keine klaren Muster erkennbar, gesundheitsorientiertes Training angenommen'
}
```
### Voraussetzungen für Ziel-Erkennung:
1. ✅ Mindestens 21-28 Tage Daten
2. ✅ Training-Type Distribution
3. ✅ Ernährungs-Pattern
4. ✅ Körper-Trends (FM, LBM, Gewicht)
5. ✅ Berechnet → **braucht Platzhalter!**
**ABER:** Ziel-Erkennung ist **nachgelagert**, nicht Voraussetzung.
---
## 4. Empfohlene Implementierungs-Strategie
### Hybrid-Ansatz: Minimal-Ziele SOFORT, Voll-System parallel
## Phase 0a: Minimal-Zielesystem (2-3h) ⭐ **START HIER**
### Ziel
User kann manuell Ziel setzen, System nutzt es für Berechnungen.
### Implementierung
**1. DB-Schema erweitern:**
```sql
-- Migration 023
ALTER TABLE profiles ADD COLUMN goal_mode VARCHAR(50) DEFAULT 'health';
ALTER TABLE profiles ADD COLUMN goal_weight DECIMAL(5,2);
ALTER TABLE profiles ADD COLUMN goal_bf_pct DECIMAL(4,1);
ALTER TABLE profiles ADD COLUMN goal_set_date DATE;
ALTER TABLE profiles ADD COLUMN goal_target_date DATE;
COMMENT ON COLUMN profiles.goal_mode IS
'Primary goal: weight_loss, strength, endurance, recomposition, health';
```
**2. Goal-Mode Konstanten:**
```python
# backend/goals.py (NEU)
GOAL_MODES = {
'weight_loss': {
'label': 'Gewichtsreduktion',
'description': 'Fettabbau bei Erhalt der Magermasse',
'score_weights': {
'body_progress': 0.30,
'nutrition': 0.25,
'activity': 0.20,
'recovery': 0.15,
'health_risk': 0.10
},
'focus_areas': ['fettmasse', 'gewichtstrend', 'kalorienbilanz', 'protein_sicherung']
},
'strength': {
'label': 'Kraftaufbau',
'description': 'Muskelaufbau und Kraftsteigerung',
'score_weights': {
'body_progress': 0.20,
'nutrition': 0.25,
'activity': 0.30,
'recovery': 0.20,
'health_risk': 0.05
},
'focus_areas': ['trainingsqualitaet', 'protein', 'lbm', 'recovery']
},
'endurance': {
'label': 'Ausdaueraufbau',
'description': 'Kondition und VO2max verbessern',
'score_weights': {
'body_progress': 0.10,
'nutrition': 0.20,
'activity': 0.35,
'recovery': 0.25,
'health_risk': 0.10
},
'focus_areas': ['trainingsvolumen', 'intensitaetsverteilung', 'vo2max', 'recovery']
},
'recomposition': {
'label': 'Körperrekomposition',
'description': 'Fettabbau bei gleichzeitigem Muskelaufbau',
'score_weights': {
'body_progress': 0.30,
'nutrition': 0.25,
'activity': 0.25,
'recovery': 0.15,
'health_risk': 0.05
},
'focus_areas': ['lbm', 'fettmasse', 'protein', 'trainingsqualitaet']
},
'health': {
'label': 'Allgemeine Gesundheit',
'description': 'Ausgeglichenes Gesundheits- und Fitnesstraining',
'score_weights': {
'body_progress': 0.20,
'nutrition': 0.20,
'activity': 0.20,
'recovery': 0.20,
'health_risk': 0.20
},
'focus_areas': ['bewegung', 'blutdruck', 'schlaf', 'gewicht', 'regelmaessigkeit']
}
}
```
**3. API-Endpoint:**
```python
# routers/goals.py (NEU)
from fastapi import APIRouter, Depends
from auth import require_auth
from goals import GOAL_MODES
router = APIRouter(prefix="/api/goals", tags=["goals"])
@router.get("/modes")
def get_goal_modes():
"""Return all available goal modes with descriptions."""
return GOAL_MODES
@router.get("/current")
def get_current_goal(session: dict = Depends(require_auth)):
"""Get user's current goal settings."""
profile_id = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""SELECT goal_mode, goal_weight, goal_bf_pct,
goal_set_date, goal_target_date
FROM profiles WHERE id=%s""",
(profile_id,)
)
row = r2d(cur.fetchone())
return {
**row,
'mode_config': GOAL_MODES.get(row['goal_mode'], GOAL_MODES['health'])
}
@router.post("/set")
def set_goal(
goal_mode: str,
goal_weight: Optional[float] = None,
goal_bf_pct: Optional[float] = None,
target_date: Optional[str] = None,
session: dict = Depends(require_auth)
):
"""Set user's goal."""
if goal_mode not in GOAL_MODES:
raise HTTPException(400, f"Invalid goal_mode. Must be one of: {list(GOAL_MODES.keys())}")
profile_id = session['profile_id']
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""UPDATE profiles
SET goal_mode=%s, goal_weight=%s, goal_bf_pct=%s,
goal_set_date=CURRENT_DATE, goal_target_date=%s
WHERE id=%s""",
(goal_mode, goal_weight, goal_bf_pct, target_date, profile_id)
)
conn.commit()
return {"success": True, "goal_mode": goal_mode}
```
**4. Frontend UI (Settings.jsx):**
```jsx
// Minimal Goal Selector
function GoalSettings() {
const [goalModes, setGoalModes] = useState({})
const [currentGoal, setCurrentGoal] = useState(null)
const [selectedMode, setSelectedMode] = useState('health')
useEffect(() => {
loadGoalModes()
loadCurrentGoal()
}, [])
const loadGoalModes = async () => {
const modes = await api.getGoalModes()
setGoalModes(modes)
}
const loadCurrentGoal = async () => {
const goal = await api.getCurrentGoal()
setCurrentGoal(goal)
setSelectedMode(goal.goal_mode || 'health')
}
const saveGoal = async () => {
await api.setGoal({
goal_mode: selectedMode,
goal_weight: goalWeight,
goal_bf_pct: goalBfPct,
target_date: targetDate
})
loadCurrentGoal()
}
return (
<div className="card">
<h2>🎯 Trainingsziel</h2>
<div className="form-row">
<label>Hauptziel</label>
<select value={selectedMode} onChange={e => setSelectedMode(e.target.value)}>
{Object.entries(goalModes).map(([key, config]) => (
<option key={key} value={key}>
{config.label}
</option>
))}
</select>
<p style={{fontSize: 12, color: 'var(--text3)'}}>
{goalModes[selectedMode]?.description}
</p>
</div>
{(selectedMode === 'weight_loss' || selectedMode === 'recomposition') && (
<div className="form-row">
<label>Zielgewicht (optional)</label>
<input type="number" step="0.1" value={goalWeight} onChange={...} />
</div>
)}
<button onClick={saveGoal}>Ziel speichern</button>
</div>
)
}
```
### Aufwand: 2-3h
- 1h: DB + Backend
- 1h: Frontend UI
- 0.5h: Testing
---
## Phase 0b: Goal-Aware Platzhalter (16-20h)
**Alle 84 Platzhalter implementieren, ABER:**
- Score-Berechnungen nutzen `goal_mode` von Anfang an
- Beispiel:
```python
def get_body_progress_score(profile_id: str) -> str:
"""Body Progress Score (0-100, goal-dependent)."""
profile = get_profile_data(profile_id)
goal_mode = profile.get('goal_mode', 'health')
# Hole Gewichte aus goals.GOAL_MODES
weights = GOAL_MODES[goal_mode]['score_weights']
# Berechne Sub-Scores
fm_score = calculate_fm_progress(profile_id)
lbm_score = calculate_lbm_progress(profile_id)
weight_score = calculate_weight_progress(profile_id, goal_mode)
# Gewichte nach Ziel
if goal_mode == 'weight_loss':
total = (0.50 * fm_score + 0.30 * weight_score + 0.20 * lbm_score)
elif goal_mode == 'strength':
total = (0.60 * lbm_score + 0.30 * fm_score + 0.10 * weight_score)
elif goal_mode == 'recomposition':
total = (0.45 * fm_score + 0.45 * lbm_score + 0.10 * weight_score)
else: # health, endurance
total = (0.40 * weight_score + 0.30 * fm_score + 0.30 * lbm_score)
return f"{int(total)}/100"
```
**Resultat:**
- Charts bekommen von Anfang an **korrekte** Scores
- Keine Umarbeitung nötig später
- System ist "smart" ab Tag 1
---
## Phase 2+: Vollständiges Zielesystem (6-8h)
**Features:**
1. **Ziel-Erkennung aus Daten**
- Pattern-Analyse (wie oben)
- Vorschlag mit Confidence
- "Passt dein Ziel noch?" Check
2. **Sekundäre Ziele**
- `goal_mode` = primary
- `secondary_goals[]` = weitere Schwerpunkte
- Gewichtung: 70% primary, 30% secondary
3. **Ziel-Progression Tracking**
- Fortschritt zum Ziel (%)
- Geschätzte Erreichung (Datum)
- Anpassungs-Vorschläge
4. **Goal-Aware Charts**
- Priorisierung nach goal_relevance
- Dashboard zeigt ziel-spezifische Charts zuerst
5. **Goal-Aware KI**
- Prompt-Kontext enthält goal_mode
- KI interpretiert zielspezifisch
---
## 5. Entscheidungs-Matrix
### Option A: Zielesystem komplett ZUERST
**Aufwand:** 10-12h
**Pro:**
- Alles konsistent von Anfang an
- Keine Umarbeitung
**Contra:**
- Verzögert Platzhalter-Start
- Ziel-Erkennung braucht Platzhalter (Henne-Ei)
### Option B: Platzhalter ZUERST, dann Ziele
**Aufwand:** 16-20h + später Rework
**Pro:**
- Schneller Start
**Contra:**
- ALLE Scores falsch gewichtet
- Komplette Umarbeitung nötig
- User sehen falsche Werte
### Option C: HYBRID ⭐ **EMPFOHLEN**
**Aufwand:** 2-3h (Minimal-Ziele) + 16-20h (Goal-Aware Platzhalter) + später 6-8h (Voll-System)
**Pro:**
- ✅ Beste aus beiden Welten
- ✅ Korrekte Scores von Anfang an
- ✅ Keine Umarbeitung
- ✅ Ziel-Erkennung später als Enhancement
**Contra:**
- Keinen signifikanten Nachteil
---
## 6. Empfehlung
### JA, Zielesystem VOR Platzhaltern – aber minimal!
**Reihenfolge:**
1. **Phase 0a (2-3h):** Minimal-Zielesystem
- DB: goal_mode field
- API: Get/Set Goal
- UI: Goal Selector (Settings)
- Default: "health"
2. **Phase 0b (16-20h):** Goal-Aware Platzhalter
- 84 Platzhalter implementieren
- Scores nutzen goal_mode
- Berechnungen goal-abhängig
3. **Phase 1 (12-16h):** Charts
- Nutzen goal-aware Platzhalter
- Zeigen korrekte Interpretationen
4. **Phase 2+ (6-8h):** Vollständiges Zielesystem
- Ziel-Erkennung
- Sekundäre Ziele
- Goal Progression Tracking
---
## 7. Fazit
**Deine Intuition war 100% richtig!**
✅ **Ohne Zielesystem:**
- Charts zeigen falsche Interpretationen
- Scores sind generisch und für niemanden passend
- System bleibt "dummer Datensammler"
✅ **Mit Zielesystem:**
- Charts interpretieren zielspezifisch
- Scores sind individuell gewichtet
- System wird "intelligenter Coach"
**Nächster Schritt:** Phase 0a implementieren (2-3h), dann Phase 0b mit goal-aware Platzhaltern.
**Soll ich mit Phase 0a (Minimal-Zielesystem) starten?**
+729
View File
@@ -0,0 +1,729 @@
# Goal System Redesign v2.0
**Datum:** 26. März 2026
**Status:** 📋 KONZEPTION
**Anlass:** Fundamentale Design-Probleme in Phase 0a identifiziert
---
## 1. Probleme der aktuellen Implementierung (Phase 0a)
### 1.1 Primärziel zu simplistisch
**Problem:**
- Nur EIN Primärziel erlaubt
- Binäres System (primär/nicht-primär)
- Toggle funktioniert nicht richtig beim Update
**Realität:**
- User hat MEHRERE Ziele gleichzeitig mit unterschiedlichen Prioritäten
- Beispiel: 30% Abnehmen, 25% Kraft, 25% Ausdauer, 20% Beweglichkeit
**Lösung:**
→ **Gewichtungssystem** (0-100%, Summe = 100%)
---
### 1.2 Ein Goal Mode zu simpel
**Problem:**
- User muss sich für EINEN Modus entscheiden (weight_loss ODER strength)
- In Realität: Kombinierte Ziele (Abnehmen + Kraft + Ausdauer gleichzeitig)
**Realität (User-Zitat):**
> "Ich versuche nach einer Operation Kraft und Ausdauer aufzubauen, gleichzeitig Abzunehmen und meine Beweglichkeit und Koordination wieder zu steigern."
**Lösung:**
→ **Multi-Mode mit Gewichtung** statt Single-Mode
---
### 1.3 Fehlende Current Values
**Problem:**
- `lean_mass` current value = "-" (nicht implementiert)
- `strength`, `flexibility` haben keine Datenquellen
- VO2Max wirft Internal Server Error
**Lösung:**
→ Alle Goal-Typen mit korrekten Datenquellen verbinden
---
### 1.4 Abstrakte Zieltypen
**Problem:**
- "Kraft" - was bedeutet das? Bankdrücken? Kniebeuge? Gesamt?
- "Beweglichkeit" - welcher Test? Sit-and-Reach? Hüftbeugung?
- Zu unspezifisch für konkrete Messung
**Lösung:**
→ **Konkrete, messbare Zieltypen** mit standardisierten Tests
---
### 1.5 Blutdruck als einzelner Wert
**Problem:**
- BP braucht ZWEI Werte (systolisch/diastolisch)
- Aktuelles Schema: nur ein `target_value`
**Lösung:**
→ **Compound Goals** (Ziele mit mehreren Werten)
---
### 1.6 Keine Guidance für User
**Problem:**
- User muss konkrete Zahlen eingeben ohne Kontext
- Was ist ein guter VO2Max Wert? Was ist realistisch?
**Lösung:**
→ **Richtwerte, Normen, Beispiele** in UI
---
## 2. Redesign-Konzept v2.0
### 2.1 Kern-Prinzipien
**Prinzip 1: Gewichtung statt Priorisierung**
- Alle Ziele haben eine Gewichtung (0-100%)
- Summe aller Gewichtungen = 100%
- KI berücksichtigt Gewichtung in Analysen
**Prinzip 2: Multi-dimensional statt Singular**
- Kein einzelner "Goal Mode"
- Stattdessen: Gewichtete Kombination von Fokus-Bereichen
- Realitätsnah: User hat mehrere Ziele gleichzeitig
**Prinzip 3: Konkret statt Abstrakt**
- Jedes Ziel hat klare Messbarkeit
- Standardisierte Tests wo möglich
- Datenquellen eindeutig definiert
**Prinzip 4: Guidance statt Ratlosigkeit**
- Richtwerte für jedes Ziel
- Alters-/Geschlechts-spezifische Normen
- Beispiele und Erklärungen
---
## 3. Neues Datenmodell
### 3.1 Fokus-Bereiche (statt Goal Modes)
**Tabelle: `focus_areas` (NEU)**
```sql
CREATE TABLE focus_areas (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
-- Gewichtete Fokus-Bereiche
weight_loss_pct INT DEFAULT 0, -- 0-100%
muscle_gain_pct INT DEFAULT 0, -- 0-100%
endurance_pct INT DEFAULT 0, -- 0-100%
strength_pct INT DEFAULT 0, -- 0-100%
flexibility_pct INT DEFAULT 0, -- 0-100%
health_pct INT DEFAULT 0, -- 0-100% (Erhaltung, kein spezifisches Ziel)
-- Constraint: Summe muss 100 sein
CONSTRAINT sum_equals_100 CHECK (
weight_loss_pct + muscle_gain_pct + endurance_pct +
strength_pct + flexibility_pct + health_pct = 100
),
active BOOLEAN DEFAULT true,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
-- Nur ein aktiver Fokus-Mix pro User
UNIQUE(profile_id, active) WHERE active = true
);
COMMENT ON TABLE focus_areas IS
'Weighted focus distribution - replaces single goal_mode.
Example: 30% weight loss + 25% strength + 25% endurance + 20% flexibility = 100%';
```
**Beispiel-Daten:**
```json
// User nach Operation (wie im Feedback beschrieben):
{
"weight_loss_pct": 30,
"muscle_gain_pct": 20,
"endurance_pct": 25,
"strength_pct": 15,
"flexibility_pct": 10,
"health_pct": 0
}
// User reiner Kraftfokus:
{
"weight_loss_pct": 0,
"muscle_gain_pct": 50,
"strength_pct": 40,
"endurance_pct": 10,
"flexibility_pct": 0,
"health_pct": 0
}
// User Gewichtsverlust primär:
{
"weight_loss_pct": 60,
"muscle_gain_pct": 0,
"endurance_pct": 20,
"strength_pct": 10,
"flexibility_pct": 5,
"health_pct": 5
}
```
---
### 3.2 Überarbeitete Goal-Typen
**Tabelle: `goals` (ÜBERARBEITET)**
**A) Simple Goals (ein Wert):**
```sql
goal_type:
- 'weight' → kg (aus weight_log)
- 'body_fat_pct' → % (aus caliper_log)
- 'lean_mass' → kg (berechnet: weight - (weight * bf_pct))
- 'vo2max' → ml/kg/min (aus vitals_baseline)
- 'rhr' → bpm (aus vitals_baseline)
- 'hrv' → ms (aus vitals_baseline)
```
**B) Test-based Goals (standardisierte Tests):**
```sql
goal_type:
- 'cooper_test' → Meter (12min Lauf)
- 'pushups_max' → Anzahl
- 'plank_max' → Sekunden
- 'sit_reach' → cm (Beweglichkeit)
- 'squat_1rm' → kg (Kraft Unterkörper)
- 'bench_1rm' → kg (Kraft Oberkörper)
- 'deadlift_1rm' → kg (Kraft Rücken)
```
**C) Compound Goals (mehrere Werte):**
```sql
goal_type:
- 'blood_pressure' → systolic/diastolic (mmHg)
→ Braucht: target_value_secondary
```
**Schema-Erweiterung:**
```sql
ALTER TABLE goals ADD COLUMN goal_weight INT DEFAULT 100;
-- Gewichtung dieses Ziels (0-100%)
-- Summe aller goal_weight für einen User sollte ~100% sein
ALTER TABLE goals ADD COLUMN target_value_secondary DECIMAL(10,2);
-- Für Compound Goals (z.B. BP diastolisch)
ALTER TABLE goals ADD COLUMN current_value_secondary DECIMAL(10,2);
-- Aktueller Wert für sekundären Target
ALTER TABLE goals DROP COLUMN is_primary;
-- Nicht mehr nötig (wird durch goal_weight ersetzt)
COMMENT ON COLUMN goals.goal_weight IS
'Weight/priority of this goal (0-100%).
Higher weight = more important in AI scoring.
Sum of all goal_weight should be ~100% per user.';
```
---
### 3.3 Datenquellen-Mapping
**Korrekte Current-Value Extraktion:**
```python
# backend/routers/goals.py - _get_current_value_for_goal_type()
GOAL_TYPE_SOURCES = {
# Simple values from existing tables
'weight': {
'table': 'weight_log',
'column': 'weight',
'order': 'date DESC'
},
'body_fat_pct': {
'table': 'caliper_log',
'column': 'body_fat_pct',
'order': 'date DESC'
},
'lean_mass': {
'calculation': 'weight - (weight * body_fat_pct / 100)',
'requires': ['weight_log', 'caliper_log']
},
'vo2max': {
'table': 'vitals_baseline',
'column': 'vo2_max',
'order': 'date DESC'
},
'rhr': {
'table': 'vitals_baseline',
'column': 'resting_hr',
'order': 'date DESC'
},
'hrv': {
'table': 'vitals_baseline',
'column': 'hrv',
'order': 'date DESC'
},
# Test-based values from fitness_tests
'cooper_test': {
'table': 'fitness_tests',
'filter': "test_type = 'cooper_12min'",
'column': 'result_value',
'order': 'test_date DESC'
},
'pushups_max': {
'table': 'fitness_tests',
'filter': "test_type = 'pushups_max'",
'column': 'result_value',
'order': 'test_date DESC'
},
# ... weitere Tests
# Compound goals
'blood_pressure': {
'table': 'blood_pressure_log',
'columns': ['systolic', 'diastolic'], # Beide Werte
'order': 'measured_at DESC'
}
}
```
---
## 4. UI/UX Redesign
### 4.1 Fokus-Bereiche Konfigurator
**Statt 5 einzelne Cards → Slider-Interface:**
```
┌─────────────────────────────────────────────────────┐
│ 🎯 Mein Trainings-Fokus │
├─────────────────────────────────────────────────────┤
│ Verschiebe die Regler um deine Prioritäten zu │
│ setzen. Die Summe muss 100% ergeben. │
│ │
│ 📉 Gewichtsverlust [====] 30% │
│ Schwerpunkt auf Kaloriendefizit & Fettabbau │
│ │
│ 💪 Muskelaufbau [===] 20% │
│ Magermasse steigern, Körperkomposition │
│ │
│ 🏃 Ausdauer [====] 25% │
│ VO2Max, aerobe Kapazität, Pace │
│ │
│ 🏋️ Maximalkraft [==] 15% │
│ 1RM Steigerung, progressive Belastung │
│ │
│ 🤸 Beweglichkeit [=] 10% │
│ Mobilität, Flexibilität, Koordination │
│ │
│ ❤️ Allgemeine Gesundheit [ ] 0% │
│ Erhaltung, präventiv │
│ │
│ ────────────────────────────────────────────────── │
│ Gesamt: 100% ✓ │
│ │
│ [Speichern] [Zurücksetzen] │
└─────────────────────────────────────────────────────┘
```
**Technisch:**
- HTML Range Slider (0-100)
- Live-Update der Summe
- Validierung: Summe muss 100% sein
- Auto-Adjust: Wenn User einen Slider erhöht, andere proportional reduzieren
---
### 4.2 Ziele mit Gewichtung
**Goal-List mit Gewichtungs-Indikator:**
```
┌─────────────────────────────────────────────────────┐
│ 🎯 Konkrete Ziele │
├─────────────────────────────────────────────────────┤
│ ┌───────────────────────────────────────────────┐ │
│ │ ⚖️ Zielgewicht: 82 kg [30%]│ │
│ │ Start: 95 kg → Aktuell: 89 kg → Ziel: 82 kg │ │
│ │ ████████████░░░░░░░░░░ 65% │ │
│ │ ✓ Voraussichtlich: 15.05.2026 (on track) │ │
│ │ [✏️] [🗑️] │ │
│ └───────────────────────────────────────────────┘ │
│ │
│ ┌───────────────────────────────────────────────┐ │
│ │ 💪 Magermasse: 72 kg [20%]│ │
│ │ Start: 68 kg → Aktuell: 70.5 kg → Ziel: 72 kg│ │
│ │ ██████████░░░░░░░░░░░░ 63% │ │
│ │ ⚠ Prognose: 20.06.2026 (5 Tage später) │ │
│ │ [✏️] [🗑️] │ │
│ └───────────────────────────────────────────────┘ │
│ │
│ [+ Neues Ziel] │
└─────────────────────────────────────────────────────┘
Summe Gewichtungen: 50% (noch 50% verfügbar)
```
**Änderungen:**
- Gewichtung in `[30%]` Badge angezeigt
- Summe unten angezeigt
- Warnung wenn Summe > 100%
---
### 4.3 Ziel-Editor mit Guidance
**Beispiel: VO2Max Ziel erstellen:**
```
┌─────────────────────────────────────────────────────┐
│ Neues Ziel erstellen │
├─────────────────────────────────────────────────────┤
│ Zieltyp │
│ [VO2 Max ▼] │
│ │
│ ℹ️ VO2 Max (ml/kg/min) - Maximale Sauerstoffauf- │
│ nahme. Misst die aerobe Leistungsfähigkeit. │
│ │
│ 📊 Richtwerte (Männer, 35 Jahre): │
│ Sehr gut: > 48 ml/kg/min │
│ Gut: 44-48 ml/kg/min │
│ Durchschn.: 40-44 ml/kg/min │
│ Unterdurch.: 35-40 ml/kg/min │
│ │
│ 🎯 Zielwert │
│ ┌──────────┬──────────┐ │
│ │ [ 46 ] │ ml/kg/min│ │
│ └──────────┴──────────┘ │
│ Dein aktueller Wert: 42 ml/kg/min (Durchschnitt) │
│ → Ziel liegt in "Gut"-Bereich ✓ │
│ │
│ 📅 Zieldatum (optional) │
│ [2026-06-30] │
│ │
│ ⚖️ Gewichtung │
│ [==== ] 25% │
│ Wie wichtig ist dir dieses Ziel? │
│ │
│ 💡 Name (optional) │
│ [Ausdauer für Bergwandern ] │
│ │
│ [Ziel erstellen] [Abbrechen] │
└─────────────────────────────────────────────────────┘
```
**Features:**
- Info-Box mit Erklärung
- Alters-/geschlechtsspezifische Richtwerte
- Live-Feedback zum eingegebenen Wert
- Aktueller Wert automatisch geladen
- Gewichtungs-Slider mit Live-Preview
---
### 4.4 Compound Goals (Blutdruck)
**Spezial-UI für Blutdruck:**
```
┌─────────────────────────────────────────────────────┐
│ Zieltyp: Blutdruck │
├─────────────────────────────────────────────────────┤
│ 🎯 Zielwerte │
│ │
│ Systolisch (oberer Wert) │
│ [ 120 ] mmHg │
│ │
│ Diastolisch (unterer Wert) │
│ [ 80 ] mmHg │
│ │
│ ℹ️ WHO/ISH Klassifikation: │
│ Optimal: < 120/80 mmHg │
│ Normal: 120-129 / 80-84 mmHg │
│ Hoch-norm.: 130-139 / 85-89 mmHg │
│ Hypertonie: ≥ 140/90 mmHg │
│ │
│ Dein aktueller Wert: 135/88 mmHg (Hoch-normal) │
│ Dein Ziel: 120/80 mmHg (Optimal) ✓ │
│ │
│ [Ziel erstellen] [Abbrechen] │
└─────────────────────────────────────────────────────┘
```
---
## 5. Scoring-System mit Gewichtung
### 5.1 Score-Berechnung v2.0
**Aktuell (Phase 0a):**
```python
# Feste Gewichtung per goal_mode
SCORE_WEIGHTS = {
"strength": {
"body_progress": 0.35,
"nutrition": 0.30,
# ...
}
}
```
**Neu (v2.0):**
```python
def calculate_weighted_score(profile_id):
"""
Berechnet Score basierend auf:
1. Focus Areas (Multi-dimensional statt single mode)
2. Goal Weights (individuelle Ziel-Gewichtungen)
"""
# 1. Hole Focus Areas
focus = get_focus_areas(profile_id)
# → {weight_loss: 30%, muscle_gain: 20%, endurance: 25%, ...}
# 2. Hole alle Ziele mit Gewichtung
goals = get_goals_with_weights(profile_id)
# → [{type: 'weight', weight: 30%}, {type: 'lean_mass', weight: 20%}, ...]
# 3. Berechne Basis-Scores
base_scores = {
'body_composition': calculate_body_score(profile_id),
'nutrition': calculate_nutrition_score(profile_id),
'training': calculate_training_score(profile_id),
'recovery': calculate_recovery_score(profile_id)
}
# 4. Gewichte Scores nach Focus Areas
weighted_score = 0
# Weight Loss Focus → Body Composition + Nutrition wichtiger
if focus['weight_loss_pct'] > 0:
weighted_score += (
base_scores['body_composition'] * 0.4 +
base_scores['nutrition'] * 0.4 +
base_scores['training'] * 0.1 +
base_scores['recovery'] * 0.1
) * (focus['weight_loss_pct'] / 100)
# Muscle Gain Focus → Body + Nutrition + Training
if focus['muscle_gain_pct'] > 0:
weighted_score += (
base_scores['body_composition'] * 0.35 +
base_scores['nutrition'] * 0.35 +
base_scores['training'] * 0.25 +
base_scores['recovery'] * 0.05
) * (focus['muscle_gain_pct'] / 100)
# Endurance Focus → Training + Recovery
if focus['endurance_pct'] > 0:
weighted_score += (
base_scores['training'] * 0.50 +
base_scores['recovery'] * 0.30 +
base_scores['body_composition'] * 0.10 +
base_scores['nutrition'] * 0.10
) * (focus['endurance_pct'] / 100)
# ... weitere Focus Areas
return {
'overall_score': round(weighted_score, 1),
'base_scores': base_scores,
'focus_weights': focus,
'goal_weights': [g['weight'] for g in goals]
}
```
**Beispiel:**
```python
User: 30% Weight Loss + 25% Endurance + 20% Muscle Gain + 25% Strength
Base Scores:
- Body Composition: 75/100
- Nutrition: 80/100
- Training: 70/100
- Recovery: 65/100
Calculation:
Weight Loss (30%):
= (75*0.4 + 80*0.4 + 70*0.1 + 65*0.1) * 0.30
= 69.5 * 0.30 = 20.85
Endurance (25%):
= (70*0.50 + 65*0.30 + 75*0.10 + 80*0.10) * 0.25
= 69.0 * 0.25 = 17.25
Muscle Gain (20%):
= (75*0.35 + 80*0.35 + 70*0.25 + 65*0.05) * 0.20
= 74.0 * 0.20 = 14.80
Strength (25%):
= (70*0.40 + 80*0.30 + 75*0.20 + 65*0.10) * 0.25
= 72.5 * 0.25 = 18.13
Overall Score = 20.85 + 17.25 + 14.80 + 18.13 = 71.03/100
```
---
## 6. Migration-Strategie
### 6.1 Daten-Migration von Phase 0a
**Bestehende Daten:**
- `profiles.goal_mode` (single mode)
- `goals` mit `is_primary`
**Migrations-Logik:**
```sql
-- Migration 023: Goal System Redesign v2.0
-- 1. Erstelle focus_areas Tabelle
CREATE TABLE focus_areas (...);
-- 2. Migriere bestehende goal_mode → focus_areas
INSERT INTO focus_areas (profile_id, weight_loss_pct, muscle_gain_pct, ...)
SELECT
id,
CASE goal_mode
WHEN 'weight_loss' THEN 70 -- 70% Weight Loss + 15% Health + 15% Endurance
WHEN 'strength' THEN 0
-- ...
END as weight_loss_pct,
CASE goal_mode
WHEN 'strength' THEN 60
WHEN 'recomposition' THEN 30
-- ...
END as muscle_gain_pct,
-- ... weitere
FROM profiles
WHERE goal_mode IS NOT NULL;
-- 3. Erweitere goals Tabelle
ALTER TABLE goals ADD COLUMN goal_weight INT DEFAULT 100;
ALTER TABLE goals ADD COLUMN target_value_secondary DECIMAL(10,2);
ALTER TABLE goals ADD COLUMN current_value_secondary DECIMAL(10,2);
-- 4. Migriere is_primary → goal_weight
UPDATE goals SET goal_weight = 100 WHERE is_primary = true;
UPDATE goals SET goal_weight = 50 WHERE is_primary = false;
-- 5. Cleanup (später)
-- ALTER TABLE profiles DROP COLUMN goal_mode; -- nach Verifikation
-- ALTER TABLE goals DROP COLUMN is_primary; -- nach Verifikation
```
---
## 7. Implementierungs-Phasen
### Phase 1: Konzeption ✅ (DIESES DOKUMENT)
**Dauer:** -
**Ziel:** Vollständiges Redesign-Konzept
### Phase 2: Backend Redesign (6-8h)
- Migration 023 erstellen
- `focus_areas` Tabelle + CRUD
- `goals` erweitern (weight, secondary values)
- Datenquellen-Mapping korrigieren (lean_mass, VO2Max fix, etc.)
- Scoring-System v2.0 implementieren
### Phase 3: Frontend Redesign (8-10h)
- Fokus-Bereiche Slider-UI
- Ziel-Editor mit Guidance (Richtwerte, Normen)
- Gewichtungs-System in Goal-Liste
- Compound Goals UI (Blutdruck zwei Werte)
- Neue Goal-Typen (Tests) integrieren
### Phase 4: Testing & Refinement (2-3h)
- Migration testen (Phase 0a → v2.0)
- Scoring-Logik verifizieren
- UI/UX Testing
- Edge Cases (Summe ≠ 100%, keine Ziele, etc.)
**Total: 16-21h**
---
## 8. Offene Fragen / Entscheidungen
### 8.1 Focus Areas vs Goals Weight
**Frage:** Brauchen wir BEIDE Gewichtungssysteme?
- Focus Areas (Weight Loss 30%, Strength 25%, ...)
- Goal Weights (Ziel "82kg" = 30%, Ziel "VO2Max 46" = 25%, ...)
**Option A:** NUR Focus Areas
- Einfacher
- Weniger Redundanz
- Aber: Weniger granular
**Option B:** BEIDE Systeme
- Focus Areas = Strategisch (Richtung)
- Goal Weights = Taktisch (konkrete Prioritäten)
- Komplexer, aber flexibler
**Empfehlung:** Option B - beide Systeme ergänzen sich
---
### 8.2 Konkrete vs Abstrakte Tests
**Frage:** Wie konkret sollen Strength-Goals sein?
**Option A:** Sehr konkret
- `bench_press_1rm`, `squat_1rm`, `deadlift_1rm`
- Vorteil: Präzise, messbar
- Nachteil: Viele Goal-Typen
**Option B:** Abstrakt mit Kontext
- `strength` mit Sub-Type (Bench/Squat/Deadlift)
- Vorteil: Flexibler
- Nachteil: Komplizierteres Schema
**Empfehlung:** Option A - konkrete Typen, dafür klare Messbarkeit
---
### 8.3 Auto-Update von Current Values
**Frage:** Wie oft sollen current_value aktualisiert werden?
**Option A:** On-Demand (beim Laden der Goals-Seite)
- Vorteil: Keine Background-Jobs
- Nachteil: Kann verzögert sein
**Option B:** Trigger-basiert (bei neuem Messwert)
- Vorteil: Immer aktuell
- Nachteil: Mehr Komplexität
**Empfehlung:** Option A für MVP, Option B später
---
## 9. Nächste Schritte
### User-Feedback einholen:
1. ✅ Löst das Redesign alle genannten Probleme?
2. ✅ Ist die Fokus-Bereiche UI verständlich?
3. ✅ Sind die konkreten Goal-Typen sinnvoll?
4. ✅ Brauchen wir beide Gewichtungssysteme?
5. ✅ Fehlt noch etwas?
### Nach Freigabe:
1. Migration 023 schreiben
2. Backend implementieren
3. Frontend implementieren
4. Testing
---
**Erstellt:** 26. März 2026
**Status:** 📋 WARTET AUF FEEDBACK
**Nächster Schritt:** User-Review & Freigabe
+458
View File
@@ -0,0 +1,458 @@
# Konzept-Analyse: Fachkonzept vs. Gitea Issues
**Datum:** 26. März 2026
**Analyst:** Claude Code
**Basis:** `.claude/docs/functional/mitai_jinkendo_konzept_diagramme_auswertungen_v2.md`
**Geprüfte Issues:** #26, #27, alle offenen
---
## 1. Executive Summary
### Kernerkenntnis
Das Fachkonzept ist **wesentlich umfassender** als die aktuellen Gitea Issues #26 und #27. Es definiert ein 3-stufiges Analyse-System (Deskriptiv → Diagnostisch → Präskriptiv), das weit über einfache Charts und Korrelationen hinausgeht.
### Strategische Empfehlung
**NICHT** Issues #26 und #27 einzeln implementieren, sondern:
1. **Neu-Strukturierung:** Konzept-basierte Phasen-Issues erstellen
2. **Platzhalter-First:** Erst Berechnungs-Platzhalter implementieren
3. **Dann Visualisierung:** Charts nutzen die Platzhalter
4. **Dann KI-Integration:** KI nutzt regelbasierte Scores + Rohdaten
---
## 2. Analyse: Issue #26 vs. Fachkonzept
### Issue #26: Charts & Visualisierungen erweitern
**Status:** OPEN
**Priority:** Medium-High
**Aufwand:** 8-10h
**Definierte Charts:**
- Gewicht-Trends (Line-Chart + Trendlinie)
- Umfänge-Verlauf (Multi-Line)
- Vitalwerte-Trends (RHR, HRV, BP)
- Schlaf-Analyse (Dauer, Phasen)
- Ernährungs-Charts (Kalorien, Makros)
### Fachkonzept: Diagrammkatalog
**KÖRPER (K1-K5):**
- K1: Gewichtstrend + Trendkanal + Zielprojektion
- 7d Rolling Median, 28d/90d Trend-Slope
- Prozentuale Zielannäherung
- Regelbasierte Hinweise (zu schnell/langsam)
- K2: Körperzusammensetzung (Gewicht/FM/LBM)
- FM = Gewicht × BF%, LBM = Gewicht × (1-BF%)
- 28d/90d Änderung von FM und LBM
- K3: Umfangs-Panel (8 Mini-Charts)
- Links-Rechts Asymmetrie
- Taille/Hüfte, Taille/Körpergröße
- K4: Rekompositions-Detektor (Quadranten)
- K5: Body Progress Score (0-100)
**ERNÄHRUNG (E1-E5):**
- E1: Energieaufnahme vs. Verbrauch vs. Gewichtstrend
- E2: Protein adequacy (g/Tag, g/kg, g/kg LBM)
- E3: Makroverteilung + Wochenkonsistenz
- E4: Ernährungs-Adhärenz-Score (0-100)
- E5: Energieverfügbarkeits-Warnung
**AKTIVITÄT (A1-A8):**
- A1: Trainingsvolumen pro Woche
- A2: Intensitätsverteilung / Zonenbild
- A3: Trainingsqualitäts-Matrix
- A4: Fähigkeiten-Balance / Ability Radar
- A5: Load-Monitoring (interne Last, Monotony, Strain)
- A6: Aktivitäts-Goal-Alignment-Score (0-100)
- A7: Ruhetags-/Recovery-Compliance
- A8: VO2max-Entwicklung
### Bewertung
❌ **Issue #26 ist zu eng gefasst**
- Fokus nur auf Basis-Visualisierung
- Keine Scores, keine Baselines, keine Confidence
- Keine regelbasierten Hinweise
- Keine Ziel-Abhängigkeit
✅ **Fachkonzept bietet:**
- 18 dedizierte Charts (K1-K5, E1-E5, A1-A8)
- Scores als eigenständige Visualisierungen
- Regelbasierte Aussagen ohne KI
- Ziel-Modi Steuerung
---
## 3. Analyse: Issue #27 vs. Fachkonzept
### Issue #27: Korrelationen & Insights erweitern
**Status:** OPEN
**Priority:** High
**Aufwand:** 6-8h
**Definierte Korrelationen:**
- Schlaf ↔ Erholung (Schlafdauer → RHR, Qualität → HRV)
- Training ↔ Vitalwerte (Load → RHR-Anstieg, HRV-Abfall)
- Ernährung ↔ Performance (Defizit → Intensität)
- Blutdruck ↔ Lifestyle (Stress → BP, Training → BP)
- Multi-Faktor Analyse (KI-Insights)
### Fachkonzept: Korrelationen (C1-C6)
**KORRELATIONEN (C1-C6):**
- C1: Energie-Balance vs. Gewichtsveränderung (lagged)
- Lags: 0, 3, 7, 10, 14 Tage
- Bestes Lag ermitteln, Effektstärke, Confidence
- C2: Protein adequacy vs. LBM-Trend
- 28d Fenstervergleich, Training als Moderator
- C3: Trainingslast vs. HRV/RHR (1-3 Tage verzögert)
- Duale Lag-Auswertung, individuelle Ermüdungsreaktion
- C4: Schlafdauer + Schlafregularität vs. Recovery
- Bubble-Chart, Sleep Regularity Index
- C5: Blutdruck-Kontextmatrix (Kontext-abhängig)
- Messkontext, Schlaf Vor-Nacht, Training
- C6: Plateau-Detektor (Ereignis-Karte)
- Ziel-spezifische Plateau-Definitionen
### Zusätzlich: Lag-Analyse Prinzipien
**Zwingend im Fachkonzept:**
- **NIE nur lag=0 prüfen**
- Kalorienbilanz → Gewicht: 2-14 Tage Verzögerung
- Protein/Krafttraining → LBM: 2-6 Wochen Verzögerung
- Trainingslast → HRV/RHR: 1-3 Tage Verzögerung
- Schlafdefizit → Recovery: 1-3 Tage Verzögerung
**Mindestdatenmenge:**
- Korrelationen: mind. 21 gepaarte Tageswerte
- Lag-basiert: mind. 28 gepaarte Tage
- Confidence-Klassen (hoch/mittel/niedrig/nicht auswertbar)
### Bewertung
❌ **Issue #27 ist zu oberflächlich**
- Keine Lag-Analyse
- Keine Confidence-Bewertung
- Keine Mindestdatenmenge-Checks
- Keine Ziel-Abhängigkeit
✅ **Fachkonzept bietet:**
- 6 dedizierte Korrelations-Charts mit Lag-Analyse
- Explizite Confidence-Bewertung
- Medizinischer Sicherheitsmodus
- Plateau-Detektion (regelbasiert)
---
## 4. Konflikt-Analyse
### Gibt es Widersprüche zwischen #26 und #27?
**NEIN** – Sie sind komplementär:
- #26: Deskriptive Ebene (Charts)
- #27: Diagnostische Ebene (Korrelationen)
### Aber: Beide sind zu isoliert
Das Fachkonzept zeigt: **Charts und Korrelationen müssen verzahnt sein**
**Beispiel:**
```
Fachkonzept C1: Energie-Balance vs. Gewichtsveränderung
├─ Visualisierung: Lag-Heatmap (diagnostisch)
├─ Berechnung: Cross-Correlation (0, 3, 7, 10, 14 Tage Lags)
├─ Input-Daten: Tägliche Kalorienbilanz (E-Chart)
├─ Input-Daten: 7d Gewichtsänderung (K-Chart)
└─ Regelbasierte Aussage: "Energiebilanz zeigt sich bei dir nach ~7 Tagen im Gewicht"
```
**Fazit:** Charts (K, E, A) liefern Basis-Daten für Korrelationen (C)
---
## 5. Neue Platzhalter aus Fachkonzept
### 5.1 KÖRPER (18 neue Platzhalter)
**Gewicht & Trends:**
```python
{{weight_7d_rolling_median}} # 7-Tage gleitender Median
{{weight_28d_trend_slope}} # 28-Tage Trend-Steigung (kg/Tag)
{{weight_90d_trend_slope}} # 90-Tage Trend-Steigung
{{weight_goal_progress_pct}} # Prozentuale Zielannäherung
{{weight_projection_days}} # Geschätzte Tage bis Zielgewicht
{{weight_loss_rate_weekly}} # kg/Woche (28d Mittel)
```
**Körperzusammensetzung:**
```python
{{fm_current}} # Fettmasse aktuell (kg)
{{lbm_current}} # Magermasse aktuell (kg)
{{fm_28d_delta}} # FM Änderung 28 Tage (kg)
{{lbm_28d_delta}} # LBM Änderung 28 Tage (kg)
{{fm_90d_delta}} # FM Änderung 90 Tage
{{lbm_90d_delta}} # LBM Änderung 90 Tage
{{recomposition_score}} # 0-100 (FM↓ + LBM↑ = ideal)
```
**Umfänge:**
```python
{{waist_to_hip_ratio}} # Taille/Hüfte Verhältnis
{{waist_to_height_ratio}} # Taille/Körpergröße (Gesundheitsmarker)
{{arm_asymmetry_pct}} # Links-Rechts Differenz %
{{leg_asymmetry_pct}} # Oberschenkel L-R Differenz
{{waist_28d_delta}} # Taillenumfang Änderung 28d
```
**Body Progress Score:**
```python
{{body_progress_score}} # 0-100 (zielabhängig gewichtet)
```
### 5.2 ERNÄHRUNG (15 neue Platzhalter)
**Energie & Bilanz:**
```python
{{kcal_7d_avg}} # Bereits vorhanden? Prüfen
{{kcal_28d_avg}} # 28-Tage Durchschnitt
{{kcal_estimated_tdee}} # Geschätzter Gesamtumsatz
{{kcal_balance_7d_avg}} # Durchschnittliche Bilanz 7d
{{kcal_balance_28d_avg}} # Durchschnittliche Bilanz 28d
{{energy_availability_status}} # "adequate" | "low" | "critical"
```
**Protein:**
```python
{{protein_g_per_kg}} # Protein g/kg Körpergewicht
{{protein_g_per_kg_lbm}} # Protein g/kg Magermasse
{{protein_adequacy_score}} # 0-100 (Ziel: 1.6-2.2 g/kg)
```
**Makros & Adhärenz:**
```python
{{carb_pct_7d_avg}} # % der Gesamtkalorien
{{fat_pct_7d_avg}} # % der Gesamtkalorien
{{macro_consistency_score}} # 0-100 (Regelmäßigkeit)
{{nutrition_adherence_score}} # 0-100 (Gesamtscore)
{{nutrition_days_7d}} # Erfasste Tage letzte 7d
{{nutrition_days_28d}} # Erfasste Tage letzte 28d
```
### 5.3 AKTIVITÄT (25 neue Platzhalter)
**Volumen:**
```python
{{activity_volume_7d_min}} # Gesamtminuten 7 Tage
{{activity_volume_28d_min}} # Gesamtminuten 28 Tage
{{activity_frequency_7d}} # Anzahl Sessions 7d
{{activity_frequency_28d}} # Anzahl Sessions 28d
{{activity_avg_duration_28d}} # Durchschn. Dauer pro Session
```
**Intensität:**
```python
{{activity_z1_pct}} # % Zeit in Zone 1 (7d)
{{activity_z2_pct}} # % Zeit in Zone 2
{{activity_z3_pct}} # % Zeit in Zone 3
{{activity_z4_pct}} # % Zeit in Zone 4
{{activity_z5_pct}} # % Zeit in Zone 5
{{activity_polarization_index}} # Polarisierung (Z1+Z2 vs Z4+Z5)
```
**Qualität & Load:**
```python
{{activity_quality_avg_28d}} # Durchschn. Quality-Score
{{activity_load_7d}} # Interne Last (7d Summe)
{{activity_load_28d}} # Interne Last (28d Summe)
{{activity_monotony_28d}} # Last-Variabilität
{{activity_strain_28d}} # Load × Monotony
{{activity_acwr}} # Acute:Chronic Workload Ratio
```
**Fähigkeiten:**
```python
{{ability_strength_score}} # 0-100 (aus Training Types)
{{ability_endurance_score}} # 0-100
{{ability_mobility_score}} # 0-100
{{ability_skills_score}} # 0-100
{{ability_mindfulness_score}} # 0-100
{{ability_balance_score}} # 0-100 (wie ausgewogen?)
```
**Goal Alignment:**
```python
{{activity_goal_alignment_score}} # 0-100 (zielabhängig)
{{rest_days_compliance}} # 0-100 (geplant vs. tatsächlich)
```
### 5.4 RECOVERY & GESUNDHEIT (12 neue Platzhalter)
**Baselines:**
```python
{{rhr_7d_baseline}} # 7-Tage Baseline Ruhepuls
{{rhr_28d_baseline}} # 28-Tage Baseline
{{hrv_7d_baseline}} # 7-Tage Baseline HRV
{{hrv_28d_baseline}} # 28-Tage Baseline
```
**Deltas & Trends:**
```python
{{rhr_vs_baseline_7d}} # Abweichung von Baseline (bpm)
{{hrv_vs_baseline_7d}} # Abweichung von Baseline (ms)
{{vo2max_trend_28d}} # VO2max Entwicklung
```
**Scores:**
```python
{{recovery_score}} # 0-100 (HRV, RHR, Schlaf)
{{recovery_score_confidence}} # 0-100 (Datenqualität)
{{sleep_regularity_index}} # Schlafregelmäßigkeit
{{sleep_debt_hours}} # Akkumulierte Schlafschuld
{{health_risk_score}} # 0-100 (Blutdruck, etc.)
```
### 5.5 KORRELATIONEN (8 neue Platzhalter)
```python
{{corr_energy_weight_lag}} # Bestes Lag Energie→Gewicht (Tage)
{{corr_energy_weight_r}} # Korrelationskoeffizient
{{corr_protein_lbm_r}} # Protein ↔ LBM Korrelation
{{corr_load_hrv_lag}} # Bestes Lag Load→HRV
{{corr_load_hrv_r}} # Korrelation
{{corr_sleep_rhr_r}} # Schlaf ↔ RHR Korrelation
{{plateau_detected}} # true|false (regelbasiert)
{{plateau_type}} # "weight_loss" | "strength" | etc.
```
### 5.6 META-PLATZHALTER (6 neue)
```python
{{goal_mode}} # "weight_loss" | "strength" | etc.
{{training_age_weeks}} # Trainingserfahrung
{{data_quality_score}} # 0-100 (Gesamtdatenqualität)
{{measurement_consistency}} # 0-100 (Messzeit-Konsistenz)
{{analysis_confidence}} # "high" | "medium" | "low"
{{analysis_timeframe}} # "7d" | "28d" | "90d"
```
---
## 6. Gesamt-Übersicht: Neue Platzhalter
| Kategorie | Anzahl | Beispiele |
|-----------|--------|-----------|
| KÖRPER | 18 | weight_28d_trend_slope, fm_28d_delta, recomposition_score |
| ERNÄHRUNG | 15 | protein_g_per_kg_lbm, nutrition_adherence_score, energy_availability_status |
| AKTIVITÄT | 25 | activity_quality_avg_28d, activity_strain_28d, ability_balance_score |
| RECOVERY | 12 | recovery_score, sleep_regularity_index, sleep_debt_hours |
| KORRELATIONEN | 8 | corr_energy_weight_lag, plateau_detected, corr_load_hrv_r |
| META | 6 | goal_mode, data_quality_score, analysis_confidence |
| **GESAMT** | **84** | **Neue Platzhalter aus Fachkonzept** |
---
## 7. Strategische Roadmap-Empfehlung
### Phase 0: Fundament (JETZT)
**Ziel:** Berechnungs-Platzhalter implementieren
**Aufwand:** 16-20h
**Deliverables:**
- 84 neue Platzhalter in `placeholder_resolver.py`
- Baseline-Berechnungen (7d, 28d, 90d)
- Score-Algorithmen (Body Progress, Nutrition Adherence, Activity Goal Alignment, Recovery)
- Lag-Korrelations-Funktionen
- Confidence-Berechnung
**Issues zu erstellen:**
- #52: Baseline & Trend Calculations (Körper, Ernährung, Aktivität)
- #53: Score Algorithms (4 Haupt-Scores)
- #54: Correlation & Lag Analysis
- #55: Confidence & Data Quality Metrics
### Phase 1: Visualisierung (DANN)
**Ziel:** Charts nutzen die neuen Platzhalter
**Aufwand:** 12-16h
**Deliverables:**
- K1-K5 Charts (Körper)
- E1-E5 Charts (Ernährung)
- A1-A8 Charts (Aktivität)
- C1-C6 Charts (Korrelationen)
**Issues zu konsolidieren:**
- #26 erweitern zu "Comprehensive Chart System (K, E, A, C)"
- #27 erweitern zu "Correlation & Lag Analysis Charts"
### Phase 2: Regelbasierte Insights (DANACH)
**Ziel:** System wird Coach (nicht nur Datensammler)
**Aufwand:** 8-12h
**Deliverables:**
- Regelbasierte Hinweise ohne KI
- Plateau-Detektion
- Ziel-abhängige Interpretationen
- Warnungen (Gesundheit, Übertraining, Energieverfügbarkeit)
**Neue Issues:**
- #56: Rule-Based Recommendations Engine
- #57: Goal-Mode System & Interpretation
- #58: Health & Safety Warnings
### Phase 3: KI-Integration (SPÄTER)
**Ziel:** KI nutzt Scores + Rohdaten + Regeln
**Aufwand:** 6-8h
**Deliverables:**
- KI-Prompts nutzen neue Platzhalter
- Contextual AI Analysis (nutzt goal_mode)
- Multi-Faktor Insights
---
## 8. Aktions-Empfehlungen
### SOFORT (heute)
1. ✅ **Issues #26 und #27 NICHT einzeln implementieren**
2. ✅ **Neues Issue #52 erstellen:** Baseline & Trend Calculations
3. ✅ **Neues Issue #53 erstellen:** Score Algorithms
4. ✅ **Issue #26 umbennen/erweitern:** "Comprehensive Chart System (based on Fachkonzept)"
5. ✅ **Issue #27 umbennen/erweitern:** "Correlation & Lag Analysis (based on Fachkonzept)"
### DIESE WOCHE
6. ✅ **Implementierung starten:** Phase 0 - Platzhalter
7. ✅ **Dokumentation:** Mapping Fachkonzept → Code
8. ✅ **KI-Prompts vorbereiten:** Nutzen neue Platzhalter
### NÄCHSTE WOCHE
9. ✅ **Implementierung:** Phase 1 - Charts
10. ✅ **Testing:** Alle Scores & Berechnungen
11. ✅ **Production:** Deployment vorbereiten
---
## 9. Zusammenfassung: Transformation Data Collector → Active Coach
### Aktueller Stand
**Data Collector:**
- Daten werden erfasst
- Einfache Listen
- Basis-Statistiken
- KI-Analysen manuell angestoßen
### Ziel (nach Fachkonzept)
**Active Coach:**
- Daten werden **interpretiert**
- Trends & Baselines
- Scores & Confidence
- Regelbasierte Hinweise
- Ziel-abhängige Bewertung
- Proaktive Warnungen
- KI nutzt strukturierte Insights
---
## 10. Nächste Schritte
1. **Issues neu strukturieren** (heute)
2. **Platzhalter implementieren** (Phase 0, diese Woche)
3. **Charts implementieren** (Phase 1, nächste Woche)
4. **Regelbasierte Insights** (Phase 2, Woche danach)
5. **KI-Integration** (Phase 3, dann)
**Commit:** cd2609d
**Analysiert von:** Claude Code
**Basis:** Fachkonzept v2 (2086 Zeilen, 24.03.2026)
+460
View File
@@ -0,0 +1,460 @@
# Nächste Schritte nach Phase 0a
**Stand:** 26. März 2026, nach Completion von Phase 0a (Goal System)
**Aktueller Branch:** `develop`
**Deployed:** `dev.mitai.jinkendo.de`
---
## Aktueller Stand ✅
### Abgeschlossen
- ✅ **Phase 0a:** Minimal Goal System (Strategic + Tactical)
- Migration 022, goals.py Router, GoalsPage UI
- Navigation von Dashboard + Analysis
- Mobile-friendly Design
- **Basis vorhanden für 120+ goal-aware Platzhalter**
### Offene Gitea Issues
- 🔲 **#49:** Prompt-Zuordnung zu Verlaufsseiten (6-8h)
- 🔲 **#47:** Wertetabelle Optimierung (4-6h)
- 🔲 **#46:** KI Prompt-Ersteller (später)
- 🔲 **#45:** KI Prompt-Optimierer (später)
- 🔲 **#43, #42:** Enhanced Debug UI (später)
---
## Option A: Issue #49 - Prompt Page Assignment ⚡
**Aufwand:** 6-8 Stunden
**Priorität:** Medium
**Typ:** UX Enhancement
**Labels:** feature, ux, enhancement
### Beschreibung
KI-Prompts flexibel auf verschiedenen Verlaufsseiten verfügbar machen. Jeder Prompt kann auf mehreren Seiten gleichzeitig angeboten werden (Mehrfachauswahl).
### Problem
**Aktuell:**
- Prompts nur über zentrale Analyse-Seite verfügbar
- Kein kontextbezogener Zugriff auf relevante Analysen
- User muss immer zur Analyse-Seite navigieren
**Beispiel-Szenario:**
```
User ist auf: Gewicht → Verlauf
Will: Gewichtstrend analysieren
Muss: Zur Analyse-Seite → Prompt auswählen → Zurück
```
**Wünschenswert:**
```
User ist auf: Gewicht → Verlauf
Sieht: "🤖 KI-Analyse" Widget mit relevanten Prompts
Kann: Direkt "Gewichtstrend-Analyse" starten
```
### Technische Umsetzung
**Backend (2h):**
```sql
-- Migration 023
ALTER TABLE ai_prompts ADD COLUMN available_on JSONB DEFAULT '["analysis"]';
-- Beispiel:
{
"slug": "weight_trend",
"available_on": ["analysis", "weight_history"]
}
```
**API:**
```python
# Neuer Endpoint
GET /api/prompts/for-page/{page_slug}
→ Returns: List[Prompt] where available_on contains page_slug
# CRUD erweitern
PUT /api/prompts/unified/{id}
→ Body: {..., "available_on": ["analysis", "weight_history"]}
```
**Frontend (4h):**
```javascript
// Wiederverwendbare Komponente
<PagePrompts pageSlug="weight_history" />
// UnifiedPromptModal erweitern
const PAGE_OPTIONS = [
{ value: 'analysis', label: '📊 Analyse (Hauptseite)', default: true },
{ value: 'weight_history', label: '⚖️ Gewicht → Verlauf' },
{ value: 'nutrition_history', label: '🍎 Ernährung → Verlauf' },
// ... 9 Optionen total
]
// Multi-select checkboxes in Prompt-Editor
```
**Integration in Verlaufsseiten (2h):**
- WeightPage, NutritionPage, ActivityPage erweitern
- Widget unterhalb Charts einfügen
- Modal für Inline-Analyse
### Vorteile
- ✅ Schneller Nutzen (UX-Verbesserung sofort sichtbar)
- ✅ Nutzt bestehendes Unified Prompt System (Issue #28)
- ✅ Relativ einfache Implementierung
- ✅ Bereitet vor für Phase 0b (neue Platzhalter dann sofort auf allen Seiten nutzbar)
### Nachteile
- ⚠️ Verzögert strategische Tiefe (goal-aware Analysen)
- ⚠️ Erst sinnvoll wenn mehr Prompts existieren
**Dokumentation:** Siehe `docs/issues/issue-51-prompt-page-assignment.md`
---
## Option B: Phase 0b - Goal-Aware Placeholders 🎯
**Aufwand:** 16-20 Stunden
**Priorität:** High (strategisch kritisch)
**Typ:** Core Feature
**Labels:** feature, ai, goal-system
### Beschreibung
Implementierung von 120+ neuen KI-Platzhaltern die `goal_mode` berücksichtigen. Verwandelt System von "Datensammler" zu "intelligentem Coach".
### Problem
**Aktuell:**
- Ziele existieren, aber KI-Analysen ignorieren sie
- Gleiche Daten werden für alle goal_modes gleich interpretiert
- Keine goal-spezifischen Score-Berechnungen
**Beispiel:**
```python
# Gleiche Messung: -5kg FM, -2kg LBM
# Aktuell: Generischer Score (z.B. 50/100)
# Mit Phase 0b:
goal_mode = "weight_loss" → 78/100 (FM↓ gut!)
goal_mode = "strength" → 32/100 (LBM↓ Katastrophe!)
goal_mode = "recomposition" → 65/100 (beides relevant)
```
### Technische Umsetzung
**1. Placeholder Functions (8-10h):**
**Kategorie: KÖRPER (18 neue):**
```python
def weight_7d_rolling_median(profile_id, goal_mode):
"""Rolling median statt avg für Stabilität"""
def weight_28d_trend_slope(profile_id, goal_mode):
"""Linear regression slope - kg/Woche"""
def fm_28d_delta(profile_id, goal_mode):
"""Fettmasse-Veränderung 28 Tage"""
def lbm_28d_delta(profile_id, goal_mode):
"""Magermasse-Veränderung 28 Tage"""
def recomposition_score(profile_id, goal_mode):
"""FM↓ + LBM↑ Balance-Score"""
# Nur relevant wenn goal_mode = "recomposition"
def waist_to_hip_ratio(profile_id):
"""WHR - Bauchfettverteilung"""
def waist_to_height_ratio(profile_id):
"""WHtR - Gesundheitsrisiko"""
```
**Kategorie: ERNÄHRUNG (15 neue):**
```python
def protein_g_per_kg(profile_id, goal_mode):
"""Protein pro kg Körpergewicht"""
# Target abhängig von goal_mode:
# strength: 2.0-2.2g/kg
# weight_loss: 1.8-2.0g/kg
# endurance: 1.4-1.6g/kg
def protein_g_per_kg_lbm(profile_id):
"""Protein pro kg Magermasse (präziser)"""
def nutrition_adherence_score(profile_id, goal_mode):
"""Wie gut hält User seine Makro-Ziele ein?"""
# Ziele abhängig von goal_mode
def energy_availability_status(profile_id):
"""kcal - activity_kcal - BMR = verfügbare Energie"""
# RED-S Warnung wenn < 30 kcal/kg LBM
```
**Kategorie: AKTIVITÄT (25 neue):**
```python
def activity_quality_avg_28d(profile_id):
"""Durchschnittliche Trainingsqualität"""
def activity_strain_28d(profile_id):
"""Kumulierte Belastung (Monotonie-Detektion)"""
def activity_monotony_28d(profile_id):
"""Variation im Training (Plateaus erkennen)"""
def ability_balance_score(profile_id, goal_mode):
"""Balance zwischen Fähigkeiten (Strength/Cardio/Mobility)"""
# Gewichtung abhängig von goal_mode
```
**Kategorie: RECOVERY (12 neue):**
```python
def recovery_score(profile_id):
"""
Kombiniert: RHR + HRV + Sleep Quality + Rest Days
Score: 0-100
"""
def sleep_regularity_index(profile_id):
"""Wie regelmäßig sind Schlafzeiten? (0-100)"""
def sleep_debt_hours(profile_id):
"""Kumulierte Schlafdifferenz zu Ziel"""
```
**Kategorie: KORRELATIONEN (8 neue):**
```python
def corr_energy_weight_lag(profile_id):
"""
Korrelation Kaloriendefizit → Gewicht
Mit Lag-Analysis (verzögerte Effekte)
Confidence-Score basierend auf Datenmenge
"""
def plateau_detected(profile_id):
"""
Boolean: Gewicht stagniert trotz Defizit?
Trigger für Interventionen
"""
```
**Kategorie: META (6 neue):**
```python
def goal_mode(profile_id):
"""Aktueller goal_mode (für Prompts verfügbar)"""
def data_quality_score(profile_id):
"""Wie vollständig/konsistent sind Daten? (0-100)"""
def profile_age_years(profile_id):
"""Alter für altersabhängige Normen"""
```
**2. Score-Gewichtung (4-6h):**
```python
# backend/score_calculator.py (NEU)
SCORE_WEIGHTS = {
"weight_loss": {
"body_progress": 0.30, # FM↓ wichtig
"nutrition": 0.25, # Defizit wichtig
"training_quality": 0.15, # Moderat wichtig
"recovery": 0.15, # Moderat wichtig
"adherence": 0.15 # Konsistenz wichtig
},
"strength": {
"body_progress": 0.35, # LBM↑ KRITISCH
"nutrition": 0.30, # Surplus + Protein
"training_quality": 0.25, # Progressive Overload
"recovery": 0.10 # Weniger wichtig
},
"endurance": {
"training_quality": 0.40, # VO2Max, Pace wichtig
"recovery": 0.25, # Übertraining vermeiden
"body_progress": 0.15, # Gewicht sekundär
"nutrition": 0.20 # Energie-Verfügbarkeit
},
# ... recomposition, health
}
def calculate_overall_score(profile_id, goal_mode):
"""Berechnet Gesamt-Score basierend auf goal_mode Gewichtung"""
weights = SCORE_WEIGHTS[goal_mode]
scores = {
"body_progress": calculate_body_progress_score(profile_id, goal_mode),
"nutrition": calculate_nutrition_score(profile_id, goal_mode),
"training_quality": calculate_training_score(profile_id, goal_mode),
"recovery": calculate_recovery_score(profile_id),
"adherence": calculate_adherence_score(profile_id, goal_mode)
}
overall = sum(scores[key] * weights[key] for key in weights)
return {
"overall": round(overall, 1),
"breakdown": scores,
"weights": weights
}
```
**3. Baseline-Berechnungen (2-3h):**
```python
def calculate_baselines(profile_id):
"""
Berechnet persönliche Referenzwerte:
- 7d baseline (kurzfristig)
- 28d baseline (mittelfristig)
- 90d baseline (langfristig)
Für: Gewicht, RHR, HRV, Kalorien, Protein, etc.
"""
def detect_anomalies(profile_id, metric, value):
"""
Ist Wert außerhalb von ±2 SD vom Baseline?
→ Warnung für User
"""
```
**4. Integration in Prompts (1-2h):**
```python
# Beispiel Prompt-Template:
"""
Du bist ein KI-Coach für {{goal_mode}} Training.
Aktueller Status:
- Gewichtstrend: {{weight_28d_trend_slope}} kg/Woche
- Fettmasse Δ28d: {{fm_28d_delta}} kg
- Magermasse Δ28d: {{lbm_28d_delta}} kg
- Rekompositions-Score: {{recomposition_score}}/100
Ernährung:
- Protein/kg: {{protein_g_per_kg}} g/kg (Ziel: {{protein_target_for_mode}})
- Adherence: {{nutrition_adherence_score}}/100
Training:
- Qualität (28d): {{activity_quality_avg_28d}}/5.0
- Monotonie: {{activity_monotony_28d}} (Warnung bei >2.0)
Recovery:
- Recovery Score: {{recovery_score}}/100
- Schlafschuld: {{sleep_debt_hours}}h
Gesamt-Score ({{goal_mode}}-optimiert): {{overall_score}}/100
Analyse den Fortschritt aus Sicht eines {{goal_mode}} Ziels...
"""
```
### Vorteile
- ✅ Größter strategischer Impact (System wird intelligent)
- ✅ Ziele werden tatsächlich genutzt (nicht nur Display)
- ✅ Basis für alle zukünftigen Features
- ✅ Automatische Trainingsphasen-Erkennung möglich
### Nachteile
- ⚠️ Hoher Aufwand (16-20h)
- ⚠️ Komplexe Logik (viel Testing nötig)
- ⚠️ Erfordert mehr Daten für sinnvolle Scores
---
## Option C: Issue #47 - Value Table Refinement 🔬
**Aufwand:** 4-6 Stunden
**Priorität:** Low (Polishing)
**Typ:** Enhancement
### Beschreibung
Wertetabelle übersichtlicher gestalten - Normal-Modus nur Einzelwerte, Experten-Modus mit Stage-Rohdaten.
### Vorteile
- ✅ Bessere UX für Value Table
- ✅ Weniger Überforderung im Normal-Modus
### Nachteile
- ⚠️ Kosmetisch, kein funktionaler Impact
- ⚠️ Besser warten bis Phase 0b (dann 120+ Platzhalter)
**Empfehlung:** Später (nach Phase 0b)
---
## Empfehlung 🎯
### Szenario 1: "Quick Wins first"
```
1. Issue #49 - Prompt Assignment (6-8h)
→ Bessere UX sofort
2. Phase 0b - Goal-Aware Placeholders (16-20h)
→ Neue Platzhalter profitieren von Page Assignment
→ Volle Power mit beiden Features
Total: 22-28h
```
### Szenario 2: "Strategic Depth first"
```
1. Phase 0b - Goal-Aware Placeholders (16-20h)
→ System wird intelligent
2. Issue #49 - Prompt Assignment (6-8h)
→ Intelligente Prompts dann auf allen Seiten
Total: 22-28h
```
### Persönliche Empfehlung: **Szenario 1**
**Begründung:**
- Issue #49 ist relativ einfach und bringt sofort UX-Nutzen
- Nutzt bestehendes Unified Prompt System optimal
- Phase 0b profitiert dann von besserer Navigation
- User kann neue Platzhalter (Phase 0b) direkt auf relevanten Seiten nutzen
- Psychologisch: Zwei Erfolgserlebnisse statt einem großen
---
## Nächste Session: Action Items
**Falls Issue #49 gewählt:**
1. [ ] Migration 023 erstellen (available_on JSONB)
2. [ ] Backend: `/api/prompts/for-page/{slug}` Endpoint
3. [ ] Backend: CRUD erweitern (available_on in PUT)
4. [ ] Frontend: PAGE_OPTIONS in UnifiedPromptModal
5. [ ] Frontend: PagePrompts Komponente (wiederverwendbar)
6. [ ] Integration: WeightPage, NutritionPage, ActivityPage
7. [ ] Testing: Multi-select, Modal-Inline-Analyse
**Falls Phase 0b gewählt:**
1. [ ] Placeholder-Funktionen kategorieweise implementieren (KÖRPER → ERNÄHRUNG → AKTIVITÄT → RECOVERY → KORRELATIONEN → META)
2. [ ] Score-Gewichtung pro goal_mode definieren
3. [ ] Backend: score_calculator.py erstellen
4. [ ] Baseline-Berechnungen implementieren
5. [ ] Integration in bestehende Prompts
6. [ ] Testing mit verschiedenen goal_modes
---
## Metriken & Timeline
**Geschätzte Timeline (bei 4h/Tag Entwicklung):**
| Szenario | Dauer | Fertig bis |
|----------|-------|------------|
| Issue #49 | 1.5-2 Tage | ~28.03.2026 |
| Phase 0b | 4-5 Tage | ~31.03.2026 |
| Szenario 1 (Quick Wins first) | 5.5-7 Tage | ~02.04.2026 |
| Szenario 2 (Strategic first) | 5.5-7 Tage | ~02.04.2026 |
**Bei 8h/Tag Entwicklung:** Timeline halbiert sich (~01.04.2026)
---
**Erstellt:** 26. März 2026
**Status:** Aktiv - Wartet auf Entscheidung
**Nächste Aktualisierung:** Nach Completion von gewähltem Path
+194
View File
@@ -0,0 +1,194 @@
# Status Report: 26. März 2026
## Audit & Synchronisation
Vollständige Überprüfung aller Dokumente und Gitea Issues durchgeführt.
---
## ✅ Abgeschlossene Arbeiten
### 1. Gitea Issue #28: AI-Prompts Flexibilisierung
**Status:** ✅ CLOSED (26.03.2026)
**Implementierte Features:**
- Unified Prompt System (4 Phasen)
- DB-Migration zu einheitlichem Schema (base + pipeline)
- Universeller Executor (prompt_executor.py)
- Frontend UI Consolidation (UnifiedPromptModal)
- Debug & Development Tools (Test-Button, Export/Import)
- 32 aktive Platzhalter mit Kategorisierung
- `{{placeholder|d}}` Modifier
**Commits:** 20+ commits (2e0838c bis ae6bd0d)
**Dokumentation:** CLAUDE.md "Feature: Unified Prompt System"
**Gitea Aktion:** Issue geschlossen mit Completion-Kommentar
---
### 2. Gitea Issue #44: BUG - Analysen löschen
**Status:** ✅ CLOSED (26.03.2026)
**Fix:**
- Delete-Button in InsightCard hinzugefügt
- `api.deleteInsight(id)` Funktion implementiert
- Auth-Token wird korrekt übergeben
- Liste aktualisiert sich nach Löschen
**Commit:** c56d2b2
**Dokumentation:** Gitea-Kommentar mit Code-Beispiel
**Gitea Aktion:** Issue geschlossen mit Fix-Details
---
### 3. Feature: Comprehensive Value Table
**Status:** ✅ Basis-Implementierung COMPLETE (26.03.2026)
**Implementierte Features:**
- Metadata Collection System (alle Platzhalter mit Werten)
- Expert Mode Toggle (🔬 Experten-Modus)
- Stage Output Extraction (Einzelwerte aus JSON)
- Category Grouping (PROFIL, KÖRPER, ERNÄHRUNG, etc.)
- Collapsible JSON für Stage-Rohdaten
- Best-of-Each circ_summary mit Altersangaben
**Commits:** 10+ commits (c0a50de bis 6e651b5, 159fcab)
**Dokumentation:** CLAUDE.md "Feature: Comprehensive Value Table"
**Gitea:** Basis abgeschlossen, Issue #47 für Refinement erstellt
---
### 4. Placeholder System Enhancements
**Status:** ✅ COMPLETE
**Fixes & Verbesserungen:**
- `circ_summary`: Alle 8 Umfangspunkte (statt nur 3)
- `circ_summary`: Best-of-Each mit Altersangaben ("heute", "vor 2 Wochen")
- `sleep_avg_quality`: Lowercase stage names fix
- `calculate_age`: PostgreSQL DATE object handling
- Stage outputs in debug info für Value Table
**Commits:** 7daa2e4, a43a9f1, 3ad1a19, d06d3d8, 159fcab, 6e651b5
---
## 🔲 Neue/Offene Issues
### Gitea Issue #47: Wertetabelle Optimierung
**Status:** 🔲 OPEN (neu erstellt 26.03.2026)
**Priority:** Medium
**Aufwand:** 4-6 Stunden
**Ziel:** Value Table übersichtlicher gestalten
**Kernpunkte:**
- Normal-Modus: Nur Einzelwerte (~24 statt 32)
- Experten-Modus: Zusätzlich Stage-Rohdaten
- Beschreibungen für alle 32 Platzhalter vervollständigen
- Schema-basierte Beschreibungen für extrahierte Werte
**Dokumentation:** `docs/issues/issue-50-value-table-refinement.md`
---
## 📊 Gitea Issue Übersicht
### Geschlossen (heute)
- ✅ #28: AI-Prompts Flexibilisierung
- ✅ #44: BUG - Analysen löschen
### Neu erstellt (heute)
- 🆕 #47: Wertetabelle Optimierung
### Weiterhin offen (Backlog)
- 🔲 #25: Ziele-System (Goals)
- 🔲 #26: Charts erweitern
- 🔲 #27: Korrelationen & Insights
- 🔲 #29: Abilities-Matrix UI
- 🔲 #30: Responsive UI
- 🔲 #42, #43: Enhanced Debug UI
- 🔲 #45: KI Prompt-Optimierer
- 🔲 #46: KI Prompt-Ersteller
### Bereits geschlossen (früher)
- ✅ #24: Quality-Filter für KI-Auswertungen
---
## 📝 Dokumentations-Updates
### CLAUDE.md
- ✅ "Letzte Updates (26.03.2026)" Sektion hinzugefügt
- ✅ Gitea Issue-Referenzen klargestellt (Prefix "Gitea #")
- ✅ Feature-Sections umbenannt (nicht "Issue #28/47")
- ✅ "Claude Code Verantwortlichkeiten" Sektion
- ✅ Issue-Management via Gitea API dokumentiert
### docs/issues/
- ✅ issue-50-value-table-refinement.md erstellt
- ℹ️ Weitere Files in .claude/issues/ (nicht versioniert)
### Gitea Kommentare
- ✅ Issue #28: Completion-Details mit Features & Commits
- ✅ Issue #44: Fix-Details mit Code-Beispiel
---
## 🔄 Nächste Schritte
### Empfohlen (Kurzfristig)
1. **Testing auf dev.mitai.jinkendo.de:**
- Value Table im Experten-Modus testen
- Stage-Outputs JSON Anzeige prüfen
- circ_summary mit Altersangaben verifizieren
2. **Production Deployment:**
- Develop → Main Merge (wenn Tests OK)
- Alle Features (Unified Prompts + Value Table) deployen
3. **Issue #47 Refinement:**
- Wertetabelle im Normal-Modus optimieren
- Beschreibungen vervollständigen
### Optional (Mittelfristig)
4. **Weitere offene Issues priorisieren:**
- #25: Ziele-System (Phase 1)
- #27: Korrelationen (Phase 2)
- #30: Responsive UI (Phase 0)
---
## 📈 Metriken
**Commits (heute):** 12
**Issues geschlossen:** 2 (#28, #44)
**Issues erstellt:** 1 (#47)
**Dokumentations-Updates:** 3 (CLAUDE.md, STATUS_REPORT, issue-50)
**Gitea Kommentare:** 2
**Entwicklungszeit (geschätzt):** ~6-8 Stunden
- circ_summary Enhancement: 1h
- Stage Outputs Fix: 1h
- Value Table Collapsible JSON: 1h
- Issue-Management System: 1h
- Dokumentation & Sync: 2-4h
---
## ✅ Verifizierung
- [x] Alle Gitea Issues überprüft (47 Issues total)
- [x] Abgeschlossene Arbeiten identifiziert (#28, #44)
- [x] Issues in Gitea geschlossen
- [x] Completion-Kommentare hinzugefügt
- [x] CLAUDE.md aktualisiert
- [x] Status Report erstellt
- [x] Entwicklungs-Dokumentation aktuell
**Audit durchgeführt von:** Claude Code
**Datum:** 26. März 2026, 14:55 Uhr
**Branch:** develop
**Letzter Commit:** 582f125
+284
View File
@@ -0,0 +1,284 @@
# Goal System - TODO & Offene Punkte
**Erstellt:** 27. März 2026
**Status:** Aktiv
**Zweck:** Zentrale Tracking-Liste für Goal System Entwicklung
---
## ✅ Erledigt (27.03.2026)
### Phase 0a: Minimal Goal System (26.03.2026)
- ✅ Migration 022 (goal_mode, goals, training_phases, fitness_tests)
- ✅ Backend Router goals.py (490 Zeilen)
- ✅ Frontend GoalsPage (570 Zeilen)
- ✅ Navigation Integration (Dashboard + Analysis)
### Phase 1: Quick Fixes (27.03.2026)
- ✅ goal_utils.py Abstraction Layer
- ✅ Primary Goal Toggle Fix
- ✅ Lean Mass Berechnung
- ✅ VO2Max Spaltenname Fix
---
## 🔲 Nächste Schritte (Priorität)
### Phase 1.5: Flexibles Goal System - DB-Registry ✅ KOMPLETT (27.03.2026)
**Status:** ✅ ABGESCHLOSSEN
**Priorität:** CRITICAL (blockt Phase 0b)
**Aufwand:** 8h (geplant 8-12h)
**Entscheidung:** 27.03.2026 - Option B gewählt
**Problem:**
- Aktuelles System: Hardcoded goal types (nur 8 Typen möglich)
- Jedes neue Ziel braucht Code-Änderung + Deploy
- Zukünftige Ziele (Meditation, Rituale, Planabweichung) nicht möglich
**Lösung: DB-Registry**
- Goal Types in Datenbank definiert
- Admin UI: Neue Ziele ohne Code erstellen
- Universal Value Fetcher (konfigurierbar)
- User kann eigene Custom-Metriken definieren
**Tasks:**
- ✅ Migration 024: goal_type_definitions Tabelle
- ✅ Backend: Universal Value Fetcher (_fetch_latest, _fetch_avg, _fetch_count)
- ✅ Backend: CRUD API für Goal Type Definitions
- ✅ Frontend: Dynamisches Goal Types Dropdown
- ✅ Admin UI: Goal Type Management Page
- ✅ Seed Data: 8 existierende Typen migriert
- 🔲 Testing: Alle Goals + Custom Goal erstellen (NEXT)
**Warum JETZT (vor Phase 0b)?**
- Phase 0b Platzhalter nutzen Goals für Score-Berechnungen
- Flexible Goals → automatisch in Platzhaltern verfügbar
- Später umbauen = 120+ Platzhalter anpassen (Doppelarbeit)
**Dokumentation:** Siehe unten "Flexibles Goal System Details"
---
### Phase 0b: Goal-Aware Placeholders (NACH 1.5 - 16-20h)
**Status:** 🔲 BEREIT ZUM START (Phase 1.5 ✅)
**Priorität:** HIGH (strategisch kritisch)
**Aufwand:** 16-20h
**Blockt:** Intelligente KI-Analysen
**Tasks:**
- [ ] 18 KÖRPER Platzhalter (weight_7d_rolling_median, fm_28d_delta, lbm_28d_delta, recomposition_score, etc.)
- [ ] 15 ERNÄHRUNG Platzhalter (protein_g_per_kg, nutrition_adherence_score, energy_availability_status, etc.)
- [ ] 25 AKTIVITÄT Platzhalter (activity_quality_avg_28d, activity_strain_28d, ability_balance_score, etc.)
- [ ] 12 RECOVERY Platzhalter (recovery_score, sleep_regularity_index, sleep_debt_hours, etc.)
- [ ] 8 KORRELATIONEN Platzhalter (corr_energy_weight_lag, plateau_detected, etc.)
- [ ] 6 META Platzhalter (goal_mode, data_quality_score, profile_age_years, etc.)
- [ ] Score-Gewichtung pro goal_mode (SCORE_WEIGHTS Dictionary)
- [ ] Baseline-Berechnungen (7d/28d/90d Referenzwerte)
- [ ] Integration in bestehende Prompts
**Vorteile:**
- System wird "intelligent" (kein Datensammler mehr)
- Ziele werden tatsächlich genutzt
- Basis für automatische Trainingsphasen-Erkennung
**Dokumentation:** `docs/NEXT_STEPS_2026-03-26.md` (Zeile 116-300)
---
### v2.0 Redesign (SPÄTER - 8-10h)
**Status:** 📋 KONZEPTION
**Priorität:** MEDIUM (nach Phase 0b & User-Feedback)
**Aufwand:** 8-10h (dank Abstraction Layer)
**Probleme zu lösen:**
1. ❌ Primärziel zu simplistisch (nur 1 erlaubt)
2. ❌ Goal Mode zu simpel (nur 1 Modus wählbar)
3. ✅ Fehlende Current Values (ERLEDIGT in Phase 1)
4. ❌ Abstrakte Zieltypen (strength, flexibility)
5. ❌ Blutdruck braucht 2 Werte (systolisch/diastolisch)
6. ❌ Keine Guidance für User (Richtwerte fehlen)
**Lösung:**
- Migration 023: focus_areas Tabelle mit Gewichtungssystem
- UI: Slider für 6 Fokus-Bereiche (Summe = 100%)
- Backend: `get_focus_weights()` V2 Implementierung (eine Funktion!)
- Compound Goals für BP
- Konkrete Test-basierte Goals (Cooper, Plank, etc.)
- Richtwerte & Normen in UI
**Dokumentation:** `docs/GOAL_SYSTEM_REDESIGN_v2.md`
**Entscheidung:** ⏳ Wartet auf User-Feedback nach Phase 0b
---
## 🔗 Verwandte Issues
### Gitea (http://192.168.2.144:3000/Lars/mitai-jinkendo/issues)
- **#49:** Prompt-Zuordnung zu Verlaufsseiten (6-8h, Quick Win)
- **#47:** Wertetabelle Optimierung (4-6h, Polishing)
- **#50:** Phase 0a Goal System (✅ CLOSED)
### Interne Docs
- `docs/issues/issue-50-phase-0a-goal-system.md` (✅ Completed)
- `docs/issues/issue-51-prompt-page-assignment.md` (#49 Spec)
---
## 📊 Roadmap-Übersicht
| Phase | Was | Status | Aufwand |
|-------|-----|--------|---------|
| **Phase 0a** | Minimal Goal System | ✅ DONE | 3-4h |
| **Phase 1** | Quick Fixes + Abstraction | ✅ DONE | 4-6h |
| **Phase 1.5** | 🆕 **Flexibles Goal System (DB-Registry)** | ✅ **DONE** | 8h |
| **Phase 0b** | Goal-Aware Placeholders | 🔲 READY | 16-20h |
| **Issue #49** | Prompt Page Assignment | 🔲 OPEN | 6-8h |
| **v2.0** | Redesign (Focus Areas) | 📋 LATER | 8-10h |
**Total Roadmap:** ~45-60h bis vollständiges intelligentes Goal System
**KRITISCH:** Phase 1.5 MUSS vor Phase 0b abgeschlossen sein, sonst Doppelarbeit!
---
## 💡 Wichtige Notizen
### Abstraction Layer (Keine Doppelarbeit!)
**Datei:** `backend/goal_utils.py`
```python
get_focus_weights(conn, profile_id)
```
- **V1 (jetzt):** Mappt goal_mode → Gewichte
- **V2 (v2.0):** Liest focus_areas Tabelle
- **Vorteil:** 120+ Phase 0b Platzhalter müssen NICHT umgeschrieben werden
### Testing Checklist (nach jedem Deploy)
- [ ] Goal Mode ändern → Gewichtung korrekt?
- [ ] Primäres Ziel setzen → Andere auf false?
- [ ] Lean Mass Ziel → Current Value berechnet?
- [ ] VO2Max Ziel → Kein Server Error?
- [ ] Mehrere Ziele → Progress korrekt?
---
## 📅 Timeline
| Datum | Event |
|-------|-------|
| 26.03.2026 | Phase 0a Complete |
| 27.03.2026 | Phase 1 Complete (Quick Fixes) |
| 28.03.2026 | **Phase 0b Start (geplant)** |
| 02.04.2026 | Phase 0b Complete (geschätzt bei 4h/Tag) |
| 04.04.2026 | v2.0 Redesign (wenn validiert) |
---
## 🔧 Flexibles Goal System - Technische Details
### Architektur: DB-Registry Pattern
**Vorher (Phase 0a/1):**
```javascript
// Frontend: Hardcoded
const GOAL_TYPES = {
weight: { label: 'Gewicht', unit: 'kg', icon: '⚖️' }
}
// Backend: Hardcoded if/elif
if goal_type == 'weight':
cur.execute("SELECT weight FROM weight_log...")
elif goal_type == 'body_fat':
cur.execute("SELECT body_fat_pct FROM caliper_log...")
```
**Nachher (Phase 1.5):**
```sql
-- Datenbank: Konfigurierbare Goal Types
CREATE TABLE goal_type_definitions (
type_key VARCHAR(50) UNIQUE,
label_de VARCHAR(100),
unit VARCHAR(20),
icon VARCHAR(10),
category VARCHAR(50),
source_table VARCHAR(50),
source_column VARCHAR(50),
aggregation_method VARCHAR(20), -- latest, avg_7d, count_7d, etc.
calculation_formula TEXT, -- JSON für komplexe Berechnungen
is_system BOOLEAN -- System-Typen nicht löschbar
);
```
```python
# Backend: Universal Fetcher
def get_current_value_for_goal(conn, profile_id, goal_type):
"""Liest Config aus DB, führt Query aus"""
config = get_goal_type_config(conn, goal_type)
if config['calculation_formula']:
return execute_formula(conn, profile_id, config['calculation_formula'])
else:
return fetch_by_method(
conn, profile_id,
config['source_table'],
config['source_column'],
config['aggregation_method']
)
```
```javascript
// Frontend: Dynamisch
const goalTypes = await api.getGoalTypeDefinitions()
// Lädt aktuell verfügbare Typen von API
```
### Vorteile:
**Flexibilität:**
- ✅ Neue Ziele via Admin UI (KEIN Code-Deploy)
- ✅ User kann Custom-Metriken definieren
- ✅ Zukünftige Module automatisch integriert
**Beispiele neuer Ziele:**
- 🧘 Meditation (min/Tag) → `meditation_log.duration_minutes`, avg_7d
- 📅 Trainingshäufigkeit (x/Woche) → `activity_log.id`, count_7d
- 📊 Planabweichung (%) → `activity_log.planned_vs_actual`, avg_30d
- 🎯 Ritual-Adherence (%) → `rituals_log.completed`, avg_30d
- 💤 Schlafqualität (%) → `sleep_log.quality_score`, avg_7d
**Integration mit Phase 0b:**
- Platzhalter nutzen `get_current_value_for_goal()` → automatisch alle Typen verfügbar
- Neue Ziele → sofort in KI-Analysen nutzbar
- Keine Platzhalter-Anpassungen nötig
---
**Letzte Aktualisierung:** 27. März 2026 (Phase 1.5 ✅ ABGESCHLOSSEN)
**Nächste Aktualisierung:** Nach Phase 0b Completion
---
## 🎉 Phase 1.5 Completion Report (27.03.2026)
**Commits:**
- `65ee5f8` - Phase 1.5 Part 1/2 (Backend, Migration, Universal Fetcher)
- `640ef81` - Phase 1.5 Part 2/2 (Frontend Dynamic, Admin UI) - **COMPLETE**
**Implementiert:**
1. ✅ DB-Registry für Goal Types (8 System Types seeded)
2. ✅ Universal Value Fetcher (8 Aggregationsmethoden)
3. ✅ CRUD API (admin-only, System Types geschützt)
4. ✅ Dynamic Frontend (keine hardcoded Types mehr)
5. ✅ Admin UI (vollständiges CRUD Interface)
**System ist jetzt flexibel:**
- Neue Goal Types via UI ohne Code-Deploy
- Phase 0b Platzhalter nutzen automatisch alle Types
- Custom Metrics möglich (Meditation, Rituale, etc.)
**Ready für Phase 0b:** 120+ Goal-Aware Placeholders 🚀
@@ -0,0 +1,245 @@
# Phase 0a: Minimal Goal System (Strategic + Tactical)
**Status:** ✅ ABGESCHLOSSEN (26.03.2026)
**Labels:** feature, enhancement, goal-system
**Priority:** High (Foundation for Phase 0b)
**Aufwand:** 3-4h (geschätzt) / ~4h (tatsächlich)
---
## Beschreibung
Implementierung des minimalen Zielsystems als Basis für goal-aware KI-Analysen. Zwei-Ebenen-Architektur:
- **Strategic Layer:** Goal Modes (beeinflusst Score-Gewichtung)
- **Tactical Layer:** Konkrete Zielwerte mit Progress-Tracking
---
## Implementiert ✅
### Strategic Layer (Goal Modes)
- `goal_mode` in `profiles` table
- 5 Modi: `weight_loss`, `strength`, `endurance`, `recomposition`, `health`
- Bestimmt Score-Gewichtung für alle KI-Analysen
- **UI:** 5 Goal Mode Cards mit Beschreibungen und Icons
### Tactical Layer (Concrete Goals)
- `goals` table mit vollständigem Tracking:
- Target/Current/Start values
- Progress percentage (auto-calculated)
- Projection date & on-track status
- Primary/Secondary goal concept
- 8 Goal-Typen: weight, body_fat, lean_mass, vo2max, strength, flexibility, bp, rhr
- **UI:**
- Goal CRUD mit Fortschrittsbalken
- Mobile-friendly Design (full-width inputs, labels above fields)
- Inline editing vorbereitet
### Training Phases Framework
- `training_phases` table (Auto-Detection vorbereitet für Phase 2)
- 5 Phase-Typen: calorie_deficit, calorie_surplus, deload, maintenance, periodization
- Status-Flow: suggested → accepted → active → completed → rejected
- Confidence scoring für KI-basierte Erkennung
- JSONB detection_params für Flexibilität
### Fitness Tests
- `fitness_tests` table für standardisierte Tests
- 8 Test-Typen: cooper_12min, step_test, pushups_max, plank_max, flexibility_sit_reach, vo2max_est, strength_1rm_squat, strength_1rm_bench
- Norm-Kategorisierung vorbereitet (age/gender-spezifisch)
- Baseline-Tracking für Fortschrittsmessung
---
## Technische Umsetzung
### Backend
**Migration 022:** `backend/migrations/022_goal_system.sql`
```sql
-- Strategic Layer
ALTER TABLE profiles ADD COLUMN goal_mode VARCHAR(50) DEFAULT 'health';
-- Tactical Layer
CREATE TABLE goals (...);
CREATE TABLE training_phases (...);
CREATE TABLE fitness_tests (...);
```
**Router:** `backend/routers/goals.py` (490 Zeilen)
- Vollständiges CRUD für alle 3 Ebenen
- Progress calculation (auto-update current values)
- Linear projection für target_date
- Helper functions für goal-type spezifische Current-Values
**API Endpoints:** `/api/goals/*`
- `GET/PUT /mode` - Strategic goal mode
- `GET /list` - All goals with progress
- `POST /create` - Create goal
- `PUT /{id}` - Update goal
- `DELETE /{id}` - Delete goal
- `GET/POST /phases` - Training phases
- `PUT /phases/{id}/status` - Accept/reject auto-detected phases
- `GET/POST /tests` - Fitness tests
### Frontend
**GoalsPage:** `frontend/src/pages/GoalsPage.jsx` (570 Zeilen)
- **Goal Mode Selector:** 5 Karten mit Icons, Farben, Beschreibungen
- **Goal List:** Cards mit Progress-Balken, Projection-Display, Edit/Delete
- **Goal Form:** Mobile-optimiertes Modal
- Full-width inputs
- Labels above fields (not beside)
- Section headers with emoji (🎯 Zielwert)
- Unit display as styled badge
- Primary goal checkbox in highlighted section
- Text-align: left für Text-Felder, right für Zahlen
- **Empty State:** Placeholder mit CTA
**Navigation Integration:**
- **Dashboard:** Goals Preview Card mit "Verwalten →" Link
- **Analysis Page:** 🎯 Ziele Button neben Titel (direkter Zugang)
- **Route:** `/goals` in App.jsx registriert
**api.js:** 15+ neue API-Funktionen
```javascript
// Goal Modes
getGoalMode(), updateGoalMode(mode)
// Goals CRUD
listGoals(), createGoal(data), updateGoal(id, data), deleteGoal(id)
// Training Phases
listTrainingPhases(), createTrainingPhase(data), updatePhaseStatus(id, status)
// Fitness Tests
listFitnessTests(), createFitnessTest(data)
```
---
## Commits
| Commit | Beschreibung |
|--------|-------------|
| `337667f` | feat: Phase 0a - Minimal Goal System (Strategic + Tactical) |
| `906a3b7` | fix: Migration 022 - remove invalid schema_migrations tracking |
| `75f0a5d` | refactor: mobile-friendly goal form design |
| `5be52bc` | feat: goals navigation + UX improvements |
**Branch:** `develop`
**Deployed to:** `dev.mitai.jinkendo.de` ✅
---
## Dokumentation
- ✅ `docs/GOALS_SYSTEM_UNIFIED_ANALYSIS.md` (538 Zeilen)
- Analyse beider Fachkonzepte (Konzept v2 + GOALS_VITALS.md)
- Zwei-Ebenen-Architektur erklärt
- 120+ Placeholder-Kategorisierung für Phase 0b
- ✅ Migration 022 mit vollständigen COMMENT ON statements
- ✅ API-Dokumentation in Router-Docstrings
- ✅ Dieses Issue-Dokument
---
## Basis für Phase 0b
Phase 0a bietet die Foundation für:
### Phase 0b: Goal-Aware Placeholders (16-20h)
- ✅ 120+ neue Platzhalter die `goal_mode` berücksichtigen
- ✅ Score-Berechnungen abhängig von Strategic Layer
- ✅ Baseline-Berechnungen (7d/28d/90d Trends)
- ✅ Lag-basierte Korrelationen
- ✅ Confidence Scoring
**Beispiel Goal-Mode Impact:**
```python
# Gleiche Daten, unterschiedliche Interpretation:
Δ: -5kg FM, -2kg LBM
goal_mode = "weight_loss"
→ body_progress_score = 78/100 (FM↓ gut, LBM↓ tolerierbar)
goal_mode = "strength"
→ body_progress_score = 32/100 (LBM↓ ist KATASTROPHE!)
goal_mode = "health"
→ body_progress_score = 50/100 (neutral, ohne Bias)
```
---
## Testing
✅ Migration erfolgreich auf dev.mitai.jinkendo.de
✅ Goal Mode wechselbar
✅ Goal CRUD funktioniert
✅ Progress calculation korrekt
✅ Mobile UI responsive
✅ Navigation von Dashboard + Analysis
**Manuelle Tests durchgeführt:**
- [x] Goal Mode ändern
- [x] Ziel erstellen (alle 8 Typen)
- [x] Ziel bearbeiten
- [x] Ziel löschen
- [x] Primary Goal setzen
- [x] Progress-Balken korrekt
- [x] Mobile UI full-width
- [x] Text-Align korrekt
---
## Akzeptanzkriterien
- [x] Migration 022 erfolgreich
- [x] Goal Mode in profiles funktioniert
- [x] Goals CRUD vollständig
- [x] Progress-Tracking funktioniert
- [x] Primary Goal Konzept implementiert
- [x] Mobile-friendly UI
- [x] Navigation von 2+ Stellen
- [x] API-Dokumentation vollständig
- [x] Frontend form validation
- [x] Error handling korrekt
---
## Nächste Schritte
**Empfohlen:**
1. **Option A: Issue #49 - Prompt Page Assignment (6-8h)**
- Prompts auf Verlaufsseiten zuordnen
- Quick Win für bessere UX
- Nutzt bestehendes Unified Prompt System
2. **Option B: Phase 0b - Goal-Aware Placeholders (16-20h)**
- 120+ neue Platzhalter
- Score-Berechnungen mit goal_mode
- Größter strategischer Impact
**Siehe:** `docs/NEXT_STEPS_2026-03-26.md` für detaillierte Planung
---
## Lessons Learned
### Was gut lief:
- ✅ Zwei-Ebenen-Architektur (Strategic + Tactical) macht Sinn
- ✅ Mobile-first Design von Anfang an
- ✅ Unified Analysis vor Implementierung (beide Fachkonzepte)
- ✅ Migration-System funktioniert einwandfrei
### Was zu beachten ist:
- ⚠️ Schema_migrations verwendet `filename`, nicht `version`
- ⚠️ Unnötige DO-Blocks in Migrationen vermeiden
- ⚠️ Text-align: right als Default in form-input (für Textfelder überschreiben)
---
**Erstellt:** 26. März 2026
**Status:** ✅ COMPLETE - Ready for Phase 0b
**Related Issues:** #49 (Prompt Assignment), #47 (Value Table Refinement)
@@ -0,0 +1,181 @@
# Enhancement: Wertetabelle Optimierung
**Labels:** enhancement, ux
**Priority:** Medium (Phase 1)
**Related:** Issue #47 (Value Table - Complete)
## Beschreibung
Wertetabelle übersichtlicher gestalten durch intelligente Filterung und Beschreibungs-Vervollständigung.
## Problem (aktueller Stand)
Nach Implementierung von Issue #47 haben wir eine sehr umfangreiche Wertetabelle mit:
- Reguläre Platzhalter (PROFIL, KÖRPER, etc.)
- Extrahierte Einzelwerte aus Stages (↳ Symbol)
- Rohdaten der Stage-Outputs (🔬 JSON)
**Probleme:**
1. Zu viele Werte im Normal-Modus (unübersichtlich)
2. Stage-Rohdaten sollten nur im Experten-Modus sichtbar sein
3. Einige Platzhalter haben keine/unvollständige Beschreibungen
## Gewünschtes Verhalten
### Normal-Modus (Standard)
```
📊 Verwendete Werte (24) [🔬 Experten-Modus]
PROFIL
├─ name: Lars Stommer
├─ age: 35 Jahre (Geburtsdatum 1990-05-15)
├─ height: 178cm (Körpergröße)
KÖRPER
├─ weight_aktuell: 85.2kg (Aktuelles Gewicht)
├─ bmi: 26.9 (Body-Mass-Index)
├─ bmi_interpretation: Leicht übergewichtig (BMI-Bewertung)
├─ kf_aktuell: 18.5% (Körperfettanteil)
ERNÄHRUNG
├─ kcal_avg: 2450 kcal (Durchschnitt 7 Tage)
...
Stage 1 - Body (Extrahierte Werte)
├─ ↳ trend: leicht sinkend (Gewichtstrend)
├─ ↳ ziel_erreichbar: ja, in 8 Wochen (Zielerreichbarkeit)
```
**Ausgeblendet:**
- 🔬 stage_1_stage1_body (komplettes JSON)
- Leere/nicht verfügbare Werte
### Experten-Modus
```
📊 Verwendete Werte (32) [🔬 Experten-Modus ✓]
[... wie Normal-Modus ...]
Stage 1 - Rohdaten
├─ 🔬 stage_1_stage1_body
└─ [JSON anzeigen ▼]
{
"bmi": 26.9,
"trend": "leicht sinkend",
"ziel_erreichbar": "ja, in 8 Wochen",
"interpretation": "Dein BMI liegt..."
}
Stage 2 - Rohdaten
├─ 🔬 stage_2_stage2_nutrition
└─ [JSON anzeigen ▼]
{ ... }
```
**Zusätzlich sichtbar:**
- Alle Stage-Rohdaten (🔬 JSON)
- Leere/nicht verfügbare Werte
- Debug-Informationen
## Technische Umsetzung
### 1. Filterlogik anpassen (Analysis.jsx)
**Aktuell:**
```javascript
const placeholders = expertMode
? allPlaceholders
: Object.fromEntries(
Object.entries(allPlaceholders).filter(([key, data]) => {
if (data.is_stage_raw) return false // Versteckt Rohdaten
const val = data.value || ''
return val.trim() !== '' && val !== 'nicht verfügbar'
})
)
```
**Problem:** `is_stage_raw` wird nur für Keys wie "stage_1_stage1_body" gesetzt, nicht für extrahierte Werte.
**Lösung:** Neue Flag `is_extracted` (bereits vorhanden) wird beibehalten, `is_stage_raw` nur für komplette JSON-Outputs.
### 2. Beschreibungen vervollständigen (placeholder_resolver.py)
**Fehlende Beschreibungen prüfen:**
```python
# In get_placeholder_catalog()
PLACEHOLDER_CATALOG = {
'PROFIL': [
{'key': 'name', 'description': 'Name des Nutzers', 'example': '...'},
{'key': 'age', 'description': 'Alter in Jahren', 'example': '35'},
# ... alle prüfen
],
'KÖRPER': [
{'key': 'weight_aktuell', 'description': 'Aktuelles Gewicht', 'example': '85.2kg'},
{'key': 'bmi', 'description': 'Body-Mass-Index (berechnet)', 'example': '26.9'},
# ... alle prüfen
],
# ... alle Kategorien durchgehen
}
```
**Aktionen:**
- Alle 32 Platzhalter durchgehen
- Fehlende Beschreibungen ergänzen
- Beschreibungen aus Kontext ableiten (z.B. bei extrahierten Werten aus Stage-Output)
### 3. Extrahierte Werte beschreiben (prompts.py)
**Aktuell (Line 896-901):**
```python
metadata['placeholders'][field_key] = {
'value': field_data['value'],
'description': f"Aus Stage {field_data['source_stage']} ({field_data['source_output']})",
'is_extracted': True,
'category': category
}
```
**Verbesserung:**
- Wenn Base-Prompt ein JSON-Schema hat, Feld-Beschreibungen aus Schema extrahieren
- Fallback: Generische Beschreibung aus Kontext
**Beispiel:**
```python
# Wenn output_schema verfügbar:
schema = base_prompt.get('output_schema', {})
properties = schema.get('properties', {})
field_description = properties.get(field_key, {}).get('description', '')
metadata['placeholders'][field_key] = {
'value': field_data['value'],
'description': field_description or f"Aus Stage {stage_num} ({output_name})",
'is_extracted': True,
'category': category
}
```
## Akzeptanzkriterien
- [ ] Normal-Modus zeigt nur Einzelwerte (regulär + extrahiert ↳)
- [ ] Experten-Modus zeigt zusätzlich Stage-Rohdaten (🔬 JSON)
- [ ] Alle 32 Platzhalter haben sinnvolle Beschreibungen
- [ ] Extrahierte Werte nutzen Schema-Beschreibungen (wenn vorhanden)
- [ ] Toggle "Experten-Modus" funktioniert korrekt
- [ ] Kategorien bleiben sauber getrennt
- [ ] Leere Werte werden im Normal-Modus ausgeblendet
## Abschätzung
**Aufwand:** 4-6 Stunden
- 1h: Filterlogik testen/anpassen
- 2-3h: Beschreibungen vervollständigen (32 Platzhalter)
- 1h: Schema-basierte Beschreibungen für extrahierte Werte
- 1h: Testing + Feintuning
**Priorität:** Medium (verbessert UX erheblich, aber keine kritische Funktionalität)
## Notizen
- Issue #47 hat die Grundlage geschaffen (Kategorien, Expert-Mode, Stage-Outputs)
- Diese Optimierung macht die Wertetabelle produktionsreif
- Beschreibungen sind wichtig für KI-Kontext UND User-Verständnis
- ggf. später: Beschreibungen editierbar machen (Admin-UI)
@@ -0,0 +1,425 @@
# Feature: Prompt-Zuordnung zu Verlaufsseiten
**Labels:** feature, ux, enhancement
**Priority:** Medium (Phase 1-2)
**Related:** Issue #28 (Unified Prompt System - Complete)
## Beschreibung
KI-Prompts sollen flexibel auf verschiedenen Verlaufsseiten verfügbar gemacht werden können. Jeder Prompt kann auf mehreren Seiten gleichzeitig angeboten werden (Mehrfachauswahl).
## Problem (aktueller Stand)
**Aktuell:**
- Prompts sind nur über die zentrale Analyse-Seite (📊 Analyse) verfügbar
- Kein kontextbezogener Zugriff auf relevante Analysen
- User muss immer zur Analyse-Seite navigieren
**Beispiel-Szenario:**
```
User ist auf: Gewicht → Verlauf
Will: Gewichtstrend analysieren
Muss: Zur Analyse-Seite → Prompt auswählen → Zurück
```
**Wünschenswert:**
```
User ist auf: Gewicht → Verlauf
Sieht: "🤖 KI-Analyse" Button mit relevanten Prompts
Kann: Direkt "Gewichtstrend-Analyse" starten
```
## Gewünschtes Verhalten
### 1. Prompt-Konfiguration erweitern
**Admin → KI-Prompts → Prompt bearbeiten:**
```
┌─────────────────────────────────────────────┐
│ Prompt bearbeiten: Gewichtstrend-Analyse │
├─────────────────────────────────────────────┤
│ Name: Gewichtstrend-Analyse │
│ Slug: weight_trend │
│ Type: Pipeline │
│ │
│ 📍 Verfügbar auf Seiten: │
│ ┌─────────────────────────────────────────┐ │
│ │ ☑ Analyse (Hauptseite) │ │
│ │ ☑ Gewicht → Verlauf │ │
│ │ ☐ Umfänge → Verlauf │ │
│ │ ☐ Caliper → Verlauf │ │
│ │ ☐ Aktivität → Verlauf │ │
│ │ ☐ Ernährung → Verlauf │ │
│ │ ☐ Schlaf → Verlauf │ │
│ │ ☐ Vitalwerte → Verlauf │ │
│ │ ☐ Dashboard │ │
│ └─────────────────────────────────────────┘ │
│ │
│ [Speichern] [Abbrechen] │
└─────────────────────────────────────────────┘
```
**Mehrfachauswahl:**
- Ein Prompt kann auf mehreren Seiten gleichzeitig verfügbar sein
- Mindestens eine Seite muss ausgewählt sein
- Default: "Analyse (Hauptseite)" ist immer vorausgewählt
### 2. UI auf Verlaufsseiten
**Gewicht → Verlauf:**
```
┌─────────────────────────────────────────────┐
│ 📊 Gewicht - Verlauf │
│ [Filter: 7d] [30d] [90d] [Alle] │
├─────────────────────────────────────────────┤
│ │
│ [Chart: Gewichtsverlauf] │
│ │
├─────────────────────────────────────────────┤
│ 🤖 KI-Analysen │
│ ┌─────────────────────────────────────────┐ │
│ │ Gewichtstrend-Analyse [▶ Starten]│ │
│ │ Körperkomposition-Check [▶ Starten]│ │
│ └─────────────────────────────────────────┘ │
│ │
│ [Einträge-Tabelle...] │
└─────────────────────────────────────────────┘
```
**Features:**
- Kompaktes Widget unterhalb des Charts
- Nur relevante Prompts werden angezeigt
- Button startet Analyse inline (Modal oder expandierend)
- Ergebnis wird direkt auf der Seite angezeigt
### 3. Inline-Analyse Anzeige
**Option A: Modal (empfohlen für MVP):**
```
Click auf [▶ Starten]
↓
┌─────────────────────────────────────────────┐
│ ✕ Gewichtstrend-Analyse │
├─────────────────────────────────────────────┤
│ [Spinner] Analysiere Gewichtsdaten... │
│ │
│ [Nach Abschluss:] │
│ Analyse-Text... │
│ │
│ 📊 Verwendete Werte (12) [🔬 Experten] │
│ [Value Table...] │
│ │
│ [Schließen] [In Verlauf speichern] │
└─────────────────────────────────────────────┘
```
**Option B: Expandierend (später):**
```
Click auf [▶ Starten]
↓
Widget expandiert nach unten
Zeigt Analyse-Ergebnis inline
[△ Einklappen] Button
```
## Technische Umsetzung
### 1. Datenbankschema erweitern
**Tabelle: `ai_prompts`**
```sql
ALTER TABLE ai_prompts ADD COLUMN available_on JSONB DEFAULT '["analysis"]';
COMMENT ON COLUMN ai_prompts.available_on IS
'Array of page slugs where prompt is available.
Values: analysis, weight_history, circ_history, caliper_history,
activity_history, nutrition_history, sleep_history, vitals_history, dashboard';
-- Migration 022
```
**Beispiel-Werte:**
```json
{
"slug": "weight_trend",
"name": "Gewichtstrend-Analyse",
"available_on": ["analysis", "weight_history"]
}
{
"slug": "pipeline_master",
"name": "Vollständige Analyse",
"available_on": ["analysis", "dashboard"]
}
{
"slug": "nutrition_check",
"name": "Ernährungs-Check",
"available_on": ["analysis", "nutrition_history", "activity_history"]
}
```
### 2. Backend API erweitern
**Neuer Endpoint: GET /api/prompts/for-page/{page_slug}**
```python
@router.get("/for-page/{page_slug}")
def get_prompts_for_page(page_slug: str, session: dict = Depends(require_auth)):
"""Get all prompts available for a specific page.
Args:
page_slug: Page identifier (e.g., 'weight_history', 'analysis')
Returns:
List of prompts with available_on containing page_slug
"""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""SELECT id, name, slug, type, description, available_on
FROM ai_prompts
WHERE available_on @> %s
ORDER BY name""",
(json.dumps([page_slug]),)
)
return [r2d(row) for row in cur.fetchall()]
```
**Beispiel-Aufruf:**
```javascript
// In WeightPage.jsx
const prompts = await api.getPromptsForPage('weight_history')
// Returns: [{slug: 'weight_trend', name: 'Gewichtstrend-Analyse', ...}]
```
**Prompt CRUD erweitern:**
```python
@router.put("/unified/{id}")
def update_unified_prompt(id: str, p: UnifiedPromptCreate, session=Depends(require_admin)):
# ... existing code ...
cur.execute(
"""UPDATE ai_prompts
SET name=%s, slug=%s, template=%s, ..., available_on=%s
WHERE id=%s""",
(..., json.dumps(p.available_on), id)
)
```
### 3. Frontend: Prompt-Editor erweitern
**UnifiedPromptModal.jsx:**
```javascript
const PAGE_OPTIONS = [
{ value: 'analysis', label: '📊 Analyse (Hauptseite)', default: true },
{ value: 'weight_history', label: '⚖️ Gewicht → Verlauf' },
{ value: 'circ_history', label: '📏 Umfänge → Verlauf' },
{ value: 'caliper_history', label: '📐 Caliper → Verlauf' },
{ value: 'activity_history', label: '🏃 Aktivität → Verlauf' },
{ value: 'nutrition_history', label: '🍎 Ernährung → Verlauf' },
{ value: 'sleep_history', label: '😴 Schlaf → Verlauf' },
{ value: 'vitals_history', label: '❤️ Vitalwerte → Verlauf' },
{ value: 'dashboard', label: '🏠 Dashboard' },
]
// In form:
<div className="form-row">
<label>Verfügbar auf Seiten</label>
<div style={{display: 'flex', flexDirection: 'column', gap: 8}}>
{PAGE_OPTIONS.map(opt => (
<label key={opt.value} style={{display: 'flex', gap: 8, alignItems: 'center'}}>
<input
type="checkbox"
checked={availableOn.includes(opt.value)}
onChange={e => {
if (e.target.checked) {
setAvailableOn([...availableOn, opt.value])
} else {
// Don't allow unchecking all
if (availableOn.length > 1) {
setAvailableOn(availableOn.filter(v => v !== opt.value))
}
}
}}
/>
{opt.label}
</label>
))}
</div>
</div>
```
### 4. Frontend: Verlaufsseiten erweitern
**WeightPage.jsx (Beispiel):**
```javascript
function WeightPage() {
const [prompts, setPrompts] = useState([])
const [runningAnalysis, setRunningAnalysis] = useState(null)
const [analysisResult, setAnalysisResult] = useState(null)
useEffect(() => {
loadPrompts()
}, [])
const loadPrompts = async () => {
try {
const data = await api.getPromptsForPage('weight_history')
setPrompts(data)
} catch(e) {
console.error('Failed to load prompts:', e)
}
}
const runAnalysis = async (promptSlug) => {
setRunningAnalysis(promptSlug)
try {
const result = await api.executePrompt(promptSlug, {save: true})
setAnalysisResult(result)
} catch(e) {
setError(e.message)
} finally {
setRunningAnalysis(null)
}
}
return (
<div className="page">
<h1>Gewicht - Verlauf</h1>
{/* Chart */}
<WeightChart data={data} />
{/* AI Prompts Widget */}
{prompts.length > 0 && (
<div className="ai-prompts-widget">
<h3>🤖 KI-Analysen</h3>
{prompts.map(p => (
<button
key={p.slug}
onClick={() => runAnalysis(p.slug)}
disabled={runningAnalysis === p.slug}
>
{p.name} {runningAnalysis === p.slug ? '⏳' : '▶'}
</button>
))}
</div>
)}
{/* Analysis Result Modal */}
{analysisResult && (
<AnalysisResultModal
result={analysisResult}
onClose={() => setAnalysisResult(null)}
/>
)}
{/* Data Table */}
<DataTable entries={entries} />
</div>
)
}
```
**Wiederverwendbare Komponente:**
```javascript
// components/PagePrompts.jsx
export function PagePrompts({ pageSlug }) {
// ... logic ...
return (
<div className="page-prompts">
<h3>🤖 KI-Analysen</h3>
{prompts.map(p => (
<PromptButton key={p.slug} prompt={p} onRun={runAnalysis} />
))}
</div>
)
}
// Usage in any page:
<PagePrompts pageSlug="weight_history" />
```
## Akzeptanzkriterien
- [ ] DB-Migration: `available_on` JSONB column in ai_prompts
- [ ] Backend: `GET /api/prompts/for-page/{page_slug}` Endpoint
- [ ] Backend: CRUD operations unterstützen available_on
- [ ] Frontend: Prompt-Editor zeigt Page-Auswahl (Mehrfachauswahl)
- [ ] Frontend: Mindestens 1 Page muss ausgewählt sein
- [ ] Frontend: Wiederverwendbare PagePrompts Komponente
- [ ] Frontend: Integration in mind. 2 Verlaufsseiten (Weight, Nutrition)
- [ ] UI: Inline-Analyse via Modal mit Value Table
- [ ] UI: Loading-State während Analyse läuft
- [ ] Dokumentation: API-Dokumentation aktualisiert
## Abschätzung
**Aufwand:** 6-8 Stunden
- 1h: DB-Migration + Backend Endpoint
- 2h: Prompt-Editor erweitern (Page-Auswahl)
- 2h: PagePrompts Komponente + Modal
- 2h: Integration in Verlaufsseiten (2-3 Seiten)
- 1h: Testing + Feintuning
**Priorität:** Medium
- Verbessert UX erheblich (kontextbezogene Analysen)
- Nutzt bestehendes Prompt-System (Issue #28)
- Relativ einfach zu implementieren (kein neues Backend-System)
## Use Cases
### UC1: Gewichtstrend auf Gewicht-Seite
```
User: Navigiert zu "Gewicht → Verlauf"
System: Zeigt Gewichts-Chart + verfügbare Prompts
User: Click "Gewichtstrend-Analyse ▶"
System: Startet Analyse, zeigt Modal mit Ergebnis
User: Click "In Verlauf speichern"
System: Speichert in ai_insights, zeigt in Analyse-Verlauf
```
### UC2: Ernährungs-Check auf Ernährung-Seite
```
User: Navigiert zu "Ernährung → Verlauf"
System: Zeigt Ernährungs-Charts + verfügbare Prompts
User: Click "Ernährungs-Check ▶"
System: Analysiert Makros + Kalorien der letzten 7 Tage
User: Sieht Empfehlungen direkt auf Ernährungs-Seite
```
### UC3: Multi-Page Prompt (z.B. "Vollständige Analyse")
```
Admin: Konfiguriert "Vollständige Analyse"
- Verfügbar auf: [Analyse, Dashboard, Gewicht, Ernährung]
User: Sieht denselben Prompt auf 4 verschiedenen Seiten
User: Kann von überall die gleiche umfassende Analyse starten
```
## Notizen
- **Rückwärtskompatibilität:** Bestehende Prompts ohne `available_on` → Default `["analysis"]`
- **Migration:** Alle existierenden Prompts bekommen `["analysis"]` gesetzt
- **Permissions:** Prompts respektieren weiterhin Feature-Enforcement (ai_calls)
- **Caching:** Prompts könnten gecacht werden (selten geändert)
- **Mobile:** PagePrompts sollte auch auf Mobile gut aussehen (Stack-Layout)
- **Performance:** Lazy-Loading der Prompts (nur laden wenn Seite besucht)
## Erweiterungen (Future)
- **Conditional Display:** Prompts nur anzeigen wenn Daten vorhanden
- Beispiel: "Gewichtstrend" nur wenn min. 3 Gewichts-Einträge
- **Quick Actions:** Direkt-Buttons im Chart (ohne separates Widget)
- **Page-spezifische Variablen:** Automatisch aktuelle Filter übergeben
- Beispiel: Wenn "30d" Filter aktiv → `{{timeframe}}` = 30
- **Prompt-Templates pro Page:** Vordefinierte Vorlagen für jede Seite
- **Favoriten:** User kann Prompts auf Seiten favorisieren (User-spezifisch)
## Verwandte Issues
- #28: Unified Prompt System (Basis für dieses Feature)
- #45: KI Prompt-Optimierer (könnte Page-Kontext nutzen)
- #46: KI Prompt-Ersteller (sollte Page-Auswahl anbieten)
+13
View File
@@ -0,0 +1,13 @@
#!/bin/bash
# Find correct container name
echo "Suche Backend-Container..."
echo ""
# List all running containers
echo "Alle laufenden Container:"
docker ps --format "{{.Names}}" | grep -i backend
echo ""
echo "Oder alle Container (auch gestoppte):"
docker ps -a --format "{{.Names}}" | grep -i backend
+14
View File
@@ -29,8 +29,15 @@ import AdminCouponsPage from './pages/AdminCouponsPage'
import AdminUserRestrictionsPage from './pages/AdminUserRestrictionsPage'
import AdminTrainingTypesPage from './pages/AdminTrainingTypesPage'
import AdminActivityMappingsPage from './pages/AdminActivityMappingsPage'
import AdminTrainingProfiles from './pages/AdminTrainingProfiles'
import AdminPromptsPage from './pages/AdminPromptsPage'
import AdminGoalTypesPage from './pages/AdminGoalTypesPage'
import SubscriptionPage from './pages/SubscriptionPage'
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() {
@@ -166,6 +173,10 @@ function AppShell() {
<Route path="/caliper" element={<CaliperScreen/>}/>
<Route path="/history" element={<History/>}/>
<Route path="/sleep" element={<SleepPage/>}/>
<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/>}/>
@@ -178,6 +189,9 @@ function AppShell() {
<Route path="/admin/user-restrictions" element={<AdminUserRestrictionsPage/>}/>
<Route path="/admin/training-types" element={<AdminTrainingTypesPage/>}/>
<Route path="/admin/activity-mappings" element={<AdminActivityMappingsPage/>}/>
<Route path="/admin/training-profiles" element={<AdminTrainingProfiles/>}/>
<Route path="/admin/prompts" element={<AdminPromptsPage/>}/>
<Route path="/admin/goal-types" element={<AdminGoalTypesPage/>}/>
<Route path="/subscription" element={<SubscriptionPage/>}/>
</Routes>
</main>
@@ -0,0 +1,255 @@
import { useState, useEffect } from 'react'
import { api } from '../utils/api'
import { Search, X } from 'lucide-react'
/**
* Placeholder Picker with grouped categories and search
*
* Loads placeholders dynamically from backend catalog.
* Grouped by category (Profil, Körper, Ernährung, Training, etc.)
*/
export default function PlaceholderPicker({ onSelect, onClose }) {
const [catalog, setCatalog] = useState({})
const [search, setSearch] = useState('')
const [loading, setLoading] = useState(true)
const [expandedCategories, setExpandedCategories] = useState(new Set())
useEffect(() => {
loadCatalog()
}, [])
const loadCatalog = async () => {
try {
setLoading(true)
const data = await api.listPlaceholders()
setCatalog(data)
// Expand all categories by default
setExpandedCategories(new Set(Object.keys(data)))
} catch (e) {
console.error('Failed to load placeholders:', e)
} finally {
setLoading(false)
}
}
const toggleCategory = (category) => {
const newExpanded = new Set(expandedCategories)
if (newExpanded.has(category)) {
newExpanded.delete(category)
} else {
newExpanded.add(category)
}
setExpandedCategories(newExpanded)
}
const handleSelect = (key) => {
onSelect(`{{${key}}}`)
onClose()
}
// Filter placeholders by search
const filteredCatalog = {}
const searchLower = search.toLowerCase()
Object.entries(catalog).forEach(([category, items]) => {
const filtered = items.filter(item =>
item.key.toLowerCase().includes(searchLower) ||
item.description.toLowerCase().includes(searchLower)
)
if (filtered.length > 0) {
filteredCatalog[category] = filtered
}
})
return (
<div
style={{
position: 'fixed',
inset: 0,
background: 'rgba(0,0,0,0.5)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
zIndex: 2000,
padding: 20
}}
onClick={onClose}
>
<div
onClick={e => e.stopPropagation()}
style={{
background: 'var(--bg)',
borderRadius: 12,
maxWidth: 800,
width: '100%',
maxHeight: '80vh',
display: 'flex',
flexDirection: 'column',
overflow: 'hidden'
}}
>
{/* Header */}
<div style={{
padding: 20,
borderBottom: '1px solid var(--border)',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
}}>
<h3 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>
Platzhalter auswählen
</h3>
<button
onClick={onClose}
style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4 }}
>
<X size={24} color="var(--text3)" />
</button>
</div>
{/* Search */}
<div style={{ padding: '12px 20px', borderBottom: '1px solid var(--border)' }}>
<div style={{ position: 'relative' }}>
<Search
size={16}
style={{
position: 'absolute',
left: 12,
top: '50%',
transform: 'translateY(-50%)',
color: 'var(--text3)'
}}
/>
<input
type="text"
className="form-input"
value={search}
onChange={e => setSearch(e.target.value)}
placeholder="Platzhalter suchen..."
style={{
width: '100%',
paddingLeft: 40,
textAlign: 'left'
}}
/>
</div>
</div>
{/* Categories */}
<div style={{
flex: 1,
overflow: 'auto',
padding: 20
}}>
{loading ? (
<div style={{ textAlign: 'center', padding: 40, color: 'var(--text3)' }}>
Lädt Platzhalter...
</div>
) : Object.keys(filteredCatalog).length === 0 ? (
<div style={{ textAlign: 'center', padding: 40, color: 'var(--text3)' }}>
Keine Platzhalter gefunden
</div>
) : (
Object.entries(filteredCatalog).map(([category, items]) => (
<div key={category} style={{ marginBottom: 16 }}>
<div
onClick={() => toggleCategory(category)}
style={{
padding: '8px 12px',
background: 'var(--surface)',
borderRadius: 8,
cursor: 'pointer',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 8
}}
>
<h4 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>
{category} ({items.length})
</h4>
<span style={{ fontSize: 12, color: 'var(--text3)' }}>
{expandedCategories.has(category) ? '▼' : '▶'}
</span>
</div>
{expandedCategories.has(category) && (
<div style={{ display: 'grid', gap: 6, paddingLeft: 12 }}>
{items.map(item => (
<div
key={item.key}
onClick={() => handleSelect(item.key)}
style={{
padding: '8px 12px',
background: 'var(--surface2)',
borderRadius: 6,
cursor: 'pointer',
border: '1px solid transparent',
transition: 'all 0.2s'
}}
onMouseEnter={e => {
e.currentTarget.style.borderColor = 'var(--accent)'
e.currentTarget.style.background = 'var(--surface)'
}}
onMouseLeave={e => {
e.currentTarget.style.borderColor = 'transparent'
e.currentTarget.style.background = 'var(--surface2)'
}}
>
<div>
<div>
<code style={{
fontSize: 12,
fontWeight: 600,
color: 'var(--accent)',
fontFamily: 'monospace'
}}>
{`{{${item.key}}}`}
</code>
<div style={{
fontSize: 11,
color: 'var(--text2)',
marginTop: 2
}}>
{item.description}
</div>
</div>
{item.example && (
<div style={{
fontSize: 11,
color: 'var(--text3)',
fontFamily: 'monospace',
padding: '4px 8px',
background: 'var(--bg)',
borderRadius: 4,
marginTop: 6,
wordBreak: 'break-word'
}}>
<span style={{ fontSize: 9, opacity: 0.7, marginRight: 4 }}>Beispiel:</span>
{item.example}
</div>
)}
</div>
</div>
))}
</div>
)}
</div>
))
)}
</div>
{/* Footer */}
<div style={{
padding: 16,
borderTop: '1px solid var(--border)',
textAlign: 'center',
fontSize: 11,
color: 'var(--text3)'
}}>
Klicke auf einen Platzhalter zum Einfügen
</div>
</div>
</div>
)
}
+456
View File
@@ -0,0 +1,456 @@
import { useState, useEffect } from 'react'
import { Trash2, Plus, ChevronDown, ChevronUp } from 'lucide-react'
import '../app.css'
const OPERATORS = [
{ value: 'gte', label: '≥ Größer gleich', types: ['integer', 'float'] },
{ value: 'lte', label: '≤ Kleiner gleich', types: ['integer', 'float'] },
{ value: 'gt', label: '> Größer', types: ['integer', 'float'] },
{ value: 'lt', label: '< Kleiner', types: ['integer', 'float'] },
{ value: 'eq', label: '= Gleich', types: ['integer', 'float', 'string'] },
{ value: 'neq', label: '≠ Ungleich', types: ['integer', 'float', 'string'] },
{ value: 'between', label: '⟷ Zwischen', types: ['integer', 'float'] },
]
const PASS_STRATEGIES = [
{ value: 'weighted_score', label: 'Gewichteter Score' },
{ value: 'all_must_pass', label: 'Alle müssen erfüllt sein' },
{ value: 'at_least_n', label: 'Mindestens N Regeln' },
]
export default function ProfileBuilder({ trainingType, onSave, onCancel, parameters }) {
const [profile, setProfile] = useState(null)
const [loading, setLoading] = useState(false)
const [expandedSections, setExpandedSections] = useState({ minReq: true })
const [successMessage, setSuccessMessage] = useState(null)
useEffect(() => {
// Initialize or load existing profile
if (trainingType.profile) {
setProfile(trainingType.profile)
} else {
// Create empty profile structure
setProfile({
version: '1.0',
name: `${trainingType.name_de} (Profil)`,
description: '',
rule_sets: {
minimum_requirements: {
enabled: true,
pass_strategy: 'weighted_score',
pass_threshold: 0.6,
rules: []
},
intensity_zones: {
enabled: false,
zones: []
},
training_effects: {
enabled: false,
default_effects: {
primary_abilities: [],
secondary_abilities: []
}
},
periodization: {
enabled: false,
frequency: {
per_week_optimal: 3,
per_week_max: 5
},
recovery: {
min_hours_between: 24
}
},
performance_indicators: {
enabled: false
},
safety: {
enabled: false,
warnings: []
}
}
})
}
}, [trainingType])
const toggleSection = (section) => {
setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }))
}
const updateRuleSet = (key, updates) => {
setProfile(prev => ({
...prev,
rule_sets: {
...prev.rule_sets,
[key]: {
...prev.rule_sets[key],
...updates
}
}
}))
}
const addRule = () => {
const newRule = {
parameter: parameters[0]?.key || 'duration_min',
operator: 'gte',
value: 0,
weight: 3,
optional: false,
reason: ''
}
setProfile(prev => ({
...prev,
rule_sets: {
...prev.rule_sets,
minimum_requirements: {
...prev.rule_sets.minimum_requirements,
rules: [...prev.rule_sets.minimum_requirements.rules, newRule]
}
}
}))
}
const updateRule = (index, updates) => {
setProfile(prev => {
const rules = [...prev.rule_sets.minimum_requirements.rules]
rules[index] = { ...rules[index], ...updates }
return {
...prev,
rule_sets: {
...prev.rule_sets,
minimum_requirements: {
...prev.rule_sets.minimum_requirements,
rules
}
}
}
})
}
const removeRule = (index) => {
setProfile(prev => ({
...prev,
rule_sets: {
...prev.rule_sets,
minimum_requirements: {
...prev.rule_sets.minimum_requirements,
rules: prev.rule_sets.minimum_requirements.rules.filter((_, i) => i !== index)
}
}
}))
}
const handleSave = async () => {
setLoading(true)
try {
await onSave(profile)
setSuccessMessage('✓ Profil gespeichert!')
setTimeout(() => {
setSuccessMessage(null)
}, 2000)
} catch (err) {
// Error is already handled by parent
} finally {
setLoading(false)
}
}
if (!profile) return <div className="spinner" />
const minReq = profile.rule_sets.minimum_requirements
return (
<div style={{ background: 'var(--surface)', borderRadius: '12px', padding: '20px' }}>
<div style={{ marginBottom: '20px' }}>
<h3 style={{ marginBottom: '8px' }}>
{trainingType.icon} {trainingType.name_de} - Profil konfigurieren
</h3>
<p style={{ fontSize: '13px', color: 'var(--text2)' }}>
Definiere Mindestanforderungen und Bewertungskriterien für diesen Trainingstyp
</p>
</div>
{/* Success Message */}
{successMessage && (
<div style={{
padding: '12px',
background: 'var(--accent)',
color: 'white',
borderRadius: '8px',
marginBottom: '16px',
fontSize: '14px',
fontWeight: '600'
}}>
{successMessage}
</div>
)}
{/* Minimum Requirements */}
<div className="card" style={{ marginBottom: '16px' }}>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
cursor: 'pointer'
}}
onClick={() => toggleSection('minReq')}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<h4 style={{ margin: 0 }}>Mindestanforderungen</h4>
<label style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '13px' }}>
<input
type="checkbox"
checked={minReq.enabled}
onChange={(e) => {
e.stopPropagation()
updateRuleSet('minimum_requirements', { enabled: e.target.checked })
}}
/>
Aktiviert
</label>
</div>
{expandedSections.minReq ? <ChevronUp size={18} /> : <ChevronDown size={18} />}
</div>
{expandedSections.minReq && minReq.enabled && (
<div style={{ marginTop: '16px' }}>
{/* Strategy */}
<div style={{ marginBottom: '16px', paddingBottom: '16px', borderBottom: '1px solid var(--border)' }}>
<div className="form-row" style={{ marginBottom: '8px' }}>
<label className="form-label">Pass-Strategie</label>
<select
className="form-select"
value={minReq.pass_strategy}
onChange={(e) => updateRuleSet('minimum_requirements', { pass_strategy: e.target.value })}
>
{PASS_STRATEGIES.map(s => (
<option key={s.value} value={s.value}>{s.label}</option>
))}
</select>
</div>
{minReq.pass_strategy === 'weighted_score' && (
<div className="form-row">
<label className="form-label">Threshold (Score 0-1)</label>
<input
type="number"
className="form-input"
step="0.1"
min="0"
max="1"
value={minReq.pass_threshold}
onChange={(e) => updateRuleSet('minimum_requirements', { pass_threshold: parseFloat(e.target.value) })}
/>
<span className="form-unit">{(minReq.pass_threshold * 100).toFixed(0)}%</span>
</div>
)}
</div>
{/* Rules */}
<div style={{ marginBottom: '16px' }}>
<div style={{ fontWeight: '600', fontSize: '14px', marginBottom: '12px' }}>
Regeln ({minReq.rules.length})
</div>
{minReq.rules.map((rule, idx) => {
const param = parameters.find(p => p.key === rule.parameter)
const availableOps = OPERATORS.filter(op =>
param ? op.types.includes(param.data_type) : true
)
const useWeights = minReq.pass_strategy === 'weighted_score'
return (
<div
key={idx}
style={{
background: 'var(--surface2)',
padding: '12px',
borderRadius: '8px',
marginBottom: '8px'
}}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '12px' }}>
<div style={{ fontSize: '12px', fontWeight: '600', color: 'var(--text2)' }}>
Regel {idx + 1}
</div>
<button
className="btn"
onClick={() => removeRule(idx)}
style={{ padding: '4px 8px', minWidth: 'auto', fontSize: '11px' }}
title="Regel löschen"
>
<Trash2 size={12} /> Löschen
</button>
</div>
{/* Parameter */}
<div style={{ marginBottom: '8px' }}>
<label style={{ fontSize: '11px', color: 'var(--text3)', fontWeight: '600', display: 'block', marginBottom: '4px' }}>
WAS soll geprüft werden?
</label>
<select
className="form-select"
value={rule.parameter}
onChange={(e) => updateRule(idx, { parameter: e.target.value })}
style={{ fontSize: '13px', width: '100%' }}
>
{parameters.map(p => (
<option key={p.key} value={p.key}>
{p.name_de} ({p.unit || p.data_type})
</option>
))}
</select>
</div>
{/* Operator + Value */}
<div style={{ marginBottom: '8px' }}>
<label style={{ fontSize: '11px', color: 'var(--text3)', fontWeight: '600', display: 'block', marginBottom: '4px' }}>
BEDINGUNG
</label>
<div style={{ display: 'flex', gap: '8px', alignItems: 'flex-start' }}>
<select
className="form-select"
value={rule.operator}
onChange={(e) => updateRule(idx, { operator: e.target.value })}
style={{ fontSize: '13px', flex: rule.operator === 'between' ? '0 0 80px' : '0 0 100px' }}
>
{availableOps.map(op => (
<option key={op.value} value={op.value}>{op.label}</option>
))}
</select>
{rule.operator === 'between' ? (
<div style={{ flex: 1, display: 'flex', gap: '4px' }}>
<input
type="number"
className="form-input"
placeholder="Min"
value={Array.isArray(rule.value) ? rule.value[0] : 0}
onChange={(e) => updateRule(idx, {
value: [parseFloat(e.target.value) || 0, Array.isArray(rule.value) ? rule.value[1] : 0]
})}
style={{ fontSize: '13px', flex: 1 }}
/>
<input
type="number"
className="form-input"
placeholder="Max"
value={Array.isArray(rule.value) ? rule.value[1] : 0}
onChange={(e) => updateRule(idx, {
value: [Array.isArray(rule.value) ? rule.value[0] : 0, parseFloat(e.target.value) || 0]
})}
style={{ fontSize: '13px', flex: 1 }}
/>
</div>
) : (
<input
type="number"
className="form-input"
placeholder="z.B. 90"
value={rule.value}
onChange={(e) => updateRule(idx, { value: parseFloat(e.target.value) || 0 })}
style={{ fontSize: '13px', flex: 1 }}
/>
)}
</div>
</div>
{/* Weight - nur bei weighted_score */}
{useWeights && (
<div style={{ marginBottom: '8px', paddingTop: '8px', borderTop: '1px dashed var(--border)' }}>
<label style={{ fontSize: '11px', color: 'var(--text3)', fontWeight: '600', display: 'block', marginBottom: '4px' }}>
WICHTIGKEIT dieser Regel (1 = unwichtig, 10 = sehr wichtig)
</label>
<input
type="number"
className="form-input"
placeholder="1-10"
min="1"
max="10"
value={rule.weight}
onChange={(e) => updateRule(idx, { weight: parseInt(e.target.value) || 1 })}
style={{ fontSize: '13px', width: '80px' }}
/>
</div>
)}
{/* Reason */}
<div style={{ marginBottom: '8px' }}>
<label style={{ fontSize: '11px', color: 'var(--text3)', fontWeight: '600', display: 'block', marginBottom: '4px' }}>
Begründung (optional)
</label>
<input
type="text"
className="form-input"
placeholder="z.B. 'Techniktraining sollte ruhig sein'"
value={rule.reason}
onChange={(e) => updateRule(idx, { reason: e.target.value })}
style={{ fontSize: '12px', width: '100%' }}
/>
</div>
{/* Optional Checkbox */}
<label style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '12px', color: 'var(--text2)' }}>
<input
type="checkbox"
checked={rule.optional}
onChange={(e) => updateRule(idx, { optional: e.target.checked })}
/>
Optional (Regel wird übersprungen wenn Parameter fehlt)
</label>
</div>
)
})}
<button
className="btn btn-secondary btn-full"
onClick={addRule}
style={{ marginTop: '8px' }}
>
<Plus size={14} /> Regel hinzufügen
</button>
</div>
</div>
)}
</div>
{/* Other Rule Sets - Future Features */}
<div className="card" style={{ marginBottom: '16px', padding: '12px', background: 'var(--surface2)' }}>
<div style={{ fontSize: '13px', color: 'var(--text2)' }}>
<strong>Weitere Dimensionen</strong> (Analyse & Entwicklung, folgen später):
<br />
<span style={{ fontSize: '12px', lineHeight: '1.6', display: 'block', marginTop: '4px' }}>
• <strong>Intensitätszonen:</strong> HF-Zonen-Verteilung analysieren<br />
• <strong>Training Effects:</strong> Fähigkeitenentwicklung tracken<br />
• <strong>Periodization:</strong> Frequenz & Recovery planen<br />
• <strong>Performance:</strong> Fortschritt messen (Benchmarks, Trends)<br />
• <strong>Safety:</strong> Warnungen bei Überbelastung
</span>
</div>
</div>
{/* Actions */}
<div style={{ display: 'flex', gap: '12px', marginTop: '20px' }}>
<button
className="btn btn-primary"
onClick={handleSave}
disabled={loading}
style={{ flex: 1 }}
>
💾 {loading ? 'Speichern...' : 'Profil speichern'}
</button>
<button
className="btn btn-secondary"
onClick={onCancel}
style={{ flex: 1 }}
>
Abbrechen
</button>
</div>
</div>
)
}
+190
View File
@@ -0,0 +1,190 @@
import { useState } from 'react'
import { api } from '../utils/api'
export default function PromptGenerator({ onGenerated, onClose }) {
const [goal, setGoal] = useState('')
const [dataCategories, setDataCategories] = useState(['körper', 'ernährung'])
const [exampleOutput, setExampleOutput] = useState('')
const [exampleData, setExampleData] = useState(null)
const [generating, setGenerating] = useState(false)
const [loadingExample, setLoadingExample] = useState(false)
const categories = [
{ id: 'körper', label: 'Körper (Gewicht, KF, Umfänge)' },
{ id: 'ernährung', label: 'Ernährung (Kalorien, Makros)' },
{ id: 'training', label: 'Training (Volumen, Typen)' },
{ id: 'schlaf', label: 'Schlaf (Dauer, Qualität)' },
{ id: 'vitalwerte', label: 'Vitalwerte (RHR, HRV, VO2max)' },
{ id: 'ziele', label: 'Ziele (Fortschritt, Prognose)' }
]
const handleToggleCategory = (catId) => {
if (dataCategories.includes(catId)) {
setDataCategories(dataCategories.filter(c => c !== catId))
} else {
setDataCategories([...dataCategories, catId])
}
}
const handleShowExampleData = async () => {
try {
setLoadingExample(true)
const placeholders = await api.listPlaceholders()
setExampleData(placeholders)
} catch (e) {
alert('Fehler: ' + e.message)
} finally {
setLoadingExample(false)
}
}
const handleGenerate = async () => {
if (!goal.trim()) {
alert('Bitte Ziel beschreiben')
return
}
if (dataCategories.length === 0) {
alert('Bitte mindestens einen Datenbereich wählen')
return
}
try {
setGenerating(true)
const result = await api.generatePrompt({
goal,
data_categories: dataCategories,
example_output: exampleOutput || null
})
onGenerated(result)
} catch (e) {
alert('Fehler beim Generieren: ' + e.message)
} finally {
setGenerating(false)
}
}
return (
<div style={{
position:'fixed', inset:0, background:'rgba(0,0,0,0.6)',
display:'flex', alignItems:'center', justifyContent:'center',
zIndex:1001, padding:20
}}>
<div style={{
background:'var(--bg)', borderRadius:12, maxWidth:700, width:'100%',
maxHeight:'90vh', overflow:'auto', padding:24
}}>
<h2 style={{margin:'0 0 24px 0', fontSize:18, fontWeight:600}}>
🤖 KI-Prompt generieren
</h2>
{/* Step 1: Goal */}
<div style={{marginBottom:24}}>
<label className="form-label" style={{display:'block', marginBottom:6}}>
1️⃣ Was möchtest du analysieren?
</label>
<textarea
className="form-input"
value={goal}
onChange={e => setGoal(e.target.value)}
rows={3}
placeholder="Beispiel: Ich möchte wissen ob meine Proteinzufuhr ausreichend ist für Muskelaufbau und wie ich sie optimieren kann."
style={{width:'100%', textAlign:'left', resize:'vertical'}}
/>
</div>
{/* Step 2: Data Categories */}
<div style={{marginBottom:24}}>
<label className="form-label">
2️⃣ Welche Daten sollen analysiert werden?
</label>
<div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8}}>
{categories.map(cat => (
<label
key={cat.id}
style={{
display:'flex', alignItems:'center', gap:8,
padding:8, background:'var(--surface)', borderRadius:6,
cursor:'pointer', fontSize:13
}}
>
<input
type="checkbox"
checked={dataCategories.includes(cat.id)}
onChange={() => handleToggleCategory(cat.id)}
/>
{cat.label}
</label>
))}
</div>
<button
onClick={handleShowExampleData}
disabled={loadingExample}
style={{
marginTop:12, fontSize:12, padding:'6px 12px',
background:'var(--surface2)', border:'1px solid var(--border)',
borderRadius:6, cursor:'pointer'
}}
>
{loadingExample ? 'Lädt...' : '📊 Beispieldaten anzeigen'}
</button>
</div>
{/* Example Data */}
{exampleData && (
<div style={{
marginBottom:24, padding:12, background:'var(--surface2)',
borderRadius:8, fontSize:11, fontFamily:'monospace',
maxHeight:200, overflow:'auto'
}}>
<strong style={{fontFamily:'var(--font)'}}>Deine aktuellen Daten:</strong>
<pre style={{marginTop:8, whiteSpace:'pre-wrap'}}>
{JSON.stringify(exampleData, null, 2)}
</pre>
</div>
)}
{/* Step 3: Desired Format */}
<div style={{marginBottom:24}}>
<label className="form-label" style={{display:'block', marginBottom:6}}>
3️⃣ Gewünschtes Antwort-Format (optional)
</label>
<textarea
className="form-input"
value={exampleOutput}
onChange={e => setExampleOutput(e.target.value)}
rows={4}
placeholder={'Beispiel:\n## Analyse\n[Bewertung]\n\n## Empfehlungen\n- Punkt 1\n- Punkt 2'}
style={{width:'100%', textAlign:'left', fontFamily:'monospace', fontSize:12, resize:'vertical'}}
/>
</div>
{/* Info Box */}
<div style={{
marginBottom:24, padding:12, background:'var(--surface)',
border:'1px solid var(--border)', borderRadius:8, fontSize:12,
color:'var(--text3)'
}}>
<strong style={{color:'var(--text2)'}}>💡 Tipp:</strong> Je präziser deine Zielbeschreibung,
desto besser der generierte Prompt. Die KI wählt automatisch passende Platzhalter
und strukturiert die Analyse optimal.
</div>
{/* Actions */}
<div style={{display:'flex', gap:12}}>
<button
className="btn btn-primary"
onClick={handleGenerate}
disabled={generating || !goal.trim() || dataCategories.length === 0}
style={{flex:1}}
>
{generating ? '⏳ Generiere...' : '🚀 Prompt generieren'}
</button>
<button className="btn" onClick={onClose}>
Abbrechen
</button>
</div>
</div>
</div>
)
}
+120
View File
@@ -0,0 +1,120 @@
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { api } from '../utils/api'
import dayjs from 'dayjs'
import 'dayjs/locale/de'
dayjs.locale('de')
const FOCUS_ICONS = {
muscle_recovery: '💪',
cardio_recovery: '🏃',
mental_rest: '🧘',
deload: '📉',
injury: '🩹',
}
const FOCUS_LABELS = {
muscle_recovery: 'Muskelregeneration',
cardio_recovery: 'Cardio-Erholung',
mental_rest: 'Mentale Erholung',
deload: 'Deload',
injury: 'Verletzungspause',
}
const FOCUS_COLORS = {
muscle_recovery: '#D85A30',
cardio_recovery: '#378ADD',
mental_rest: '#7B68EE',
deload: '#E67E22',
injury: '#E74C3C',
}
export default function RestDaysWidget() {
const [todayRestDays, setTodayRestDays] = useState([])
const [loading, setLoading] = useState(true)
const nav = useNavigate()
useEffect(() => {
loadTodayRestDays()
}, [])
const loadTodayRestDays = async () => {
try {
const today = dayjs().format('YYYY-MM-DD')
const allRestDays = await api.listRestDays(7) // Last 7 days
const todayOnly = allRestDays.filter(d => d.date === today)
setTodayRestDays(todayOnly)
} catch (err) {
console.error('Failed to load rest days:', err)
} finally {
setLoading(false)
}
}
if (loading) {
return (
<div className="card">
<div className="card-title">🛌 Ruhetage</div>
<div style={{ padding: '20px 0', textAlign: 'center', color: 'var(--text3)' }}>
Lädt...
</div>
</div>
)
}
return (
<div className="card">
<div className="card-title">🛌 Ruhetage</div>
{todayRestDays.length === 0 ? (
<div style={{ padding: '12px 0', color: 'var(--text3)', fontSize: 13 }}>
Heute kein Ruhetag geplant
</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{todayRestDays.map(day => {
const focus = day.rest_config?.focus || 'mental_rest'
const icon = FOCUS_ICONS[focus] || '📅'
const label = FOCUS_LABELS[focus] || focus
const color = FOCUS_COLORS[focus] || '#888'
return (
<div
key={day.id}
style={{
display: 'flex',
alignItems: 'center',
gap: 10,
padding: '8px 10px',
borderRadius: 8,
background: `${color}14`,
border: `1px solid ${color}`,
}}
>
<div style={{ fontSize: 20 }}>{icon}</div>
<div style={{ flex: 1 }}>
<div style={{ fontSize: 13, fontWeight: 600, color }}>
{label}
</div>
{day.note && (
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 2 }}>
{day.note}
</div>
)}
</div>
</div>
)
})}
</div>
)}
<button
className="btn btn-secondary btn-full"
style={{ marginTop: 12, fontSize: 13 }}
onClick={() => nav('/rest-days')}
>
Ruhetage verwalten
</button>
</div>
)
}
@@ -1,6 +1,7 @@
import { useState, useEffect } from 'react'
import { PieChart, Pie, Cell, ResponsiveContainer, Legend, Tooltip } from 'recharts'
import { api } from '../utils/api'
import { useProfile } from '../context/ProfileContext'
/**
* TrainingTypeDistribution - Pie chart showing activity distribution by type
@@ -8,6 +9,7 @@ import { api } from '../utils/api'
* @param {number} days - Number of days to analyze (default: 28)
*/
export default function TrainingTypeDistribution({ days = 28 }) {
const { activeProfile } = useProfile() // Issue #31: Trigger reload on quality filter change
const [data, setData] = useState([])
const [categories, setCategories] = useState({})
const [loading, setLoading] = useState(true)
@@ -41,7 +43,7 @@ export default function TrainingTypeDistribution({ days = 28 }) {
console.error('Failed to load training type distribution:', err)
setLoading(false)
})
}, [days])
}, [days, activeProfile?.quality_filter_level]) // Issue #31: Reload when quality filter changes
if (loading) {
return (
@@ -0,0 +1,872 @@
import { useState, useEffect, useRef } from 'react'
import { api } from '../utils/api'
import { X, Plus, Trash2, MoveUp, MoveDown, Code } from 'lucide-react'
import PlaceholderPicker from './PlaceholderPicker'
/**
* Unified Prompt Editor Modal (Issue #28 Phase 3)
*
* Supports both prompt types:
* - Base: Single reusable template
* - Pipeline: Multi-stage workflow with dynamic stages
*/
export default function UnifiedPromptModal({ prompt, onSave, onClose }) {
const [name, setName] = useState('')
const [slug, setSlug] = useState('')
const [displayName, setDisplayName] = useState('')
const [description, setDescription] = useState('')
const [type, setType] = useState('pipeline') // 'base' or 'pipeline'
const [category, setCategory] = useState('ganzheitlich')
const [active, setActive] = useState(true)
const [sortOrder, setSortOrder] = useState(0)
// Base prompt fields
const [template, setTemplate] = useState('')
const [outputFormat, setOutputFormat] = useState('text')
// Pipeline prompt fields
const [stages, setStages] = useState([
{
stage: 1,
prompts: []
}
])
// Available prompts for reference selection
const [availablePrompts, setAvailablePrompts] = useState([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
const [showPlaceholderPicker, setShowPlaceholderPicker] = useState(false)
const [pickerTarget, setPickerTarget] = useState(null) // 'base' or {stage, promptIdx}
const [cursorPosition, setCursorPosition] = useState(null) // Track cursor position for insertion
const baseTemplateRef = useRef(null)
const stageTemplateRefs = useRef({}) // Map of stage_promptIdx -> ref
// Test functionality
const [testing, setTesting] = useState(false)
const [testResult, setTestResult] = useState(null)
const [showDebug, setShowDebug] = useState(false)
useEffect(() => {
loadAvailablePrompts()
if (prompt) {
// Edit mode
setName(prompt.name || '')
setSlug(prompt.slug || '')
setDisplayName(prompt.display_name || '')
setDescription(prompt.description || '')
setType(prompt.type || 'pipeline')
setCategory(prompt.category || 'ganzheitlich')
setActive(prompt.active ?? true)
setSortOrder(prompt.sort_order || 0)
setTemplate(prompt.template || '')
setOutputFormat(prompt.output_format || 'text')
// Parse stages if editing pipeline
if (prompt.type === 'pipeline' && prompt.stages) {
try {
const parsedStages = typeof prompt.stages === 'string'
? JSON.parse(prompt.stages)
: prompt.stages
setStages(parsedStages.length > 0 ? parsedStages : [{ stage: 1, prompts: [] }])
} catch (e) {
console.error('Failed to parse stages:', e)
setStages([{ stage: 1, prompts: [] }])
}
}
}
}, [prompt])
const loadAvailablePrompts = async () => {
try {
const prompts = await api.listAdminPrompts()
setAvailablePrompts(prompts)
} catch (e) {
setError('Fehler beim Laden der Prompts: ' + e.message)
}
}
const addStage = () => {
const nextStageNum = Math.max(...stages.map(s => s.stage), 0) + 1
setStages([...stages, { stage: nextStageNum, prompts: [] }])
}
const removeStage = (stageNum) => {
if (stages.length === 1) {
setError('Mindestens eine Stage erforderlich')
return
}
setStages(stages.filter(s => s.stage !== stageNum))
}
const moveStage = (stageNum, direction) => {
const idx = stages.findIndex(s => s.stage === stageNum)
if (idx === -1) return
const newStages = [...stages]
if (direction === 'up' && idx > 0) {
[newStages[idx], newStages[idx - 1]] = [newStages[idx - 1], newStages[idx]]
} else if (direction === 'down' && idx < newStages.length - 1) {
[newStages[idx], newStages[idx + 1]] = [newStages[idx + 1], newStages[idx]]
}
// Renumber stages
newStages.forEach((s, i) => s.stage = i + 1)
setStages(newStages)
}
const addPromptToStage = (stageNum) => {
setStages(stages.map(s => {
if (s.stage === stageNum) {
return {
...s,
prompts: [...s.prompts, {
source: 'inline',
template: '',
output_key: `output_${Date.now()}`,
output_format: 'text'
}]
}
}
return s
}))
}
const removePromptFromStage = (stageNum, promptIdx) => {
setStages(stages.map(s => {
if (s.stage === stageNum) {
return {
...s,
prompts: s.prompts.filter((_, i) => i !== promptIdx)
}
}
return s
}))
}
const updateStagePrompt = (stageNum, promptIdx, field, value) => {
setStages(stages.map(s => {
if (s.stage === stageNum) {
const newPrompts = [...s.prompts]
newPrompts[promptIdx] = { ...newPrompts[promptIdx], [field]: value }
return { ...s, prompts: newPrompts }
}
return s
}))
}
const handleSave = async () => {
// Validation
if (!name.trim() || !slug.trim()) {
setError('Name und Slug sind Pflichtfelder')
return
}
if (type === 'base' && !template.trim()) {
setError('Basis-Prompts benötigen ein Template')
return
}
if (type === 'pipeline' && stages.length === 0) {
setError('Pipeline-Prompts benötigen mindestens eine Stage')
return
}
if (type === 'pipeline') {
// Validate all stages have at least one prompt
const emptyStages = stages.filter(s => s.prompts.length === 0)
if (emptyStages.length > 0) {
setError(`Stage ${emptyStages[0].stage} hat keine Prompts`)
return
}
// Validate all prompts have required fields
for (const stage of stages) {
for (const p of stage.prompts) {
if (!p.output_key) {
setError(`Stage ${stage.stage}: Output-Key fehlt`)
return
}
if (p.source === 'inline' && !p.template) {
setError(`Stage ${stage.stage}: Inline-Prompt ohne Template`)
return
}
if (p.source === 'reference' && !p.slug) {
setError(`Stage ${stage.stage}: Referenz-Prompt ohne Slug`)
return
}
}
}
}
setLoading(true)
setError(null)
try {
const data = {
name,
slug,
display_name: displayName,
description,
type,
category,
active,
sort_order: sortOrder,
output_format: outputFormat
}
if (type === 'base') {
data.template = template
data.stages = null
} else {
data.template = null
data.stages = stages
}
if (prompt?.id) {
await api.updateUnifiedPrompt(prompt.id, data)
} else {
await api.createUnifiedPrompt(data)
}
onSave()
} catch (e) {
setError(e.message)
} finally {
setLoading(false)
}
}
const handleExport = () => {
// Export complete prompt configuration as JSON
const exportData = {
name,
slug,
display_name: displayName,
description,
type,
category,
active,
sort_order: sortOrder,
output_format: outputFormat,
template: type === 'base' ? template : null,
stages: type === 'pipeline' ? stages : null
}
const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `prompt-${slug || 'new'}-${new Date().toISOString().split('T')[0]}.json`
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
URL.revokeObjectURL(url)
}
const handleTest = async () => {
// Can only test existing prompts (need slug in database)
if (!prompt?.slug) {
setError('Bitte erst speichern, dann testen')
return
}
setTesting(true)
setError(null)
setTestResult(null)
try {
const result = await api.executeUnifiedPrompt(prompt.slug, null, null, true)
setTestResult(result)
setShowDebug(true)
} catch (e) {
// Show error AND try to extract debug info from error
const errorMsg = e.message
let debugData = null
// Try to parse error message for embedded debug info
try {
const parsed = JSON.parse(errorMsg)
if (parsed.detail) {
setError('Test-Fehler: ' + parsed.detail)
debugData = parsed
} else {
setError('Test-Fehler: ' + errorMsg)
}
} catch {
setError('Test-Fehler: ' + errorMsg)
}
// Set result with error info so debug viewer shows it
setTestResult({
error: true,
error_message: errorMsg,
debug: debugData || { error: errorMsg }
})
setShowDebug(true) // ALWAYS show debug on test, even on error
} finally {
setTesting(false)
}
}
const handleExportPlaceholders = () => {
if (!testResult) return
// Extract all placeholder data from test result
const debug = testResult.debug || testResult
const exportData = {
export_date: new Date().toISOString(),
prompt_slug: prompt?.slug || 'unknown',
prompt_name: name || 'Unnamed Prompt',
placeholders: {}
}
// For pipeline prompts, collect from all stages
if (debug.stages && Array.isArray(debug.stages)) {
debug.stages.forEach(stage => {
exportData.placeholders[`stage_${stage.stage}`] = {
available_variables: stage.available_variables || [],
prompts: stage.prompts?.map(p => ({
source: p.source,
resolved: p.resolved_placeholders || p.ref_debug?.resolved_placeholders || {},
unresolved: p.unresolved_placeholders || p.ref_debug?.unresolved_placeholders || []
})) || []
}
})
}
// For base prompts or direct execution
if (debug.resolved_placeholders) {
exportData.placeholders.resolved = debug.resolved_placeholders
}
if (debug.unresolved_placeholders) {
exportData.placeholders.unresolved = debug.unresolved_placeholders
}
if (debug.available_variables) {
exportData.available_variables = debug.available_variables
}
if (debug.initial_variables) {
exportData.initial_variables = debug.initial_variables
}
// Download as JSON
const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `placeholders-${prompt?.slug || 'test'}-${new Date().toISOString().split('T')[0]}.json`
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
URL.revokeObjectURL(url)
}
return (
<div style={{
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
zIndex: 1000, padding: 20, overflow: 'auto'
}}>
<div style={{
background: 'var(--bg)', borderRadius: 12, maxWidth: 1000, width: '100%',
maxHeight: '90vh', overflow: 'auto', padding: 24
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
<h2 style={{ margin: 0, fontSize: 20, fontWeight: 600 }}>
{prompt ? 'Prompt bearbeiten' : 'Neuer Prompt'}
</h2>
<button
onClick={onClose}
style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4 }}
>
<X size={24} color="var(--text3)" />
</button>
</div>
{error && (
<div style={{
padding: 12, background: '#fee', color: '#c00', borderRadius: 8, marginBottom: 16, fontSize: 13
}}>
{error}
</div>
)}
{/* Basic Info */}
<div style={{ display: 'grid', gap: 16, marginBottom: 24 }}>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
<div>
<label className="form-label">Name *</label>
<input
className="form-input"
value={name}
onChange={e => setName(e.target.value)}
placeholder="Interner Name"
style={{ width: '100%', textAlign: 'left' }}
/>
</div>
<div>
<label className="form-label">Slug *</label>
<input
className="form-input"
value={slug}
onChange={e => setSlug(e.target.value)}
placeholder="technischer_name"
style={{ width: '100%', textAlign: 'left' }}
disabled={!!prompt}
/>
</div>
</div>
<div>
<label className="form-label">Anzeigename</label>
<input
className="form-input"
value={displayName}
onChange={e => setDisplayName(e.target.value)}
placeholder="Name für Benutzer (optional)"
style={{ width: '100%', textAlign: 'left' }}
/>
</div>
<div>
<label className="form-label">Beschreibung</label>
<textarea
className="form-input"
value={description}
onChange={e => setDescription(e.target.value)}
rows={2}
placeholder="Kurze Beschreibung des Prompts"
style={{ width: '100%', textAlign: 'left', resize: 'vertical' }}
/>
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
<div>
<label className="form-label">Typ *</label>
<select
className="form-select"
value={type}
onChange={e => setType(e.target.value)}
style={{ width: '100%' }}
disabled={!!prompt}
>
<option value="base">Basis-Prompt</option>
<option value="pipeline">Pipeline</option>
</select>
</div>
<div>
<label className="form-label">Kategorie</label>
<select
className="form-select"
value={category}
onChange={e => setCategory(e.target.value)}
style={{ width: '100%' }}
>
<option value="ganzheitlich">Ganzheitlich</option>
<option value="körper">Körper</option>
<option value="ernährung">Ernährung</option>
<option value="training">Training</option>
<option value="schlaf">Schlaf</option>
<option value="pipeline">Pipeline</option>
</select>
</div>
<div>
<label className="form-label">Output-Format</label>
<select
className="form-select"
value={outputFormat}
onChange={e => setOutputFormat(e.target.value)}
style={{ width: '100%' }}
>
<option value="text">Text</option>
<option value="json">JSON</option>
</select>
</div>
</div>
<div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
<label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
<input
type="checkbox"
checked={active}
onChange={e => setActive(e.target.checked)}
/>
<span style={{ fontSize: 13 }}>Aktiv</span>
</label>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<label className="form-label" style={{ margin: 0 }}>Sortierung:</label>
<input
type="number"
className="form-input"
value={sortOrder}
onChange={e => setSortOrder(parseInt(e.target.value) || 0)}
style={{ width: 80, padding: '4px 8px' }}
/>
</div>
</div>
</div>
{/* Type-specific editor */}
{type === 'base' && (
<div style={{ marginBottom: 24 }}>
<h3 style={{ fontSize: 16, fontWeight: 600, marginBottom: 12 }}>Template</h3>
<textarea
ref={baseTemplateRef}
className="form-input"
value={template}
onChange={e => setTemplate(e.target.value)}
onClick={e => setCursorPosition(e.target.selectionStart)}
onKeyUp={e => setCursorPosition(e.target.selectionStart)}
rows={12}
placeholder="Prompt-Template mit {{placeholders}}..."
style={{ width: '100%', textAlign: 'left', resize: 'vertical', fontFamily: 'monospace', fontSize: 12 }}
/>
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 4 }}>
<button
className="btn"
onClick={() => {
setPickerTarget('base')
setShowPlaceholderPicker(true)
}}
style={{
fontSize: 12,
padding: '6px 12px',
display: 'flex',
alignItems: 'center',
gap: 6
}}
>
<Code size={14} />
Platzhalter einfügen
</button>
</div>
</div>
)}
{type === 'pipeline' && (
<div style={{ marginBottom: 24 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
<h3 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>Stages ({stages.length})</h3>
<button className="btn" onClick={addStage} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<Plus size={16} /> Stage hinzufügen
</button>
</div>
{stages.map((stage, sIdx) => (
<div key={stage.stage} style={{
background: 'var(--surface)', padding: 16, borderRadius: 8,
border: '1px solid var(--border)', marginBottom: 12
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
<h4 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>Stage {stage.stage}</h4>
<div style={{ display: 'flex', gap: 4 }}>
{sIdx > 0 && (
<button
className="btn"
onClick={() => moveStage(stage.stage, 'up')}
style={{ padding: '4px 8px' }}
>
<MoveUp size={14} />
</button>
)}
{sIdx < stages.length - 1 && (
<button
className="btn"
onClick={() => moveStage(stage.stage, 'down')}
style={{ padding: '4px 8px' }}
>
<MoveDown size={14} />
</button>
)}
<button
className="btn"
onClick={() => removeStage(stage.stage)}
style={{ padding: '4px 8px', color: 'var(--danger)' }}
disabled={stages.length === 1}
>
<Trash2 size={14} />
</button>
</div>
</div>
{/* Prompts in this stage */}
{stage.prompts.map((p, pIdx) => (
<div key={pIdx} style={{
background: 'var(--bg)', padding: 12, borderRadius: 6, marginBottom: 8,
border: '1px solid var(--border)'
}}>
<div style={{ display: 'grid', gap: 8 }}>
<div style={{ display: 'grid', gridTemplateColumns: '120px 1fr 120px auto', gap: 8, alignItems: 'center' }}>
<select
className="form-select"
value={p.source || 'inline'}
onChange={e => updateStagePrompt(stage.stage, pIdx, 'source', e.target.value)}
style={{ fontSize: 12 }}
>
<option value="inline">Inline</option>
<option value="reference">Referenz</option>
</select>
<input
className="form-input"
value={p.output_key || ''}
onChange={e => updateStagePrompt(stage.stage, pIdx, 'output_key', e.target.value)}
placeholder="output_key"
style={{ fontSize: 12, textAlign: 'left' }}
/>
<select
className="form-select"
value={p.output_format || 'text'}
onChange={e => updateStagePrompt(stage.stage, pIdx, 'output_format', e.target.value)}
style={{ fontSize: 12 }}
>
<option value="text">Text</option>
<option value="json">JSON</option>
</select>
<button
onClick={() => removePromptFromStage(stage.stage, pIdx)}
style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4 }}
>
<Trash2 size={16} color="var(--danger)" />
</button>
</div>
{p.source === 'reference' ? (
<select
className="form-select"
value={p.slug || ''}
onChange={e => updateStagePrompt(stage.stage, pIdx, 'slug', e.target.value)}
style={{ fontSize: 12 }}
>
<option value="">-- Prompt wählen --</option>
{availablePrompts
.filter(ap => ap.type === 'base' || !ap.type)
.map(ap => (
<option key={ap.slug} value={ap.slug}>
{ap.display_name || ap.name} ({ap.slug})
</option>
))}
</select>
) : (
<div>
<textarea
ref={el => stageTemplateRefs.current[`${stage.stage}_${pIdx}`] = el}
className="form-input"
value={p.template || ''}
onChange={e => updateStagePrompt(stage.stage, pIdx, 'template', e.target.value)}
onClick={e => {
setCursorPosition(e.target.selectionStart)
setPickerTarget({ stage: stage.stage, promptIdx: pIdx })
}}
onKeyUp={e => {
setCursorPosition(e.target.selectionStart)
setPickerTarget({ stage: stage.stage, promptIdx: pIdx })
}}
rows={3}
placeholder="Inline-Template mit {{placeholders}}..."
style={{ width: '100%', fontSize: 12, textAlign: 'left', resize: 'vertical', fontFamily: 'monospace' }}
/>
<div style={{ fontSize: 10, color: 'var(--text3)', marginTop: 4 }}>
<button
className="btn"
onClick={() => {
setPickerTarget({ stage: stage.stage, promptIdx: pIdx })
setShowPlaceholderPicker(true)
}}
style={{
fontSize: 11,
padding: '4px 8px',
display: 'flex',
alignItems: 'center',
gap: 4
}}
>
<Code size={12} />
Platzhalter
</button>
</div>
</div>
)}
</div>
</div>
))}
<button
className="btn"
onClick={() => addPromptToStage(stage.stage)}
style={{ fontSize: 12, display: 'flex', alignItems: 'center', gap: 4 }}
>
<Plus size={14} /> Prompt hinzufügen
</button>
</div>
))}
</div>
)}
{/* Debug Output */}
{showDebug && testResult && (
<div style={{
marginTop: 16,
padding: 16,
background: 'var(--surface2)',
borderRadius: 8,
border: '1px solid var(--border)'
}}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 12
}}>
<h3 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>
🔬 Debug-Info
</h3>
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<button
className="btn"
onClick={handleExportPlaceholders}
style={{
padding: '4px 8px',
fontSize: 11,
background: 'var(--accent)',
color: 'white'
}}
title="Exportiere alle Platzhalter mit Werten als JSON"
>
📋 Platzhalter exportieren
</button>
<button
onClick={() => setShowDebug(false)}
style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4 }}
>
<X size={16} color="var(--text3)" />
</button>
</div>
</div>
<pre style={{
fontSize: 11,
fontFamily: 'monospace',
background: 'var(--bg)',
padding: 12,
borderRadius: 6,
overflow: 'auto',
maxHeight: 400,
lineHeight: 1.5,
color: 'var(--text2)'
}}>
{JSON.stringify(testResult.debug || testResult, null, 2)}
</pre>
</div>
)}
{/* Actions */}
<div style={{
display: 'flex', gap: 12, justifyContent: 'space-between',
paddingTop: 16, borderTop: '1px solid var(--border)'
}}>
<div style={{ display: 'flex', gap: 8 }}>
<button
className="btn"
onClick={handleTest}
disabled={testing || loading}
style={{
background: testing ? 'var(--surface)' : 'var(--accent)',
color: testing ? 'var(--text3)' : 'white'
}}
title={!prompt?.slug ? 'Bitte erst speichern, dann testen' : 'Test mit Debug-Modus ausführen'}
>
{testing ? '🔬 Teste...' : '🔬 Test ausführen'}
</button>
<button
className="btn"
onClick={handleExport}
disabled={loading}
title="Exportiere Prompt-Konfiguration als JSON"
>
📥 Export
</button>
</div>
<div style={{ display: 'flex', gap: 12 }}>
<button className="btn" onClick={onClose}>
Abbrechen
</button>
<button
className="btn btn-primary"
onClick={handleSave}
disabled={loading}
>
{loading ? 'Speichern...' : 'Speichern'}
</button>
</div>
</div>
</div>
{/* Placeholder Picker */}
{showPlaceholderPicker && (
<PlaceholderPicker
onSelect={(placeholder) => {
if (pickerTarget === 'base') {
// Insert into base template at cursor position
const pos = cursorPosition ?? template.length
const newTemplate = template.slice(0, pos) + placeholder + template.slice(pos)
setTemplate(newTemplate)
// Restore focus and cursor position after insertion
setTimeout(() => {
if (baseTemplateRef.current) {
baseTemplateRef.current.focus()
const newPos = pos + placeholder.length
baseTemplateRef.current.setSelectionRange(newPos, newPos)
setCursorPosition(newPos)
}
}, 0)
} else if (pickerTarget && typeof pickerTarget === 'object') {
// Insert into pipeline stage template at cursor position
const { stage: stageNum, promptIdx } = pickerTarget
setStages(stages.map(s => {
if (s.stage === stageNum) {
const newPrompts = [...s.prompts]
const currentTemplate = newPrompts[promptIdx].template || ''
const pos = cursorPosition ?? currentTemplate.length
const newTemplate = currentTemplate.slice(0, pos) + placeholder + currentTemplate.slice(pos)
newPrompts[promptIdx] = {
...newPrompts[promptIdx],
template: newTemplate
}
// Restore focus and cursor position
setTimeout(() => {
const refKey = `${stageNum}_${promptIdx}`
const textarea = stageTemplateRefs.current[refKey]
if (textarea) {
textarea.focus()
const newPos = pos + placeholder.length
textarea.setSelectionRange(newPos, newPos)
setCursorPosition(newPos)
}
}, 0)
return { ...s, prompts: newPrompts }
}
return s
}))
}
}}
onClose={() => {
setShowPlaceholderPicker(false)
setPickerTarget(null)
}}
/>
)}
</div>
)
}
+60
View File
@@ -354,6 +354,66 @@ export default function ActivityPage() {
<div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start'}}>
<div style={{flex:1}}>
<div style={{display:'flex',alignItems:'center',gap:6,marginBottom:2}}>
{/* Evaluation Status Indicator */}
{e.quality_label ? (
<div
style={{
display:'inline-flex',
alignItems:'center',
justifyContent:'center',
width:18,
height:18,
borderRadius:9,
background: e.quality_label === 'excellent' || e.quality_label === 'good' ? '#1D9E75' :
e.quality_label === 'acceptable' ? '#EF9F27' : '#D85A30',
color:'white',
fontSize:10,
fontWeight:700,
flexShrink:0
}}
title={`Evaluation: ${e.quality_label} (Score: ${e.overall_score || 'n/a'})`}
>
✓
</div>
) : e.training_type_id ? (
<div
style={{
display:'inline-flex',
alignItems:'center',
justifyContent:'center',
width:18,
height:18,
borderRadius:9,
background:'#EF9F27',
color:'white',
fontSize:10,
fontWeight:700,
flexShrink:0
}}
title="Trainingstyp zugeordnet, aber nicht evaluiert (kein Profil konfiguriert)"
>
⚠
</div>
) : (
<div
style={{
display:'inline-flex',
alignItems:'center',
justifyContent:'center',
width:18,
height:18,
borderRadius:9,
background:'#888780',
color:'white',
fontSize:10,
fontWeight:700,
flexShrink:0
}}
title="Kein Trainingstyp zugeordnet"
>
✕
</div>
)}
<div style={{fontSize:14,fontWeight:600}}>{e.activity_type}</div>
{e.training_category && categories[e.training_category] && (
<div style={{
+520
View File
@@ -0,0 +1,520 @@
import { useState, useEffect } from 'react'
import { Settings, Plus, Pencil, Trash2, Database } from 'lucide-react'
import { api } from '../utils/api'
export default function AdminGoalTypesPage() {
const [goalTypes, setGoalTypes] = useState([])
const [schemaInfo, setSchemaInfo] = useState(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [showForm, setShowForm] = useState(false)
const [editingType, setEditingType] = useState(null)
const [toast, setToast] = useState(null)
const [formData, setFormData] = useState({
type_key: '',
label_de: '',
unit: '',
icon: '',
category: 'custom',
source_table: '',
source_column: '',
aggregation_method: 'latest',
filter_conditions: '',
description: ''
})
const CATEGORIES = ['body', 'mind', 'activity', 'nutrition', 'recovery', 'custom']
const AGGREGATION_METHODS = [
{ value: 'latest', label: 'Letzter Wert' },
{ value: 'avg_7d', label: 'Durchschnitt 7 Tage' },
{ value: 'avg_30d', label: 'Durchschnitt 30 Tage' },
{ value: 'sum_30d', label: 'Summe 30 Tage' },
{ value: 'count_7d', label: 'Anzahl 7 Tage' },
{ value: 'count_30d', label: 'Anzahl 30 Tage' },
{ value: 'min_30d', label: 'Minimum 30 Tage' },
{ value: 'max_30d', label: 'Maximum 30 Tage' }
]
useEffect(() => {
loadGoalTypes()
}, [])
const loadGoalTypes = async () => {
setLoading(true)
setError(null)
try {
const [typesData, schema] = await Promise.all([
api.listGoalTypeDefinitions(),
api.getSchemaInfo()
])
console.log('[DEBUG] Loaded goal types:', typesData)
console.log('[DEBUG] Loaded schema info:', schema)
setGoalTypes(typesData || [])
setSchemaInfo(schema || {})
} catch (err) {
console.error('[ERROR] Failed to load goal types:', err)
setError(`Fehler beim Laden der Goal Types: ${err.message || err.toString()}`)
} finally {
setLoading(false)
}
}
const showToast = (message) => {
setToast(message)
setTimeout(() => setToast(null), 2000)
}
const handleCreate = () => {
setEditingType(null)
setFormData({
type_key: '',
label_de: '',
unit: '',
icon: '',
category: 'custom',
source_table: '',
source_column: '',
aggregation_method: 'latest',
filter_conditions: '',
description: ''
})
setShowForm(true)
}
const handleEdit = (type) => {
setEditingType(type.id)
setFormData({
type_key: type.type_key,
label_de: type.label_de,
unit: type.unit,
icon: type.icon || '',
category: type.category || 'custom',
source_table: type.source_table || '',
source_column: type.source_column || '',
aggregation_method: type.aggregation_method || 'latest',
filter_conditions: type.filter_conditions ? JSON.stringify(type.filter_conditions, null, 2) : '',
description: type.description || ''
})
setShowForm(true)
}
const handleSave = async () => {
if (!formData.label_de || !formData.unit) {
setError('Bitte Label und Einheit ausfüllen')
return
}
// Parse filter_conditions from string to JSON
let payload = { ...formData }
if (formData.filter_conditions && formData.filter_conditions.trim()) {
try {
payload.filter_conditions = JSON.parse(formData.filter_conditions)
} catch (e) {
setError('Ungültiges JSON in Filter-Bedingungen')
return
}
} else {
payload.filter_conditions = null
}
try {
if (editingType) {
await api.updateGoalType(editingType, payload)
showToast('✓ Goal Type aktualisiert')
} else {
if (!formData.type_key) {
setError('Bitte eindeutigen Key angeben (z.B. meditation_minutes)')
return
}
await api.createGoalType(payload)
showToast('✓ Goal Type erstellt')
}
await loadGoalTypes()
setShowForm(false)
setError(null)
} catch (err) {
setError(err.message || 'Fehler beim Speichern')
}
}
const handleDelete = async (typeId, typeName, isSystem) => {
if (isSystem) {
if (!confirm(`System Goal Type "${typeName}" deaktivieren? (Nicht löschbar)`)) return
} else {
if (!confirm(`Goal Type "${typeName}" wirklich löschen?`)) return
}
try {
await api.deleteGoalType(typeId)
showToast('✓ Goal Type gelöscht/deaktiviert')
await loadGoalTypes()
} catch (err) {
setError(err.message || 'Fehler beim Löschen')
}
}
if (loading) {
return (
<div className="page">
<div style={{ textAlign: 'center', padding: 40 }}>
<div className="spinner"></div>
</div>
</div>
)
}
return (
<div className="page">
<div className="page-header">
<h1><Database size={24} /> Goal Type Verwaltung</h1>
</div>
{error && (
<div className="card" style={{ background: '#FEF2F2', border: '1px solid #FCA5A5', marginBottom: 16 }}>
<p style={{ color: '#DC2626', margin: 0 }}>{error}</p>
</div>
)}
{toast && (
<div style={{
position: 'fixed',
top: 16,
right: 16,
background: 'var(--accent)',
color: 'white',
padding: '12px 20px',
borderRadius: 8,
boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
zIndex: 1000
}}>
{toast}
</div>
)}
<div className="card" style={{ marginBottom: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
<div>
<h2 style={{ margin: 0, marginBottom: 4 }}>Verfügbare Goal Types</h2>
<p style={{ fontSize: 13, color: 'var(--text2)', margin: 0 }}>
{goalTypes.length} Types registriert ({goalTypes.filter(t => t.is_system).length} System, {goalTypes.filter(t => !t.is_system).length} Custom)
</p>
</div>
<button className="btn-primary" onClick={handleCreate}>
<Plus size={16} /> Neuer Type
</button>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{goalTypes.map(type => (
<div
key={type.id}
className="card"
style={{
background: 'var(--surface2)',
padding: 12,
border: type.is_system ? '2px solid var(--accent)' : '1px solid var(--border)'
}}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
<div style={{ flex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
<span style={{ fontSize: 20 }}>{type.icon || '📊'}</span>
<span style={{ fontWeight: 600 }}>{type.label_de}</span>
<span style={{
fontSize: 11,
padding: '2px 8px',
borderRadius: 4,
background: 'var(--surface)',
color: 'var(--text2)'
}}>
{type.unit}
</span>
{type.is_system && (
<span style={{
fontSize: 11,
padding: '2px 8px',
borderRadius: 4,
background: 'var(--accent)',
color: 'white'
}}>
SYSTEM
</span>
)}
{!type.is_active && (
<span style={{
fontSize: 11,
padding: '2px 8px',
borderRadius: 4,
background: '#F59E0B',
color: 'white'
}}>
INAKTIV
</span>
)}
</div>
<div style={{ fontSize: 12, color: 'var(--text2)' }}>
<strong>Key:</strong> {type.type_key}
{type.source_table && (
<>
{' | '}<strong>Quelle:</strong> {type.source_table}.{type.source_column}
{' | '}<strong>Methode:</strong> {type.aggregation_method}
</>
)}
{type.calculation_formula && (
<>
{' | '}<strong>Formel:</strong> Komplex (JSON)
</>
)}
</div>
{type.description && (
<div style={{ fontSize: 12, color: 'var(--text2)', marginTop: 4, fontStyle: 'italic' }}>
{type.description}
</div>
)}
</div>
<div style={{ display: 'flex', gap: 8 }}>
<button
className="btn-secondary"
onClick={() => handleEdit(type)}
style={{ padding: '6px 12px' }}
>
<Pencil size={14} />
</button>
<button
className="btn-secondary"
onClick={() => handleDelete(type.id, type.label_de, type.is_system)}
style={{ padding: '6px 12px', color: type.is_system ? '#F59E0B' : '#DC2626' }}
>
<Trash2 size={14} />
</button>
</div>
</div>
</div>
))}
</div>
</div>
{/* Form Modal */}
{showForm && (
<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,
paddingTop: 40,
overflowY: 'auto'
}}>
<div className="card" style={{ maxWidth: 600, width: '100%', marginBottom: 40 }}>
<div className="card-title">
{editingType ? 'Goal Type bearbeiten' : 'Neuer Goal Type'}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
{/* Type Key (nur bei Create) */}
{!editingType && (
<div>
<label className="form-label">
Eindeutiger Key * (z.B. meditation_minutes)
</label>
<input
type="text"
className="form-input"
style={{ width: '100%' }}
value={formData.type_key}
onChange={e => setFormData(f => ({ ...f, type_key: e.target.value }))}
placeholder="snake_case verwenden"
/>
</div>
)}
{/* Label */}
<div>
<label className="form-label">Label (Deutsch) *</label>
<input
type="text"
className="form-input"
style={{ width: '100%' }}
value={formData.label_de}
onChange={e => setFormData(f => ({ ...f, label_de: e.target.value }))}
placeholder="z.B. Meditation"
/>
</div>
{/* Unit & Icon */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
<div>
<label className="form-label">Einheit *</label>
<input
type="text"
className="form-input"
style={{ width: '100%' }}
value={formData.unit}
onChange={e => setFormData(f => ({ ...f, unit: e.target.value }))}
placeholder="z.B. min/Tag"
/>
</div>
<div>
<label className="form-label">Icon (Emoji)</label>
<input
type="text"
className="form-input"
style={{ width: '100%' }}
value={formData.icon}
onChange={e => setFormData(f => ({ ...f, icon: e.target.value }))}
placeholder="🧘"
/>
</div>
</div>
{/* Category */}
<div>
<label className="form-label">Kategorie</label>
<select
className="form-input"
style={{ width: '100%' }}
value={formData.category}
onChange={e => setFormData(f => ({ ...f, category: e.target.value }))}
>
{CATEGORIES.map(cat => (
<option key={cat} value={cat}>{cat}</option>
))}
</select>
</div>
{/* Data Source */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
<div>
<label className="form-label">Tabelle</label>
{schemaInfo ? (
<select
className="form-input"
style={{ width: '100%' }}
value={formData.source_table}
onChange={e => setFormData(f => ({ ...f, source_table: e.target.value, source_column: '' }))}
>
<option value="">-- Optional --</option>
{Object.entries(schemaInfo).map(([table, info]) => (
<option key={table} value={table} title={info.description}>
{table} - {info.description}
</option>
))}
</select>
) : (
<input
type="text"
className="form-input"
style={{ width: '100%' }}
value={formData.source_table}
onChange={e => setFormData(f => ({ ...f, source_table: e.target.value }))}
placeholder="Lade Schema..."
disabled
/>
)}
</div>
<div>
<label className="form-label">Spalte</label>
{schemaInfo && formData.source_table && schemaInfo[formData.source_table] ? (
<select
className="form-input"
style={{ width: '100%' }}
value={formData.source_column}
onChange={e => setFormData(f => ({ ...f, source_column: e.target.value }))}
>
<option value="">-- Wählen --</option>
{Object.entries(schemaInfo[formData.source_table].columns).map(([col, info]) => (
<option key={col} value={col} title={info.description}>
{col} - {info.description}
</option>
))}
</select>
) : (
<input
type="text"
className="form-input"
style={{ width: '100%' }}
value={formData.source_column}
onChange={e => setFormData(f => ({ ...f, source_column: e.target.value }))}
placeholder={formData.source_table ? "Spalte wählen..." : "Erst Tabelle wählen"}
disabled={!formData.source_table}
/>
)}
</div>
</div>
{/* Aggregation Method */}
<div>
<label className="form-label">Aggregationsmethode</label>
<select
className="form-input"
style={{ width: '100%' }}
value={formData.aggregation_method}
onChange={e => setFormData(f => ({ ...f, aggregation_method: e.target.value }))}
>
{AGGREGATION_METHODS.map(method => (
<option key={method.value} value={method.value}>{method.label}</option>
))}
</select>
</div>
{/* Filter Conditions */}
<div>
<label className="form-label">Filter (optional, JSON)</label>
<textarea
className="form-input"
style={{ width: '100%', minHeight: 80, fontFamily: 'monospace', fontSize: 13 }}
value={formData.filter_conditions}
onChange={e => setFormData(f => ({ ...f, filter_conditions: e.target.value }))}
placeholder={'Beispiel:\n{\n "training_type": "strength"\n}\n\nOder mehrere Werte:\n{\n "training_type": ["strength", "hiit"]\n}'}
/>
<div style={{ fontSize: 12, color: 'var(--text2)', marginTop: 4 }}>
💡 Filtert Einträge nach Spalten. Beispiel: <code>{`{"training_type": "strength"}`}</code> zählt nur Krafttraining
</div>
</div>
{/* Description */}
<div>
<label className="form-label">Beschreibung (optional)</label>
<textarea
className="form-input"
style={{ width: '100%', minHeight: 60 }}
value={formData.description}
onChange={e => setFormData(f => ({ ...f, description: e.target.value }))}
placeholder="Kurze Erklärung..."
/>
</div>
{/* Buttons */}
<div style={{ display: 'flex', gap: 12, marginTop: 8 }}>
<button className="btn-primary" onClick={handleSave} style={{ flex: 1 }}>
Speichern
</button>
<button
className="btn-secondary"
onClick={() => {
setShowForm(false)
setError(null)
}}
style={{ flex: 1 }}
>
Abbrechen
</button>
</div>
</div>
</div>
</div>
)}
</div>
)
}
+39
View File
@@ -444,6 +444,45 @@ export default function AdminPanel() {
🔗 Activity-Mappings (lernendes System)
</button>
</Link>
<Link to="/admin/training-profiles">
<button className="btn btn-secondary btn-full">
⭐ Training Type Profiles (#15)
</button>
</Link>
</div>
</div>
{/* KI-Prompts 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)"/> KI-Prompts (v9f)
</div>
<div style={{fontSize:12,color:'var(--text3)',marginBottom:12,lineHeight:1.5}}>
Verwalte AI-Prompts mit KI-Unterstützung: Generiere, optimiere und organisiere Prompts.
</div>
<div style={{display:'grid',gap:8}}>
<Link to="/admin/prompts">
<button className="btn btn-secondary btn-full">
🤖 KI-Prompts verwalten
</button>
</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>
+588
View File
@@ -0,0 +1,588 @@
import { useState, useEffect } from 'react'
import { api } from '../utils/api'
import UnifiedPromptModal from '../components/UnifiedPromptModal'
import { Star, Trash2, Edit, Copy, Filter, ArrowDownToLine } from 'lucide-react'
/**
* Admin Prompts Page - Unified System (Issue #28 Phase 3)
*
* Manages both base and pipeline-type prompts in one interface.
*/
export default function AdminPromptsPage() {
const [prompts, setPrompts] = useState([])
const [filteredPrompts, setFilteredPrompts] = useState([])
const [typeFilter, setTypeFilter] = useState('all') // 'all' | 'base' | 'pipeline'
const [category, setCategory] = useState('all')
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [editingPrompt, setEditingPrompt] = useState(null)
const [showNewPrompt, setShowNewPrompt] = useState(false)
const [importing, setImporting] = useState(false)
const [importResult, setImportResult] = useState(null)
const categories = [
{ id: 'all', label: 'Alle Kategorien' },
{ id: 'körper', label: 'Körper' },
{ id: 'ernährung', label: 'Ernährung' },
{ id: 'training', label: 'Training' },
{ id: 'schlaf', label: 'Schlaf' },
{ id: 'vitalwerte', label: 'Vitalwerte' },
{ id: 'ziele', label: 'Ziele' },
{ id: 'ganzheitlich', label: 'Ganzheitlich' },
{ id: 'pipeline', label: 'Pipeline' }
]
useEffect(() => {
loadPrompts()
}, [])
useEffect(() => {
let filtered = prompts
// Filter by type
if (typeFilter === 'base') {
filtered = filtered.filter(p => p.type === 'base')
} else if (typeFilter === 'pipeline') {
filtered = filtered.filter(p => p.type === 'pipeline')
}
// Filter by category
if (category !== 'all') {
filtered = filtered.filter(p => p.category === category)
}
setFilteredPrompts(filtered)
}, [typeFilter, category, prompts])
const loadPrompts = async () => {
try {
setLoading(true)
const data = await api.listAdminPrompts()
setPrompts(data)
setError(null)
} catch (e) {
setError(e.message)
} finally {
setLoading(false)
}
}
const handleToggleActive = async (prompt) => {
try {
await api.updateUnifiedPrompt(prompt.id, { active: !prompt.active })
await loadPrompts()
} catch (e) {
alert('Fehler: ' + e.message)
}
}
const handleDelete = async (prompt) => {
if (!confirm(`Prompt "${prompt.name}" wirklich löschen?`)) return
try {
await api.deletePrompt(prompt.id)
await loadPrompts()
} catch (e) {
alert('Fehler: ' + e.message)
}
}
const handleDuplicate = async (prompt) => {
try {
await api.duplicatePrompt(prompt.id)
await loadPrompts()
} catch (e) {
alert('Fehler: ' + e.message)
}
}
const handleConvertToBase = async (prompt) => {
// Convert a 1-stage pipeline to a base prompt
if (prompt.type !== 'pipeline') {
alert('Nur Pipeline-Prompts können konvertiert werden')
return
}
const stages = typeof prompt.stages === 'string'
? JSON.parse(prompt.stages)
: prompt.stages
if (!stages || stages.length !== 1) {
alert('Nur 1-stage Pipeline-Prompts können zu Basis-Prompts konvertiert werden')
return
}
const stage1 = stages[0]
if (!stage1.prompts || stage1.prompts.length !== 1) {
alert('Stage muss genau einen Prompt haben')
return
}
const firstPrompt = stage1.prompts[0]
if (firstPrompt.source !== 'inline' || !firstPrompt.template) {
alert('Nur inline Templates können konvertiert werden')
return
}
if (!confirm(`"${prompt.name}" zu Basis-Prompt konvertieren?`)) return
try {
await api.updateUnifiedPrompt(prompt.id, {
type: 'base',
template: firstPrompt.template,
output_format: firstPrompt.output_format || 'text',
stages: null
})
await loadPrompts()
} catch (e) {
alert('Fehler: ' + e.message)
}
}
const handleSave = async () => {
setEditingPrompt(null)
setShowNewPrompt(false)
await loadPrompts()
}
const getStageCount = (prompt) => {
if (prompt.type !== 'pipeline' || !prompt.stages) return 0
try {
const stages = typeof prompt.stages === 'string'
? JSON.parse(prompt.stages)
: prompt.stages
return stages.length
} catch (e) {
return 0
}
}
const getTypeLabel = (type) => {
if (type === 'base') return 'Basis'
if (type === 'pipeline') return 'Pipeline'
return type || 'Pipeline' // Default for old prompts
}
const getTypeColor = (type) => {
if (type === 'base') return 'var(--accent)'
if (type === 'pipeline') return '#6366f1'
return 'var(--text3)'
}
const handleExportAll = async () => {
try {
const data = await api.exportAllPrompts()
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `all-prompts-${new Date().toISOString().split('T')[0]}.json`
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
URL.revokeObjectURL(url)
} catch (e) {
setError('Export-Fehler: ' + e.message)
}
}
const handleImport = async (event) => {
const file = event.target.files[0]
if (!file) return
setImporting(true)
setError(null)
setImportResult(null)
try {
const text = await file.text()
const data = JSON.parse(text)
// Ask user about overwrite
const overwrite = confirm(
'Bestehende Prompts überschreiben?\n\n' +
'JA = Existierende Prompts aktualisieren\n' +
'NEIN = Nur neue Prompts erstellen, Duplikate überspringen'
)
const result = await api.importPrompts(data, overwrite)
setImportResult(result)
await loadPrompts()
} catch (e) {
setError('Import-Fehler: ' + e.message)
} finally {
setImporting(false)
event.target.value = '' // Reset file input
}
}
return (
<div style={{
padding: 20,
maxWidth: 1400,
margin: '0 auto',
paddingBottom: 80
}}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 24
}}>
<h1 style={{ margin: 0, fontSize: 24, fontWeight: 600 }}>
KI-Prompts ({filteredPrompts.length})
</h1>
<div style={{ display: 'flex', gap: 8 }}>
<button
className="btn"
onClick={handleExportAll}
title="Alle Prompts als JSON exportieren (Backup / Dev→Prod Sync)"
>
📦 Alle exportieren
</button>
<label className="btn" style={{ margin: 0, cursor: 'pointer' }}>
📥 Importieren
<input
type="file"
accept=".json"
onChange={handleImport}
disabled={importing}
style={{ display: 'none' }}
/>
</label>
<button
className="btn btn-primary"
onClick={() => setShowNewPrompt(true)}
>
+ Neuer Prompt
</button>
</div>
</div>
{error && (
<div style={{
padding: 16,
background: '#fee',
color: '#c00',
borderRadius: 8,
marginBottom: 16
}}>
{error}
</div>
)}
{importResult && (
<div style={{
padding: 16,
background: '#efe',
color: '#060',
borderRadius: 8,
marginBottom: 16
}}>
<div style={{ fontWeight: 600, marginBottom: 4 }}>
✅ Import erfolgreich
</div>
<div style={{ fontSize: 13 }}>
{importResult.created} erstellt · {importResult.updated} aktualisiert · {importResult.skipped} übersprungen
</div>
<button
onClick={() => setImportResult(null)}
style={{ marginTop: 8, fontSize: 12, padding: '4px 8px' }}
className="btn"
>
OK
</button>
</div>
)}
{/* Filters */}
<div style={{
display: 'flex',
gap: 12,
marginBottom: 24,
flexWrap: 'wrap',
alignItems: 'center'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<Filter size={16} color="var(--text3)" />
<span style={{ fontSize: 13, color: 'var(--text3)' }}>Typ:</span>
</div>
<div style={{ display: 'flex', gap: 6 }}>
<button
className={typeFilter === 'all' ? 'btn btn-primary' : 'btn'}
onClick={() => setTypeFilter('all')}
style={{ fontSize: 13, padding: '6px 12px' }}
>
Alle ({prompts.length})
</button>
<button
className={typeFilter === 'base' ? 'btn btn-primary' : 'btn'}
onClick={() => setTypeFilter('base')}
style={{ fontSize: 13, padding: '6px 12px' }}
>
Basis-Prompts ({prompts.filter(p => p.type === 'base').length})
</button>
<button
className={typeFilter === 'pipeline' ? 'btn btn-primary' : 'btn'}
onClick={() => setTypeFilter('pipeline')}
style={{ fontSize: 13, padding: '6px 12px' }}
>
Pipelines ({prompts.filter(p => p.type === 'pipeline' || !p.type).length})
</button>
</div>
<div style={{
width: 1,
height: 24,
background: 'var(--border)',
margin: '0 8px'
}} />
<select
className="form-select"
value={category}
onChange={e => setCategory(e.target.value)}
style={{ fontSize: 13, padding: '6px 12px' }}
>
{categories.map(cat => (
<option key={cat.id} value={cat.id}>
{cat.label}
</option>
))}
</select>
</div>
{/* Prompts Table */}
{loading ? (
<div style={{ textAlign: 'center', padding: 40, color: 'var(--text3)' }}>
Lädt...
</div>
) : (
<div style={{
background: 'var(--surface)',
borderRadius: 12,
border: '1px solid var(--border)',
overflowX: 'auto'
}}>
<table style={{ width: '100%', minWidth: 900, borderCollapse: 'collapse' }}>
<thead>
<tr style={{
background: 'var(--surface2)',
borderBottom: '1px solid var(--border)'
}}>
<th style={{
padding: 12,
textAlign: 'left',
fontSize: 12,
fontWeight: 600,
color: 'var(--text3)',
width: 80
}}>
Typ
</th>
<th style={{
padding: 12,
textAlign: 'left',
fontSize: 12,
fontWeight: 600,
color: 'var(--text3)'
}}>
Name
</th>
<th style={{
padding: 12,
textAlign: 'left',
fontSize: 12,
fontWeight: 600,
color: 'var(--text3)',
width: 120
}}>
Kategorie
</th>
<th style={{
padding: 12,
textAlign: 'center',
fontSize: 12,
fontWeight: 600,
color: 'var(--text3)',
width: 100
}}>
Stages
</th>
<th style={{
padding: 12,
textAlign: 'center',
fontSize: 12,
fontWeight: 600,
color: 'var(--text3)',
width: 80
}}>
Status
</th>
<th style={{
padding: 12,
textAlign: 'right',
fontSize: 12,
fontWeight: 600,
color: 'var(--text3)',
width: 120
}}>
Aktionen
</th>
</tr>
</thead>
<tbody>
{filteredPrompts.length === 0 ? (
<tr>
<td colSpan="6" style={{
padding: 40,
textAlign: 'center',
color: 'var(--text3)'
}}>
Keine Prompts gefunden
</td>
</tr>
) : (
filteredPrompts.map(prompt => (
<tr
key={prompt.id}
style={{
borderBottom: '1px solid var(--border)',
opacity: prompt.active ? 1 : 0.5
}}
>
<td style={{ padding: 12 }}>
<div style={{
display: 'inline-block',
padding: '2px 8px',
background: getTypeColor(prompt.type) + '20',
color: getTypeColor(prompt.type),
borderRadius: 6,
fontSize: 11,
fontWeight: 600
}}>
{getTypeLabel(prompt.type)}
</div>
</td>
<td style={{ padding: 12 }}>
<div>
<div style={{ fontSize: 14, fontWeight: 500 }}>
{prompt.display_name || prompt.name}
</div>
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 2 }}>
{prompt.slug}
</div>
</div>
</td>
<td style={{ padding: 12, fontSize: 13 }}>
{prompt.category || 'ganzheitlich'}
</td>
<td style={{ padding: 12, textAlign: 'center', fontSize: 13 }}>
{prompt.type === 'pipeline' ? (
<span style={{
background: 'var(--surface2)',
padding: '2px 6px',
borderRadius: 4,
fontSize: 11
}}>
{getStageCount(prompt)} Stages
</span>
) : (
<span style={{ color: 'var(--text3)', fontSize: 11 }}>—</span>
)}
</td>
<td style={{ padding: 12, textAlign: 'center' }}>
<label style={{
display: 'inline-flex',
alignItems: 'center',
cursor: 'pointer'
}}>
<input
type="checkbox"
checked={prompt.active}
onChange={() => handleToggleActive(prompt)}
style={{ margin: 0 }}
/>
</label>
</td>
<td style={{ padding: 12 }}>
<div style={{
display: 'flex',
gap: 6,
justifyContent: 'flex-end'
}}>
<button
onClick={() => setEditingPrompt(prompt)}
style={{
background: 'none',
border: 'none',
cursor: 'pointer',
padding: 4
}}
title="Bearbeiten"
>
<Edit size={16} color="var(--accent)" />
</button>
{/* Show convert button for 1-stage pipelines */}
{prompt.type === 'pipeline' && getStageCount(prompt) === 1 && (
<button
onClick={() => handleConvertToBase(prompt)}
style={{
background: 'none',
border: 'none',
cursor: 'pointer',
padding: 4
}}
title="Zu Basis-Prompt konvertieren"
>
<ArrowDownToLine size={16} color="#6366f1" />
</button>
)}
<button
onClick={() => handleDuplicate(prompt)}
style={{
background: 'none',
border: 'none',
cursor: 'pointer',
padding: 4
}}
title="Duplizieren"
>
<Copy size={16} color="var(--text3)" />
</button>
<button
onClick={() => handleDelete(prompt)}
style={{
background: 'none',
border: 'none',
cursor: 'pointer',
padding: 4
}}
title="Löschen"
>
<Trash2 size={16} color="var(--danger)" />
</button>
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
)}
{/* Unified Prompt Modal */}
{(editingPrompt || showNewPrompt) && (
<UnifiedPromptModal
prompt={editingPrompt}
onSave={handleSave}
onClose={() => {
setEditingPrompt(null)
setShowNewPrompt(false)
}}
/>
)}
</div>
)
}
@@ -0,0 +1,307 @@
import { useState, useEffect } from 'react'
import { api } from '../utils/api'
import '../app.css'
export default function AdminTrainingProfiles() {
const [stats, setStats] = useState(null)
const [trainingTypes, setTrainingTypes] = useState([])
const [templates, setTemplates] = useState([])
const [selectedType, setSelectedType] = useState(null)
const [editingProfile, setEditingProfile] = useState(null)
const [profileJson, setProfileJson] = useState('')
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [success, setSuccess] = useState('')
useEffect(() => {
load()
}, [])
const load = async () => {
try {
setLoading(true)
const [typesData, statsData, templatesData] = await Promise.all([
api.adminListTrainingTypes(),
api.getProfileStats(),
api.getProfileTemplates()
])
setTrainingTypes(typesData)
setStats(statsData)
setTemplates(templatesData)
} catch (e) {
setError(e.message)
} finally {
setLoading(false)
}
}
const openEditor = (type) => {
setSelectedType(type)
setEditingProfile(type.profile || null)
setProfileJson(JSON.stringify(type.profile || {}, null, 2))
setError('')
setSuccess('')
}
const closeEditor = () => {
setSelectedType(null)
setEditingProfile(null)
setProfileJson('')
}
const saveProfile = async () => {
try {
// Validate JSON
const profile = JSON.parse(profileJson)
// Update training type
await api.adminUpdateTrainingType(selectedType.id, { profile })
setSuccess(`Profil für "${selectedType.name_de}" gespeichert`)
closeEditor()
load()
} catch (e) {
setError(e.message || 'Ungültiges JSON')
}
}
const applyTemplate = async (typeId, templateKey) => {
if (!confirm(`Template "${templateKey}" auf diesen Trainingstyp anwenden?`)) return
try {
await api.applyProfileTemplate(typeId, templateKey)
setSuccess('Template erfolgreich angewendet')
load()
} catch (e) {
setError(e.message)
}
}
const batchReEvaluate = async () => {
if (!confirm('Alle Aktivitäten neu evaluieren? Das kann einige Sekunden dauern.')) return
try {
const result = await api.batchEvaluateActivities()
let message = `Batch-Evaluation abgeschlossen: ${result.stats.evaluated} evaluiert, ` +
`${result.stats.skipped} übersprungen, ${result.stats.errors} Fehler`
// Show error details if available
if (result.stats.error_details && result.stats.error_details.length > 0) {
message += '\n\nErste Fehler:\n' + result.stats.error_details.map(err =>
`- Aktivität ${err.activity_id} (Typ: ${err.training_type_id || 'keine'}): ${err.error}`
).join('\n')
}
if (result.stats.errors > 0) {
setError(message)
} else {
setSuccess(message)
}
} catch (e) {
setError(e.message)
}
}
if (loading) return <div className="spinner" />
return (
<div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto', paddingBottom: '100px' }}>
<h1>Training Type Profiles</h1>
<p style={{ color: 'var(--text2)', marginBottom: '24px' }}>
Konfiguriere Bewertungsprofile für Trainingstypen
</p>
{error && (
<div style={{
padding: '12px',
background: 'var(--danger)',
color: 'white',
borderRadius: '8px',
marginBottom: '16px'
}}>
{error}
</div>
)}
{success && (
<div style={{
padding: '12px',
background: 'var(--accent)',
color: 'white',
borderRadius: '8px',
marginBottom: '16px'
}}>
{success}
</div>
)}
{/* Statistics */}
{stats && (
<div className="card" style={{ marginBottom: '24px' }}>
<h3>Übersicht</h3>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px', marginTop: '16px' }}>
<div>
<div style={{ fontSize: '32px', fontWeight: '600', color: 'var(--accent)' }}>{stats.total}</div>
<div style={{ color: 'var(--text2)', fontSize: '14px' }}>Trainingstypen gesamt</div>
</div>
<div>
<div style={{ fontSize: '32px', fontWeight: '600', color: 'var(--accent)' }}>{stats.configured}</div>
<div style={{ color: 'var(--text2)', fontSize: '14px' }}>Profile konfiguriert</div>
</div>
<div>
<div style={{ fontSize: '32px', fontWeight: '600', color: 'var(--text3)' }}>{stats.unconfigured}</div>
<div style={{ color: 'var(--text2)', fontSize: '14px' }}>Noch keine Profile</div>
</div>
</div>
<button
onClick={batchReEvaluate}
className="btn btn-primary"
style={{ marginTop: '16px', width: '100%' }}
>
🔄 Alle Aktivitäten neu evaluieren
</button>
</div>
)}
{/* Training Types List */}
<div className="card">
<h3>Trainingstypen</h3>
<div style={{ marginTop: '16px' }}>
{trainingTypes.map(type => (
<div
key={type.id}
style={{
padding: '16px',
borderBottom: '1px solid var(--border)',
display: 'flex',
alignItems: 'center',
gap: '16px'
}}
>
<div style={{ fontSize: '24px' }}>{type.icon || '📊'}</div>
<div style={{ flex: 1 }}>
<div style={{ fontWeight: '500', marginBottom: '4px' }}>
{type.name_de}
{type.profile && (
<span style={{
marginLeft: '8px',
padding: '2px 8px',
background: 'var(--accent)',
color: 'white',
borderRadius: '4px',
fontSize: '12px'
}}>
✓ Profil
</span>
)}
</div>
<div style={{ fontSize: '14px', color: 'var(--text2)' }}>
{type.category} {type.subcategory && `· ${type.subcategory}`}
</div>
</div>
<div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
{/* Template Buttons */}
{templates.map(template => (
<button
key={template.key}
onClick={() => applyTemplate(type.id, template.key)}
className="btn"
style={{ padding: '6px 12px', fontSize: '13px' }}
title={`Template "${template.name_de}" anwenden`}
>
{template.icon} {template.name_de}
</button>
))}
<button
onClick={() => openEditor(type)}
className="btn btn-primary"
style={{ padding: '6px 16px' }}
>
{type.profile ? '✏️ Bearbeiten' : '➕ Profil erstellen'}
</button>
</div>
</div>
))}
</div>
</div>
{/* Profile Editor Modal */}
{selectedType && (
<div style={{
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
background: 'rgba(0,0,0,0.7)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
zIndex: 1000,
padding: '20px'
}}>
<div style={{
background: 'var(--bg)',
borderRadius: '12px',
maxWidth: '900px',
width: '100%',
maxHeight: '90vh',
overflow: 'auto',
padding: '24px'
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
<h2>{selectedType.icon} {selectedType.name_de} - Profil bearbeiten</h2>
<button onClick={closeEditor} className="btn" style={{ padding: '8px 16px' }}>✕ Schließen</button>
</div>
<p style={{ color: 'var(--text2)', marginBottom: '16px' }}>
JSON-basierter Editor. Siehe Dokumentation für vollständige Struktur.
</p>
<textarea
value={profileJson}
onChange={(e) => setProfileJson(e.target.value)}
style={{
width: '100%',
minHeight: '400px',
padding: '12px',
fontFamily: 'monospace',
fontSize: '13px',
border: '1px solid var(--border)',
borderRadius: '8px',
background: 'var(--surface)',
color: 'var(--text1)',
resize: 'vertical'
}}
/>
<div style={{ display: 'flex', gap: '12px', marginTop: '16px' }}>
<button onClick={saveProfile} className="btn btn-primary" style={{ flex: 1 }}>
💾 Profil speichern
</button>
<button onClick={closeEditor} className="btn" style={{ flex: 1 }}>
Abbrechen
</button>
</div>
{selectedType.profile && (
<div style={{ marginTop: '16px', padding: '12px', background: 'var(--surface2)', borderRadius: '8px' }}>
<strong>Aktuelles Profil:</strong>
<div style={{ fontSize: '13px', color: 'var(--text2)', marginTop: '8px' }}>
Version: {selectedType.profile.version || 'n/a'}
<br />
Regel-Sets: {selectedType.profile.rule_sets ? Object.keys(selectedType.profile.rule_sets).join(', ') : 'keine'}
</div>
</div>
)}
</div>
</div>
)}
</div>
)
}
+209 -51
View File
@@ -1,7 +1,8 @@
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Pencil, Trash2, Plus, Save, X, ArrowLeft } from 'lucide-react'
import { Pencil, Trash2, Plus, Save, X, ArrowLeft, Settings } from 'lucide-react'
import { api } from '../utils/api'
import ProfileBuilder from '../components/ProfileBuilder'
/**
* AdminTrainingTypesPage - CRUD for training types
@@ -16,6 +17,8 @@ export default function AdminTrainingTypesPage() {
const [formData, setFormData] = useState(null)
const [error, setError] = useState(null)
const [saving, setSaving] = useState(false)
const [editingProfileId, setEditingProfileId] = useState(null)
const [parameters, setParameters] = useState([])
useEffect(() => {
load()
@@ -25,10 +28,12 @@ export default function AdminTrainingTypesPage() {
setLoading(true)
Promise.all([
api.adminListTrainingTypes(),
api.getTrainingCategories()
]).then(([typesData, catsData]) => {
api.getTrainingCategories(),
api.getTrainingParameters()
]).then(([typesData, catsData, paramsData]) => {
setTypes(typesData)
setCategories(catsData)
setParameters(paramsData.parameters || [])
setLoading(false)
}).catch(err => {
console.error('Failed to load training types:', err)
@@ -109,6 +114,31 @@ export default function AdminTrainingTypesPage() {
}
}
const startEditProfile = (typeId) => {
setEditingProfileId(typeId)
setEditingId(null) // Close type editor if open
setFormData(null)
}
const cancelEditProfile = () => {
setEditingProfileId(null)
}
const handleSaveProfile = async (profile) => {
try {
await api.adminUpdateTrainingType(editingProfileId, { profile })
await load()
// Success message is shown by ProfileBuilder component
// Don't close editor immediately - let user see success message
setTimeout(() => {
setEditingProfileId(null)
}, 2000)
} catch (err) {
// Error will be thrown to ProfileBuilder
throw err
}
}
// Group by category
const grouped = {}
types.forEach(type => {
@@ -162,8 +192,8 @@ export default function AdminTrainingTypesPage() {
</button>
)}
{/* Edit form */}
{editingId && formData && (
{/* Edit form (only for new type creation, at top) */}
{editingId === 'new' && formData && (
<div className="card" style={{ padding: 16, marginBottom: 16 }}>
<div style={{ fontWeight: 600, marginBottom: 12 }}>
{editingId === 'new' ? '➕ Neuer Trainingstyp' : '✏️ Trainingstyp bearbeiten'}
@@ -321,54 +351,182 @@ export default function AdminTrainingTypesPage() {
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{catTypes.sort((a, b) => a.sort_order - b.sort_order).map(type => (
<div
key={type.id}
style={{
display: 'flex',
alignItems: 'center',
gap: 8,
padding: 8,
background: 'var(--surface)',
borderRadius: 6
}}
>
<div style={{ fontSize: 18 }}>{type.icon}</div>
<div style={{ flex: 1 }}>
<div style={{ fontSize: 13, fontWeight: 500 }}>
{type.name_de} <span style={{ color: 'var(--text3)' }}>/ {type.name_en}</span>
</div>
{type.subcategory && (
<div style={{ fontSize: 11, color: 'var(--text3)' }}>
Subkategorie: {type.subcategory}
<div key={type.id}>
{/* Type Row */}
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 8,
padding: 8,
background: 'var(--surface)',
borderRadius: 6
}}
>
<div style={{ fontSize: 18 }}>{type.icon}</div>
<div style={{ flex: 1 }}>
<div style={{ fontSize: 13, fontWeight: 500 }}>
{type.name_de} <span style={{ color: 'var(--text3)' }}>/ {type.name_en}</span>
{type.profile && (
<span style={{
marginLeft: 8,
padding: '2px 6px',
background: 'var(--accent)',
color: 'white',
borderRadius: 4,
fontSize: 10
}}>
✓ Profil
</span>
)}
</div>
)}
{type.subcategory && (
<div style={{ fontSize: 11, color: 'var(--text3)' }}>
Subkategorie: {type.subcategory}
</div>
)}
</div>
<button
onClick={() => startEditProfile(type.id)}
style={{
background: 'none',
border: 'none',
cursor: 'pointer',
padding: 6,
color: 'var(--accent)'
}}
title="Profil konfigurieren"
>
<Settings size={16} />
</button>
<button
onClick={() => startEdit(type)}
style={{
background: 'none',
border: 'none',
cursor: 'pointer',
padding: 6,
color: 'var(--accent)'
}}
title="Bearbeiten"
>
<Pencil size={16} />
</button>
<button
onClick={() => handleDelete(type.id, type.name_de)}
style={{
background: 'none',
border: 'none',
cursor: 'pointer',
padding: 6,
color: '#D85A30'
}}
title="Löschen"
>
<Trash2 size={16} />
</button>
</div>
<button
onClick={() => startEdit(type)}
style={{
background: 'none',
border: 'none',
cursor: 'pointer',
padding: 6,
color: 'var(--accent)'
}}
title="Bearbeiten"
>
<Pencil size={16} />
</button>
<button
onClick={() => handleDelete(type.id, type.name_de)}
style={{
background: 'none',
border: 'none',
cursor: 'pointer',
padding: 6,
color: '#D85A30'
}}
title="Löschen"
>
<Trash2 size={16} />
</button>
{/* Inline Profile Builder */}
{editingProfileId === type.id && (
<div style={{ marginTop: 8 }}>
<ProfileBuilder
trainingType={type}
parameters={parameters}
onSave={handleSaveProfile}
onCancel={cancelEditProfile}
/>
</div>
)}
{/* Inline Type Editor */}
{editingId === type.id && formData && (
<div style={{ marginTop: 8, padding: 16, background: 'var(--surface2)', borderRadius: 8 }}>
<div style={{ fontWeight: 600, marginBottom: 12 }}>✏️ Trainingstyp bearbeiten</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<div>
<div className="form-label">Kategorie *</div>
<select
className="form-input"
value={formData.category}
onChange={e => setFormData({ ...formData, category: e.target.value })}
style={{ width: '100%' }}
>
{Object.keys(categories).map(cat => (
<option key={cat} value={cat}>
{categories[cat].icon} {categories[cat].name_de}
</option>
))}
</select>
</div>
<div>
<div className="form-label">Subkategorie</div>
<input
className="form-input"
value={formData.subcategory}
onChange={e => setFormData({ ...formData, subcategory: e.target.value })}
placeholder="z.B. running, hypertrophy, meditation"
style={{ width: '100%' }}
/>
</div>
<div>
<div className="form-label">Name (Deutsch) *</div>
<input
className="form-input"
value={formData.name_de}
onChange={e => setFormData({ ...formData, name_de: e.target.value })}
placeholder="z.B. Laufen"
style={{ width: '100%' }}
/>
</div>
<div>
<div className="form-label">Name (English) *</div>
<input
className="form-input"
value={formData.name_en}
onChange={e => setFormData({ ...formData, name_en: e.target.value })}
placeholder="e.g. Running"
style={{ width: '100%' }}
/>
</div>
<div>
<div className="form-label">Icon (Emoji)</div>
<input
className="form-input"
value={formData.icon}
onChange={e => setFormData({ ...formData, icon: e.target.value })}
placeholder="🏃"
maxLength={10}
style={{ width: '100%' }}
/>
</div>
<div>
<div className="form-label">Sortierung</div>
<input
type="number"
className="form-input"
value={formData.sort_order}
onChange={e => setFormData({ ...formData, sort_order: parseInt(e.target.value) })}
style={{ width: '100%' }}
/>
</div>
<div style={{ display: 'flex', gap: 8 }}>
<button onClick={handleSave} disabled={saving} className="btn btn-primary" style={{ flex: 1 }}>
{saving ? <><div className="spinner" style={{ width: 14, height: 14 }} /> Speichere...</> : <><Save size={16} /> Speichern</>}
</button>
<button onClick={cancelEdit} disabled={saving} className="btn btn-secondary" style={{ flex: 1 }}>
<X size={16} /> Abbrechen
</button>
</div>
</div>
</div>
)}
</div>
))}
</div>
+348 -309
View File
@@ -1,5 +1,6 @@
import { useState, useEffect } from 'react'
import { Brain, Pencil, Trash2, ChevronDown, ChevronUp, Check, X } from 'lucide-react'
import React, { useState, useEffect } from 'react'
import { Brain, Trash2, ChevronDown, ChevronUp, Target } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { api } from '../utils/api'
import { useAuth } from '../context/AuthContext'
import Markdown from '../utils/Markdown'
@@ -8,30 +9,83 @@ import dayjs from 'dayjs'
import 'dayjs/locale/de'
dayjs.locale('de')
// Legacy fallback labels (display_name takes precedence)
const SLUG_LABELS = {
gesamt: '🔍 Gesamtanalyse',
koerper: '🫧 Körperkomposition',
ernaehrung: '🍽️ Ernährung',
aktivitaet: '🏋️ Aktivität',
gesundheit: '❤️ Gesundheitsindikatoren',
ziele: '🎯 Zielfortschritt',
pipeline: '🔬 Mehrstufige Gesamtanalyse',
pipeline_body: '🔬 Pipeline: Körper-Analyse (JSON)',
pipeline_nutrition: '🔬 Pipeline: Ernährungs-Analyse (JSON)',
pipeline_activity: '🔬 Pipeline: Aktivitäts-Analyse (JSON)',
pipeline_synthesis: '🔬 Pipeline: Synthese',
pipeline_goals: '🔬 Pipeline: Zielabgleich',
pipeline: '🔬 Mehrstufige Gesamtanalyse'
}
function InsightCard({ ins, onDelete, defaultOpen=false }) {
function InsightCard({ ins, onDelete, defaultOpen=false, prompts=[] }) {
const [open, setOpen] = useState(defaultOpen)
// Parse metadata early to determine showOnlyValues
const metadataRaw = ins.metadata ? (typeof ins.metadata === 'string' ? JSON.parse(ins.metadata) : ins.metadata) : null
const isBasePrompt = metadataRaw?.prompt_type === 'base'
const isJsonOutput = ins.content && (ins.content.trim().startsWith('{') || ins.content.trim().startsWith('['))
const placeholdersRaw = metadataRaw?.placeholders || {}
const showOnlyValues = isBasePrompt && isJsonOutput && Object.keys(placeholdersRaw).length > 0
const [showValues, setShowValues] = useState(showOnlyValues) // Auto-expand for base prompts with JSON
const [expertMode, setExpertMode] = useState(false) // Show empty/technical placeholders
// Find matching prompt to get display_name
const prompt = prompts.find(p => p.slug === ins.scope)
const displayName = prompt?.display_name || SLUG_LABELS[ins.scope] || ins.scope
// Use already-parsed metadata
const metadata = metadataRaw
const allPlaceholders = placeholdersRaw
// Filter placeholders: In normal mode, hide empty values and raw stage outputs
const placeholders = expertMode
? allPlaceholders
: Object.fromEntries(
Object.entries(allPlaceholders).filter(([key, data]) => {
// Hide raw stage outputs (JSON) in normal mode
if (data.is_stage_raw) return false
// Hide empty values
const val = data.value || ''
return val.trim() !== '' && val !== 'nicht verfügbar' && val !== '[Nicht verfügbar]'
})
)
const placeholderCount = Object.keys(placeholders).length
const hiddenCount = Object.keys(allPlaceholders).length - placeholderCount
// Group placeholders by category
const groupedPlaceholders = Object.entries(placeholders).reduce((acc, [key, data]) => {
const category = data.category || 'Sonstiges'
if (!acc[category]) acc[category] = []
acc[category].push([key, data])
return acc
}, {})
// Sort categories: Regular categories first, then Stage outputs, then Rohdaten
const sortedCategories = Object.keys(groupedPlaceholders).sort((a, b) => {
const aIsStage = a.startsWith('Stage')
const bIsStage = b.startsWith('Stage')
const aIsRohdaten = a.includes('Rohdaten')
const bIsRohdaten = b.includes('Rohdaten')
// Rohdaten last
if (aIsRohdaten && !bIsRohdaten) return 1
if (!aIsRohdaten && bIsRohdaten) return -1
// Stage outputs after regular categories
if (!aIsStage && bIsStage) return -1
if (aIsStage && !bIsStage) return 1
// Otherwise alphabetical
return a.localeCompare(b)
})
return (
<div className="card section-gap" style={{borderLeft:`3px solid var(--accent)`}}>
<div style={{display:'flex',alignItems:'center',gap:8,marginBottom:open?12:0,cursor:'pointer'}}
onClick={()=>setOpen(o=>!o)}>
<div style={{flex:1}}>
<div style={{fontSize:13,fontWeight:600}}>
{SLUG_LABELS[ins.scope] || ins.scope}
{displayName}
</div>
<div style={{fontSize:11,color:'var(--text3)'}}>
{dayjs(ins.created).format('DD. MMMM YYYY, HH:mm')}
@@ -43,79 +97,195 @@ function InsightCard({ ins, onDelete, defaultOpen=false }) {
</button>
{open ? <ChevronUp size={16} color="var(--text3)"/> : <ChevronDown size={16} color="var(--text3)"/>}
</div>
{open && <Markdown text={ins.content}/>}
{open && (
<>
{/* For base prompts with JSON: Only show value table */}
{showOnlyValues && (
<div style={{ padding: '12px 16px', background: 'var(--surface)', borderRadius: 8, marginBottom: 12 }}>
<div style={{ fontSize: 11, color: 'var(--text3)', marginBottom: 8 }}>
ℹ️ Basis-Prompt Rohdaten (JSON-Struktur für technische Nutzung)
</div>
<details style={{ fontSize: 11, color: 'var(--text3)' }}>
<summary style={{ cursor: 'pointer' }}>Technische Daten anzeigen</summary>
<pre style={{
marginTop: 8,
padding: 8,
background: 'var(--bg)',
borderRadius: 4,
overflow: 'auto',
fontSize: 10,
fontFamily: 'monospace'
}}>
{ins.content}
</pre>
</details>
</div>
)}
{/* For other prompts: Show full content */}
{!showOnlyValues && <Markdown text={ins.content}/>}
{/* Value Table */}
{placeholderCount > 0 && (
<div style={{ marginTop: 16, borderTop: '1px solid var(--border)', paddingTop: 12 }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<div
onClick={() => setShowValues(!showValues)}
style={{
cursor: 'pointer',
fontSize: 12,
color: 'var(--text2)',
fontWeight: 600,
display: 'flex',
alignItems: 'center',
gap: 6
}}
>
{showValues ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
📊 Verwendete Werte ({placeholderCount})
{hiddenCount > 0 && !expertMode && (
<span style={{ fontSize: 10, color: 'var(--text3)', fontWeight: 400 }}>
(+{hiddenCount} ausgeblendet)
</span>
)}
</div>
{showValues && Object.keys(allPlaceholders).length > 0 && (
<button
onClick={(e) => {
e.stopPropagation()
setExpertMode(!expertMode)
}}
className="btn"
style={{
fontSize: 10,
padding: '4px 8px',
background: expertMode ? 'var(--accent)' : 'var(--surface)',
color: expertMode ? 'white' : 'var(--text2)'
}}
>
🔬 Experten-Modus
</button>
)}
</div>
{showValues && (
<div style={{ marginTop: 12, fontSize: 11 }}>
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead>
<tr style={{ borderBottom: '1px solid var(--border)', textAlign: 'left' }}>
<th style={{ padding: '6px 8px', color: 'var(--text3)', fontWeight: 600 }}>Platzhalter</th>
<th style={{ padding: '6px 8px', color: 'var(--text3)', fontWeight: 600 }}>Wert</th>
<th style={{ padding: '6px 8px', color: 'var(--text3)', fontWeight: 600 }}>Beschreibung</th>
</tr>
</thead>
<tbody>
{sortedCategories.map(category => (
<React.Fragment key={category}>
{/* Category Header */}
<tr style={{ background: 'var(--surface2)', borderTop: '2px solid var(--border)' }}>
<td colSpan="3" style={{
padding: '8px',
fontWeight: 600,
fontSize: 11,
color: 'var(--text2)',
letterSpacing: '0.5px'
}}>
{category}
</td>
</tr>
{/* Category Values */}
{groupedPlaceholders[category].map(([key, data]) => {
const isExtracted = data.is_extracted
const isStageRaw = data.is_stage_raw
return (
<tr key={key} style={{
borderBottom: '1px solid var(--border)',
background: isStageRaw && expertMode ? 'var(--surface)' : 'transparent'
}}>
<td style={{
padding: '6px 8px',
fontFamily: 'monospace',
color: isStageRaw ? 'var(--text3)' : (isExtracted ? '#6B8E23' : 'var(--accent)'),
whiteSpace: 'nowrap',
verticalAlign: 'top',
fontSize: isStageRaw ? 10 : 11
}}>
{isExtracted && '↳ '}
{isStageRaw && '🔬 '}
{key}
</td>
<td style={{
padding: '6px 8px',
fontFamily: 'monospace',
wordBreak: 'break-word',
maxWidth: '400px',
verticalAlign: 'top',
fontSize: isStageRaw ? 9 : 11,
color: isStageRaw ? 'var(--text3)' : 'var(--text1)'
}}>
{isStageRaw ? (
<details style={{ cursor: 'pointer' }}>
<summary style={{
fontWeight: 600,
color: 'var(--accent)',
fontSize: 10,
marginBottom: '4px'
}}>
JSON anzeigen ▼
</summary>
<pre style={{
background: 'var(--surface2)',
padding: '8px',
borderRadius: '4px',
fontSize: 9,
overflow: 'auto',
maxHeight: '300px',
margin: 0
}}>
{data.value}
</pre>
</details>
) : data.value}
</td>
<td style={{
padding: '6px 8px',
color: 'var(--text3)',
fontSize: 10,
verticalAlign: 'top',
fontStyle: isExtracted ? 'italic' : 'normal'
}}>
{data.description || '—'}
</td>
</tr>
)
})}
</React.Fragment>
))}
</tbody>
</table>
</div>
)}
</div>
)}
</>
)}
</div>
)
}
function PromptEditor({ prompt, onSave, onCancel }) {
const [template, setTemplate] = useState(prompt.template)
const [name, setName] = useState(prompt.name)
const [desc, setDesc] = useState(prompt.description||'')
const VARS = ['{{name}}','{{geschlecht}}','{{height}}','{{goal_weight}}','{{goal_bf_pct}}',
'{{weight_trend}}','{{weight_aktuell}}','{{kf_aktuell}}','{{caliper_summary}}',
'{{circ_summary}}','{{nutrition_summary}}','{{nutrition_detail}}',
'{{protein_ziel_low}}','{{protein_ziel_high}}','{{activity_summary}}',
'{{activity_kcal_summary}}','{{activity_detail}}']
return (
<div className="card section-gap">
<div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:12}}>
<div className="card-title" style={{margin:0}}>Prompt bearbeiten</div>
<button style={{background:'none',border:'none',cursor:'pointer',color:'var(--text3)'}}
onClick={onCancel}><X size={16}/></button>
</div>
<div className="form-row">
<label className="form-label">Name</label>
<input type="text" className="form-input" value={name} onChange={e=>setName(e.target.value)}/>
<span className="form-unit"/>
</div>
<div className="form-row">
<label className="form-label">Beschreibung</label>
<input type="text" className="form-input" value={desc} onChange={e=>setDesc(e.target.value)}/>
<span className="form-unit"/>
</div>
<div style={{marginBottom:8}}>
<div style={{fontSize:12,fontWeight:600,color:'var(--text3)',marginBottom:6}}>
Variablen (antippen zum Einfügen):
</div>
<div style={{display:'flex',flexWrap:'wrap',gap:4}}>
{VARS.map(v=>(
<button key={v} onClick={()=>setTemplate(t=>t+v)}
style={{fontSize:10,padding:'2px 7px',borderRadius:4,border:'1px solid var(--border2)',
background:'var(--surface2)',cursor:'pointer',fontFamily:'monospace',color:'var(--accent)'}}>
{v}
</button>
))}
</div>
</div>
<textarea value={template} onChange={e=>setTemplate(e.target.value)}
style={{width:'100%',minHeight:280,padding:10,fontFamily:'monospace',fontSize:12,
background:'var(--surface2)',border:'1.5px solid var(--border2)',borderRadius:8,
color:'var(--text1)',resize:'vertical',lineHeight:1.5,boxSizing:'border-box'}}/>
<div style={{display:'flex',gap:8,marginTop:8}}>
<button className="btn btn-primary" style={{flex:1}}
onClick={()=>onSave({name,description:desc,template})}>
<Check size={14}/> Speichern
</button>
<button className="btn btn-secondary" style={{flex:1}} onClick={onCancel}>Abbrechen</button>
</div>
</div>
)
}
export default function Analysis() {
const { canUseAI, isAdmin } = useAuth()
const { canUseAI } = useAuth()
const navigate = useNavigate()
const [prompts, setPrompts] = useState([])
const [allInsights, setAllInsights] = useState([])
const [loading, setLoading] = useState(null)
const [error, setError] = useState(null)
const [editing, setEditing] = useState(null)
const [tab, setTab] = useState('run')
const [newResult, setNewResult] = useState(null)
const [pipelineLoading, setPipelineLoading] = useState(false)
const [aiUsage, setAiUsage] = useState(null) // Phase 3: Usage badge
const [newResult, setNewResult] = useState(null)
const [aiUsage, setAiUsage] = useState(null)
const loadAll = async () => {
const [p, i] = await Promise.all([
@@ -135,48 +305,74 @@ export default function Analysis() {
}).catch(err => console.error('Failed to load usage:', err))
},[])
const runPipeline = async () => {
setPipelineLoading(true); setError(null); setNewResult(null)
try {
const result = await api.insightPipeline()
setNewResult(result)
await loadAll()
setTab('run')
} catch(e) {
setError('Pipeline-Fehler: ' + e.message)
} finally { setPipelineLoading(false) }
}
const runPrompt = async (slug) => {
setLoading(slug); setError(null); setNewResult(null)
try {
const result = await api.runInsight(slug)
setNewResult(result) // show immediately
await loadAll() // refresh lists
setTab('run') // stay on run tab to see result
// Use new unified executor with save=true
const result = await api.executeUnifiedPrompt(slug, null, null, false, true)
// Transform result to match old format for InsightCard
let content = ''
if (result.type === 'pipeline') {
// For pipeline, extract final output
const finalOutput = result.output || {}
if (typeof finalOutput === 'object' && Object.keys(finalOutput).length === 1) {
content = Object.values(finalOutput)[0]
} else {
content = JSON.stringify(finalOutput, null, 2)
}
} else {
// For base prompts, use output directly
content = typeof result.output === 'string' ? result.output : JSON.stringify(result.output, null, 2)
}
// Build metadata from debug info (same logic as backend)
let metadata = null
if (result.debug && result.debug.resolved_placeholders) {
const placeholders = {}
const resolved = result.debug.resolved_placeholders
// For pipeline, collect from all stages
if (result.type === 'pipeline' && result.debug.stages) {
for (const stage of result.debug.stages) {
for (const promptDebug of (stage.prompts || [])) {
const stageResolved = promptDebug.resolved_placeholders || promptDebug.ref_debug?.resolved_placeholders || {}
for (const [key, value] of Object.entries(stageResolved)) {
if (!placeholders[key]) {
placeholders[key] = { value, description: '' }
}
}
}
}
} else {
// For base prompts
for (const [key, value] of Object.entries(resolved)) {
placeholders[key] = { value, description: '' }
}
}
if (Object.keys(placeholders).length > 0) {
metadata = { prompt_type: result.type, placeholders }
}
}
setNewResult({ scope: slug, content, metadata })
await loadAll()
setTab('run')
} catch(e) {
setError('Fehler: ' + e.message)
} finally { setLoading(null) }
}
const savePrompt = async (promptId, data) => {
const token = localStorage.getItem('bodytrack_token')||''
await fetch(`/api/prompts/${promptId}`, {
method:'PUT',
headers:{'Content-Type':'application/json', 'X-Auth-Token': token},
body:JSON.stringify(data)
})
setEditing(null); await loadAll()
}
const deleteInsight = async (id) => {
if (!confirm('Analyse löschen?')) return
const pid = localStorage.getItem('bodytrack_active_profile')||''
await fetch(`/api/insights/${id}`, {
method:'DELETE', headers: pid ? {'X-Profile-Id':pid} : {}
})
if (newResult?.id === id) setNewResult(null)
await loadAll()
try {
await api.deleteInsight(id)
if (newResult?.id === id) setNewResult(null)
await loadAll()
} catch (e) {
setError('Löschen fehlgeschlagen: ' + e.message)
}
}
// Group insights by scope for history view
@@ -187,15 +383,21 @@ export default function Analysis() {
grouped[key].push(ins)
})
const activePrompts = prompts.filter(p=>p.active && !p.slug.startsWith('pipeline_') && p.slug !== 'pipeline')
// Pipeline is available if the "pipeline" prompt is active
const pipelinePrompt = prompts.find(p=>p.slug==='pipeline')
const pipelineAvailable = pipelinePrompt?.active ?? true // Default to true if not found (backwards compatibility)
// Show only active pipeline-type prompts
const pipelinePrompts = prompts.filter(p => p.active && p.type === 'pipeline')
return (
<div>
<h1 className="page-title">KI-Analyse</h1>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
<h1 className="page-title" style={{ margin: 0 }}>KI-Analyse</h1>
<button
className="btn btn-secondary"
onClick={() => navigate('/goals')}
style={{ fontSize: 13, padding: '6px 12px' }}
>
<Target size={14} /> Ziele
</button>
</div>
<div className="tabs">
<button className={'tab'+(tab==='run'?' active':'')} onClick={()=>setTab('run')}>Analysen starten</button>
@@ -204,7 +406,6 @@ export default function Analysis() {
{allInsights.length>0 && <span style={{marginLeft:4,fontSize:10,background:'var(--accent)',
color:'white',padding:'1px 5px',borderRadius:8}}>{allInsights.length}</span>}
</button>
{isAdmin && <button className={'tab'+(tab==='prompts'?' active':'')} onClick={()=>setTab('prompts')}>Prompts</button>}
</div>
{error && (
@@ -231,56 +432,11 @@ export default function Analysis() {
ins={{...newResult, created: new Date().toISOString()}}
onDelete={deleteInsight}
defaultOpen={true}
prompts={prompts}
/>
</div>
)}
{/* Pipeline button - only if all sub-prompts are active */}
{pipelineAvailable && (
<div className="card" style={{marginBottom:16,borderColor:'var(--accent)',borderWidth:2}}>
<div style={{display:'flex',alignItems:'flex-start',gap:12}}>
<div style={{flex:1}}>
<div className="badge-container-right" style={{fontWeight:700,fontSize:15,color:'var(--accent)'}}>
<span>🔬 Mehrstufige Gesamtanalyse</span>
{aiUsage && <UsageBadge {...aiUsage} />}
</div>
<div style={{fontSize:12,color:'var(--text2)',marginTop:3,lineHeight:1.5}}>
3 spezialisierte KI-Calls parallel (Körper + Ernährung + Aktivität),
dann Synthese + Zielabgleich. Detaillierteste Auswertung.
</div>
{allInsights.find(i=>i.scope==='pipeline') && (
<div style={{fontSize:11,color:'var(--text3)',marginTop:3}}>
Letzte Analyse: {dayjs(allInsights.find(i=>i.scope==='pipeline').created).format('DD.MM.YYYY, HH:mm')}
</div>
)}
</div>
<div
title={aiUsage && !aiUsage.allowed ? `Limit erreicht (${aiUsage.used}/${aiUsage.limit}). Kontaktiere den Admin oder warte bis zum nächsten Reset.` : ''}
style={{display:'inline-block'}}
>
<button
className="btn btn-primary"
style={{flexShrink:0,minWidth:100, cursor: (aiUsage && !aiUsage.allowed) ? 'not-allowed' : 'pointer'}}
onClick={runPipeline}
disabled={!!loading||pipelineLoading||(aiUsage && !aiUsage.allowed)}
>
{pipelineLoading
? <><div className="spinner" style={{width:13,height:13}}/> Läuft…</>
: (aiUsage && !aiUsage.allowed) ? '🔒 Limit'
: <><Brain size={13}/> Starten</>}
</button>
</div>
{!canUseAI && <div style={{fontSize:11,color:'#D85A30',marginTop:4}}>🔒 KI nicht freigeschaltet</div>}
</div>
{pipelineLoading && (
<div style={{marginTop:10,padding:'8px 12px',background:'var(--accent-light)',
borderRadius:8,fontSize:12,color:'var(--accent-dark)'}}>
⚡ Stufe 1: 3 parallele Analyse-Calls… dann Synthese… dann Zielabgleich
</div>
)}
</div>
)}
{!canUseAI && (
<div style={{padding:'14px 16px',background:'#FCEBEB',borderRadius:10,
border:'1px solid #D85A3033',marginBottom:16}}>
@@ -294,25 +450,31 @@ export default function Analysis() {
</div>
</div>
)}
{canUseAI && <p style={{fontSize:13,color:'var(--text2)',marginBottom:14,lineHeight:1.6}}>
Oder wähle eine Einzelanalyse:
</p>}
{activePrompts.map(p => {
// Show latest existing insight for this prompt
{canUseAI && pipelinePrompts.length > 0 && (
<p style={{fontSize:13,color:'var(--text2)',marginBottom:14,lineHeight:1.6}}>
Wähle eine mehrstufige KI-Analyse:
</p>
)}
{pipelinePrompts.map(p => {
const existing = allInsights.find(i=>i.scope===p.slug)
return (
<div key={p.id} className="card section-gap">
<div key={p.id} className="card" style={{marginBottom:16,borderColor:'var(--accent)',borderWidth:2}}>
<div style={{display:'flex',alignItems:'flex-start',gap:12}}>
<div style={{flex:1}}>
<div className="badge-container-right" style={{fontWeight:600,fontSize:15}}>
<span>{SLUG_LABELS[p.slug]||p.name}</span>
<div className="badge-container-right" style={{fontWeight:700,fontSize:15,color:'var(--accent)'}}>
<span>{p.display_name || SLUG_LABELS[p.slug] || p.name}</span>
{aiUsage && <UsageBadge {...aiUsage} />}
</div>
{p.description && <div style={{fontSize:12,color:'var(--text3)',marginTop:2}}>{p.description}</div>}
{p.description && (
<div style={{fontSize:12,color:'var(--text2)',marginTop:3,lineHeight:1.5}}>
{p.description}
</div>
)}
{existing && (
<div style={{fontSize:11,color:'var(--text3)',marginTop:3}}>
Letzte Auswertung: {dayjs(existing.created).format('DD.MM.YYYY, HH:mm')}
Letzte Analyse: {dayjs(existing.created).format('DD.MM.YYYY, HH:mm')}
</div>
)}
</div>
@@ -322,28 +484,34 @@ export default function Analysis() {
>
<button
className="btn btn-primary"
style={{flexShrink:0,minWidth:90, cursor: (aiUsage && !aiUsage.allowed) ? 'not-allowed' : 'pointer'}}
style={{flexShrink:0,minWidth:100, cursor: (aiUsage && !aiUsage.allowed) ? 'not-allowed' : 'pointer'}}
onClick={()=>runPrompt(p.slug)}
disabled={!!loading||!canUseAI||(aiUsage && !aiUsage.allowed)}
>
{loading===p.slug
? <><div className="spinner" style={{width:13,height:13}}/> Läuft…</>
: (aiUsage && !aiUsage.allowed) ? '🔒 Limit'
: <><Brain size={13}/> {existing?'Neu erstellen':'Starten'}</>}
: <><Brain size={13}/> Starten</>}
</button>
</div>
</div>
{/* Show existing result collapsed */}
{existing && newResult?.id !== existing.id && (
<div style={{marginTop:8,borderTop:'1px solid var(--border)',paddingTop:8}}>
<InsightCard ins={existing} onDelete={deleteInsight} defaultOpen={false}/>
<InsightCard ins={existing} onDelete={deleteInsight} defaultOpen={false} prompts={prompts}/>
</div>
)}
</div>
)
})}
{activePrompts.length===0 && (
<div className="empty-state"><p>Keine aktiven Prompts. Aktiviere im Tab "Prompts".</p></div>
{canUseAI && pipelinePrompts.length === 0 && (
<div className="empty-state">
<p>Keine aktiven Pipeline-Prompts verfügbar.</p>
<p style={{fontSize:12,color:'var(--text3)',marginTop:8}}>
Erstelle Pipeline-Prompts im Admin-Bereich (Einstellungen → Admin → KI-Prompts).
</p>
</div>
)}
</div>
)}
@@ -357,143 +525,14 @@ export default function Analysis() {
<div key={scope} style={{marginBottom:20}}>
<div style={{fontSize:13,fontWeight:700,color:'var(--text3)',
textTransform:'uppercase',letterSpacing:'0.05em',marginBottom:8}}>
{SLUG_LABELS[scope]||scope} ({ins.length})
{prompts.find(p => p.slug === scope)?.display_name || SLUG_LABELS[scope] || scope} ({ins.length})
</div>
{ins.map(i => <InsightCard key={i.id} ins={i} onDelete={deleteInsight}/>)}
{ins.map(i => <InsightCard key={i.id} ins={i} onDelete={deleteInsight} prompts={prompts}/>)}
</div>
))
}
</div>
)}
{/* ── Prompts ── */}
{tab==='prompts' && (
<div>
<p style={{fontSize:13,color:'var(--text2)',marginBottom:14,lineHeight:1.6}}>
Passe Prompts an. Variablen wie{' '}
<code style={{fontSize:11,background:'var(--surface2)',padding:'1px 4px',borderRadius:3}}>{'{{name}}'}</code>{' '}
werden automatisch mit deinen Daten befüllt.
</p>
{editing ? (
<PromptEditor prompt={editing}
onSave={(data)=>savePrompt(editing.id,data)}
onCancel={()=>setEditing(null)}/>
) : (() => {
const singlePrompts = prompts.filter(p=>!p.slug.startsWith('pipeline_'))
const pipelinePrompts = prompts.filter(p=>p.slug.startsWith('pipeline_'))
const jsonSlugs = ['pipeline_body','pipeline_nutrition','pipeline_activity']
return (
<>
{/* Single prompts */}
<div style={{fontSize:12,fontWeight:700,color:'var(--text3)',
textTransform:'uppercase',letterSpacing:'0.05em',marginBottom:8}}>
Einzelanalysen
</div>
{singlePrompts.map(p=>(
<div key={p.id} className="card section-gap" style={{opacity:p.active?1:0.6}}>
<div style={{display:'flex',alignItems:'center',gap:10}}>
<div style={{flex:1}}>
<div style={{fontWeight:600,fontSize:14,display:'flex',alignItems:'center',gap:8}}>
{SLUG_LABELS[p.slug]||p.name}
{!p.active && <span style={{fontSize:10,color:'#D85A30',
background:'#FCEBEB',padding:'2px 8px',borderRadius:4,fontWeight:600}}>⏸ Deaktiviert</span>}
</div>
{p.description && <div style={{fontSize:12,color:'var(--text3)',marginTop:1}}>{p.description}</div>}
</div>
<button className="btn btn-secondary" style={{padding:'5px 8px',fontSize:12}}
onClick={()=>{
const token = localStorage.getItem('bodytrack_token')||''
fetch(`/api/prompts/${p.id}`,{
method:'PUT',
headers:{'Content-Type':'application/json','X-Auth-Token':token},
body:JSON.stringify({active:!p.active})
}).then(loadAll)
}}>
{p.active?'Deaktivieren':'Aktivieren'}
</button>
<button className="btn btn-secondary" style={{padding:'5px 8px'}}
onClick={()=>setEditing(p)}><Pencil size={13}/></button>
</div>
<div style={{marginTop:8,padding:'8px 10px',background:'var(--surface2)',borderRadius:6,
fontSize:11,fontFamily:'monospace',color:'var(--text3)',maxHeight:60,overflow:'hidden',lineHeight:1.4}}>
{p.template.slice(0,200)}…
</div>
</div>
))}
{/* Pipeline prompts */}
<div style={{display:'flex',alignItems:'center',justifyContent:'space-between',margin:'20px 0 8px'}}>
<div style={{fontSize:12,fontWeight:700,color:'var(--text3)',
textTransform:'uppercase',letterSpacing:'0.05em'}}>
Mehrstufige Pipeline
</div>
{(() => {
const pipelinePrompt = prompts.find(p=>p.slug==='pipeline')
return pipelinePrompt && (
<button className="btn btn-secondary" style={{padding:'5px 12px',fontSize:12}}
onClick={()=>{
const token = localStorage.getItem('bodytrack_token')||''
fetch(`/api/prompts/${pipelinePrompt.id}`,{
method:'PUT',
headers:{'Content-Type':'application/json','X-Auth-Token':token},
body:JSON.stringify({active:!pipelinePrompt.active})
}).then(loadAll)
}}>
{pipelinePrompt.active ? 'Gesamte Pipeline deaktivieren' : 'Gesamte Pipeline aktivieren'}
</button>
)
})()}
</div>
{(() => {
const pipelinePrompt = prompts.find(p=>p.slug==='pipeline')
const isPipelineActive = pipelinePrompt?.active ?? true
return (
<div style={{padding:'10px 12px',
background: isPipelineActive ? 'var(--warn-bg)' : '#FCEBEB',
borderRadius:8,fontSize:12,
color: isPipelineActive ? 'var(--warn-text)' : '#D85A30',
marginBottom:12,lineHeight:1.6}}>
{isPipelineActive ? (
<>⚠️ <strong>Hinweis:</strong> Pipeline-Stage-1-Prompts müssen valides JSON zurückgeben.
Halte das JSON-Format im Prompt erhalten. Stage 2 + 3 können frei angepasst werden.</>
) : (
<>⏸ <strong>Pipeline deaktiviert:</strong> Die mehrstufige Gesamtanalyse ist aktuell nicht verfügbar.
Aktiviere sie mit dem Schalter oben, um sie auf der Analyse-Seite zu nutzen.</>
)}
</div>
)
})()}
{pipelinePrompts.map(p=>{
const isJson = jsonSlugs.includes(p.slug)
return (
<div key={p.id} className="card section-gap"
style={{borderLeft:`3px solid ${isJson?'var(--warn)':'var(--accent)'}`,opacity:p.active?1:0.6}}>
<div style={{display:'flex',alignItems:'center',gap:10}}>
<div style={{flex:1}}>
<div style={{fontWeight:600,fontSize:14,display:'flex',alignItems:'center',gap:8}}>
{p.name}
{isJson && <span style={{fontSize:10,background:'var(--warn-bg)',
color:'var(--warn-text)',padding:'1px 6px',borderRadius:4}}>JSON-Output</span>}
{!p.active && <span style={{fontSize:10,color:'#D85A30',
background:'#FCEBEB',padding:'2px 8px',borderRadius:4,fontWeight:600}}>⏸ Deaktiviert</span>}
</div>
{p.description && <div style={{fontSize:12,color:'var(--text3)',marginTop:1}}>{p.description}</div>}
</div>
<button className="btn btn-secondary" style={{padding:'5px 8px'}}
onClick={()=>setEditing(p)}><Pencil size={13}/></button>
</div>
<div style={{marginTop:8,padding:'8px 10px',background:'var(--surface2)',borderRadius:6,
fontSize:11,fontFamily:'monospace',color:'var(--text3)',maxHeight:80,overflow:'hidden',lineHeight:1.4}}>
{p.template.slice(0,300)}…
</div>
</div>
)
})}
</>
)
})()}
</div>
)}
</div>
)
}
+21
View File
@@ -52,6 +52,27 @@ const ENTRIES = [
to: '/sleep',
color: '#7B68EE',
},
{
icon: '🛌',
label: 'Ruhetage',
sub: 'Kraft-, Cardio-, oder Entspannungs-Ruhetag erfassen',
to: '/rest-days',
color: '#9B59B6',
},
{
icon: '❤️',
label: 'Vitalwerte',
sub: 'Ruhepuls und HRV morgens erfassen',
to: '/vitals',
color: '#E74C3C',
},
{
icon: '🎯',
label: 'Eigene Ziele',
sub: 'Fortschritte für individuelle Ziele erfassen',
to: '/custom-goals',
color: '#1D9E75',
},
{
icon: '📖',
label: 'Messanleitung',
+370
View File
@@ -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>
)
}
+21
View File
@@ -12,6 +12,7 @@ import TrialBanner from '../components/TrialBanner'
import EmailVerificationBanner from '../components/EmailVerificationBanner'
import TrainingTypeDistribution from '../components/TrainingTypeDistribution'
import SleepWidget from '../components/SleepWidget'
import RestDaysWidget from '../components/RestDaysWidget'
import { getInterpretation, getStatusColor, getStatusBg } from '../utils/interpret'
import Markdown from '../utils/Markdown'
import dayjs from 'dayjs'
@@ -477,6 +478,11 @@ export default function Dashboard() {
<SleepWidget/>
</div>
{/* Rest Days Widget */}
<div style={{marginBottom:16}}>
<RestDaysWidget/>
</div>
{/* Training Type Distribution */}
{activities.length > 0 && (
<div className="card section-gap" style={{marginBottom:16}}>
@@ -491,6 +497,21 @@ export default function Dashboard() {
</div>
)}
{/* Goals Preview */}
<div className="card section-gap" style={{marginBottom:16,cursor:'pointer'}}
onClick={()=>nav('/goals')}>
<div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:12}}>
<div style={{fontWeight:600,fontSize:13}}>🎯 Ziele</div>
<button style={{background:'none',border:'none',fontSize:12,color:'var(--accent)',cursor:'pointer'}}
onClick={(e)=>{e.stopPropagation();nav('/goals')}}>
Verwalten →
</button>
</div>
<div style={{fontSize:12,color:'var(--text2)',padding:'8px 0'}}>
Definiere deine Trainingsmodus und konkrete Ziele für bessere KI-Analysen
</div>
</div>
{/* Latest AI insight */}
<div className="card section-gap">
<div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8}}>
File diff suppressed because it is too large. Load diff
+29 -3
View File
@@ -1,5 +1,6 @@
import { useState, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useProfile } from '../context/ProfileContext'
import {
LineChart, Line, BarChart, Bar,
XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid,
@@ -586,13 +587,15 @@ function NutritionSection({ nutrition, weights, profile, insights, onRequest, lo
}
// ── Activity Section ──────────────────────────────────────────────────────────
function ActivitySection({ activities, insights, onRequest, loadingSlug, filterActiveSlugs }) {
function ActivitySection({ activities, insights, onRequest, loadingSlug, filterActiveSlugs, globalQualityLevel }) {
const [period, setPeriod] = useState(30)
if (!activities?.length) return (
<EmptySection text="Noch keine Aktivitätsdaten." to="/activity" toLabel="Aktivität erfassen"/>
)
const cutoff = dayjs().subtract(period,'day').format('YYYY-MM-DD')
const filtA = activities.filter(d=>period===9999||d.date>=cutoff)
// Issue #31: Backend already filters by global quality level - only filter by period here
const filtA = activities.filter(d => period === 9999 || d.date >= cutoff)
const byDate={}
filtA.forEach(a=>{ byDate[a.date]=(byDate[a.date]||0)+(a.kcal_active||0) })
@@ -620,6 +623,28 @@ function ActivitySection({ activities, insights, onRequest, loadingSlug, filterA
<div>
<SectionHeader title="🏋️ Aktivität" to="/activity" toLabel="Alle Einträge" lastUpdated={activities[0]?.date}/>
<PeriodSelector value={period} onChange={setPeriod}/>
{/* Issue #31: Show active global quality filter */}
{globalQualityLevel && globalQualityLevel !== 'all' && (
<div style={{
marginBottom:12, padding:'8px 12px', borderRadius:8,
background:'var(--surface2)', border:'1px solid var(--border)',
fontSize:12, color:'var(--text2)', display:'flex', alignItems:'center', gap:8
}}>
<span>
{globalQualityLevel === 'quality' && '✓ Filter: Hochwertig (excellent, good, acceptable)'}
{globalQualityLevel === 'very_good' && '✓✓ Filter: Sehr gut (excellent, good)'}
{globalQualityLevel === 'excellent' && '⭐ Filter: Exzellent (nur excellent)'}
</span>
<a href="/settings" style={{
marginLeft:'auto', color:'var(--accent)', textDecoration:'none',
fontSize:11, fontWeight:500, whiteSpace:'nowrap'
}}>
Hier ändern →
</a>
</div>
)}
<div style={{display:'flex',gap:6,marginBottom:12}}>
{[['Trainings',filtA.length,'var(--text1)'],['Kcal',totalKcal,'#EF9F27'],
['Stunden',Math.round(totalMin/60*10)/10,'#378ADD'],
@@ -899,6 +924,7 @@ const TABS = [
]
export default function History() {
const { activeProfile } = useProfile() // Issue #31: Get global quality filter
const location = useLocation?.() || {}
const [tab, setTab] = useState((location.state?.tab)||'body')
const [weights, setWeights] = useState([])
@@ -967,7 +993,7 @@ export default function History() {
</div>
{tab==='body' && <BodySection weights={weights} calipers={calipers} circs={circs} profile={profile} {...sp}/>}
{tab==='nutrition' && <NutritionSection nutrition={nutrition} weights={weights} profile={profile} {...sp}/>}
{tab==='activity' && <ActivitySection activities={activities} {...sp}/>}
{tab==='activity' && <ActivitySection activities={activities} globalQualityLevel={activeProfile?.quality_filter_level} {...sp}/>}
{tab==='correlation' && <CorrelationSection corrData={corrData} profile={profile} {...sp}/>}
{tab==='photos' && <PhotoGrid/>}
</div>
+507
View File
@@ -0,0 +1,507 @@
import { useState, useEffect } from 'react'
import { Pencil, Trash2, Check, X } from 'lucide-react'
import { api } from '../utils/api'
import dayjs from 'dayjs'
import 'dayjs/locale/de'
dayjs.locale('de')
// Quick Mode Presets
const PRESETS = [
{
id: 'muscle_recovery',
icon: '💪',
label: 'Kraft-Ruhetag',
description: 'Muskelregeneration – Kraft & HIIT pausieren, Cardio erlaubt',
color: '#D85A30',
config: {
focus: 'muscle_recovery',
rest_from: ['strength', 'hiit'],
allows: ['cardio_low', 'meditation', 'mobility', 'walk'],
intensity_max: 60,
}
},
{
id: 'cardio_recovery',
icon: '🏃',
label: 'Cardio-Ruhetag',
description: 'Ausdauererholung – Cardio pausieren, Kraft & Mobility erlaubt',
color: '#378ADD',
config: {
focus: 'cardio_recovery',
rest_from: ['cardio', 'cardio_low', 'cardio_high'],
allows: ['strength', 'mobility', 'meditation'],
intensity_max: 70,
}
},
{
id: 'mental_rest',
icon: '🧘',
label: 'Entspannungstag',
description: 'Mentale Erholung – Nur Meditation & Spaziergang',
color: '#7B68EE',
config: {
focus: 'mental_rest',
rest_from: ['strength', 'cardio', 'hiit', 'power'],
allows: ['meditation', 'walk'],
intensity_max: 40,
}
},
{
id: 'deload',
icon: '📉',
label: 'Deload',
description: 'Reduzierte Intensität – Alles erlaubt, max 70% Last',
color: '#E67E22',
config: {
focus: 'deload',
rest_from: [],
allows: ['strength', 'cardio', 'mobility', 'meditation'],
intensity_max: 70,
}
},
]
const FOCUS_LABELS = {
muscle_recovery: 'Muskelregeneration',
cardio_recovery: 'Cardio-Erholung',
mental_rest: 'Mentale Erholung',
deload: 'Deload',
injury: 'Verletzungspause',
}
export default function RestDaysPage() {
const [restDays, setRestDays] = useState([])
const [showForm, setShowForm] = useState(false)
const [formData, setFormData] = useState({
date: dayjs().format('YYYY-MM-DD'),
preset: null,
note: '',
})
const [editing, setEditing] = useState(null)
const [saving, setSaving] = useState(false)
const [error, setError] = useState(null)
const [toast, setToast] = useState(null)
useEffect(() => {
loadRestDays()
}, [])
const loadRestDays = async () => {
try {
const data = await api.listRestDays(90)
setRestDays(data)
} catch (err) {
console.error('Failed to load rest days:', err)
setError('Fehler beim Laden der Ruhetage')
}
}
const showToast = (message, duration = 2000) => {
setToast(message)
setTimeout(() => setToast(null), duration)
}
const handlePresetSelect = (preset) => {
setFormData(f => ({ ...f, preset: preset.id }))
}
const handleSave = async () => {
if (!formData.preset) {
setError('Bitte wähle einen Ruhetag-Typ')
return
}
setSaving(true)
setError(null)
try {
const preset = PRESETS.find(p => p.id === formData.preset)
await api.createRestDay({
date: formData.date,
rest_config: preset.config,
note: formData.note,
})
showToast('✓ Ruhetag gespeichert')
await loadRestDays()
setShowForm(false)
setFormData({
date: dayjs().format('YYYY-MM-DD'),
preset: null,
note: '',
})
} catch (err) {
console.error('Save failed:', err)
setError(err.message || 'Fehler beim Speichern')
} finally {
setSaving(false)
}
}
const handleDelete = async (id) => {
if (!confirm('Ruhetag löschen?')) return
try {
await api.deleteRestDay(id)
showToast('✓ Gelöscht')
await loadRestDays()
} catch (err) {
console.error('Delete failed:', err)
setError(err.message || 'Fehler beim Löschen')
}
}
const startEdit = (day) => {
setEditing({
...day,
note: day.note || '',
})
}
const cancelEdit = () => {
setEditing(null)
}
const handleUpdate = async () => {
try {
await api.updateRestDay(editing.id, {
note: editing.note,
})
showToast('✓ Aktualisiert')
setEditing(null)
await loadRestDays()
} catch (err) {
console.error('Update failed:', err)
setError(err.message || 'Fehler beim Aktualisieren')
}
}
return (
<div>
<h1 className="page-title">Ruhetage</h1>
{/* Toast Notification */}
{toast && (
<div style={{
position: 'fixed',
top: 70,
left: '50%',
transform: 'translateX(-50%)',
background: 'var(--accent)',
color: 'white',
padding: '10px 20px',
borderRadius: 8,
fontSize: 14,
fontWeight: 600,
zIndex: 1000,
animation: 'slideDown 0.3s ease',
}}>
{toast}
</div>
)}
{/* New Entry Form */}
{!showForm ? (
<button
className="btn btn-primary btn-full"
style={{ marginBottom: 16 }}
onClick={() => setShowForm(true)}
>
+ Ruhetag erfassen
</button>
) : (
<div className="card" style={{ marginBottom: 16 }}>
<div className="card-title">Neuer Ruhetag</div>
{/* Date */}
<div className="form-row">
<label className="form-label">Datum</label>
<input
type="date"
className="form-input"
style={{ width: 140 }}
value={formData.date}
onChange={e => setFormData(f => ({ ...f, date: e.target.value }))}
/>
<span className="form-unit" />
</div>
{/* Presets */}
<div style={{ marginTop: 16 }}>
<label className="form-label" style={{ marginBottom: 8 }}>Typ wählen:</label>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{PRESETS.map(preset => (
<button
key={preset.id}
onClick={() => handlePresetSelect(preset)}
style={{
display: 'flex',
alignItems: 'center',
gap: 12,
padding: '12px 14px',
borderRadius: 10,
border: formData.preset === preset.id
? `2px solid ${preset.color}`
: '1.5px solid var(--border)',
background: formData.preset === preset.id
? `${preset.color}14`
: 'var(--surface)',
cursor: 'pointer',
textAlign: 'left',
transition: 'all 0.15s',
}}
>
<div style={{
fontSize: 24,
width: 40,
height: 40,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
borderRadius: 8,
background: `${preset.color}22`,
flexShrink: 0,
}}>
{preset.icon}
</div>
<div style={{ flex: 1 }}>
<div style={{
fontSize: 14,
fontWeight: 600,
color: formData.preset === preset.id ? preset.color : 'var(--text1)',
marginBottom: 2,
}}>
{preset.label}
</div>
<div style={{ fontSize: 11, color: 'var(--text3)' }}>
{preset.description}
</div>
</div>
{formData.preset === preset.id && (
<Check size={18} style={{ color: preset.color, flexShrink: 0 }} />
)}
</button>
))}
</div>
</div>
{/* Note */}
<div className="form-row" style={{ marginTop: 16 }}>
<label className="form-label">Notiz</label>
<input
type="text"
className="form-input"
placeholder="optional"
value={formData.note}
onChange={e => setFormData(f => ({ ...f, note: e.target.value }))}
/>
<span className="form-unit" />
</div>
{/* Error */}
{error && (
<div style={{
padding: '10px',
background: 'var(--danger-bg)',
border: '1px solid var(--danger)',
borderRadius: 8,
fontSize: 13,
color: 'var(--danger)',
marginTop: 8,
}}>
{error}
</div>
)}
{/* Actions */}
<div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
<button
className="btn btn-primary"
style={{ flex: 1 }}
onClick={handleSave}
disabled={saving}
>
{saving ? '...' : 'Speichern'}
</button>
<button
className="btn btn-secondary"
style={{ flex: 1 }}
onClick={() => {
setShowForm(false)
setFormData({
date: dayjs().format('YYYY-MM-DD'),
preset: null,
note: '',
})
setError(null)
}}
>
Abbrechen
</button>
</div>
</div>
)}
{/* List */}
<div className="section-gap">
<div className="card-title" style={{ marginBottom: 8 }}>
Verlauf ({restDays.length})
</div>
{restDays.length === 0 && (
<p className="muted">Noch keine Ruhetage erfasst.</p>
)}
{restDays.map(day => {
const isEditing = editing?.id === day.id
const focus = day.rest_config?.focus || 'mental_rest'
const preset = PRESETS.find(p => p.id === focus)
const isToday = day.date === dayjs().format('YYYY-MM-DD')
return (
<div key={day.id} className="card" style={{
marginBottom: 8,
border: isToday ? '2px solid var(--accent)' : undefined,
background: isToday ? 'var(--accent)08' : undefined,
}}>
{isEditing ? (
<div>
<div style={{ fontWeight: 600, fontSize: 14, marginBottom: 8 }}>
{dayjs(day.date).format('DD. MMMM YYYY')}
</div>
<div className="form-row">
<label className="form-label">Notiz</label>
<input
type="text"
className="form-input"
value={editing.note}
onChange={e => setEditing(d => ({ ...d, note: e.target.value }))}
/>
<span className="form-unit" />
</div>
<div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
<button
className="btn btn-primary"
style={{ flex: 1 }}
onClick={handleUpdate}
>
<Check size={13} /> Speichern
</button>
<button
className="btn btn-secondary"
style={{ flex: 1 }}
onClick={cancelEdit}
>
<X size={13} /> Abbrechen
</button>
</div>
</div>
) : (
<div>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 8,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<div style={{ fontWeight: 600, fontSize: 14 }}>
{dayjs(day.date).format('DD. MMMM YYYY')}
</div>
{isToday && (
<span style={{
padding: '2px 8px',
borderRadius: 4,
background: 'var(--accent)',
color: 'white',
fontSize: 11,
fontWeight: 600,
}}>
HEUTE
</span>
)}
</div>
<div style={{ display: 'flex', gap: 6 }}>
<button
className="btn btn-secondary"
style={{ padding: '5px 8px' }}
onClick={() => startEdit(day)}
>
<Pencil size={13} />
</button>
<button
className="btn btn-danger"
style={{ padding: '5px 8px' }}
onClick={() => handleDelete(day.id)}
>
<Trash2 size={13} />
</button>
</div>
</div>
{/* Preset Badge */}
<div style={{
display: 'inline-flex',
alignItems: 'center',
gap: 6,
padding: '4px 10px',
borderRadius: 6,
background: `${preset?.color || '#888'}22`,
border: `1px solid ${preset?.color || '#888'}`,
fontSize: 12,
fontWeight: 600,
color: preset?.color || '#888',
marginBottom: day.note ? 8 : 0,
}}>
<span style={{ fontSize: 14 }}>{preset?.icon || '📅'}</span>
{FOCUS_LABELS[focus] || focus}
</div>
{/* Note */}
{day.note && (
<p style={{
fontSize: 12,
color: 'var(--text2)',
fontStyle: 'italic',
marginTop: 6,
}}>
"{day.note}"
</p>
)}
{/* Details (collapsible, optional for later) */}
{day.rest_config && (
<div style={{
marginTop: 8,
padding: 8,
background: 'var(--bg)',
borderRadius: 6,
fontSize: 11,
color: 'var(--text3)',
}}>
{day.rest_config.rest_from?.length > 0 && (
<div>
<strong>Pausiert:</strong> {day.rest_config.rest_from.join(', ')}
</div>
)}
{day.rest_config.allows?.length > 0 && (
<div>
<strong>Erlaubt:</strong> {day.rest_config.allows.join(', ')}
</div>
)}
{day.rest_config.intensity_max && (
<div>
<strong>Max Intensität:</strong> {day.rest_config.intensity_max}% HFmax
</div>
)}
</div>
)}
</div>
)}
</div>
)
})}
</div>
</div>
)
}
+79
View File
@@ -202,6 +202,16 @@ export default function SettingsPage() {
}
}
const handleQualityFilterChange = async (level) => {
// Issue #31: Update global quality filter
await api.updateActiveProfile({ quality_filter_level: level })
await refreshProfiles()
const updated = profiles.find(p => p.id === activeProfile?.id)
if (updated) setActiveProfile({...updated, quality_filter_level: level})
setSaved(true)
setTimeout(() => setSaved(false), 2000)
}
const handleSave = async (form, profileId) => {
const data = {}
if (form.name) data.name = form.name
@@ -241,6 +251,23 @@ export default function SettingsPage() {
setEditingId(null)
}
const handleExportPlaceholders = async () => {
try {
const data = await api.exportPlaceholderValues()
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `placeholders-${activeProfile?.name || 'profile'}-${new Date().toISOString().split('T')[0]}.json`
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
URL.revokeObjectURL(url)
} catch (e) {
alert('Fehler beim Export: ' + e.message)
}
}
return (
<div>
<h1 className="page-title">Einstellungen</h1>
@@ -399,6 +426,16 @@ export default function SettingsPage() {
<span className="badge-button-description">maschinenlesbar, alles in einer Datei</span>
</div>
</button>
<button className="btn btn-full"
onClick={handleExportPlaceholders}
style={{ background: 'var(--surface2)', border: '1px solid var(--border)' }}>
<div className="badge-button-layout">
<div className="badge-button-header">
<span><BarChart3 size={14}/> Platzhalter exportieren</span>
</div>
<span className="badge-button-description">alle verfügbaren Platzhalter mit aktuellen Werten</span>
</div>
</button>
</>}
</div>
<p style={{fontSize:11,color:'var(--text3)',marginTop:8}}>
@@ -455,6 +492,48 @@ export default function SettingsPage() {
</p>
</div>
{/* Issue #31: Global Quality Filter */}
<div className="card section-gap">
<div className="card-title">Datenqualität</div>
<p style={{fontSize:13,color:'var(--text2)',marginBottom:12,lineHeight:1.6}}>
Qualitätsfilter wirkt auf <strong>alle Ansichten</strong>: Dashboard, Charts, Statistiken und KI-Analysen.
</p>
<div style={{marginBottom:8}}>
<label style={{fontSize:12,fontWeight:600,color:'var(--text3)',display:'block',marginBottom:6}}>
QUALITÄTSFILTER (GLOBAL)
</label>
<select
className="form-select"
value={activeProfile?.quality_filter_level || 'all'}
onChange={e => handleQualityFilterChange(e.target.value)}
style={{width:'100%',fontSize:13}}>
<option value="all">📊 Alle Activities</option>
<option value="quality">✓ Hochwertig (excellent, good, acceptable)</option>
<option value="very_good">✓✓ Sehr gut (excellent, good)</option>
<option value="excellent">⭐ Exzellent (nur excellent)</option>
</select>
</div>
<div style={{padding:'10px 12px',background:'var(--surface2)',borderRadius:8,fontSize:11,
color:'var(--text3)',lineHeight:1.5}}>
<div style={{fontWeight:600,marginBottom:4,color:'var(--text2)'}}>Aktuell: {
{
'all': '📊 Alle Activities (kein Filter)',
'quality': '✓ Hochwertig (excellent, good, acceptable)',
'very_good': '✓✓ Sehr gut (excellent, good)',
'excellent': '⭐ Exzellent (nur excellent)'
}[activeProfile?.quality_filter_level || 'all']
}</div>
Diese Einstellung wirkt auf:
<ul style={{margin:'6px 0 0 20px',padding:0}}>
<li>Dashboard Charts</li>
<li>Verlauf & Auswertungen</li>
<li>Trainingstyp-Verteilung</li>
<li>KI-Analysen & Pipeline</li>
<li>Alle Statistiken</li>
</ul>
</div>
</div>
{saved && (
<div style={{position:'fixed',bottom:80,left:'50%',transform:'translateX(-50%)',
background:'var(--accent)',color:'white',padding:'8px 20px',borderRadius:20,
File diff suppressed because it is too large. Load diff
+136 -1
View File
@@ -15,7 +15,16 @@ function hdrs(extra={}) {
async function req(path, opts={}) {
const res = await fetch(BASE+path, {...opts, headers:hdrs(opts.headers||{})})
if (!res.ok) { const err=await res.text(); throw new Error(err) }
if (!res.ok) {
const err = await res.text()
// Try to parse JSON error with detail field
try {
const parsed = JSON.parse(err)
throw new Error(parsed.detail || err)
} catch {
throw new Error(err)
}
}
return res.json()
}
const json=(d)=>({method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(d)})
@@ -98,6 +107,7 @@ export const api = {
insightPipeline: () => req('/insights/pipeline',{method:'POST'}),
listInsights: () => req('/insights'),
latestInsights: () => req('/insights/latest'),
deleteInsight: (id) => req(`/insights/${id}`, {method:'DELETE'}),
exportZip: async () => {
const res = await fetch(`${BASE}/export/zip`, {headers: hdrs()})
if (!res.ok) throw new Error('Export failed')
@@ -205,6 +215,14 @@ export const api = {
adminDeleteTrainingType: (id) => req(`/admin/training-types/${id}`, {method:'DELETE'}),
getAbilitiesTaxonomy: () => req('/admin/training-types/taxonomy/abilities'),
// Admin: Training Type Profiles (Phase 2 #15)
getProfileStats: () => req('/admin/training-types/profiles/stats'),
getProfileTemplates: () => req('/admin/training-types/profiles/templates'),
getProfileTemplate: (key) => req(`/admin/training-types/profiles/templates/${key}`),
applyProfileTemplate: (id,templateKey) => req(`/admin/training-types/${id}/profile/apply-template`, json({template_key: templateKey})),
getTrainingParameters: () => req('/evaluation/parameters'),
batchEvaluateActivities: () => req('/evaluation/batch', {method:'POST'}),
// Admin: Activity Type Mappings (v9d Phase 1b - Learnable System)
adminListActivityMappings: (profileId, globalOnly) => req(`/admin/activity-mappings${profileId?'?profile_id='+profileId:''}${globalOnly?'?global_only=true':''}`),
adminGetActivityMapping: (id) => req(`/admin/activity-mappings/${id}`),
@@ -230,4 +248,121 @@ export const api = {
fd.append('file', file)
return req('/sleep/import/apple-health', {method:'POST', body:fd})
},
// Rest Days (v9d Phase 2a)
listRestDays: (l=90) => req(`/rest-days?limit=${l}`),
createRestDay: (d) => req('/rest-days', json(d)),
getRestDay: (id) => req(`/rest-days/${id}`),
updateRestDay: (id,d) => req(`/rest-days/${id}`, jput(d)),
deleteRestDay: (id) => req(`/rest-days/${id}`, {method:'DELETE'}),
getRestDaysStats: (weeks=4) => req(`/rest-days/stats?weeks=${weeks}`),
validateActivity: (date, activityType) => req('/rest-days/validate-activity', json({date, activity_type: activityType})),
// Vitals Baseline (v9d Phase 2d Refactored - once daily, morning)
listBaseline: (l=90) => req(`/vitals/baseline?limit=${l}`),
getBaselineByDate: (date) => req(`/vitals/baseline/by-date/${date}`),
createBaseline: (d) => req('/vitals/baseline', json(d)),
updateBaseline: (id,d) => req(`/vitals/baseline/${id}`, jput(d)),
deleteBaseline: (id) => req(`/vitals/baseline/${id}`, {method:'DELETE'}),
getBaselineStats: (days=30) => req(`/vitals/baseline/stats?days=${days}`),
importBaselineAppleHealth: (file) => {
const fd = new FormData()
fd.append('file', file)
return req('/vitals/baseline/import/apple-health', {method:'POST', body:fd})
},
// Blood Pressure (v9d Phase 2d Refactored - multiple daily, context-aware)
listBloodPressure: (l=90) => req(`/blood-pressure?limit=${l}`),
getBPByDate: (date) => req(`/blood-pressure/by-date/${date}`),
createBloodPressure:(d) => req('/blood-pressure', json(d)),
updateBloodPressure:(id,d) => req(`/blood-pressure/${id}`, jput(d)),
deleteBloodPressure:(id) => req(`/blood-pressure/${id}`, {method:'DELETE'}),
getBPStats: (days=30) => req(`/blood-pressure/stats?days=${days}`),
importBPOmron: (file) => {
const fd = new FormData()
fd.append('file', file)
return req('/blood-pressure/import/omron', {method:'POST', body:fd})
},
// AI Prompts Management (Issue #28)
listAdminPrompts: () => req('/prompts'),
createPrompt: (d) => req('/prompts', json(d)),
updatePrompt: (id,d) => req(`/prompts/${id}`, jput(d)),
deletePrompt: (id) => req(`/prompts/${id}`, {method:'DELETE'}),
duplicatePrompt: (id) => req(`/prompts/${id}/duplicate`, json({})),
reorderPrompts: (order) => req('/prompts/reorder', jput(order)),
previewPrompt: (tpl) => req('/prompts/preview', json({template:tpl})),
generatePrompt: (d) => req('/prompts/generate', json(d)),
optimizePrompt: (id) => req(`/prompts/${id}/optimize`, json({})),
listPlaceholders: () => req('/prompts/placeholders'),
resetPromptToDefault: (id) => req(`/prompts/${id}/reset-to-default`, json({})),
// Pipeline Configs Management (Issue #28 Phase 2)
listPipelineConfigs: () => req('/prompts/pipeline-configs'),
createPipelineConfig: (d) => req('/prompts/pipeline-configs', json(d)),
updatePipelineConfig: (id,d) => req(`/prompts/pipeline-configs/${id}`, jput(d)),
deletePipelineConfig: (id) => req(`/prompts/pipeline-configs/${id}`, {method:'DELETE'}),
setDefaultPipelineConfig: (id) => req(`/prompts/pipeline-configs/${id}/set-default`, json({})),
// Pipeline Execution (Issue #28 Phase 2)
executePipeline: (configId=null) => req('/insights/pipeline' + (configId ? `?config_id=${configId}` : ''), json({})),
// Unified Prompt System (Issue #28 Phase 2)
executeUnifiedPrompt: (slug, modules=null, timeframes=null, debug=false, save=false) => {
const params = new URLSearchParams({ prompt_slug: slug })
if (debug) params.append('debug', 'true')
if (save) params.append('save', 'true')
const body = {}
if (modules) body.modules = modules
if (timeframes) body.timeframes = timeframes
return req('/prompts/execute?' + params, json(body))
},
createUnifiedPrompt: (d) => req('/prompts/unified', json(d)),
updateUnifiedPrompt: (id,d) => req(`/prompts/unified/${id}`, jput(d)),
// Batch Import/Export
exportAllPrompts: () => req('/prompts/export-all'),
importPrompts: (data, overwrite=false) => {
const params = new URLSearchParams()
if (overwrite) params.append('overwrite', 'true')
return req(`/prompts/import?${params}`, json(data))
},
// Placeholder Export
exportPlaceholderValues: () => req('/prompts/placeholders/export-values'),
// v9e: Goals System (Strategic + Tactical)
getGoalMode: () => req('/goals/mode'),
updateGoalMode: (mode) => req('/goals/mode', jput({goal_mode: mode})),
// Focus Areas (v2.0)
getFocusAreas: () => req('/goals/focus-areas'),
updateFocusAreas: (d) => req('/goals/focus-areas', jput(d)),
listGoals: () => req('/goals/list'),
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)),
updateGoalType: (id,d) => req(`/goals/goal-types/${id}`, jput(d)),
deleteGoalType: (id) => req(`/goals/goal-types/${id}`, {method:'DELETE'}),
getSchemaInfo: () => req('/goals/schema-info'),
// Training Phases
listTrainingPhases: () => req('/goals/phases'),
createTrainingPhase: (d) => req('/goals/phases', json(d)),
updatePhaseStatus: (id,status) => req(`/goals/phases/${id}/status?status=${status}`, jput({})),
// Fitness Tests
listFitnessTests: () => req('/goals/tests'),
createFitnessTest: (d) => req('/goals/tests', json(d)),
}
+68
View File
@@ -0,0 +1,68 @@
#!/bin/bash
# API-Tests für Pipeline-System (Issue #28)
# Ausführen auf Server oder lokal: bash test-pipeline-api.sh
echo "═══════════════════════════════════════════════════════════"
echo "Pipeline-System API Tests"
echo "═══════════════════════════════════════════════════════════"
echo ""
# Configuration
API_URL="https://dev.mitai.jinkendo.de"
TOKEN="" # <-- Füge deinen Admin-Token hier ein
if [ -z "$TOKEN" ]; then
echo "❌ Bitte TOKEN in Zeile 11 eintragen (Admin-Token von dev.mitai.jinkendo.de)"
echo ""
echo "1. In Browser einloggen: https://dev.mitai.jinkendo.de"
echo "2. Developer Tools öffnen (F12)"
echo "3. Application/Storage → localStorage → auth_token kopieren"
exit 1
fi
echo "Test 1: GET /api/prompts/pipeline-configs"
echo "─────────────────────────────────────────────────────────"
curl -s "$API_URL/api/prompts/pipeline-configs" \
-H "X-Auth-Token: $TOKEN" | jq -r '.[] | "\(.name) (default: \(.is_default), active: \(.active))"'
echo ""
echo "Test 2: GET /api/prompts/pipeline-configs - Full JSON"
echo "─────────────────────────────────────────────────────────"
curl -s "$API_URL/api/prompts/pipeline-configs" \
-H "X-Auth-Token: $TOKEN" | jq '.[0] | {name, is_default, modules, stage1_prompts, stage2_prompt}'
echo ""
echo "Test 3: POST /api/insights/pipeline (default config)"
echo "─────────────────────────────────────────────────────────"
echo "Hinweis: Dies startet eine echte KI-Analyse (kann 30-60s dauern)"
read -p "Fortfahren? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
RESULT=$(curl -s -X POST "$API_URL/api/insights/pipeline" \
-H "X-Auth-Token: $TOKEN" \
-H "Content-Type: application/json")
echo "$RESULT" | jq '{
scope,
config: .config,
stage1_results: (.stage1 | keys),
content_length: (.content | length)
}'
echo ""
echo "Full content (first 500 chars):"
echo "$RESULT" | jq -r '.content' | head -c 500
echo "..."
else
echo "Übersprungen."
fi
echo ""
echo "Test 4: GET /api/prompts - Prüfe auf is_system_default"
echo "─────────────────────────────────────────────────────────"
curl -s "$API_URL/api/prompts" \
-H "X-Auth-Token: $TOKEN" | jq -r '.[] | select(.slug | startswith("pipeline_")) | "\(.slug): is_system_default=\(.is_system_default // false)"' | head -6
echo ""
echo "═══════════════════════════════════════════════════════════"
echo "API-Tests abgeschlossen!"
echo "═══════════════════════════════════════════════════════════"
+53
View File
@@ -0,0 +1,53 @@
#!/bin/bash
# Test-Script für Pipeline-System Backend (Issue #28)
# Ausführen auf Server: bash test-pipeline-backend.sh
echo "═══════════════════════════════════════════════════════════"
echo "Pipeline-System Backend Tests"
echo "═══════════════════════════════════════════════════════════"
echo ""
# Container Names (from docker-compose.dev-env.yml)
POSTGRES_CONTAINER="dev-mitai-postgres"
DB_USER="mitai_dev"
DB_NAME="mitai_dev"
echo "Test 1: Migration 019 ausgeführt"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
"SELECT version, applied_at FROM schema_migrations WHERE version = '019';"
echo ""
echo "Test 2: Tabelle pipeline_configs existiert"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
"\d pipeline_configs" | head -40
echo ""
echo "Test 3: Seed-Daten (3 Configs erwartet)"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
"SELECT name, is_default, active, stage2_prompt, stage3_prompt FROM pipeline_configs ORDER BY is_default DESC, name;"
echo ""
echo "Test 4: ai_prompts erweitert (is_system_default)"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
"SELECT slug, is_system_default, (default_template IS NOT NULL) as has_default FROM ai_prompts WHERE slug LIKE 'pipeline_%' ORDER BY slug;"
echo ""
echo "Test 5: stage1_prompts Array-Inhalte"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
"SELECT name, stage1_prompts FROM pipeline_configs WHERE name = 'Alltags-Check';"
echo ""
echo "Test 6: modules JSONB"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
"SELECT name, jsonb_pretty(modules) as modules FROM pipeline_configs WHERE name = 'Alltags-Check';"
echo ""
echo "═══════════════════════════════════════════════════════════"
echo "Alle DB-Tests abgeschlossen!"
echo "═══════════════════════════════════════════════════════════"
+74
View File
@@ -0,0 +1,74 @@
#!/bin/bash
# Test Migration 020: Unified Prompt System (Issue #28)
echo "═══════════════════════════════════════════════════════════"
echo "Migration 020: Unified Prompt System - Verification Tests"
echo "═══════════════════════════════════════════════════════════"
echo ""
POSTGRES_CONTAINER="dev-mitai-postgres"
DB_USER="mitai_dev"
DB_NAME="mitai_dev"
echo "Test 1: Migration 020 applied"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
"SELECT version, applied_at FROM schema_migrations WHERE version = '020';"
echo ""
echo "Test 2: New columns exist in ai_prompts"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
"SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = 'ai_prompts'
AND column_name IN ('type', 'stages', 'output_format', 'output_schema')
ORDER BY column_name;"
echo ""
echo "Test 3: Existing prompts migrated to pipeline type"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
"SELECT slug, type,
CASE WHEN stages IS NOT NULL THEN 'Has stages' ELSE 'No stages' END as stages_status,
output_format
FROM ai_prompts
WHERE slug LIKE 'pipeline_%'
LIMIT 5;"
echo ""
echo "Test 4: Pipeline configs migrated to ai_prompts"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
"SELECT slug, name, type,
jsonb_array_length(stages) as num_stages
FROM ai_prompts
WHERE slug LIKE 'pipeline_config_%';"
echo ""
echo "Test 5: Stages JSONB structure (sample)"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
"SELECT slug, jsonb_pretty(stages) as stages_structure
FROM ai_prompts
WHERE slug LIKE 'pipeline_config_%'
LIMIT 1;"
echo ""
echo "Test 6: Backup table created"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
"SELECT COUNT(*) as backup_count FROM pipeline_configs_backup_pre_020;"
echo ""
echo "Test 7: Indices created"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
"SELECT indexname FROM pg_indexes
WHERE tablename = 'ai_prompts'
AND indexname LIKE 'idx_ai_prompts_%';"
echo ""
echo "═══════════════════════════════════════════════════════════"
echo "Migration 020 Tests Complete!"
echo "═══════════════════════════════════════════════════════════"