Author SHA1 Message Date
LarsandClaude Opus 4.6 548d733048 refactor: move init_db() to db.py
Deploy Development / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Phase 1.1 - Database-Logik konsolidieren

ÄNDERUNGEN:
- init_db() von main.py nach db.py verschoben
- main.py importiert init_db von db
- startup_event() ruft db.init_db() auf
- Keine funktionalen Änderungen

DATEIEN:
- backend/db.py: +60 Zeilen (init_db Funktion)
- backend/main.py: -48 Zeilen (init_db entfernt, import hinzugefügt)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 09:49:46 +01:00
LarsandClaude Opus 4.6 6845397866 fix: Migration-Fehler - meas_id Spalte in ai_insights
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 12s
PROBLEM:
- Backend crasht beim Start auf Prod
- Migration schlägt fehl: column 'meas_id' does not exist
- SQLite ai_insights hat Legacy-Spalte meas_id
- PostgreSQL schema hat diese Spalte nicht mehr

FIX:
- COLUMN_WHITELIST für ai_insights hinzugefügt
- Nur erlaubte Spalten werden migriert:
  id, profile_id, scope, content, created
- meas_id wird beim Import gefiltert

DATEIEN:
- backend/migrate_to_postgres.py

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 08:39:36 +01:00
Lars 2df70b2a6b docker-compose.yml aktualisiert
Deploy Development / deploy (push) Successful in 53s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
2026-03-19 08:28:30 +01:00
LarsandClaude Opus 4.6 85f48907a4 fix: startup crash - init_db() jetzt mit Error-Handling
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
PROBLEM:
- Backend crasht beim Start auf Prod
- Login zeigt HTML statt JSON (Backend nicht erreichbar)
- Ursache: init_db() wirft Exception beim Startup

FIX:
1. startup_event() wrapped in try-except (non-fatal)
2. init_db() prüft ob ai_prompts Tabelle existiert
3. init_db() hat eigenen try-except
4. Bessere Fehlermeldungen in stdout

ERGEBNIS:
- Backend startet auch wenn init_db() fehlschlägt
- Pipeline-Prompt kann manuell angelegt werden falls nötig
- Login funktioniert wieder

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 08:26:09 +01:00
LarsandClaude Opus 4.6 c40b30737a feat: zentraler Schalter für Pipeline-Deaktivierung
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
VORHER:
- Pipeline-Deaktivierung war nicht sichtbar im UI
- Deaktivierung sollte über Sub-Prompts erfolgen (nicht intuitiv)

JETZT:
- Zentraler Toggle-Button direkt unter "Mehrstufige Pipeline"
- Button-Text: "Gesamte Pipeline aktivieren/deaktivieren"
- Visuelles Feedback: Warning-Box wird rot wenn deaktiviert

IMPLEMENTIERUNG:

Backend (main.py):
- Neuer "pipeline" Master-Prompt wird automatisch angelegt
- startup_event() ruft init_db() auf
- Prompt: slug='pipeline', sort_order=-10 (ganz oben)
- Template: 'PIPELINE_MASTER' (nur Steuerung, kein echtes Template)

Frontend (Analysis.jsx):
- Toggle-Button unter Sektionsüberschrift
- Prüft: prompts.find(p=>p.slug==='pipeline')?.active
- pipelineAvailable basiert auf diesem Prompt (nicht Sub-Prompts)
- Warning-Box wechselt Farbe + Text:
  * Aktiv: Orange + JSON-Hinweis
  * Inaktiv: Rot + "Pipeline deaktiviert"

VERHALTEN:
✅ Button im Prompts-Tab unter "Mehrstufige Pipeline"
✅ Klar sichtbar: "Gesamte Pipeline deaktivieren"
✅ Pipeline verschwindet von Analyse-Seite wenn deaktiviert
✅ Sub-Prompts bleiben unabhängig editierbar

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 07:56:36 +01:00
LarsandClaude Opus 4.6 961f905279 fix: drei kritische Bugs in KI-Analysen behoben
Deploy Development / deploy (push) Successful in 57s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 13s
PROBLEM 1: Deaktivierte Prompts auf Verlaufsseiten sichtbar
- Deaktivierte Analysen (z.B. "Komposition") wurden auf Verlaufsseiten
  (Körper, Ernährung, etc.) als klickbare Buttons angezeigt
FIX:
- Prompts werden jetzt in History.jsx geladen (api.listPrompts)
- filterActiveSlugs() filtert nur aktive Prompts
- InsightBox zeigt nur Buttons für aktive Analysen

PROBLEM 2: Pipeline konnte nicht deaktiviert werden
- Mehrstufige Gesamtanalyse war immer sichtbar
FIX:
- Pipeline ist nur verfügbar wenn ALLE Sub-Prompts aktiv sind
- Prüft: pipeline_body, pipeline_nutrition, pipeline_activity,
  pipeline_synthesis, pipeline_goals
- Deaktiviere einen Sub-Prompt → Pipeline verschwindet

PROBLEM 3: Fehler "z.text is not a function"
- Nach Analyse-Ausführung auf Verlaufsseiten kam Fehler
- Code behandelte api.runInsight() wie fetch()-Response
FIX:
- api.runInsight() gibt bereits JSON zurück, nicht Response
- Entfernte fehlerhafte if(!r.ok) und await r.text()
- Error-Handling wie in Analysis.jsx (catch e.message)

DATEIEN:
- frontend/src/pages/History.jsx: alle 3 Fixes
- frontend/src/pages/Analysis.jsx: Pipeline-Verfügbarkeit

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 07:47:59 +01:00
LarsandClaude Opus 4.6 3f4ef75463 fix: Prompt-Deaktivierung jetzt voll funktionsfähig
Deploy Development / deploy (push) Successful in 57s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
PROBLEME behoben:
1. Falscher Datentyp: Frontend sendete 0/1 statt boolean
2. Button-Text: "Aktiv." → "Aktivieren"
3. Keine visuelle Markierung für deaktivierte Prompts

FIXES:

Backend (main.py):
- active-Wert wird explizit zu boolean konvertiert
- Akzeptiert jetzt sowohl true/false als auch 1/0

Frontend (Analysis.jsx):
- Sendet jetzt !p.active (boolean) statt p.active?0:1
- Button-Text: "Deaktivieren" / "Aktivieren" (klar lesbar)
- Visuelle Markierung für inaktive Prompts:
  * Opacity 0.6 (ausgegraut)
  * Rotes Badge "⏸ Deaktiviert"
- Gilt für Einzel- UND Pipeline-Prompts

RESULTAT:
✅ Deaktivierte Prompts werden nicht mehr auf "Analysen starten" gezeigt
✅ Klare visuelle Unterscheidung im Prompts-Tab
✅ Button-Text eindeutig ("Aktivieren" vs "Deaktivieren")

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 07:27:56 +01:00
LarsandClaude Opus 4.6 4886f00826 fix: Auth-Token für Prompt-Bearbeitung fehlte
Deploy Development / deploy (push) Successful in 53s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
KRITISCHER BUG behoben:
- savePrompt() und Aktivieren/Deaktivieren sendeten KEIN Auth-Token
- Backend require_admin() warf deshalb 401 Unauthorized
- Prompt-Bearbeitung funktionierte überhaupt nicht (auch für Admins)

Fix:
- X-Auth-Token Header zu beiden fetch()-Calls hinzugefügt
- Token aus localStorage wie in anderen Admin-Funktionen

Rechtesystem BESTÄTIGT korrekt:
✅ Backend: nur require_admin() darf Prompts ändern
✅ DB: ai_prompts hat KEINE profile_id → universell
✅ Frontend: Tab "Prompts" nur für isAdmin sichtbar

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 06:36:37 +01:00
LarsandClaude Opus 4.6 518e417b1d fix: admins können jetzt alle Prompts sehen und bearbeiten
Deploy Development / deploy (push) Successful in 57s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- /api/prompts checkt nun ob User admin ist
- Admins sehen ALLE Prompts (inkl. pipeline_ und inaktive)
- Normale User sehen nur aktive Einzelanalysen (wie bisher)
- Frontend (Analysis.jsx) zeigt Pipeline-Prompts bereits korrekt:
  * Gruppiert nach "Einzelanalysen" und "Mehrstufige Pipeline"
  * JSON-Prompts (Stage 1) mit oranger Border und Badge
  * Warnung über JSON-Format bereits vorhanden
- CSS-Variablen --warn, --warn-bg, --warn-text bereits definiert

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 06:28:48 +01:00
LarsandClaude Opus 4.6 115d975335 feat: add ZIP import functionality
Deploy Development / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 11s
- Backend: POST /api/import/zip endpoint with validation and rollback
- CSV import with ON CONFLICT DO NOTHING for duplicate detection
- Photo import with existence check
- AI insights import
- Frontend: file upload UI in SettingsPage
- Import summary showing count per category
- Full transaction rollback on error

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 22:52:35 +01:00
LarsandClaude Opus 4.6 e10e9d7eb9 fix: photos now display in History with token auth
Deploy Development / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Problem: Photo endpoint requires auth header, but <img src> can't send headers.

Solution:
- Backend: Added require_auth_flexible() that accepts token via header OR query param
- Backend: Photo endpoint uses flexible auth
- Frontend: photoUrl() now appends ?token=xxx to URL

Photos in History/Verlauf now display correctly.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 22:48:40 +01:00
LarsandClaude Opus 4.6 b6f8b11685 fix: handle datetime.date object for birth_year in ZIP export
Deploy Development / deploy (push) Successful in 58s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
PostgreSQL returns dob as datetime.date object, not string.
Changed from prof['dob'][:4] to prof['dob'].year

Error was: TypeError: 'datetime.date' object is not subscriptable

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 22:41:51 +01:00
LarsandClaude Opus 4.6 64d1b9bf7b feat: implement comprehensive ZIP export per v9c specification
Deploy Development / deploy (push) Successful in 1m15s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Complete rewrite of ZIP export to match CLAUDE.md specification.

