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
9 changed files with 973 additions and 142 deletions

No files matched your search

+145
View File
@@ -502,3 +502,148 @@ count = cur.fetchone()['count'] # Dict key
- Prompt-Bearbeitung: PUT-Endpoint für Admins - Prompt-Bearbeitung: PUT-Endpoint für Admins
**Tool:** Vollständiger Audit via Explore-Agent empfohlen bei größeren Änderungen **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
+487 -71
View File
@@ -2,6 +2,7 @@ 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
@@ -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"
@@ -1047,10 +1066,22 @@ 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)
cur.execute("SELECT * FROM ai_prompts WHERE active=true AND slug NOT LIKE 'pipeline_%' ORDER BY sort_order") 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")
return [r2d(r) for r in cur.fetchall()] return [r2d(r) for r in cur.fetchall()]
@app.put("/api/prompts/{prompt_id}") @app.put("/api/prompts/{prompt_id}")
@@ -1071,7 +1102,8 @@ def update_prompt(prompt_id: str, data: dict, session: dict=Depends(require_admi
values.append(data['template']) values.append(data['template'])
if 'active' in data: if 'active' in data:
updates.append('active=%s') updates.append('active=%s')
values.append(data['active']) # Convert to boolean (accepts true/false, 1/0)
values.append(bool(data['active']))
if updates: if updates:
cur.execute(f"UPDATE ai_prompts SET {', '.join(updates)}, updated=CURRENT_TIMESTAMP WHERE id=%s", cur.execute(f"UPDATE ai_prompts SET {', '.join(updates)}, updated=CURRENT_TIMESTAMP WHERE id=%s",
@@ -1430,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(
@@ -1499,7 +1531,12 @@ def export_json(x_profile_id: Optional[str]=Header(default=None), session: dict=
cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,)) cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,))
data['insights'] = [r2d(r) for r in cur.fetchall()] data['insights'] = [r2d(r) for r in cur.fetchall()]
json_str = json.dumps(data, indent=2, default=str) 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( return Response(
content=json_str, content=json_str,
media_type="application/json", media_type="application/json",
@@ -1508,62 +1545,441 @@ def export_json(x_profile_id: Optional[str]=Header(default=None), session: dict=
@app.get("/api/export/zip") @app.get("/api/export/zip")
def export_zip(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)): def export_zip(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Export all data as ZIP (JSON + photos).""" """Export all data as ZIP (CSV + JSON + photos) per specification."""
pid = get_pid(x_profile_id) pid = get_pid(x_profile_id)
# Check export permission # Check export permission & get profile
with get_db() as conn: with get_db() as conn:
cur = get_cursor(conn) cur = get_cursor(conn)
cur.execute("SELECT export_enabled FROM profiles WHERE id=%s", (pid,)) cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
prof = cur.fetchone() prof = r2d(cur.fetchone())
if not prof or not prof['export_enabled']: if not prof or not prof.get('export_enabled'):
raise HTTPException(403, "Export ist für dieses Profil deaktiviert") raise HTTPException(403, "Export ist für dieses Profil deaktiviert")
# Create ZIP in memory # 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() 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 zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zf:
# Add JSON data
data = {}
with get_db() as conn: with get_db() as conn:
cur = get_cursor(conn) cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,)) # 1. README.txt
data['profile'] = r2d(cur.fetchone()) readme = f"""Mitai Jinkendo – Datenexport
Version: 2
Exportiert am: {export_date}
Profil: {profile_name}
cur.execute("SELECT * FROM weight_log WHERE profile_id=%s ORDER BY date", (pid,)) Inhalt:
data['weight'] = [r2d(r) for r in cur.fetchall()] - profile.json: Profildaten und Einstellungen
- data/*.csv: Messdaten (Semikolon-getrennt, UTF-8)
- insights/: KI-Auswertungen (JSON)
- photos/: Progress-Fotos (JPEG)
cur.execute("SELECT * FROM circumference_log WHERE profile_id=%s ORDER BY date", (pid,)) Import:
data['circumferences'] = [r2d(r) for r in cur.fetchall()] Dieser Export kann in Mitai Jinkendo unter
Einstellungen → Import → "Mitai Backup importieren"
wieder eingespielt werden.
cur.execute("SELECT * FROM caliper_log WHERE profile_id=%s ORDER BY date", (pid,)) Format-Version 2 (ab v9b):
data['caliper'] = [r2d(r) for r in cur.fetchall()] Alle CSV-Dateien sind UTF-8 mit BOM kodiert.
Trennzeichen: Semikolon (;)
Datumsformat: YYYY-MM-DD
"""
zf.writestr("README.txt", readme.encode('utf-8'))
cur.execute("SELECT * FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,)) # 2. profile.json (ohne Passwort-Hash)
data['nutrition'] = [r2d(r) for r in cur.fetchall()] 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']
cur.execute("SELECT * FROM activity_log WHERE profile_id=%s ORDER BY date", (pid,)) profile_data = {
data['activity'] = [r2d(r) for r in cur.fetchall()] "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'))
cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,)) # 3. data/weight.csv
data['insights'] = [r2d(r) for r in cur.fetchall()] 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'])
zf.writestr("data.json", json.dumps(data, indent=2, default=str)) # 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'])
# Add photos if they exist # 5. data/caliper.csv
with get_db() as conn: 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,))
cur = get_cursor(conn) 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,)) cur.execute("SELECT * FROM photos WHERE profile_id=%s ORDER BY date", (pid,))
photos = [r2d(r) for r in cur.fetchall()] photos = [r2d(r) for r in cur.fetchall()]
for i, photo in enumerate(photos): for i, photo in enumerate(photos):
photo_path = Path(PHOTOS_DIR) / photo['path'] photo_path = Path(PHOTOS_DIR) / photo['path']
if photo_path.exists(): if photo_path.exists():
zf.write(photo_path, f"photos/{photo['date'] or i}_{photo_path.name}") filename = f"{photo.get('date') or export_date}_{i+1}{photo_path.suffix}"
zf.write(photo_path, f"photos/{filename}")
zip_buffer.seek(0) zip_buffer.seek(0)
filename = f"mitai-export-{profile_name.replace(' ','-')}-{export_date}.zip"
return StreamingResponse( return StreamingResponse(
iter([zip_buffer.getvalue()]), iter([zip_buffer.getvalue()]),
media_type="application/zip", media_type="application/zip",
headers={"Content-Disposition": f"attachment; filename=mitai-export-{pid}.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)}")
+17 -2
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,8 +179,17 @@ 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
columns = list(converted_rows[0].keys()) 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())
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
+92 -44
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,36 +225,38 @@ export default function Analysis() {
</div> </div>
)} )}
{/* Pipeline button */} {/* Pipeline button - only if all sub-prompts are active */}
<div className="card" style={{marginBottom:16,borderColor:'var(--accent)',borderWidth:2}}> {pipelineAvailable && (
<div style={{display:'flex',alignItems:'flex-start',gap:12}}> <div className="card" style={{marginBottom:16,borderColor:'var(--accent)',borderWidth:2}}>
<div style={{flex:1}}> <div style={{display:'flex',alignItems:'flex-start',gap:12}}>
<div style={{fontWeight:700,fontSize:15,color:'var(--accent)'}}>🔬 Mehrstufige Gesamtanalyse</div> <div style={{flex:1}}>
<div style={{fontSize:12,color:'var(--text2)',marginTop:3,lineHeight:1.5}}> <div style={{fontWeight:700,fontSize:15,color:'var(--accent)'}}>🔬 Mehrstufige Gesamtanalyse</div>
3 spezialisierte KI-Calls parallel (Körper + Ernährung + Aktivität), <div style={{fontSize:12,color:'var(--text2)',marginTop:3,lineHeight:1.5}}>
dann Synthese + Zielabgleich. Detaillierteste Auswertung. 3 spezialisierte KI-Calls parallel (Körper + Ernährung + Aktivität),
</div> dann Synthese + Zielabgleich. Detaillierteste Auswertung.
{allInsights.find(i=>i.scope==='pipeline') && (
<div style={{fontSize:11,color:'var(--text3)',marginTop:3}}>
Letzte Analyse: {dayjs(allInsights.find(i=>i.scope==='pipeline').created).format('DD.MM.YYYY, HH:mm')}
</div> </div>
)} {allInsights.find(i=>i.scope==='pipeline') && (
<div style={{fontSize:11,color:'var(--text3)',marginTop:3}}>
Letzte Analyse: {dayjs(allInsights.find(i=>i.scope==='pipeline').created).format('DD.MM.YYYY, HH:mm')}
</div>
)}
</div>
<button className="btn btn-primary" style={{flexShrink:0,minWidth:100}}
onClick={runPipeline} disabled={!!loading||pipelineLoading}>
{pipelineLoading
? <><div className="spinner" style={{width:13,height:13}}/> Läuft…</>
: <><Brain size={13}/> Starten</>}
</button>
{!canUseAI && <div style={{fontSize:11,color:'#D85A30',marginTop:4}}>🔒 KI nicht freigeschaltet</div>}
</div> </div>
<button className="btn btn-primary" style={{flexShrink:0,minWidth:100}} {pipelineLoading && (
onClick={runPipeline} disabled={!!loading||pipelineLoading}> <div style={{marginTop:10,padding:'8px 12px',background:'var(--accent-light)',
{pipelineLoading borderRadius:8,fontSize:12,color:'var(--accent-dark)'}}>
? <><div className="spinner" style={{width:13,height:13}}/> Läuft…</> ⚡ Stufe 1: 3 parallele Analyse-Calls… dann Synthese… dann Zielabgleich
: <><Brain size={13}/> Starten</>} </div>
</button> )}
{!canUseAI && <div style={{fontSize:11,color:'#D85A30',marginTop:4}}>🔒 KI nicht freigeschaltet</div>}
</div> </div>
{pipelineLoading && ( )}
<div style={{marginTop:10,padding:'8px 12px',background:'var(--accent-light)',
borderRadius:8,fontSize:12,color:'var(--accent-dark)'}}>
⚡ Stufe 1: 3 parallele Analyse-Calls… dann Synthese… dann Zielabgleich
</div>
)}
</div>
{!canUseAI && ( {!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={{fontSize:12,fontWeight:700,color:'var(--text3)', <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',margin:'20px 0 8px'}}>
textTransform:'uppercase',letterSpacing:'0.05em',margin:'20px 0 8px'}}> <div style={{fontSize:12,fontWeight:700,color:'var(--text3)',
Mehrstufige Pipeline textTransform:'uppercase',letterSpacing:'0.05em'}}>
</div> Mehrstufige Pipeline
<div style={{padding:'10px 12px',background:'var(--warn-bg)',borderRadius:8, </div>
fontSize:12,color:'var(--warn-text)',marginBottom:12,lineHeight:1.6}}> {(() => {
⚠️ <strong>Hinweis:</strong> Pipeline-Stage-1-Prompts müssen valides JSON zurückgeben. const pipelinePrompt = prompts.find(p=>p.slug==='pipeline')
Halte das JSON-Format im Prompt erhalten. Stage 2 + 3 können frei angepasst werden. return pipelinePrompt && (
<button className="btn btn-secondary" style={{padding:'5px 12px',fontSize:12}}
onClick={()=>{
const token = localStorage.getItem('bodytrack_token')||''
fetch(`/api/prompts/${pipelinePrompt.id}`,{
method:'PUT',
headers:{'Content-Type':'application/json','X-Auth-Token':token},
body:JSON.stringify({active:!pipelinePrompt.active})
}).then(loadAll)
}}>
{pipelinePrompt.active ? 'Gesamte Pipeline deaktivieren' : 'Gesamte Pipeline aktivieren'}
</button>
)
})()}
</div> </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>
+24 -15
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'),