Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
548d733048 | ||
|
|
6845397866 | ||
|
|
2df70b2a6b | ||
|
|
85f48907a4 | ||
|
|
c40b30737a | ||
|
|
961f905279 | ||
|
|
3f4ef75463 | ||
|
|
4886f00826 | ||
|
|
518e417b1d | ||
|
|
115d975335 | ||
|
|
e10e9d7eb9 | ||
|
|
b6f8b11685 | ||
|
|
64d1b9bf7b | ||
|
|
a0660e7a40 | ||
|
|
0797a8f55c | ||
|
|
47a268f426 | ||
|
|
f7f7f745b1 |
No files matched your search
@@ -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]
|
||||||
|
```
|
||||||
@@ -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
|
||||||
+486
-70
@@ -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)
|
||||||
|
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}")
|
@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)}")
|
||||||
@@ -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
@@ -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
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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'),
|
||||||
|
|||||||
Reference in new issue
Block a user