**Structure:**
- README.txt (format explanation)
- profile.json (no password hash, includes stats)
- data/*.csv (5 separate CSV files)
- insights/ai_insights.json
- photos/*.jpg

**CSV Format:**
- Delimiter: semicolon (;)
- Encoding: UTF-8 with BOM (Excel compatible)
- Date format: YYYY-MM-DD
- Decimal separator: dot (.)
- NULL values: empty string
- First row: header

**Files:**
- data/weight.csv (id, date, weight, note, source, created)
- data/circumferences.csv (8 measurement points)
- data/caliper.csv (skinfold measurements + bf%)
- data/nutrition.csv (kcal, protein, fat, carbs)
- data/activity.csv (type, duration, kcal, HR, distance)

**Filename:** mitai-export-{name}-{YYYY-MM-DD}.zip

Ready for import functionality (v9c).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 22:15:31 +01:00
LarsandClaude Opus 4.6 a0660e7a40 fix: use api.exportZip/Json instead of window.open
Deploy Development / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
SettingsPage was still calling window.open() directly,
bypassing the auth-enabled fetch methods in api.js.

Changed buttons to use api.exportZip() and api.exportJson()
which properly include authentication headers.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 22:04:42 +01:00
LarsandClaude Opus 4.6 0797a8f55c fix: export endpoints now include auth headers
Deploy Development / deploy (push) Successful in 58s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Changed from window.open() to fetch() + Blob download.
window.open() cannot send custom headers, causing 401 errors.

**Changed:**
- exportZip: fetch with auth, download blob as .zip
- exportJson: fetch with auth, download blob as .json
- exportCsv: fetch with auth, download blob as .csv

All exports now work with authenticated sessions.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 22:00:35 +01:00
LarsandClaude Opus 4.6 47a268f426 fix: comprehensive PostgreSQL Decimal handling across all endpoints
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Fixed all remaining Decimal → float conversion issues found by audit.

**Fixed Endpoints:**
1. Weight Stats: min/max/avg calculations
2. Activity Stats: kcal/duration accumulation
3. Nutrition Weekly: average calculations
4. Template Variables: all f-string Decimal formatting
5. CSV Export: all numeric value formatting
6. JSON Export: added Decimal handler
7. ZIP Export: added Decimal handler
8. Correlations: weight, nutrition, caliper values

**Changes:**
- Added `from decimal import Decimal` import
- Weight stats: convert to float for min/max/avg
- Activity: float() in sum() and accumulation
- Nutrition: float() in averages
- Template vars: float() for weight_aktuell, kf_aktuell, goals
- CSV: float() in all f-strings (weight, circ, caliper, nutrition, activity)
- JSON/ZIP: custom decimal_handler for json.dumps()
- Correlations: float() for all numeric DB values

Prevents:
- TypeError in math operations
- "Decimal('X')" strings in exports
- JSON serialization failures

All numeric values from PostgreSQL now properly converted to float.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 21:52:57 +01:00
LarsandClaude Opus 4.6 f7f7f745b1 fix: convert PostgreSQL Decimal to float for math operations
Deploy Development / deploy (push) Successful in 59s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Fixed TypeError when preparing AI prompt template variables.
PostgreSQL returns NUMERIC columns as decimal.Decimal, not float.

**Fixed in _prepare_template_vars:**
- Weight calculations (protein targets, delta)
- Nutrition averages (kcal, protein, fat, carbs)
- Activity totals (kcal_active)

All Decimal values now converted to float before math operations.

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

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 21:44:10 +01:00
LarsandClaude Opus 4.6 8e25b54cc2 docs: update CLAUDE.md for v9b release
Deploy Development / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Updated documentation to reflect v9b (PostgreSQL) release:

**Version Update:**
- v9a → v9b (PostgreSQL Migration complete)
- Tech Stack: SQLite → PostgreSQL 16 (Alpine)
- 60+ protected endpoints (was 44)

**New Features Documented:**
- ✅ PostgreSQL migration (auto-migrate from SQLite)
- ✅ Export: CSV, JSON, ZIP (with photos)
- ✅ Admin: Edit prompts, set email/PIN
- ✅ All API endpoints aligned (11 fixes)

**Environment Variables:**
- Added DB_* variables (PostgreSQL connection)
- Added ANTHROPIC_API_KEY (alternative to OpenRouter)

**Important Hints:**
- Updated: PostgreSQL migrations instead of SQLite safe_alters
- Added: RealDictCursor usage for dict-like row access
- Added: PostgreSQL boolean syntax (true/false not 1/0)

**New Section: v9b Migration – Lessons Learned**
- Docker build optimization (removed apt-get)
- Empty date string handling
- Boolean field conversion
- API endpoint consistency audit

**Roadmap Adjustment:**
- v9c: Tier System (was in v9b)
- v9d: OAuth2 Connectors (was in v9c)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 21:39:14 +01:00
LarsandClaude Opus 4.6 1db780858b fix: align all API endpoints between frontend and backend
Fixed 11 critical endpoint mismatches found during codebase audit.

**Renamed Endpoints (consistency):**
- /api/ai/analyze/{slug} → /api/insights/run/{slug}
- /api/ai/analyze-pipeline → /api/insights/pipeline
- /api/auth/password-reset-request → /api/auth/forgot-password
- /api/auth/password-reset-confirm → /api/auth/reset-password
- /api/admin/test-email → /api/admin/email/test

**Added Missing Endpoints:**
- POST /api/auth/pin (change PIN/password for current user)
- PUT /api/admin/profiles/{id}/permissions (set permissions)
- PUT /api/admin/profiles/{id}/email (set email)
- PUT /api/admin/profiles/{id}/pin (admin set PIN)
- GET /api/admin/email/status (check SMTP config)
- PUT /api/prompts/{id} (edit prompt templates, admin only)
- GET /api/export/json (export all data as JSON)
- GET /api/export/zip (export data + photos as ZIP)

**Updated:**
- Added imports: json, zipfile, Response
- Fixed admin email test endpoint to accept dict body

All frontend API calls now have matching backend implementations.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 17:07:41 +01:00
9 changed files with 1213 additions and 105 deletions

No files matched your search

+221 -18
View File
@@ -10,7 +10,7 @@
|-----------|-------------|---------| |-----------|-------------|---------|
| Frontend | React 18 + Vite + PWA | Node 20 | | Frontend | React 18 + Vite + PWA | Node 20 |
| Backend | FastAPI (Python) | Python 3.12 | | Backend | FastAPI (Python) | Python 3.12 |
| Datenbank | SQLite (v9a) → PostgreSQL (v9b geplant) | - | | Datenbank | PostgreSQL 16 (Alpine) | v9b |
| Container | Docker + Docker Compose | - | | Container | Docker + Docker Compose | - |
| Webserver | nginx (Reverse Proxy) | Alpine | | Webserver | nginx (Reverse Proxy) | Alpine |
| Auth | Token-basiert + bcrypt | - | | Auth | Token-basiert + bcrypt | - |
@@ -53,36 +53,38 @@ mitai-jinkendo/
└── CLAUDE.md # Diese Datei └── CLAUDE.md # Diese Datei
``` ```
## Aktuelle Version: v9a ## Aktuelle Version: v9b
### Was implementiert ist: ### Was implementiert ist:
- ✅ Multi-User mit E-Mail + Passwort Login (bcrypt) - ✅ Multi-User mit E-Mail + Passwort Login (bcrypt)
- ✅ Auth-Middleware auf ALLE Endpoints (44 Endpoints geschützt) - ✅ Auth-Middleware auf ALLE Endpoints (60+ Endpoints geschützt)
- ✅ Rate Limiting (Login: 5/min, Reset: 3/min) - ✅ Rate Limiting (Login: 5/min, Reset: 3/min)
- ✅ CORS konfigurierbar via ALLOWED_ORIGINS in .env - ✅ CORS konfigurierbar via ALLOWED_ORIGINS in .env
- ✅ Admin/User Rollen, KI-Limits, Export-Berechtigungen - ✅ Admin/User Rollen, KI-Limits, Export-Berechtigungen
- ✅ Gewicht, Umfänge, Caliper (4 Formeln), Ernährung, Aktivität - ✅ Gewicht, Umfänge, Caliper (4 Formeln), Ernährung, Aktivität
- ✅ FDDB CSV-Import (Ernährung), Apple Health CSV-Import (Aktivität) - ✅ FDDB CSV-Import (Ernährung), Apple Health CSV-Import (Aktivität)
- ✅ KI-Analyse: 6 Einzel-Prompts + 3-stufige Pipeline (parallel) - ✅ KI-Analyse: 6 Einzel-Prompts + 3-stufige Pipeline (parallel)
- ✅ Konfigurierbare Prompts mit Template-Variablen - ✅ Konfigurierbare Prompts mit Template-Variablen (Admin kann bearbeiten)
- ✅ Verlauf mit 5 Tabs + Zeitraumfilter + KI pro Sektion - ✅ Verlauf mit 5 Tabs + Zeitraumfilter + KI pro Sektion
- ✅ Dashboard mit Kennzahlen, Zielfortschritt, Combo-Chart - ✅ Dashboard mit Kennzahlen, Zielfortschritt, Combo-Chart
- ✅ Assistent-Modus (Schritt-für-Schritt Messung) - ✅ Assistent-Modus (Schritt-für-Schritt Messung)
- ✅ PWA (iPhone Home Screen), Jinkendo Ensō-Logo - ✅ PWA (iPhone Home Screen), Jinkendo Ensō-Logo
- ✅ E-Mail (SMTP) für Password-Recovery - ✅ E-Mail (SMTP) für Password-Recovery
- ✅ Admin-Panel: User verwalten, KI-Limits, E-Mail-Test - ✅ Admin-Panel: User verwalten, KI-Limits, E-Mail-Test, PIN/Email setzen
- ✅ Multi-Environment: Prod (mitai.jinkendo.de) + Dev (dev.mitai.jinkendo.de) - ✅ Multi-Environment: Prod (mitai.jinkendo.de) + Dev (dev.mitai.jinkendo.de)
- ✅ Gitea CI/CD mit Auto-Deploy auf Raspberry Pi 5 - ✅ Gitea CI/CD mit Auto-Deploy auf Raspberry Pi 5
- ✅ PostgreSQL 16 Migration (vollständig von SQLite migriert)
- ✅ Export: CSV, JSON, ZIP (mit Fotos)
- ✅ Automatische SQLite→PostgreSQL Migration bei Container-Start
### Was in v9b kommt: ### Was in v9c kommt:
- 🔲 PostgreSQL Migration (aktuell noch SQLite)
- 🔲 Selbst-Registrierung mit E-Mail-Bestätigung - 🔲 Selbst-Registrierung mit E-Mail-Bestätigung
- 🔲 Freemium Tier-System (free/basic/premium/selfhosted) - 🔲 Freemium Tier-System (free/basic/premium/selfhosted)
- 🔲 14-Tage Trial automatisch - 🔲 14-Tage Trial automatisch
- 🔲 Einladungslinks für Beta-Nutzer - 🔲 Einladungslinks für Beta-Nutzer
- 🔲 Admin kann Tiers manuell setzen - 🔲 Admin kann Tiers manuell setzen
### Was in v9c kommt: ### Was in v9d kommt:
- 🔲 OAuth2-Grundgerüst für Fitness-Connectoren - 🔲 OAuth2-Grundgerüst für Fitness-Connectoren
- 🔲 Strava Connector - 🔲 Strava Connector
- 🔲 Withings Connector (Waage) - 🔲 Withings Connector (Waage)
@@ -116,20 +118,24 @@ docker compose -f docker-compose.dev-env.yml build --no-cache
docker compose -f docker-compose.dev-env.yml up -d docker compose -f docker-compose.dev-env.yml up -d
``` ```
## Datenbank-Schema (SQLite, v9a) ## Datenbank-Schema (PostgreSQL 16, v9b)
### Wichtige Tabellen: ### Wichtige Tabellen:
- `profiles` – Nutzer (role, pin_hash/bcrypt, email, auth_type, ai_enabled) - `profiles` – Nutzer (role, pin_hash/bcrypt, email, auth_type, ai_enabled, tier)
- `sessions` – Auth-Tokens mit Ablaufdatum - `sessions` – Auth-Tokens mit Ablaufdatum
- `weight_log` – Gewichtseinträge (profile_id, date, weight) - `weight_log` – Gewichtseinträge (profile_id, date, weight)
- `circumference_log` – 8 Umfangspunkte - `circumference_log` – 8 Umfangspunkte
- `caliper_log` – Hautfaltenmessung, 4 Methoden - `caliper_log` – Hautfaltenmessung, 4 Methoden
- `nutrition_log` – Kalorien + Makros (aus FDDB-CSV) - `nutrition_log` – Kalorien + Makros (aus FDDB-CSV)
- `activity_log` – Training (aus Apple Health oder manuell) - `activity_log` – Training (aus Apple Health oder manuell)
- `photos` – Progress Photos
- `ai_insights` – KI-Auswertungen (scope = prompt-slug) - `ai_insights` – KI-Auswertungen (scope = prompt-slug)
- `ai_prompts` – Konfigurierbare Prompts mit Templates (11 Prompts) - `ai_prompts` – Konfigurierbare Prompts mit Templates (11 Prompts)
- `ai_usage` – KI-Calls pro Tag pro Profil - `ai_usage` – KI-Calls pro Tag pro Profil
## Auth-Flow (v9a) **Schema-Datei:** `backend/schema.sql` (vollständiges PostgreSQL-Schema)
**Migration-Script:** `backend/migrate_to_postgres.py` (SQLite→PostgreSQL, automatisch)
## Auth-Flow (v9b)
``` ```
Login-Screen → E-Mail + Passwort → Token im localStorage Login-Screen → E-Mail + Passwort → Token im localStorage
Token → X-Auth-Token Header → Backend require_auth() Token → X-Auth-Token Header → Backend require_auth()
@@ -146,29 +152,44 @@ SHA256 Passwörter → automatisch zu bcrypt migriert beim Login
## Umgebungsvariablen (.env) ## Umgebungsvariablen (.env)
``` ```
OPENROUTER_API_KEY= # KI-Calls # Database (PostgreSQL)
DB_HOST=postgres
DB_PORT=5432
DB_NAME=mitai_prod
DB_USER=mitai_prod
DB_PASSWORD= # REQUIRED
# AI
OPENROUTER_API_KEY= # KI-Calls (optional, alternativ ANTHROPIC_API_KEY)
OPENROUTER_MODEL=anthropic/claude-sonnet-4 OPENROUTER_MODEL=anthropic/claude-sonnet-4
SMTP_HOST= # E-Mail ANTHROPIC_API_KEY= # Direkte Anthropic API (optional)
# Email
SMTP_HOST= # E-Mail (für Recovery)
SMTP_PORT=587 SMTP_PORT=587
SMTP_USER= SMTP_USER=
SMTP_PASS= SMTP_PASS=
SMTP_FROM= SMTP_FROM=
# App
APP_URL=https://mitai.jinkendo.de APP_URL=https://mitai.jinkendo.de
ALLOWED_ORIGINS=https://mitai.jinkendo.de ALLOWED_ORIGINS=https://mitai.jinkendo.de
DATA_DIR=/app/data DATA_DIR=/app/data
PHOTOS_DIR=/app/photos PHOTOS_DIR=/app/photos
ENVIRONMENT=production
``` ```
## Wichtige Hinweise für Claude Code ## Wichtige Hinweise für Claude Code
1. **Ports immer 3002/8002 (Prod) oder 3099/8099 (Dev)** – nie ändern 1. **Ports immer 3002/8002 (Prod) oder 3099/8099 (Dev)** – nie ändern
2. **npm install** (nicht npm ci) – kein package-lock.json vorhanden 2. **npm install** (nicht npm ci) – kein package-lock.json vorhanden
3. **SQLite safe_alters** – neue Spalten immer via safe_alters Liste 3. **PostgreSQL-Migrations** – Schema-Änderungen in `backend/schema.sql`, dann Container neu bauen
4. **Pipeline-Prompts** haben slug-Prefix `pipeline_` – nie als Einzelanalyse zeigen 4. **Pipeline-Prompts** haben slug-Prefix `pipeline_` – nie als Einzelanalyse zeigen
5. **dayjs.week()** braucht Plugin – stattdessen native JS ISO-Wochenberechnung 5. **dayjs.week()** braucht Plugin – stattdessen native JS ISO-Wochenberechnung
6. **useNavigate()** nur in React-Komponenten, nicht in Helper-Functions 6. **useNavigate()** nur in React-Komponenten, nicht in Helper-Functions
7. **api.js nutzen** für alle API-Calls – injiziert Token automatisch 7. **api.js nutzen** für alle API-Calls – injiziert Token automatisch
8. **bcrypt** für alle neuen Passwort-Operationen verwenden 8. **bcrypt** für alle neuen Passwort-Operationen verwenden
9. **session=Depends(require_auth)** als separater Parameter – nie in Header() einbetten 9. **session=Depends(require_auth)** als separater Parameter – nie in Header() einbetten
10. **RealDictCursor verwenden** – `get_cursor(conn)` statt `conn.cursor()` für dict-like row access
## Code-Style ## Code-Style
- React: Functional Components, Hooks - React: Functional Components, Hooks
@@ -437,10 +458,192 @@ def endpoint(x_profile_id: Optional[str] = Header(default=None),
<Bar fill="#1D9E75"/> <Bar fill="#1D9E75"/>
``` ```
### SQLite neue Spalten hinzufügen ### PostgreSQL Boolean-Syntax
```python ```python
# In _safe_alters Liste hinzufügen (NICHT direkt ALTER TABLE): # ❌ Falsch (SQLite-Syntax):
_safe_alters = [ cur.execute("SELECT * FROM ai_prompts WHERE active=1")
("profiles", "neue_spalte TEXT DEFAULT NULL"),
# ✅ Richtig (PostgreSQL):
cur.execute("SELECT * FROM ai_prompts WHERE active=true")
```
### RealDictCursor für dict-like row access
```python
# ❌ Falsch:
cur = conn.cursor()
cur.execute("SELECT COUNT(*) FROM weight_log")
count = cur.fetchone()[0] # Tuple index
# ✅ Richtig:
cur = get_cursor(conn) # Returns RealDictCursor
cur.execute("SELECT COUNT(*) as count FROM weight_log")
count = cur.fetchone()['count'] # Dict key
```
## v9b Migration – Lessons Learned
### PostgreSQL Migration (SQLite → PostgreSQL)
**Problem:** Docker Build hing 30+ Minuten bei `apt-get install postgresql-client`
**Lösung:** Alle apt-get dependencies entfernt, reine Python-Lösung mit psycopg2-binary
**Problem:** Leere date-Strings (`''`) führten zu PostgreSQL-Fehlern
**Lösung:** Migration-Script konvertiert leere Strings zu NULL für DATE-Spalten
**Problem:** Boolean-Felder (SQLite INTEGER 0/1 vs PostgreSQL BOOLEAN)
**Lösung:** Migration konvertiert automatisch, Backend nutzt `active=true` statt `active=1`
### API Endpoint Consistency (März 2026)
**Problem:** 11 kritische Endpoint-Mismatches zwischen Frontend und Backend gefunden
**Gelöst:**
- AI-Endpoints konsistent: `/api/insights/run/{slug}`, `/api/insights/pipeline`
- Password-Reset: `/api/auth/forgot-password`, `/api/auth/reset-password`
- Admin-Endpoints: `/permissions`, `/email`, `/pin` Sub-Routes
- Export: JSON + ZIP Endpoints hinzugefügt
- Prompt-Bearbeitung: PUT-Endpoint für Admins
**Tool:** Vollständiger Audit via Explore-Agent empfohlen bei größeren Änderungen
## Export/Import Spezifikation (v9c)
### ZIP-Export Struktur
```
mitai-export-{name}-{YYYY-MM-DD}.zip
├── README.txt ← Erklärung des Formats + Versionsnummer
├── profile.json ← Profildaten (ohne Passwort-Hash)
├── data/
│ ├── weight.csv ← Gewichtsverlauf
│ ├── circumferences.csv ← Umfänge (8 Messpunkte)
│ ├── caliper.csv ← Caliper-Messungen
│ ├── nutrition.csv ← Ernährungsdaten
│ └── activity.csv ← Aktivitäten
├── insights/
│ └── ai_insights.json ← KI-Auswertungen (alle gespeicherten)
└── photos/
├── {date}_{id}.jpg ← Progress-Fotos
└── ...
```
### CSV Format (alle Dateien)
```
- Trennzeichen: Semikolon (;) – Excel/LibreOffice kompatibel
- Encoding: UTF-8 mit BOM (für Windows Excel)
- Datumsformat: YYYY-MM-DD
- Dezimaltrennzeichen: Punkt (.)
- Erste Zeile: Header
- Nullwerte: leer (nicht "null" oder "NULL")
```
### weight.csv Spalten
```
id;date;weight;note;source;created
```
### circumferences.csv Spalten
```
id;date;waist;hip;chest;neck;upper_arm;thigh;calf;forearm;note;created
```
### caliper.csv Spalten
```
id;date;chest;abdomen;thigh;tricep;subscapular;suprailiac;midaxillary;method;bf_percent;note;created
```
### nutrition.csv Spalten
```
id;date;meal_name;kcal;protein;fat;carbs;fiber;note;source;created
```
### activity.csv Spalten
```
id;date;name;type;duration_min;kcal;heart_rate_avg;heart_rate_max;distance_km;note;source;created
```
### profile.json Struktur
```json
{
"export_version": "2",
"export_date": "2026-03-18",
"app": "Mitai Jinkendo",
"profile": {
"name": "Lars",
"email": "lars@stommer.com",
"sex": "m",
"height": 178,
"birth_year": 1980,
"goal_weight": 82,
"goal_bf_pct": 14,
"avatar_color": "#1D9E75",
"auth_type": "password",
"session_days": 30,
"ai_enabled": true,
"tier": "selfhosted"
},
"stats": {
"weight_entries": 150,
"nutrition_entries": 300,
"activity_entries": 45,
"photos": 12
}
}
```
### ai_insights.json Struktur
```json
[
{
"id": "uuid",
"scope": "gesamt",
"created": "2026-03-18T10:00:00",
"result": "KI-Analyse Text..."
}
] ]
``` ```
### README.txt Inhalt
```
Mitai Jinkendo – Datenexport
Version: 2
Exportiert am: YYYY-MM-DD
Profil: {name}
Inhalt:
- profile.json: Profildaten und Einstellungen
- data/*.csv: Messdaten (Semikolon-getrennt, UTF-8)
- insights/: KI-Auswertungen (JSON)
- photos/: Progress-Fotos (JPEG)
Import:
Dieser Export kann in Mitai Jinkendo unter
Einstellungen → Import → "Mitai Backup importieren"
wieder eingespielt werden.
Format-Version 2 (ab v9b):
Alle CSV-Dateien sind UTF-8 mit BOM kodiert.
Trennzeichen: Semikolon (;)
Datumsformat: YYYY-MM-DD
```
### Import-Funktion (zu implementieren)
**Endpoint:** `POST /api/import/zip`
**Verhalten:**
- Akzeptiert ZIP-Datei (multipart/form-data)
- Erkennt export_version aus profile.json
- Importiert nur fehlende Einträge (kein Duplikat)
- Fotos werden nicht überschrieben falls bereits vorhanden
- Gibt Zusammenfassung zurück: wie viele Einträge je Kategorie importiert
- Bei Fehler: vollständiger Rollback (alle oder nichts)
**Duplikat-Erkennung:**
```python
# INSERT ... ON CONFLICT (profile_id, date) DO NOTHING
# weight: UNIQUE (profile_id, date)
# nutrition: UNIQUE (profile_id, date, meal_name)
# activity: UNIQUE (profile_id, date, name)
# caliper: UNIQUE (profile_id, date)
# circumferences: UNIQUE (profile_id, date)
```
**Frontend:** Neuer Button in SettingsPage:
```
[ZIP exportieren] [JSON exportieren] [Backup importieren]
```
+45
View File
@@ -148,3 +148,48 @@ def execute_write(conn, query: str, params: tuple = ()) -> None:
""" """
with get_cursor(conn) as cur: with get_cursor(conn) as cur:
cur.execute(query, params) cur.execute(query, params)
def init_db():
"""
Initialize database with required data.
Ensures critical data exists (e.g., pipeline master prompt).
Safe to call multiple times - checks before inserting.
Called automatically on app startup.
"""
try:
with get_db() as conn:
cur = get_cursor(conn)
# Check if table exists first
cur.execute("""
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'ai_prompts'
) as table_exists
""")
if not cur.fetchone()['table_exists']:
print("⚠️ ai_prompts table doesn't exist yet - skipping pipeline prompt creation")
return
# Ensure "pipeline" master prompt exists
cur.execute("SELECT COUNT(*) as count FROM ai_prompts WHERE slug='pipeline'")
if cur.fetchone()['count'] == 0:
cur.execute("""
INSERT INTO ai_prompts (slug, name, description, template, active, sort_order)
VALUES (
'pipeline',
'Mehrstufige Gesamtanalyse',
'Master-Schalter für die gesamte Pipeline. Deaktiviere diese Analyse, um die Pipeline komplett zu verstecken.',
'PIPELINE_MASTER',
true,
-10
)
""")
conn.commit()
print("✓ Pipeline master prompt created")
except Exception as e:
print(f"⚠️ Could not create pipeline prompt: {e}")
# Don't fail startup - prompt can be created manually
+682 -47
View File
@@ -1,11 +1,12 @@
import os, csv, io, uuid import os, csv, io, uuid, json, zipfile
from pathlib import Path from pathlib import Path
from typing import Optional from typing import Optional
from datetime import datetime from datetime import datetime
from decimal import Decimal
from fastapi import FastAPI, HTTPException, UploadFile, File, Header, Query, Depends from fastapi import FastAPI, HTTPException, UploadFile, File, Header, Query, Depends
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, FileResponse from fastapi.responses import StreamingResponse, FileResponse, Response
from pydantic import BaseModel from pydantic import BaseModel
import aiofiles import aiofiles
import bcrypt import bcrypt
@@ -14,7 +15,7 @@ from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded from slowapi.errors import RateLimitExceeded
from starlette.requests import Request from starlette.requests import Request
from db import get_db, get_cursor, r2d from db import get_db, get_cursor, r2d, init_db
DATA_DIR = Path(os.getenv("DATA_DIR", "./data")) DATA_DIR = Path(os.getenv("DATA_DIR", "./data"))
PHOTOS_DIR = Path(os.getenv("PHOTOS_DIR", "./photos")) PHOTOS_DIR = Path(os.getenv("PHOTOS_DIR", "./photos"))
@@ -39,11 +40,14 @@ app.add_middleware(
AVATAR_COLORS = ['#1D9E75','#378ADD','#D85A30','#EF9F27','#7F77DD','#D4537E','#639922','#888780'] AVATAR_COLORS = ['#1D9E75','#378ADD','#D85A30','#EF9F27','#7F77DD','#D4537E','#639922','#888780']
def init_db(): @app.on_event("startup")
"""Initialize database - Schema is loaded by startup.sh""" async def startup_event():
# Schema loading and migration handled by startup.sh """Run migrations and initialization on startup."""
# This function kept for backwards compatibility try:
pass init_db()
except Exception as e:
print(f"⚠️ init_db() failed (non-fatal): {e}")
# Don't crash on startup - pipeline prompt can be created manually
# ── Helper: get profile_id from header ─────────────────────────────────────── # ── Helper: get profile_id from header ───────────────────────────────────────
def get_pid(x_profile_id: Optional[str] = Header(default=None)) -> str: def get_pid(x_profile_id: Optional[str] = Header(default=None)) -> str:
@@ -148,6 +152,12 @@ def require_auth(x_auth_token: Optional[str]=Header(default=None)):
if not session: raise HTTPException(401, "Nicht eingeloggt") if not session: raise HTTPException(401, "Nicht eingeloggt")
return session return session
def require_auth_flexible(x_auth_token: Optional[str]=Header(default=None), token: Optional[str]=Query(default=None)):
"""Auth via header OR query parameter (for <img> tags)."""
session = get_session(x_auth_token or token)
if not session: raise HTTPException(401, "Nicht eingeloggt")
return session
def require_admin(x_auth_token: Optional[str]=Header(default=None)): def require_admin(x_auth_token: Optional[str]=Header(default=None)):
session = get_session(x_auth_token) session = get_session(x_auth_token)
if not session: raise HTTPException(401, "Nicht eingeloggt") if not session: raise HTTPException(401, "Nicht eingeloggt")
@@ -268,9 +278,9 @@ def weight_stats(x_profile_id: Optional[str]=Header(default=None), session: dict
cur.execute("SELECT date,weight FROM weight_log WHERE profile_id=%s ORDER BY date DESC LIMIT 90", (pid,)) cur.execute("SELECT date,weight FROM weight_log WHERE profile_id=%s ORDER BY date DESC LIMIT 90", (pid,))
rows = cur.fetchall() rows = cur.fetchall()
if not rows: return {"count":0,"latest":None,"prev":None,"min":None,"max":None,"avg_7d":None} if not rows: return {"count":0,"latest":None,"prev":None,"min":None,"max":None,"avg_7d":None}
w=[r['weight'] for r in rows] w=[float(r['weight']) for r in rows]
return {"count":len(rows),"latest":{"date":rows[0]['date'],"weight":rows[0]['weight']}, return {"count":len(rows),"latest":{"date":rows[0]['date'],"weight":float(rows[0]['weight'])},
"prev":{"date":rows[1]['date'],"weight":rows[1]['weight']} if len(rows)>1 else None, "prev":{"date":rows[1]['date'],"weight":float(rows[1]['weight'])} if len(rows)>1 else None,
"min":min(w),"max":max(w),"avg_7d":round(sum(w[:7])/min(7,len(w)),2)} "min":min(w),"max":max(w),"avg_7d":round(sum(w[:7])/min(7,len(w)),2)}
# ── Circumferences ──────────────────────────────────────────────────────────── # ── Circumferences ────────────────────────────────────────────────────────────
@@ -428,13 +438,14 @@ def activity_stats(x_profile_id: Optional[str]=Header(default=None), session: di
"SELECT * FROM activity_log WHERE profile_id=%s ORDER BY date DESC LIMIT 30", (pid,)) "SELECT * FROM activity_log WHERE profile_id=%s ORDER BY date DESC LIMIT 30", (pid,))
rows = [r2d(r) for r in cur.fetchall()] rows = [r2d(r) for r in cur.fetchall()]
if not rows: return {"count":0,"total_kcal":0,"total_min":0,"by_type":{}} if not rows: return {"count":0,"total_kcal":0,"total_min":0,"by_type":{}}
total_kcal=sum(r.get('kcal_active') or 0 for r in rows) total_kcal=sum(float(r.get('kcal_active') or 0) for r in rows)
total_min=sum(r.get('duration_min') or 0 for r in rows) total_min=sum(float(r.get('duration_min') or 0) for r in rows)
by_type={} by_type={}
for r in rows: for r in rows:
t=r['activity_type']; by_type.setdefault(t,{'count':0,'kcal':0,'min':0}) t=r['activity_type']; by_type.setdefault(t,{'count':0,'kcal':0,'min':0})
by_type[t]['count']+=1; by_type[t]['kcal']+=r.get('kcal_active') or 0 by_type[t]['count']+=1
by_type[t]['min']+=r.get('duration_min') or 0 by_type[t]['kcal']+=float(r.get('kcal_active') or 0)
by_type[t]['min']+=float(r.get('duration_min') or 0)
return {"count":len(rows),"total_kcal":round(total_kcal),"total_min":round(total_min),"by_type":by_type} return {"count":len(rows),"total_kcal":round(total_kcal),"total_min":round(total_min),"by_type":by_type}
@app.post("/api/activity/import-csv") @app.post("/api/activity/import-csv")
@@ -498,13 +509,17 @@ async def upload_photo(file: UploadFile=File(...), date: str="",
return {"id":fid,"date":date} return {"id":fid,"date":date}
@app.get("/api/photos/{fid}") @app.get("/api/photos/{fid}")
def get_photo(fid: str, session: dict=Depends(require_auth)): def get_photo(fid: str, session: dict=Depends(require_auth_flexible)):
"""Get photo by ID. Auth via header or query param (for <img> tags)."""
with get_db() as conn: with get_db() as conn:
cur = get_cursor(conn) cur = get_cursor(conn)
cur.execute("SELECT path FROM photos WHERE id=%s", (fid,)) cur.execute("SELECT path FROM photos WHERE id=%s", (fid,))
row = cur.fetchone() row = cur.fetchone()
if not row: raise HTTPException(404) if not row: raise HTTPException(404, "Photo not found")
return FileResponse(row['path']) photo_path = Path(PHOTOS_DIR) / row['path']
if not photo_path.exists():
raise HTTPException(404, "Photo file not found")
return FileResponse(photo_path)
@app.get("/api/photos") @app.get("/api/photos")
def list_photos(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)): def list_photos(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
@@ -590,11 +605,13 @@ def nutrition_correlations(x_profile_id: Optional[str]=Header(default=None), ses
for d in all_dates: for d in all_dates:
if d not in nutr and d not in wlog: continue if d not in nutr and d not in wlog: continue
row={'date':d} row={'date':d}
if d in nutr: row.update({k:nutr[d][k] for k in ['kcal','protein_g','fat_g','carbs_g']}) if d in nutr: row.update({k:float(nutr[d][k]) if nutr[d][k] is not None else None for k in ['kcal','protein_g','fat_g','carbs_g']})
if d in wlog: row['weight']=wlog[d] if d in wlog: row['weight']=float(wlog[d])
if d in cal_by_date: if d in cal_by_date:
row['lean_mass']=cal_by_date[d].get('lean_mass') lm = cal_by_date[d].get('lean_mass')
row['body_fat_pct']=cal_by_date[d].get('body_fat_pct') bf = cal_by_date[d].get('body_fat_pct')
row['lean_mass']=float(lm) if lm is not None else None
row['body_fat_pct']=float(bf) if bf is not None else None
result.append(row) result.append(row)
return result return result
@@ -613,7 +630,7 @@ def nutrition_weekly(weeks: int=16, x_profile_id: Optional[str]=Header(default=N
result=[] result=[]
for wk in sorted(wm): for wk in sorted(wm):
en=wm[wk]; n=len(en) en=wm[wk]; n=len(en)
def avg(k): return round(sum(e.get(k) or 0 for e in en)/n,1) def avg(k): return round(sum(float(e.get(k) or 0) for e in en)/n,1)
result.append({'week':wk,'days':n,'kcal':avg('kcal'),'protein_g':avg('protein_g'),'fat_g':avg('fat_g'),'carbs_g':avg('carbs_g')}) result.append({'week':wk,'days':n,'kcal':avg('kcal'),'protein_g':avg('protein_g'),'fat_g':avg('fat_g'),'carbs_g':avg('carbs_g')})
return result return result
@@ -768,10 +785,10 @@ def _prepare_template_vars(data: dict) -> dict:
"name": prof.get('name', 'Nutzer'), "name": prof.get('name', 'Nutzer'),
"geschlecht": "männlich" if prof.get('sex') == 'm' else "weiblich", "geschlecht": "männlich" if prof.get('sex') == 'm' else "weiblich",
"height": prof.get('height', 178), "height": prof.get('height', 178),
"goal_weight": prof.get('goal_weight') or "nicht gesetzt", "goal_weight": float(prof.get('goal_weight')) if prof.get('goal_weight') else "nicht gesetzt",
"goal_bf_pct": prof.get('goal_bf_pct') or "nicht gesetzt", "goal_bf_pct": float(prof.get('goal_bf_pct')) if prof.get('goal_bf_pct') else "nicht gesetzt",
"weight_aktuell": weight[0]['weight'] if weight else "keine Daten", "weight_aktuell": float(weight[0]['weight']) if weight else "keine Daten",
"kf_aktuell": caliper[0]['body_fat_pct'] if caliper and caliper[0].get('body_fat_pct') else "unbekannt", "kf_aktuell": float(caliper[0]['body_fat_pct']) if caliper and caliper[0].get('body_fat_pct') else "unbekannt",
} }
# Calculate age from dob # Calculate age from dob
@@ -790,7 +807,7 @@ def _prepare_template_vars(data: dict) -> dict:
# Weight trend summary # Weight trend summary
if len(weight) >= 2: if len(weight) >= 2:
recent = weight[:30] recent = weight[:30]
delta = recent[0]['weight'] - recent[-1]['weight'] delta = float(recent[0]['weight']) - float(recent[-1]['weight'])
vars['weight_trend'] = f"{len(recent)} Einträge, Δ30d: {delta:+.1f}kg" vars['weight_trend'] = f"{len(recent)} Einträge, Δ30d: {delta:+.1f}kg"
else: else:
vars['weight_trend'] = "zu wenig Daten" vars['weight_trend'] = "zu wenig Daten"
@@ -798,7 +815,8 @@ def _prepare_template_vars(data: dict) -> dict:
# Caliper summary # Caliper summary
if caliper: if caliper:
c = caliper[0] c = caliper[0]
vars['caliper_summary'] = f"KF: {c.get('body_fat_pct','?')}%, Methode: {c.get('sf_method','?')}" bf = float(c.get('body_fat_pct')) if c.get('body_fat_pct') else '?'
vars['caliper_summary'] = f"KF: {bf}%, Methode: {c.get('sf_method','?')}"
else: else:
vars['caliper_summary'] = "keine Daten" vars['caliper_summary'] = "keine Daten"
@@ -807,7 +825,7 @@ def _prepare_template_vars(data: dict) -> dict:
c = circ[0] c = circ[0]
parts = [] parts = []
for k in ['c_waist', 'c_belly', 'c_hip']: for k in ['c_waist', 'c_belly', 'c_hip']:
if c.get(k): parts.append(f"{k.split('_')[1]}: {c[k]}cm") if c.get(k): parts.append(f"{k.split('_')[1]}: {float(c[k])}cm")
vars['circ_summary'] = ", ".join(parts) if parts else "keine Daten" vars['circ_summary'] = ", ".join(parts) if parts else "keine Daten"
else: else:
vars['circ_summary'] = "keine Daten" vars['circ_summary'] = "keine Daten"
@@ -815,15 +833,15 @@ def _prepare_template_vars(data: dict) -> dict:
# Nutrition summary # Nutrition summary
if nutrition: if nutrition:
n = len(nutrition) n = len(nutrition)
avg_kcal = sum(d.get('kcal',0) for d in nutrition) / n avg_kcal = sum(float(d.get('kcal',0) or 0) for d in nutrition) / n
avg_prot = sum(d.get('protein_g',0) for d in nutrition) / n avg_prot = sum(float(d.get('protein_g',0) or 0) for d in nutrition) / n
vars['nutrition_summary'] = f"{n} Tage, Ø {avg_kcal:.0f}kcal, {avg_prot:.0f}g Protein" vars['nutrition_summary'] = f"{n} Tage, Ø {avg_kcal:.0f}kcal, {avg_prot:.0f}g Protein"
vars['nutrition_detail'] = vars['nutrition_summary'] vars['nutrition_detail'] = vars['nutrition_summary']
vars['nutrition_days'] = n vars['nutrition_days'] = n
vars['kcal_avg'] = round(avg_kcal) vars['kcal_avg'] = round(avg_kcal)
vars['protein_avg'] = round(avg_prot,1) vars['protein_avg'] = round(avg_prot,1)
vars['fat_avg'] = round(sum(d.get('fat_g',0) for d in nutrition) / n,1) vars['fat_avg'] = round(sum(float(d.get('fat_g',0) or 0) for d in nutrition) / n,1)
vars['carb_avg'] = round(sum(d.get('carbs_g',0) for d in nutrition) / n,1) vars['carb_avg'] = round(sum(float(d.get('carbs_g',0) or 0) for d in nutrition) / n,1)
else: else:
vars['nutrition_summary'] = "keine Daten" vars['nutrition_summary'] = "keine Daten"
vars['nutrition_detail'] = "keine Daten" vars['nutrition_detail'] = "keine Daten"
@@ -835,13 +853,14 @@ def _prepare_template_vars(data: dict) -> dict:
# Protein targets # Protein targets
w = weight[0]['weight'] if weight else prof.get('height',178) - 100 w = weight[0]['weight'] if weight else prof.get('height',178) - 100
w = float(w) # Convert Decimal to float for math operations
vars['protein_ziel_low'] = round(w * 1.6) vars['protein_ziel_low'] = round(w * 1.6)
vars['protein_ziel_high'] = round(w * 2.2) vars['protein_ziel_high'] = round(w * 2.2)
# Activity summary # Activity summary
if activity: if activity:
n = len(activity) n = len(activity)
total_kcal = sum(a.get('kcal_active',0) for a in activity) total_kcal = sum(float(a.get('kcal_active',0) or 0) for a in activity)
vars['activity_summary'] = f"{n} Trainings, {total_kcal:.0f}kcal gesamt" vars['activity_summary'] = f"{n} Trainings, {total_kcal:.0f}kcal gesamt"
vars['activity_detail'] = vars['activity_summary'] vars['activity_detail'] = vars['activity_summary']
vars['activity_kcal_summary'] = f"Ø {total_kcal/n:.0f}kcal/Training" vars['activity_kcal_summary'] = f"Ø {total_kcal/n:.0f}kcal/Training"
@@ -852,7 +871,7 @@ def _prepare_template_vars(data: dict) -> dict:
return vars return vars
@app.post("/api/ai/analyze/{slug}") @app.post("/api/insights/run/{slug}")
async def analyze_with_prompt(slug: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)): async def analyze_with_prompt(slug: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Run AI analysis with specified prompt template.""" """Run AI analysis with specified prompt template."""
pid = get_pid(x_profile_id) pid = get_pid(x_profile_id)
@@ -909,7 +928,7 @@ async def analyze_with_prompt(slug: str, x_profile_id: Optional[str]=Header(defa
inc_ai_usage(pid) inc_ai_usage(pid)
return {"scope": slug, "content": content} return {"scope": slug, "content": content}
@app.post("/api/ai/analyze-pipeline") @app.post("/api/insights/pipeline")
async def analyze_pipeline(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)): async def analyze_pipeline(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Run 3-stage pipeline analysis.""" """Run 3-stage pipeline analysis."""
pid = get_pid(x_profile_id) pid = get_pid(x_profile_id)
@@ -1047,12 +1066,51 @@ async def analyze_pipeline(x_profile_id: Optional[str]=Header(default=None), ses
@app.get("/api/prompts") @app.get("/api/prompts")
def list_prompts(session: dict=Depends(require_auth)): def list_prompts(session: dict=Depends(require_auth)):
"""List all available AI prompts.""" """
List AI prompts.
- Admins: see ALL prompts (including pipeline and inactive)
- Users: see only active single-analysis prompts
"""
with get_db() as conn: with get_db() as conn:
cur = get_cursor(conn) cur = get_cursor(conn)
is_admin = session.get('role') == 'admin'
if is_admin:
# Admin sees everything
cur.execute("SELECT * FROM ai_prompts ORDER BY sort_order, slug")
else:
# Users see only active, non-pipeline prompts
cur.execute("SELECT * FROM ai_prompts WHERE active=true AND slug NOT LIKE 'pipeline_%' ORDER BY sort_order") cur.execute("SELECT * FROM ai_prompts WHERE active=true AND slug NOT LIKE 'pipeline_%' ORDER BY sort_order")
return [r2d(r) for r in cur.fetchall()] return [r2d(r) for r in cur.fetchall()]
@app.put("/api/prompts/{prompt_id}")
def update_prompt(prompt_id: str, data: dict, session: dict=Depends(require_admin)):
"""Update AI prompt template (admin only)."""
with get_db() as conn:
cur = get_cursor(conn)
updates = []
values = []
if 'name' in data:
updates.append('name=%s')
values.append(data['name'])
if 'description' in data:
updates.append('description=%s')
values.append(data['description'])
if 'template' in data:
updates.append('template=%s')
values.append(data['template'])
if 'active' in data:
updates.append('active=%s')
# Convert to boolean (accepts true/false, 1/0)
values.append(bool(data['active']))
if updates:
cur.execute(f"UPDATE ai_prompts SET {', '.join(updates)}, updated=CURRENT_TIMESTAMP WHERE id=%s",
values + [prompt_id])
return {"ok": True}
@app.get("/api/ai/usage") @app.get("/api/ai/usage")
def get_ai_usage(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)): def get_ai_usage(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get AI usage stats for current profile.""" """Get AI usage stats for current profile."""
@@ -1145,7 +1203,22 @@ def auth_status():
"""Health check endpoint.""" """Health check endpoint."""
return {"status": "ok", "service": "mitai-jinkendo", "version": "v9b"} return {"status": "ok", "service": "mitai-jinkendo", "version": "v9b"}
@app.post("/api/auth/password-reset-request") @app.post("/api/auth/pin")
def change_pin(req: dict, session: dict=Depends(require_auth)):
"""Change PIN/password for current user."""
pid = session['profile_id']
new_pin = req.get('pin', '')
if len(new_pin) < 4:
raise HTTPException(400, "PIN/Passwort muss mind. 4 Zeichen haben")
new_hash = hash_pin(new_pin)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, pid))
return {"ok": True}
@app.post("/api/auth/forgot-password")
@limiter.limit("3/minute") @limiter.limit("3/minute")
async def password_reset_request(req: PasswordResetRequest, request: Request): async def password_reset_request(req: PasswordResetRequest, request: Request):
"""Request password reset email.""" """Request password reset email."""
@@ -1203,7 +1276,7 @@ Dein Mitai Jinkendo Team
return {"ok": True, "message": "Falls die E-Mail existiert, wurde ein Reset-Link gesendet."} return {"ok": True, "message": "Falls die E-Mail existiert, wurde ein Reset-Link gesendet."}
@app.post("/api/auth/password-reset-confirm") @app.post("/api/auth/reset-password")
def password_reset_confirm(req: PasswordResetConfirm): def password_reset_confirm(req: PasswordResetConfirm):
"""Confirm password reset with token.""" """Confirm password reset with token."""
with get_db() as conn: with get_db() as conn:
@@ -1264,9 +1337,79 @@ def admin_update_profile(pid: str, data: AdminProfileUpdate, session: dict=Depen
return {"ok": True} return {"ok": True}
@app.post("/api/admin/test-email") @app.put("/api/admin/profiles/{pid}/permissions")
def admin_test_email(email: str, session: dict=Depends(require_admin)): def admin_set_permissions(pid: str, data: dict, session: dict=Depends(require_admin)):
"""Admin: Set profile permissions."""
with get_db() as conn:
cur = get_cursor(conn)
updates = []
values = []
if 'ai_enabled' in data:
updates.append('ai_enabled=%s')
values.append(data['ai_enabled'])
if 'ai_limit_day' in data:
updates.append('ai_limit_day=%s')
values.append(data['ai_limit_day'])
if 'export_enabled' in data:
updates.append('export_enabled=%s')
values.append(data['export_enabled'])
if 'role' in data:
updates.append('role=%s')
values.append(data['role'])
if updates:
cur.execute(f"UPDATE profiles SET {', '.join(updates)} WHERE id=%s", values + [pid])
return {"ok": True}
@app.put("/api/admin/profiles/{pid}/email")
def admin_set_email(pid: str, data: dict, session: dict=Depends(require_admin)):
"""Admin: Set profile email."""
email = data.get('email', '').strip().lower()
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("UPDATE profiles SET email=%s WHERE id=%s", (email if email else None, pid))
return {"ok": True}
@app.put("/api/admin/profiles/{pid}/pin")
def admin_set_pin(pid: str, data: dict, session: dict=Depends(require_admin)):
"""Admin: Set profile PIN/password."""
new_pin = data.get('pin', '')
if len(new_pin) < 4:
raise HTTPException(400, "PIN/Passwort muss mind. 4 Zeichen haben")
new_hash = hash_pin(new_pin)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, pid))
return {"ok": True}
@app.get("/api/admin/email/status")
def admin_email_status(session: dict=Depends(require_admin)):
"""Admin: Check email configuration status."""
smtp_host = os.getenv("SMTP_HOST")
smtp_user = os.getenv("SMTP_USER")
smtp_pass = os.getenv("SMTP_PASS")
app_url = os.getenv("APP_URL", "http://localhost:3002")
configured = bool(smtp_host and smtp_user and smtp_pass)
return {
"configured": configured,
"smtp_host": smtp_host or "",
"smtp_user": smtp_user or "",
"app_url": app_url
}
@app.post("/api/admin/email/test")
def admin_test_email(data: dict, session: dict=Depends(require_admin)):
"""Admin: Send test email.""" """Admin: Send test email."""
email = data.get('to', '')
if not email:
raise HTTPException(400, "E-Mail-Adresse fehlt")
try: try:
import smtplib import smtplib
from email.mime.text import MIMEText from email.mime.text import MIMEText
@@ -1319,28 +1462,28 @@ def export_csv(x_profile_id: Optional[str]=Header(default=None), session: dict=D
cur = get_cursor(conn) cur = get_cursor(conn)
cur.execute("SELECT date, weight, note FROM weight_log WHERE profile_id=%s ORDER BY date", (pid,)) cur.execute("SELECT date, weight, note FROM weight_log WHERE profile_id=%s ORDER BY date", (pid,))
for r in cur.fetchall(): for r in cur.fetchall():
writer.writerow(["Gewicht", r['date'], f"{r['weight']}kg", r['note'] or ""]) writer.writerow(["Gewicht", r['date'], f"{float(r['weight'])}kg", r['note'] or ""])
# Circumferences # Circumferences
cur.execute("SELECT date, c_waist, c_belly, c_hip FROM circumference_log WHERE profile_id=%s ORDER BY date", (pid,)) cur.execute("SELECT date, c_waist, c_belly, c_hip FROM circumference_log WHERE profile_id=%s ORDER BY date", (pid,))
for r in cur.fetchall(): for r in cur.fetchall():
details = f"Taille:{r['c_waist']}cm Bauch:{r['c_belly']}cm Hüfte:{r['c_hip']}cm" details = f"Taille:{float(r['c_waist'])}cm Bauch:{float(r['c_belly'])}cm Hüfte:{float(r['c_hip'])}cm"
writer.writerow(["Umfänge", r['date'], "", details]) writer.writerow(["Umfänge", r['date'], "", details])
# Caliper # Caliper
cur.execute("SELECT date, body_fat_pct, lean_mass FROM caliper_log WHERE profile_id=%s ORDER BY date", (pid,)) cur.execute("SELECT date, body_fat_pct, lean_mass FROM caliper_log WHERE profile_id=%s ORDER BY date", (pid,))
for r in cur.fetchall(): for r in cur.fetchall():
writer.writerow(["Caliper", r['date'], f"{r['body_fat_pct']}%", f"Magermasse:{r['lean_mass']}kg"]) writer.writerow(["Caliper", r['date'], f"{float(r['body_fat_pct'])}%", f"Magermasse:{float(r['lean_mass'])}kg"])
# Nutrition # Nutrition
cur.execute("SELECT date, kcal, protein_g FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,)) cur.execute("SELECT date, kcal, protein_g FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,))
for r in cur.fetchall(): for r in cur.fetchall():
writer.writerow(["Ernährung", r['date'], f"{r['kcal']}kcal", f"Protein:{r['protein_g']}g"]) writer.writerow(["Ernährung", r['date'], f"{float(r['kcal'])}kcal", f"Protein:{float(r['protein_g'])}g"])
# Activity # Activity
cur.execute("SELECT date, activity_type, duration_min, kcal_active FROM activity_log WHERE profile_id=%s ORDER BY date", (pid,)) cur.execute("SELECT date, activity_type, duration_min, kcal_active FROM activity_log WHERE profile_id=%s ORDER BY date", (pid,))
for r in cur.fetchall(): for r in cur.fetchall():
writer.writerow(["Training", r['date'], r['activity_type'], f"{r['duration_min']}min {r['kcal_active']}kcal"]) writer.writerow(["Training", r['date'], r['activity_type'], f"{float(r['duration_min'])}min {float(r['kcal_active'])}kcal"])
output.seek(0) output.seek(0)
return StreamingResponse( return StreamingResponse(
@@ -1348,3 +1491,495 @@ def export_csv(x_profile_id: Optional[str]=Header(default=None), session: dict=D
media_type="text/csv", media_type="text/csv",
headers={"Content-Disposition": f"attachment; filename=mitai-export-{pid}.csv"} headers={"Content-Disposition": f"attachment; filename=mitai-export-{pid}.csv"}
) )
@app.get("/api/export/json")
def export_json(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Export all data as JSON."""
pid = get_pid(x_profile_id)
# Check export permission
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT export_enabled FROM profiles WHERE id=%s", (pid,))
prof = cur.fetchone()
if not prof or not prof['export_enabled']:
raise HTTPException(403, "Export ist für dieses Profil deaktiviert")
# Collect all data
data = {}
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
data['profile'] = r2d(cur.fetchone())
cur.execute("SELECT * FROM weight_log WHERE profile_id=%s ORDER BY date", (pid,))
data['weight'] = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM circumference_log WHERE profile_id=%s ORDER BY date", (pid,))
data['circumferences'] = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM caliper_log WHERE profile_id=%s ORDER BY date", (pid,))
data['caliper'] = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,))
data['nutrition'] = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM activity_log WHERE profile_id=%s ORDER BY date", (pid,))
data['activity'] = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,))
data['insights'] = [r2d(r) for r in cur.fetchall()]
def decimal_handler(obj):
if isinstance(obj, Decimal):
return float(obj)
return str(obj)
json_str = json.dumps(data, indent=2, default=decimal_handler)
return Response(
content=json_str,
media_type="application/json",
headers={"Content-Disposition": f"attachment; filename=mitai-export-{pid}.json"}
)
@app.get("/api/export/zip")
def export_zip(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Export all data as ZIP (CSV + JSON + photos) per specification."""
pid = get_pid(x_profile_id)
# Check export permission & get profile
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
prof = r2d(cur.fetchone())
if not prof or not prof.get('export_enabled'):
raise HTTPException(403, "Export ist für dieses Profil deaktiviert")
# Helper: CSV writer with UTF-8 BOM + semicolon
def write_csv(zf, filename, rows, columns):
if not rows:
return
output = io.StringIO()
writer = csv.writer(output, delimiter=';')
writer.writerow(columns)
for r in rows:
writer.writerow([
'' if r.get(col) is None else
(float(r[col]) if isinstance(r.get(col), Decimal) else r[col])
for col in columns
])
# UTF-8 with BOM for Excel
csv_bytes = '\ufeff'.encode('utf-8') + output.getvalue().encode('utf-8')
zf.writestr(f"data/{filename}", csv_bytes)
# Create ZIP
zip_buffer = io.BytesIO()
export_date = datetime.now().strftime('%Y-%m-%d')
profile_name = prof.get('name', 'export')
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zf:
with get_db() as conn:
cur = get_cursor(conn)
# 1. README.txt
readme = f"""Mitai Jinkendo – Datenexport
Version: 2
Exportiert am: {export_date}
Profil: {profile_name}
Inhalt:
- profile.json: Profildaten und Einstellungen
- data/*.csv: Messdaten (Semikolon-getrennt, UTF-8)
- insights/: KI-Auswertungen (JSON)
- photos/: Progress-Fotos (JPEG)
Import:
Dieser Export kann in Mitai Jinkendo unter
Einstellungen → Import → "Mitai Backup importieren"
wieder eingespielt werden.
Format-Version 2 (ab v9b):
Alle CSV-Dateien sind UTF-8 mit BOM kodiert.
Trennzeichen: Semikolon (;)
Datumsformat: YYYY-MM-DD
"""
zf.writestr("README.txt", readme.encode('utf-8'))
# 2. profile.json (ohne Passwort-Hash)
cur.execute("SELECT COUNT(*) as c FROM weight_log WHERE profile_id=%s", (pid,))
w_count = cur.fetchone()['c']
cur.execute("SELECT COUNT(*) as c FROM nutrition_log WHERE profile_id=%s", (pid,))
n_count = cur.fetchone()['c']
cur.execute("SELECT COUNT(*) as c FROM activity_log WHERE profile_id=%s", (pid,))
a_count = cur.fetchone()['c']
cur.execute("SELECT COUNT(*) as c FROM photos WHERE profile_id=%s", (pid,))
p_count = cur.fetchone()['c']
profile_data = {
"export_version": "2",
"export_date": export_date,
"app": "Mitai Jinkendo",
"profile": {
"name": prof.get('name'),
"email": prof.get('email'),
"sex": prof.get('sex'),
"height": float(prof['height']) if prof.get('height') else None,
"birth_year": prof['dob'].year if prof.get('dob') else None,
"goal_weight": float(prof['goal_weight']) if prof.get('goal_weight') else None,
"goal_bf_pct": float(prof['goal_bf_pct']) if prof.get('goal_bf_pct') else None,
"avatar_color": prof.get('avatar_color'),
"auth_type": prof.get('auth_type'),
"session_days": prof.get('session_days'),
"ai_enabled": prof.get('ai_enabled'),
"tier": prof.get('tier')
},
"stats": {
"weight_entries": w_count,
"nutrition_entries": n_count,
"activity_entries": a_count,
"photos": p_count
}
}
zf.writestr("profile.json", json.dumps(profile_data, indent=2, ensure_ascii=False).encode('utf-8'))
# 3. data/weight.csv
cur.execute("SELECT id, date, weight, note, source, created FROM weight_log WHERE profile_id=%s ORDER BY date", (pid,))
write_csv(zf, "weight.csv", [r2d(r) for r in cur.fetchall()],
['id','date','weight','note','source','created'])
# 4. data/circumferences.csv
cur.execute("SELECT id, date, c_waist, c_hip, c_chest, c_neck, c_arm, c_thigh, c_calf, notes, created FROM circumference_log WHERE profile_id=%s ORDER BY date", (pid,))
rows = [r2d(r) for r in cur.fetchall()]
# Rename columns to match spec
for r in rows:
r['waist'] = r.pop('c_waist', None)
r['hip'] = r.pop('c_hip', None)
r['chest'] = r.pop('c_chest', None)
r['neck'] = r.pop('c_neck', None)
r['upper_arm'] = r.pop('c_arm', None)
r['thigh'] = r.pop('c_thigh', None)
r['calf'] = r.pop('c_calf', None)
r['forearm'] = None # not tracked
r['note'] = r.pop('notes', None)
write_csv(zf, "circumferences.csv", rows,
['id','date','waist','hip','chest','neck','upper_arm','thigh','calf','forearm','note','created'])
# 5. data/caliper.csv
cur.execute("SELECT id, date, sf_chest, sf_abdomen, sf_thigh, sf_triceps, sf_subscap, sf_suprailiac, sf_axilla, sf_method, body_fat_pct, notes, created FROM caliper_log WHERE profile_id=%s ORDER BY date", (pid,))
rows = [r2d(r) for r in cur.fetchall()]
for r in rows:
r['chest'] = r.pop('sf_chest', None)
r['abdomen'] = r.pop('sf_abdomen', None)
r['thigh'] = r.pop('sf_thigh', None)
r['tricep'] = r.pop('sf_triceps', None)
r['subscapular'] = r.pop('sf_subscap', None)
r['suprailiac'] = r.pop('sf_suprailiac', None)
r['midaxillary'] = r.pop('sf_axilla', None)
r['method'] = r.pop('sf_method', None)
r['bf_percent'] = r.pop('body_fat_pct', None)
r['note'] = r.pop('notes', None)
write_csv(zf, "caliper.csv", rows,
['id','date','chest','abdomen','thigh','tricep','subscapular','suprailiac','midaxillary','method','bf_percent','note','created'])
# 6. data/nutrition.csv
cur.execute("SELECT id, date, kcal, protein_g, fat_g, carbs_g, source, created FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,))
rows = [r2d(r) for r in cur.fetchall()]
for r in rows:
r['meal_name'] = '' # not tracked per meal
r['protein'] = r.pop('protein_g', None)
r['fat'] = r.pop('fat_g', None)
r['carbs'] = r.pop('carbs_g', None)
r['fiber'] = None # not tracked
r['note'] = ''
write_csv(zf, "nutrition.csv", rows,
['id','date','meal_name','kcal','protein','fat','carbs','fiber','note','source','created'])
# 7. data/activity.csv
cur.execute("SELECT id, date, activity_type, duration_min, kcal_active, hr_avg, hr_max, distance_km, notes, source, created FROM activity_log WHERE profile_id=%s ORDER BY date", (pid,))
rows = [r2d(r) for r in cur.fetchall()]
for r in rows:
r['name'] = r['activity_type']
r['type'] = r.pop('activity_type', None)
r['kcal'] = r.pop('kcal_active', None)
r['heart_rate_avg'] = r.pop('hr_avg', None)
r['heart_rate_max'] = r.pop('hr_max', None)
r['note'] = r.pop('notes', None)
write_csv(zf, "activity.csv", rows,
['id','date','name','type','duration_min','kcal','heart_rate_avg','heart_rate_max','distance_km','note','source','created'])
# 8. insights/ai_insights.json
cur.execute("SELECT id, scope, content, created FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,))
insights = []
for r in cur.fetchall():
rd = r2d(r)
insights.append({
"id": rd['id'],
"scope": rd['scope'],
"created": rd['created'].isoformat() if hasattr(rd['created'], 'isoformat') else str(rd['created']),
"result": rd['content']
})
if insights:
zf.writestr("insights/ai_insights.json", json.dumps(insights, indent=2, ensure_ascii=False).encode('utf-8'))
# 9. photos/
cur.execute("SELECT * FROM photos WHERE profile_id=%s ORDER BY date", (pid,))
photos = [r2d(r) for r in cur.fetchall()]
for i, photo in enumerate(photos):
photo_path = Path(PHOTOS_DIR) / photo['path']
if photo_path.exists():
filename = f"{photo.get('date') or export_date}_{i+1}{photo_path.suffix}"
zf.write(photo_path, f"photos/{filename}")
zip_buffer.seek(0)
filename = f"mitai-export-{profile_name.replace(' ','-')}-{export_date}.zip"
return StreamingResponse(
iter([zip_buffer.getvalue()]),
media_type="application/zip",
headers={"Content-Disposition": f"attachment; filename={filename}"}
)
# ── Import ZIP ──────────────────────────────────────────────────
@app.post("/api/import/zip")
async def import_zip(
file: UploadFile = File(...),
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""
Import data from ZIP export file.
- Validates export format
- Imports missing entries only (ON CONFLICT DO NOTHING)
- Imports photos
- Returns import summary
- Full rollback on error
"""
pid = get_pid(x_profile_id)
# Read uploaded file
content = await file.read()
zip_buffer = io.BytesIO(content)
try:
with zipfile.ZipFile(zip_buffer, 'r') as zf:
# 1. Validate profile.json
if 'profile.json' not in zf.namelist():
raise HTTPException(400, "Ungültiger Export: profile.json fehlt")
profile_data = json.loads(zf.read('profile.json').decode('utf-8'))
export_version = profile_data.get('export_version', '1')
# Stats tracker
stats = {
'weight': 0,
'circumferences': 0,
'caliper': 0,
'nutrition': 0,
'activity': 0,
'photos': 0,
'insights': 0
}
with get_db() as conn:
cur = get_cursor(conn)
try:
# 2. Import weight.csv
if 'data/weight.csv' in zf.namelist():
csv_data = zf.read('data/weight.csv').decode('utf-8-sig')
reader = csv.DictReader(io.StringIO(csv_data), delimiter=';')
for row in reader:
cur.execute("""
INSERT INTO weight_log (profile_id, date, weight, note, source, created)
VALUES (%s, %s, %s, %s, %s, %s)
ON CONFLICT (profile_id, date) DO NOTHING
""", (
pid,
row['date'],
float(row['weight']) if row['weight'] else None,
row.get('note', ''),
row.get('source', 'import'),
row.get('created', datetime.now())
))
if cur.rowcount > 0:
stats['weight'] += 1
# 3. Import circumferences.csv
if 'data/circumferences.csv' in zf.namelist():
csv_data = zf.read('data/circumferences.csv').decode('utf-8-sig')
reader = csv.DictReader(io.StringIO(csv_data), delimiter=';')
for row in reader:
# Map CSV columns to DB columns
cur.execute("""
INSERT INTO circumference_log (
profile_id, date, c_waist, c_hip, c_chest, c_neck,
c_arm, c_thigh, c_calf, notes, created
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (profile_id, date) DO NOTHING
""", (
pid,
row['date'],
float(row['waist']) if row.get('waist') else None,
float(row['hip']) if row.get('hip') else None,
float(row['chest']) if row.get('chest') else None,
float(row['neck']) if row.get('neck') else None,
float(row['upper_arm']) if row.get('upper_arm') else None,
float(row['thigh']) if row.get('thigh') else None,
float(row['calf']) if row.get('calf') else None,
row.get('note', ''),
row.get('created', datetime.now())
))
if cur.rowcount > 0:
stats['circumferences'] += 1
# 4. Import caliper.csv
if 'data/caliper.csv' in zf.namelist():
csv_data = zf.read('data/caliper.csv').decode('utf-8-sig')
reader = csv.DictReader(io.StringIO(csv_data), delimiter=';')
for row in reader:
cur.execute("""
INSERT INTO caliper_log (
profile_id, date, sf_chest, sf_abdomen, sf_thigh,
sf_triceps, sf_subscap, sf_suprailiac, sf_axilla,
sf_method, body_fat_pct, notes, created
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (profile_id, date) DO NOTHING
""", (
pid,
row['date'],
float(row['chest']) if row.get('chest') else None,
float(row['abdomen']) if row.get('abdomen') else None,
float(row['thigh']) if row.get('thigh') else None,
float(row['tricep']) if row.get('tricep') else None,
float(row['subscapular']) if row.get('subscapular') else None,
float(row['suprailiac']) if row.get('suprailiac') else None,
float(row['midaxillary']) if row.get('midaxillary') else None,
row.get('method', 'jackson3'),
float(row['bf_percent']) if row.get('bf_percent') else None,
row.get('note', ''),
row.get('created', datetime.now())
))
if cur.rowcount > 0:
stats['caliper'] += 1
# 5. Import nutrition.csv
if 'data/nutrition.csv' in zf.namelist():
csv_data = zf.read('data/nutrition.csv').decode('utf-8-sig')
reader = csv.DictReader(io.StringIO(csv_data), delimiter=';')
for row in reader:
cur.execute("""
INSERT INTO nutrition_log (
profile_id, date, kcal, protein_g, fat_g, carbs_g, source, created
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (profile_id, date) DO NOTHING
""", (
pid,
row['date'],
float(row['kcal']) if row.get('kcal') else None,
float(row['protein']) if row.get('protein') else None,
float(row['fat']) if row.get('fat') else None,
float(row['carbs']) if row.get('carbs') else None,
row.get('source', 'import'),
row.get('created', datetime.now())
))
if cur.rowcount > 0:
stats['nutrition'] += 1
# 6. Import activity.csv
if 'data/activity.csv' in zf.namelist():
csv_data = zf.read('data/activity.csv').decode('utf-8-sig')
reader = csv.DictReader(io.StringIO(csv_data), delimiter=';')
for row in reader:
cur.execute("""
INSERT INTO activity_log (
profile_id, date, activity_type, duration_min,
kcal_active, hr_avg, hr_max, distance_km, notes, source, created
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
""", (
pid,
row['date'],
row.get('type', 'Training'),
float(row['duration_min']) if row.get('duration_min') else None,
float(row['kcal']) if row.get('kcal') else None,
float(row['heart_rate_avg']) if row.get('heart_rate_avg') else None,
float(row['heart_rate_max']) if row.get('heart_rate_max') else None,
float(row['distance_km']) if row.get('distance_km') else None,
row.get('note', ''),
row.get('source', 'import'),
row.get('created', datetime.now())
))
if cur.rowcount > 0:
stats['activity'] += 1
# 7. Import ai_insights.json
if 'insights/ai_insights.json' in zf.namelist():
insights_data = json.loads(zf.read('insights/ai_insights.json').decode('utf-8'))
for insight in insights_data:
cur.execute("""
INSERT INTO ai_insights (profile_id, scope, content, created)
VALUES (%s, %s, %s, %s)
""", (
pid,
insight['scope'],
insight['result'],
insight.get('created', datetime.now())
))
stats['insights'] += 1
# 8. Import photos
photo_files = [f for f in zf.namelist() if f.startswith('photos/') and not f.endswith('/')]
for photo_file in photo_files:
# Extract date from filename (format: YYYY-MM-DD_N.jpg)
filename = Path(photo_file).name
parts = filename.split('_')
photo_date = parts[0] if len(parts) > 0 else datetime.now().strftime('%Y-%m-%d')
# Generate new ID and path
photo_id = str(uuid.uuid4())
ext = Path(filename).suffix
new_filename = f"{photo_id}{ext}"
target_path = PHOTOS_DIR / new_filename
# Check if photo already exists for this date
cur.execute("""
SELECT id FROM photos
WHERE profile_id = %s AND date = %s
""", (pid, photo_date))
if cur.fetchone() is None:
# Write photo file
with open(target_path, 'wb') as f:
f.write(zf.read(photo_file))
# Insert DB record
cur.execute("""
INSERT INTO photos (id, profile_id, date, path, created)
VALUES (%s, %s, %s, %s, %s)
""", (photo_id, pid, photo_date, new_filename, datetime.now()))
stats['photos'] += 1
# Commit transaction
conn.commit()
except Exception as e:
# Rollback on any error
conn.rollback()
raise HTTPException(500, f"Import fehlgeschlagen: {str(e)}")
return {
"ok": True,
"message": "Import erfolgreich",
"stats": stats,
"total": sum(stats.values())
}
except zipfile.BadZipFile:
raise HTTPException(400, "Ungültige ZIP-Datei")
except Exception as e:
raise HTTPException(500, f"Import-Fehler: {str(e)}")
+16 -1
View File
@@ -69,6 +69,12 @@ BOOLEAN_COLUMNS = {
'ai_prompts': ['active'], 'ai_prompts': ['active'],
} }
# Column whitelist for tables that have schema differences
# Only these columns will be migrated (filters out legacy columns)
COLUMN_WHITELIST = {
'ai_insights': ['id', 'profile_id', 'scope', 'content', 'created'],
}
# ================================================================ # ================================================================
# CONVERSION HELPERS # CONVERSION HELPERS
@@ -173,7 +179,16 @@ def migrate_table(pg_conn, table: str) -> Dict[str, int]:
# Convert rows # Convert rows
converted_rows = [convert_row(row, table) for row in sqlite_rows] converted_rows = [convert_row(row, table) for row in sqlite_rows]
# Get column names # Get column names - filter if whitelist exists for this table
if table in COLUMN_WHITELIST:
allowed_columns = COLUMN_WHITELIST[table]
# Filter rows to only include allowed columns
converted_rows = [
{k: v for k, v in row.items() if k in allowed_columns}
for row in converted_rows
]
columns = allowed_columns
else:
columns = list(converted_rows[0].keys()) columns = list(converted_rows[0].keys())
cols_str = ', '.join(columns) cols_str = ', '.join(columns)
placeholders = ', '.join(['%s'] * len(columns)) placeholders = ', '.join(['%s'] * len(columns))
+1 -3
View File
@@ -1,7 +1,7 @@
services: services:
postgres: postgres:
image: postgres:16-alpine image: postgres:16-alpine
container_name: mitai-db container_name: mitai-db-prod
restart: unless-stopped restart: unless-stopped
environment: environment:
POSTGRES_DB: mitai_prod POSTGRES_DB: mitai_prod
@@ -9,8 +9,6 @@ services:
POSTGRES_PASSWORD: ${DB_PASSWORD:-change_me_in_production} POSTGRES_PASSWORD: ${DB_PASSWORD:-change_me_in_production}
volumes: volumes:
- mitai_postgres_data:/var/lib/postgresql/data - mitai_postgres_data:/var/lib/postgresql/data
ports:
- "127.0.0.1:5432:5432"
healthcheck: healthcheck:
test: ["CMD-SHELL", "pg_isready -U mitai_prod"] test: ["CMD-SHELL", "pg_isready -U mitai_prod"]
interval: 10s interval: 10s
+63 -15
View File
@@ -150,8 +150,11 @@ export default function Analysis() {
} }
const savePrompt = async (promptId, data) => { const savePrompt = async (promptId, data) => {
const token = localStorage.getItem('bodytrack_token')||''
await fetch(`/api/prompts/${promptId}`, { await fetch(`/api/prompts/${promptId}`, {
method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(data) method:'PUT',
headers:{'Content-Type':'application/json', 'X-Auth-Token': token},
body:JSON.stringify(data)
}) })
setEditing(null); await loadAll() setEditing(null); await loadAll()
} }
@@ -176,6 +179,10 @@ export default function Analysis() {
const activePrompts = prompts.filter(p=>p.active && !p.slug.startsWith('pipeline_')) const activePrompts = prompts.filter(p=>p.active && !p.slug.startsWith('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)
return ( return (
<div> <div>
<h1 className="page-title">KI-Analyse</h1> <h1 className="page-title">KI-Analyse</h1>
@@ -218,7 +225,8 @@ export default function Analysis() {
</div> </div>
)} )}
{/* Pipeline button */} {/* Pipeline button - only if all sub-prompts are active */}
{pipelineAvailable && (
<div className="card" style={{marginBottom:16,borderColor:'var(--accent)',borderWidth:2}}> <div className="card" style={{marginBottom:16,borderColor:'var(--accent)',borderWidth:2}}>
<div style={{display:'flex',alignItems:'flex-start',gap:12}}> <div style={{display:'flex',alignItems:'flex-start',gap:12}}>
<div style={{flex:1}}> <div style={{flex:1}}>
@@ -248,6 +256,7 @@ export default function Analysis() {
</div> </div>
)} )}
</div> </div>
)}
{!canUseAI && ( {!canUseAI && (
<div style={{padding:'14px 16px',background:'#FCEBEB',borderRadius:10, <div style={{padding:'14px 16px',background:'#FCEBEB',borderRadius:10,
@@ -345,21 +354,26 @@ export default function Analysis() {
Einzelanalysen Einzelanalysen
</div> </div>
{singlePrompts.map(p=>( {singlePrompts.map(p=>(
<div key={p.id} className="card section-gap"> <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={{display:'flex',alignItems:'center',gap:10}}>
<div style={{flex:1}}> <div style={{flex:1}}>
<div style={{fontWeight:600,fontSize:14,display:'flex',alignItems:'center',gap:8}}> <div style={{fontWeight:600,fontSize:14,display:'flex',alignItems:'center',gap:8}}>
{SLUG_LABELS[p.slug]||p.name} {SLUG_LABELS[p.slug]||p.name}
{!p.active && <span style={{fontSize:10,color:'var(--text3)', {!p.active && <span style={{fontSize:10,color:'#D85A30',
background:'var(--surface2)',padding:'1px 6px',borderRadius:4}}>Inaktiv</span>} background:'#FCEBEB',padding:'2px 8px',borderRadius:4,fontWeight:600}}>⏸ Deaktiviert</span>}
</div> </div>
{p.description && <div style={{fontSize:12,color:'var(--text3)',marginTop:1}}>{p.description}</div>} {p.description && <div style={{fontSize:12,color:'var(--text3)',marginTop:1}}>{p.description}</div>}
</div> </div>
<button className="btn btn-secondary" style={{padding:'5px 8px',fontSize:12}} <button className="btn btn-secondary" style={{padding:'5px 8px',fontSize:12}}
onClick={()=>fetch(`/api/prompts/${p.id}`,{method:'PUT', onClick={()=>{
headers:{'Content-Type':'application/json'}, const token = localStorage.getItem('bodytrack_token')||''
body:JSON.stringify({active:p.active?0:1})}).then(loadAll)}> fetch(`/api/prompts/${p.id}`,{
{p.active?'Deaktiv.':'Aktiv.'} 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>
<button className="btn btn-secondary" style={{padding:'5px 8px'}} <button className="btn btn-secondary" style={{padding:'5px 8px'}}
onClick={()=>setEditing(p)}><Pencil size={13}/></button> onClick={()=>setEditing(p)}><Pencil size={13}/></button>
@@ -372,26 +386,60 @@ export default function Analysis() {
))} ))}
{/* Pipeline prompts */} {/* Pipeline prompts */}
<div style={{display:'flex',alignItems:'center',justifyContent:'space-between',margin:'20px 0 8px'}}>
<div style={{fontSize:12,fontWeight:700,color:'var(--text3)', <div style={{fontSize:12,fontWeight:700,color:'var(--text3)',
textTransform:'uppercase',letterSpacing:'0.05em',margin:'20px 0 8px'}}> textTransform:'uppercase',letterSpacing:'0.05em'}}>
Mehrstufige Pipeline Mehrstufige Pipeline
</div> </div>
<div style={{padding:'10px 12px',background:'var(--warn-bg)',borderRadius:8, {(() => {
fontSize:12,color:'var(--warn-text)',marginBottom:12,lineHeight:1.6}}> const pipelinePrompt = prompts.find(p=>p.slug==='pipeline')
⚠️ <strong>Hinweis:</strong> Pipeline-Stage-1-Prompts müssen valides JSON zurückgeben. return pipelinePrompt && (
Halte das JSON-Format im Prompt erhalten. Stage 2 + 3 können frei angepasst werden. <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> </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=>{ {pipelinePrompts.map(p=>{
const isJson = jsonSlugs.includes(p.slug) const isJson = jsonSlugs.includes(p.slug)
return ( return (
<div key={p.id} className="card section-gap" <div key={p.id} className="card section-gap"
style={{borderLeft:`3px solid ${isJson?'var(--warn)':'var(--accent)'}`}}> 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={{display:'flex',alignItems:'center',gap:10}}>
<div style={{flex:1}}> <div style={{flex:1}}>
<div style={{fontWeight:600,fontSize:14,display:'flex',alignItems:'center',gap:8}}> <div style={{fontWeight:600,fontSize:14,display:'flex',alignItems:'center',gap:8}}>
{p.name} {p.name}
{isJson && <span style={{fontSize:10,background:'var(--warn-bg)', {isJson && <span style={{fontSize:10,background:'var(--warn-bg)',
color:'var(--warn-text)',padding:'1px 6px',borderRadius:4}}>JSON-Output</span>} 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> </div>
{p.description && <div style={{fontSize:12,color:'var(--text3)',marginTop:1}}>{p.description}</div>} {p.description && <div style={{fontSize:12,color:'var(--text3)',marginTop:1}}>{p.description}</div>}
</div> </div>
+23 -14
View File
@@ -147,7 +147,7 @@ function PeriodSelector({ value, onChange }) {
} }
// ── Body Section (Weight + Composition combined) ────────────────────────────── // ── Body Section (Weight + Composition combined) ──────────────────────────────
function BodySection({ weights, calipers, circs, profile, insights, onRequest, loadingSlug }) { function BodySection({ weights, calipers, circs, profile, insights, onRequest, loadingSlug, filterActiveSlugs }) {
const [period, setPeriod] = useState(90) const [period, setPeriod] = useState(90)
const sex = profile?.sex||'m' const sex = profile?.sex||'m'
const height = profile?.height||178 const height = profile?.height||178
@@ -394,14 +394,14 @@ function BodySection({ weights, calipers, circs, profile, insights, onRequest, l
</div> </div>
)} )}
<InsightBox insights={insights} slugs={['pipeline','koerper','gesundheit','ziele']} <InsightBox insights={insights} slugs={filterActiveSlugs(['pipeline','koerper','gesundheit','ziele'])}
onRequest={onRequest} loading={loadingSlug}/> onRequest={onRequest} loading={loadingSlug}/>
</div> </div>
) )
} }
// ── Nutrition Section ───────────────────────────────────────────────────────── // ── Nutrition Section ─────────────────────────────────────────────────────────
function NutritionSection({ nutrition, weights, profile, insights, onRequest, loadingSlug }) { function NutritionSection({ nutrition, weights, profile, insights, onRequest, loadingSlug, filterActiveSlugs }) {
const [period, setPeriod] = useState(30) const [period, setPeriod] = useState(30)
if (!nutrition?.length) return ( if (!nutrition?.length) return (
<EmptySection text="Noch keine Ernährungsdaten." to="/nutrition" toLabel="FDDB importieren"/> <EmptySection text="Noch keine Ernährungsdaten." to="/nutrition" toLabel="FDDB importieren"/>
@@ -579,13 +579,13 @@ function NutritionSection({ nutrition, weights, profile, insights, onRequest, lo
<div style={{fontSize:12,fontWeight:600,color:'var(--text3)',marginBottom:8}}>BEWERTUNG</div> <div style={{fontSize:12,fontWeight:600,color:'var(--text3)',marginBottom:8}}>BEWERTUNG</div>
{macroRules.map((item,i)=><RuleCard key={i} item={item}/>)} {macroRules.map((item,i)=><RuleCard key={i} item={item}/>)}
</div> </div>
<InsightBox insights={insights} slugs={['ernaehrung']} onRequest={onRequest} loading={loadingSlug}/> <InsightBox insights={insights} slugs={filterActiveSlugs(['ernaehrung'])} onRequest={onRequest} loading={loadingSlug}/>
</div> </div>
) )
} }
// ── Activity Section ────────────────────────────────────────────────────────── // ── Activity Section ──────────────────────────────────────────────────────────
function ActivitySection({ activities, insights, onRequest, loadingSlug }) { function ActivitySection({ activities, insights, onRequest, loadingSlug, filterActiveSlugs }) {
const [period, setPeriod] = useState(30) const [period, setPeriod] = useState(30)
if (!activities?.length) return ( if (!activities?.length) return (
<EmptySection text="Noch keine Aktivitätsdaten." to="/activity" toLabel="Aktivität erfassen"/> <EmptySection text="Noch keine Aktivitätsdaten." to="/activity" toLabel="Aktivität erfassen"/>
@@ -657,13 +657,13 @@ function ActivitySection({ activities, insights, onRequest, loadingSlug }) {
<div style={{fontSize:12,fontWeight:600,color:'var(--text3)',marginBottom:8}}>BEWERTUNG</div> <div style={{fontSize:12,fontWeight:600,color:'var(--text3)',marginBottom:8}}>BEWERTUNG</div>
{actRules.map((item,i)=><RuleCard key={i} item={item}/>)} {actRules.map((item,i)=><RuleCard key={i} item={item}/>)}
</div> </div>
<InsightBox insights={insights} slugs={['aktivitaet']} onRequest={onRequest} loading={loadingSlug}/> <InsightBox insights={insights} slugs={filterActiveSlugs(['aktivitaet'])} onRequest={onRequest} loading={loadingSlug}/>
</div> </div>
) )
} }
// ── Correlation Section ─────────────────────────────────────────────────────── // ── Correlation Section ───────────────────────────────────────────────────────
function CorrelationSection({ corrData, insights, profile, onRequest, loadingSlug }) { function CorrelationSection({ corrData, insights, profile, onRequest, loadingSlug, filterActiveSlugs }) {
const filtered = (corrData||[]).filter(d=>d.kcal&&d.weight) const filtered = (corrData||[]).filter(d=>d.kcal&&d.weight)
if (filtered.length < 5) return ( if (filtered.length < 5) return (
<EmptySection text="Für Korrelationen werden Gewichts- und Ernährungsdaten benötigt (mind. 5 gemeinsame Tage)."/> <EmptySection text="Für Korrelationen werden Gewichts- und Ernährungsdaten benötigt (mind. 5 gemeinsame Tage)."/>
@@ -852,7 +852,7 @@ function CorrelationSection({ corrData, insights, profile, onRequest, loadingSlu
</div> </div>
)} )}
<InsightBox insights={insights} slugs={['gesamt','ziele']} onRequest={onRequest} loading={loadingSlug}/> <InsightBox insights={insights} slugs={filterActiveSlugs(['gesamt','ziele'])} onRequest={onRequest} loading={loadingSlug}/>
</div> </div>
) )
} }
@@ -903,6 +903,7 @@ export default function History() {
const [activities, setActivities] = useState([]) const [activities, setActivities] = useState([])
const [corrData, setCorrData] = useState([]) const [corrData, setCorrData] = useState([])
const [insights, setInsights] = useState([]) const [insights, setInsights] = useState([])
const [prompts, setPrompts] = useState([])
const [profile, setProfile] = useState(null) const [profile, setProfile] = useState(null)
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [loadingSlug,setLoadingSlug]= useState(null) const [loadingSlug,setLoadingSlug]= useState(null)
@@ -911,10 +912,12 @@ export default function History() {
api.listWeight(365), api.listCaliper(), api.listCirc(), api.listWeight(365), api.listCaliper(), api.listCirc(),
api.listNutrition(90), api.listActivity(200), api.listNutrition(90), api.listActivity(200),
api.nutritionCorrelations(), api.latestInsights(), api.getProfile(), api.nutritionCorrelations(), api.latestInsights(), api.getProfile(),
]).then(([w,ca,ci,n,a,corr,ins,p])=>{ api.listPrompts(),
]).then(([w,ca,ci,n,a,corr,ins,p,pr])=>{
setWeights(w); setCalipers(ca); setCircs(ci) setWeights(w); setCalipers(ca); setCircs(ci)
setNutrition(n); setActivities(a); setCorrData(corr) setNutrition(n); setActivities(a); setCorrData(corr)
setInsights(Array.isArray(ins)?ins:[]); setProfile(p) setInsights(Array.isArray(ins)?ins:[]); setProfile(p)
setPrompts(Array.isArray(pr)?pr:[])
setLoading(false) setLoading(false)
}) })
@@ -923,17 +926,23 @@ export default function History() {
const requestInsight = async (slug) => { const requestInsight = async (slug) => {
setLoadingSlug(slug) setLoadingSlug(slug)
try { try {
const pid=localStorage.getItem('bodytrack_active_profile')||'' const result = await api.runInsight(slug)
const r=await api.runInsight(slug) // result is already JSON, not a Response object
if(!r.ok) throw new Error(await r.text())
const ins = await api.latestInsights() const ins = await api.latestInsights()
setInsights(Array.isArray(ins)?ins:[]) setInsights(Array.isArray(ins)?ins:[])
} catch(e){ alert('KI-Fehler: '+e.message) } } catch(e){
alert('KI-Fehler: '+e.message)
}
finally{ setLoadingSlug(null) } finally{ setLoadingSlug(null) }
} }
if(loading) return <div className="empty-state"><div className="spinner"/></div> if(loading) return <div className="empty-state"><div className="spinner"/></div>
const sp={insights,onRequest:requestInsight,loadingSlug}
// Filter active prompts
const activeSlugs = prompts.filter(p=>p.active).map(p=>p.slug)
const filterActiveSlugs = (slugs) => slugs.filter(s=>activeSlugs.includes(s))
const sp={insights,onRequest:requestInsight,loadingSlug,filterActiveSlugs}
return ( return (
<div> <div>
+119 -3
View File
@@ -1,5 +1,5 @@
import { useState } from 'react' import { useState } from 'react'
import { Save, Download, Trash2, Plus, Check, Pencil, X, LogOut, Shield, Key } from 'lucide-react' import { Save, Download, Upload, Trash2, Plus, Check, Pencil, X, LogOut, Shield, Key } from 'lucide-react'
import { useProfile } from '../context/ProfileContext' import { useProfile } from '../context/ProfileContext'
import { useAuth } from '../context/AuthContext' import { useAuth } from '../context/AuthContext'
import { Avatar } from './ProfileSelect' import { Avatar } from './ProfileSelect'
@@ -123,6 +123,73 @@ export default function SettingsPage() {
// editingId: string ID of profile being edited, or 'new' for new profile, or null // editingId: string ID of profile being edited, or 'new' for new profile, or null
const [editingId, setEditingId] = useState(null) const [editingId, setEditingId] = useState(null)
const [saved, setSaved] = useState(false) const [saved, setSaved] = useState(false)
const [importing, setImporting] = useState(false)
const [importMsg, setImportMsg] = useState(null)
const handleImport = async (e) => {
const file = e.target.files?.[0]
if (!file) return
if (!confirm(`Backup "${file.name}" importieren? Vorhandene Einträge werden nicht überschrieben.`)) {
e.target.value = '' // Reset file input
return
}
setImporting(true)
setImportMsg(null)
try {
const formData = new FormData()
formData.append('file', file)
const token = localStorage.getItem('bodytrack_token')||''
const pid = localStorage.getItem('bodytrack_active_profile')||''
const res = await fetch('/api/import/zip', {
method: 'POST',
headers: {
'X-Auth-Token': token,
'X-Profile-Id': pid
},
body: formData
})
const data = await res.json()
if (!res.ok) {
throw new Error(data.detail || 'Import fehlgeschlagen')
}
// Show success message with stats
const stats = data.stats
const lines = []
if (stats.weight > 0) lines.push(`${stats.weight} Gewicht`)
if (stats.circumferences > 0) lines.push(`${stats.circumferences} Umfänge`)
if (stats.caliper > 0) lines.push(`${stats.caliper} Caliper`)
if (stats.nutrition > 0) lines.push(`${stats.nutrition} Ernährung`)
if (stats.activity > 0) lines.push(`${stats.activity} Aktivität`)
if (stats.photos > 0) lines.push(`${stats.photos} Fotos`)
if (stats.insights > 0) lines.push(`${stats.insights} KI-Analysen`)
setImportMsg({
type: 'success',
text: `✓ Import erfolgreich: ${lines.join(', ')}`
})
// Refresh data (in case new entries were added)
await refreshProfiles()
} catch (err) {
setImportMsg({
type: 'error',
text: `✗ ${err.message}`
})
} finally {
setImporting(false)
e.target.value = '' // Reset file input
setTimeout(() => setImportMsg(null), 5000)
}
}
const handleSave = async (form, profileId) => { const handleSave = async (form, profileId) => {
const data = {} const data = {}
@@ -291,12 +358,12 @@ export default function SettingsPage() {
)} )}
{canExport && <> {canExport && <>
<button className="btn btn-primary btn-full" <button className="btn btn-primary btn-full"
onClick={()=>window.open('/api/export/zip')}> onClick={()=>api.exportZip()}>
<Download size={14}/> ZIP exportieren <Download size={14}/> ZIP exportieren
<span style={{fontSize:11,opacity:0.8,marginLeft:6}}>— je eine CSV pro Kategorie</span> <span style={{fontSize:11,opacity:0.8,marginLeft:6}}>— je eine CSV pro Kategorie</span>
</button> </button>
<button className="btn btn-secondary btn-full" <button className="btn btn-secondary btn-full"
onClick={()=>window.open('/api/export/json')}> onClick={()=>api.exportJson()}>
<Download size={14}/> JSON exportieren <Download size={14}/> JSON exportieren
<span style={{fontSize:11,opacity:0.8,marginLeft:6}}>— maschinenlesbar, alles in einer Datei</span> <span style={{fontSize:11,opacity:0.8,marginLeft:6}}>— maschinenlesbar, alles in einer Datei</span>
</button> </button>
@@ -307,6 +374,55 @@ export default function SettingsPage() {
</p> </p>
</div> </div>
{/* Import */}
<div className="card section-gap">
<div className="card-title">Backup importieren</div>
<p style={{fontSize:13,color:'var(--text2)',marginBottom:12,lineHeight:1.6}}>
Importiere einen ZIP-Export zurück in <strong>{activeProfile?.name}</strong>.
Vorhandene Einträge werden nicht überschrieben.
</p>
<div style={{display:'flex',flexDirection:'column',gap:8}}>
{!canExport && (
<div style={{padding:'10px 12px',background:'#FCEBEB',borderRadius:8,
fontSize:13,color:'#D85A30',marginBottom:8}}>
🔒 Import ist für dein Profil nicht freigeschaltet. Bitte den Admin kontaktieren.
</div>
)}
{canExport && (
<>
<label className="btn btn-primary btn-full"
style={{cursor:importing?'wait':'pointer',opacity:importing?0.6:1}}>
<input type="file" accept=".zip" onChange={handleImport}
disabled={importing}
style={{display:'none'}}/>
{importing ? (
<>Importiere...</>
) : (
<>
<Upload size={14}/> ZIP-Backup importieren
</>
)}
</label>
{importMsg && (
<div style={{
padding:'10px 12px',
background: importMsg.type === 'success' ? '#E1F5EE' : '#FCEBEB',
borderRadius:8,
fontSize:12,
color: importMsg.type === 'success' ? 'var(--accent)' : '#D85A30',
lineHeight:1.4
}}>
{importMsg.text}
</div>
)}
</>
)}
</div>
<p style={{fontSize:11,color:'var(--text3)',marginTop:8}}>
Der Import erkennt automatisch das Format und importiert nur neue Einträge.
</p>
</div>
{saved && ( {saved && (
<div style={{position:'fixed',bottom:80,left:'50%',transform:'translateX(-50%)', <div style={{position:'fixed',bottom:80,left:'50%',transform:'translateX(-50%)',
background:'var(--accent)',color:'white',padding:'8px 20px',borderRadius:20, background:'var(--accent)',color:'white',padding:'8px 20px',borderRadius:20,
+43 -4
View File
@@ -68,7 +68,10 @@ export const api = {
return fetch(`${BASE}/photos`,{method:'POST',body:fd,headers:hdrs()}).then(r=>r.json()) return fetch(`${BASE}/photos`,{method:'POST',body:fd,headers:hdrs()}).then(r=>r.json())
}, },
listPhotos: () => req('/photos'), listPhotos: () => req('/photos'),
photoUrl: (pid) => `${BASE}/photos/${pid}`, photoUrl: (pid) => {
const token = getToken()
return `${BASE}/photos/${pid}${token ? `?token=${token}` : ''}`
},
// Nutrition // Nutrition
importCsv: async(file)=>{ importCsv: async(file)=>{
@@ -88,9 +91,45 @@ export const api = {
insightPipeline: () => req('/insights/pipeline',{method:'POST'}), insightPipeline: () => req('/insights/pipeline',{method:'POST'}),
listInsights: () => req('/insights'), listInsights: () => req('/insights'),
latestInsights: () => req('/insights/latest'), latestInsights: () => req('/insights/latest'),
exportZip: () => window.open(`${BASE}/export/zip`), exportZip: async () => {
exportJson: () => window.open(`${BASE}/export/json`), const res = await fetch(`${BASE}/export/zip`, {headers: hdrs()})
exportCsv: () => window.open(`${BASE}/export/csv`), if (!res.ok) throw new Error('Export failed')
const blob = await res.blob()
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `mitai-export-${new Date().toISOString().split('T')[0]}.zip`
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
window.URL.revokeObjectURL(url)
},
exportJson: async () => {
const res = await fetch(`${BASE}/export/json`, {headers: hdrs()})
if (!res.ok) throw new Error('Export failed')
const blob = await res.blob()
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `mitai-export-${new Date().toISOString().split('T')[0]}.json`
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
window.URL.revokeObjectURL(url)
},
exportCsv: async () => {
const res = await fetch(`${BASE}/export/csv`, {headers: hdrs()})
if (!res.ok) throw new Error('Export failed')
const blob = await res.blob()
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `mitai-export-${new Date().toISOString().split('T')[0]}.csv`
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
window.URL.revokeObjectURL(url)
},
// Admin // Admin
adminListProfiles: () => req('/admin/profiles'), adminListProfiles: () => req('/admin/profiles'),