Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e6a542289 | ||
|
|
c7d283c0c9 | ||
|
|
d826524789 | ||
|
|
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
|
||||
|
||||
**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]
|
||||
```
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
"""
|
||||
Authentication and Authorization for Mitai Jinkendo
|
||||
|
||||
Provides password hashing, session management, and auth dependencies
|
||||
for FastAPI endpoints.
|
||||
"""
|
||||
import hashlib
|
||||
import secrets
|
||||
from typing import Optional
|
||||
from fastapi import Header, Query, HTTPException
|
||||
import bcrypt
|
||||
|
||||
from db import get_db, get_cursor
|
||||
|
||||
|
||||
def hash_pin(pin: str) -> str:
|
||||
"""Hash password with bcrypt. Falls back gracefully from legacy SHA256."""
|
||||
return bcrypt.hashpw(pin.encode(), bcrypt.gensalt()).decode()
|
||||
|
||||
|
||||
def verify_pin(pin: str, stored_hash: str) -> bool:
|
||||
"""Verify password - supports both bcrypt and legacy SHA256."""
|
||||
if not stored_hash:
|
||||
return False
|
||||
# Detect bcrypt hash (starts with $2b$ or $2a$)
|
||||
if stored_hash.startswith('$2'):
|
||||
try:
|
||||
return bcrypt.checkpw(pin.encode(), stored_hash.encode())
|
||||
except Exception:
|
||||
return False
|
||||
# Legacy SHA256 support (auto-upgrade to bcrypt on next login)
|
||||
return stored_hash == hashlib.sha256(pin.encode()).hexdigest()
|
||||
|
||||
|
||||
def make_token() -> str:
|
||||
"""Generate a secure random token for sessions."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def get_session(token: str):
|
||||
"""
|
||||
Get session data for a given token.
|
||||
|
||||
Returns session dict with profile info, or None if invalid/expired.
|
||||
"""
|
||||
if not token:
|
||||
return None
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT s.*, p.role, p.name, p.ai_enabled, p.ai_limit_day, p.export_enabled "
|
||||
"FROM sessions s JOIN profiles p ON s.profile_id=p.id "
|
||||
"WHERE s.token=%s AND s.expires_at > CURRENT_TIMESTAMP",
|
||||
(token,)
|
||||
)
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def require_auth(x_auth_token: Optional[str] = Header(default=None)):
|
||||
"""
|
||||
FastAPI dependency - requires valid authentication.
|
||||
|
||||
Usage:
|
||||
@app.get("/api/endpoint")
|
||||
def endpoint(session: dict = Depends(require_auth)):
|
||||
profile_id = session['profile_id']
|
||||
...
|
||||
|
||||
Raises:
|
||||
HTTPException 401 if not authenticated
|
||||
"""
|
||||
session = get_session(x_auth_token)
|
||||
if not session:
|
||||
raise HTTPException(401, "Nicht eingeloggt")
|
||||
return session
|
||||
|
||||
|
||||
def require_auth_flexible(x_auth_token: Optional[str] = Header(default=None), token: Optional[str] = Query(default=None)):
|
||||
"""
|
||||
FastAPI dependency - auth via header OR query parameter.
|
||||
|
||||
Used for endpoints accessed by <img> tags that can't send headers.
|
||||
|
||||
Usage:
|
||||
@app.get("/api/photos/{id}")
|
||||
def get_photo(id: str, session: dict = Depends(require_auth_flexible)):
|
||||
...
|
||||
|
||||
Raises:
|
||||
HTTPException 401 if not authenticated
|
||||
"""
|
||||
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)):
|
||||
"""
|
||||
FastAPI dependency - requires admin authentication.
|
||||
|
||||
Usage:
|
||||
@app.put("/api/admin/endpoint")
|
||||
def admin_endpoint(session: dict = Depends(require_admin)):
|
||||
...
|
||||
|
||||
Raises:
|
||||
HTTPException 401 if not authenticated
|
||||
HTTPException 403 if not admin
|
||||
"""
|
||||
session = get_session(x_auth_token)
|
||||
if not session:
|
||||
raise HTTPException(401, "Nicht eingeloggt")
|
||||
if session['role'] != 'admin':
|
||||
raise HTTPException(403, "Nur für Admins")
|
||||
return session
|
||||
@@ -148,3 +148,48 @@ def execute_write(conn, query: str, params: tuple = ()) -> None:
|
||||
"""
|
||||
with get_cursor(conn) as cur:
|
||||
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
|
||||
+490
-181
@@ -2,6 +2,7 @@ import os, csv, io, uuid, json, zipfile
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from fastapi import FastAPI, HTTPException, UploadFile, File, Header, Query, Depends
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
@@ -14,7 +15,13 @@ from slowapi.util import get_remote_address
|
||||
from slowapi.errors import RateLimitExceeded
|
||||
from starlette.requests import Request
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from db import get_db, get_cursor, r2d, init_db
|
||||
from auth import hash_pin, verify_pin, make_token, get_session, require_auth, require_auth_flexible, require_admin
|
||||
from models import (
|
||||
ProfileCreate, ProfileUpdate, WeightEntry, CircumferenceEntry,
|
||||
CaliperEntry, ActivityEntry, NutritionDay, LoginRequest,
|
||||
PasswordResetRequest, PasswordResetConfirm, AdminProfileUpdate
|
||||
)
|
||||
|
||||
DATA_DIR = Path(os.getenv("DATA_DIR", "./data"))
|
||||
PHOTOS_DIR = Path(os.getenv("PHOTOS_DIR", "./photos"))
|
||||
@@ -39,11 +46,14 @@ app.add_middleware(
|
||||
|
||||
AVATAR_COLORS = ['#1D9E75','#378ADD','#D85A30','#EF9F27','#7F77DD','#D4537E','#639922','#888780']
|
||||
|
||||
def init_db():
|
||||
"""Initialize database - Schema is loaded by startup.sh"""
|
||||
# Schema loading and migration handled by startup.sh
|
||||
# This function kept for backwards compatibility
|
||||
pass
|
||||
@app.on_event("startup")
|
||||
async def startup_event():
|
||||
"""Run migrations and initialization on startup."""
|
||||
try:
|
||||
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 ───────────────────────────────────────
|
||||
def get_pid(x_profile_id: Optional[str] = Header(default=None)) -> str:
|
||||
@@ -58,101 +68,11 @@ def get_pid(x_profile_id: Optional[str] = Header(default=None)) -> str:
|
||||
raise HTTPException(400, "Kein Profil gefunden")
|
||||
|
||||
# ── Models ────────────────────────────────────────────────────────────────────
|
||||
class ProfileCreate(BaseModel):
|
||||
name: str
|
||||
avatar_color: Optional[str] = '#1D9E75'
|
||||
sex: Optional[str] = 'm'
|
||||
dob: Optional[str] = None
|
||||
height: Optional[float] = 178
|
||||
goal_weight: Optional[float] = None
|
||||
goal_bf_pct: Optional[float] = None
|
||||
|
||||
class ProfileUpdate(BaseModel):
|
||||
name: Optional[str] = None
|
||||
avatar_color: Optional[str] = None
|
||||
sex: Optional[str] = None
|
||||
dob: Optional[str] = None
|
||||
height: Optional[float] = None
|
||||
goal_weight: Optional[float] = None
|
||||
goal_bf_pct: Optional[float] = None
|
||||
|
||||
class WeightEntry(BaseModel):
|
||||
date: str; weight: float; note: Optional[str]=None
|
||||
|
||||
class CircumferenceEntry(BaseModel):
|
||||
date: str
|
||||
c_neck: Optional[float]=None; c_chest: Optional[float]=None
|
||||
c_waist: Optional[float]=None; c_belly: Optional[float]=None
|
||||
c_hip: Optional[float]=None; c_thigh: Optional[float]=None
|
||||
c_calf: Optional[float]=None; c_arm: Optional[float]=None
|
||||
notes: Optional[str]=None; photo_id: Optional[str]=None
|
||||
|
||||
class CaliperEntry(BaseModel):
|
||||
date: str; sf_method: Optional[str]='jackson3'
|
||||
sf_chest: Optional[float]=None; sf_axilla: Optional[float]=None
|
||||
sf_triceps: Optional[float]=None; sf_subscap: Optional[float]=None
|
||||
sf_suprailiac: Optional[float]=None; sf_abdomen: Optional[float]=None
|
||||
sf_thigh: Optional[float]=None; sf_calf_med: Optional[float]=None
|
||||
sf_lowerback: Optional[float]=None; sf_biceps: Optional[float]=None
|
||||
body_fat_pct: Optional[float]=None; lean_mass: Optional[float]=None
|
||||
fat_mass: Optional[float]=None; notes: Optional[str]=None
|
||||
|
||||
class ActivityEntry(BaseModel):
|
||||
date: str; start_time: Optional[str]=None; end_time: Optional[str]=None
|
||||
activity_type: str; duration_min: Optional[float]=None
|
||||
kcal_active: Optional[float]=None; kcal_resting: Optional[float]=None
|
||||
hr_avg: Optional[float]=None; hr_max: Optional[float]=None
|
||||
distance_km: Optional[float]=None; rpe: Optional[int]=None
|
||||
source: Optional[str]='manual'; notes: Optional[str]=None
|
||||
|
||||
class NutritionDay(BaseModel):
|
||||
date: str; kcal: Optional[float]=None; protein_g: Optional[float]=None
|
||||
fat_g: Optional[float]=None; carbs_g: Optional[float]=None
|
||||
|
||||
# ── Profiles ──────────────────────────────────────────────────────────────────
|
||||
import hashlib, secrets
|
||||
from datetime import timedelta
|
||||
|
||||
def hash_pin(pin: str) -> str:
|
||||
"""Hash password with bcrypt. Falls back gracefully from legacy SHA256."""
|
||||
return bcrypt.hashpw(pin.encode(), bcrypt.gensalt()).decode()
|
||||
|
||||
def verify_pin(pin: str, stored_hash: str) -> bool:
|
||||
"""Verify password - supports both bcrypt and legacy SHA256."""
|
||||
if not stored_hash:
|
||||
return False
|
||||
# Detect bcrypt hash (starts with $2b$ or $2a$)
|
||||
if stored_hash.startswith('$2'):
|
||||
return bcrypt.checkpw(pin.encode(), stored_hash.encode())
|
||||
# Legacy SHA256 fallback - auto-upgrade on successful login
|
||||
import hashlib
|
||||
return hashlib.sha256(pin.encode()).hexdigest() == stored_hash
|
||||
|
||||
def make_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
def get_session(token: str):
|
||||
if not token: return None
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT s.*, p.role, p.name, p.ai_enabled, p.ai_limit_day, p.export_enabled "
|
||||
"FROM sessions s JOIN profiles p ON s.profile_id=p.id "
|
||||
"WHERE s.token=%s AND s.expires_at > CURRENT_TIMESTAMP", (token,)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return r2d(row)
|
||||
|
||||
def require_auth(x_auth_token: Optional[str]=Header(default=None)):
|
||||
session = get_session(x_auth_token)
|
||||
if not session: raise HTTPException(401, "Nicht eingeloggt")
|
||||
return session
|
||||
|
||||
def require_admin(x_auth_token: Optional[str]=Header(default=None)):
|
||||
session = get_session(x_auth_token)
|
||||
if not session: raise HTTPException(401, "Nicht eingeloggt")
|
||||
if session['role'] != 'admin': raise HTTPException(403, "Nur für Admins")
|
||||
return session
|
||||
# Models moved to models.py
|
||||
# Auth functions moved to auth.py
|
||||
|
||||
@app.get("/api/profiles")
|
||||
def list_profiles(session=Depends(require_auth)):
|
||||
@@ -268,9 +188,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,))
|
||||
rows = cur.fetchall()
|
||||
if not rows: return {"count":0,"latest":None,"prev":None,"min":None,"max":None,"avg_7d":None}
|
||||
w=[r['weight'] for r in rows]
|
||||
return {"count":len(rows),"latest":{"date":rows[0]['date'],"weight":rows[0]['weight']},
|
||||
"prev":{"date":rows[1]['date'],"weight":rows[1]['weight']} if len(rows)>1 else None,
|
||||
w=[float(r['weight']) for r in rows]
|
||||
return {"count":len(rows),"latest":{"date":rows[0]['date'],"weight":float(rows[0]['weight'])},
|
||||
"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)}
|
||||
|
||||
# ── Circumferences ────────────────────────────────────────────────────────────
|
||||
@@ -428,13 +348,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,))
|
||||
rows = [r2d(r) for r in cur.fetchall()]
|
||||
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_min=sum(r.get('duration_min') or 0 for r in rows)
|
||||
total_kcal=sum(float(r.get('kcal_active') or 0) for r in rows)
|
||||
total_min=sum(float(r.get('duration_min') or 0) for r in rows)
|
||||
by_type={}
|
||||
for r in rows:
|
||||
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]['min']+=r.get('duration_min') or 0
|
||||
by_type[t]['count']+=1
|
||||
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}
|
||||
|
||||
@app.post("/api/activity/import-csv")
|
||||
@@ -498,13 +419,17 @@ async def upload_photo(file: UploadFile=File(...), date: str="",
|
||||
return {"id":fid,"date":date}
|
||||
|
||||
@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:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT path FROM photos WHERE id=%s", (fid,))
|
||||
row = cur.fetchone()
|
||||
if not row: raise HTTPException(404)
|
||||
return FileResponse(row['path'])
|
||||
if not row: raise HTTPException(404, "Photo not found")
|
||||
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")
|
||||
def list_photos(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||
@@ -590,11 +515,13 @@ def nutrition_correlations(x_profile_id: Optional[str]=Header(default=None), ses
|
||||
for d in all_dates:
|
||||
if d not in nutr and d not in wlog: continue
|
||||
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 wlog: row['weight']=wlog[d]
|
||||
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']=float(wlog[d])
|
||||
if d in cal_by_date:
|
||||
row['lean_mass']=cal_by_date[d].get('lean_mass')
|
||||
row['body_fat_pct']=cal_by_date[d].get('body_fat_pct')
|
||||
lm = cal_by_date[d].get('lean_mass')
|
||||
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)
|
||||
return result
|
||||
|
||||
@@ -613,7 +540,7 @@ def nutrition_weekly(weeks: int=16, x_profile_id: Optional[str]=Header(default=N
|
||||
result=[]
|
||||
for wk in sorted(wm):
|
||||
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')})
|
||||
return result
|
||||
|
||||
@@ -768,10 +695,10 @@ def _prepare_template_vars(data: dict) -> dict:
|
||||
"name": prof.get('name', 'Nutzer'),
|
||||
"geschlecht": "männlich" if prof.get('sex') == 'm' else "weiblich",
|
||||
"height": prof.get('height', 178),
|
||||
"goal_weight": prof.get('goal_weight') or "nicht gesetzt",
|
||||
"goal_bf_pct": prof.get('goal_bf_pct') or "nicht gesetzt",
|
||||
"weight_aktuell": 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",
|
||||
"goal_weight": float(prof.get('goal_weight')) if prof.get('goal_weight') else "nicht gesetzt",
|
||||
"goal_bf_pct": float(prof.get('goal_bf_pct')) if prof.get('goal_bf_pct') else "nicht gesetzt",
|
||||
"weight_aktuell": float(weight[0]['weight']) if weight else "keine Daten",
|
||||
"kf_aktuell": float(caliper[0]['body_fat_pct']) if caliper and caliper[0].get('body_fat_pct') else "unbekannt",
|
||||
}
|
||||
|
||||
# Calculate age from dob
|
||||
@@ -790,7 +717,7 @@ def _prepare_template_vars(data: dict) -> dict:
|
||||
# Weight trend summary
|
||||
if len(weight) >= 2:
|
||||
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"
|
||||
else:
|
||||
vars['weight_trend'] = "zu wenig Daten"
|
||||
@@ -798,7 +725,8 @@ def _prepare_template_vars(data: dict) -> dict:
|
||||
# Caliper summary
|
||||
if caliper:
|
||||
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:
|
||||
vars['caliper_summary'] = "keine Daten"
|
||||
|
||||
@@ -807,7 +735,7 @@ def _prepare_template_vars(data: dict) -> dict:
|
||||
c = circ[0]
|
||||
parts = []
|
||||
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"
|
||||
else:
|
||||
vars['circ_summary'] = "keine Daten"
|
||||
@@ -815,15 +743,15 @@ def _prepare_template_vars(data: dict) -> dict:
|
||||
# Nutrition summary
|
||||
if nutrition:
|
||||
n = len(nutrition)
|
||||
avg_kcal = sum(d.get('kcal',0) for d in nutrition) / n
|
||||
avg_prot = sum(d.get('protein_g',0) for d in nutrition) / n
|
||||
avg_kcal = sum(float(d.get('kcal',0) or 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_detail'] = vars['nutrition_summary']
|
||||
vars['nutrition_days'] = n
|
||||
vars['kcal_avg'] = round(avg_kcal)
|
||||
vars['protein_avg'] = round(avg_prot,1)
|
||||
vars['fat_avg'] = round(sum(d.get('fat_g',0) for d in nutrition) / n,1)
|
||||
vars['carb_avg'] = round(sum(d.get('carbs_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(float(d.get('carbs_g',0) or 0) for d in nutrition) / n,1)
|
||||
else:
|
||||
vars['nutrition_summary'] = "keine Daten"
|
||||
vars['nutrition_detail'] = "keine Daten"
|
||||
@@ -835,13 +763,14 @@ def _prepare_template_vars(data: dict) -> dict:
|
||||
|
||||
# Protein targets
|
||||
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_high'] = round(w * 2.2)
|
||||
|
||||
# Activity summary
|
||||
if 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_detail'] = vars['activity_summary']
|
||||
vars['activity_kcal_summary'] = f"Ø {total_kcal/n:.0f}kcal/Training"
|
||||
@@ -1047,10 +976,22 @@ async def analyze_pipeline(x_profile_id: Optional[str]=Header(default=None), ses
|
||||
|
||||
@app.get("/api/prompts")
|
||||
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:
|
||||
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()]
|
||||
|
||||
@app.put("/api/prompts/{prompt_id}")
|
||||
@@ -1071,7 +1012,8 @@ def update_prompt(prompt_id: str, data: dict, session: dict=Depends(require_admi
|
||||
values.append(data['template'])
|
||||
if 'active' in data:
|
||||
updates.append('active=%s')
|
||||
values.append(data['active'])
|
||||
# Convert to boolean (accepts true/false, 1/0)
|
||||
values.append(bool(data['active']))
|
||||
|
||||
if updates:
|
||||
cur.execute(f"UPDATE ai_prompts SET {', '.join(updates)}, updated=CURRENT_TIMESTAMP WHERE id=%s",
|
||||
@@ -1105,17 +1047,6 @@ def get_ai_usage(x_profile_id: Optional[str]=Header(default=None), session: dict
|
||||
}
|
||||
|
||||
# ── Auth ──────────────────────────────────────────────────────────────────────
|
||||
class LoginRequest(BaseModel):
|
||||
email: str
|
||||
password: str
|
||||
|
||||
class PasswordResetRequest(BaseModel):
|
||||
email: str
|
||||
|
||||
class PasswordResetConfirm(BaseModel):
|
||||
token: str
|
||||
new_password: str
|
||||
|
||||
@app.post("/api/auth/login")
|
||||
@limiter.limit("5/minute")
|
||||
async def login(req: LoginRequest, request: Request):
|
||||
@@ -1171,7 +1102,7 @@ def auth_status():
|
||||
"""Health check endpoint."""
|
||||
return {"status": "ok", "service": "mitai-jinkendo", "version": "v9b"}
|
||||
|
||||
@app.post("/api/auth/pin")
|
||||
@app.put("/api/auth/pin")
|
||||
def change_pin(req: dict, session: dict=Depends(require_auth)):
|
||||
"""Change PIN/password for current user."""
|
||||
pid = session['profile_id']
|
||||
@@ -1263,12 +1194,6 @@ def password_reset_confirm(req: PasswordResetConfirm):
|
||||
return {"ok": True, "message": "Passwort erfolgreich zurückgesetzt"}
|
||||
|
||||
# ── Admin ─────────────────────────────────────────────────────────────────────
|
||||
class AdminProfileUpdate(BaseModel):
|
||||
role: Optional[str] = None
|
||||
ai_enabled: Optional[int] = None
|
||||
ai_limit_day: Optional[int] = None
|
||||
export_enabled: Optional[int] = None
|
||||
|
||||
@app.get("/api/admin/profiles")
|
||||
def admin_list_profiles(session: dict=Depends(require_admin)):
|
||||
"""Admin: List all profiles with stats."""
|
||||
@@ -1430,28 +1355,28 @@ def export_csv(x_profile_id: Optional[str]=Header(default=None), session: dict=D
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT date, weight, note FROM weight_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||
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
|
||||
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():
|
||||
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])
|
||||
|
||||
# Caliper
|
||||
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():
|
||||
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
|
||||
cur.execute("SELECT date, kcal, protein_g FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||
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
|
||||
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():
|
||||
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)
|
||||
return StreamingResponse(
|
||||
@@ -1499,7 +1424,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,))
|
||||
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(
|
||||
content=json_str,
|
||||
media_type="application/json",
|
||||
@@ -1508,62 +1438,441 @@ def export_json(x_profile_id: Optional[str]=Header(default=None), session: dict=
|
||||
|
||||
@app.get("/api/export/zip")
|
||||
def export_zip(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||
"""Export all data as ZIP (JSON + photos)."""
|
||||
"""Export all data as ZIP (CSV + JSON + photos) per specification."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
# Check export permission
|
||||
# Check export permission & get profile
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT export_enabled FROM profiles WHERE id=%s", (pid,))
|
||||
prof = cur.fetchone()
|
||||
if not prof or not prof['export_enabled']:
|
||||
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||
prof = r2d(cur.fetchone())
|
||||
if not prof or not prof.get('export_enabled'):
|
||||
raise HTTPException(403, "Export ist für dieses Profil deaktiviert")
|
||||
|
||||
# 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()
|
||||
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:
|
||||
# Add JSON data
|
||||
data = {}
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||
data['profile'] = r2d(cur.fetchone())
|
||||
# 1. README.txt
|
||||
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,))
|
||||
data['weight'] = [r2d(r) for r in cur.fetchall()]
|
||||
Inhalt:
|
||||
- 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,))
|
||||
data['circumferences'] = [r2d(r) for r in cur.fetchall()]
|
||||
Import:
|
||||
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,))
|
||||
data['caliper'] = [r2d(r) for r in cur.fetchall()]
|
||||
Format-Version 2 (ab v9b):
|
||||
Alle CSV-Dateien sind UTF-8 mit BOM kodiert.
|
||||
Trennzeichen: Semikolon (;)
|
||||
Datumsformat: YYYY-MM-DD
|
||||
"""
|
||||
zf.writestr("README.txt", readme.encode('utf-8'))
|
||||
|
||||
cur.execute("SELECT * FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||
data['nutrition'] = [r2d(r) for r in cur.fetchall()]
|
||||
# 2. profile.json (ohne Passwort-Hash)
|
||||
cur.execute("SELECT COUNT(*) as c FROM weight_log WHERE profile_id=%s", (pid,))
|
||||
w_count = cur.fetchone()['c']
|
||||
cur.execute("SELECT COUNT(*) as c FROM nutrition_log WHERE profile_id=%s", (pid,))
|
||||
n_count = cur.fetchone()['c']
|
||||
cur.execute("SELECT COUNT(*) as c FROM activity_log WHERE profile_id=%s", (pid,))
|
||||
a_count = cur.fetchone()['c']
|
||||
cur.execute("SELECT COUNT(*) as c FROM photos WHERE profile_id=%s", (pid,))
|
||||
p_count = cur.fetchone()['c']
|
||||
|
||||
cur.execute("SELECT * FROM activity_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||
data['activity'] = [r2d(r) for r in cur.fetchall()]
|
||||
profile_data = {
|
||||
"export_version": "2",
|
||||
"export_date": export_date,
|
||||
"app": "Mitai Jinkendo",
|
||||
"profile": {
|
||||
"name": prof.get('name'),
|
||||
"email": prof.get('email'),
|
||||
"sex": prof.get('sex'),
|
||||
"height": float(prof['height']) if prof.get('height') else None,
|
||||
"birth_year": prof['dob'].year if prof.get('dob') else None,
|
||||
"goal_weight": float(prof['goal_weight']) if prof.get('goal_weight') else None,
|
||||
"goal_bf_pct": float(prof['goal_bf_pct']) if prof.get('goal_bf_pct') else None,
|
||||
"avatar_color": prof.get('avatar_color'),
|
||||
"auth_type": prof.get('auth_type'),
|
||||
"session_days": prof.get('session_days'),
|
||||
"ai_enabled": prof.get('ai_enabled'),
|
||||
"tier": prof.get('tier')
|
||||
},
|
||||
"stats": {
|
||||
"weight_entries": w_count,
|
||||
"nutrition_entries": n_count,
|
||||
"activity_entries": a_count,
|
||||
"photos": p_count
|
||||
}
|
||||
}
|
||||
zf.writestr("profile.json", json.dumps(profile_data, indent=2, ensure_ascii=False).encode('utf-8'))
|
||||
|
||||
cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,))
|
||||
data['insights'] = [r2d(r) for r in cur.fetchall()]
|
||||
# 3. data/weight.csv
|
||||
cur.execute("SELECT id, date, weight, note, source, created FROM weight_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||
write_csv(zf, "weight.csv", [r2d(r) for r in cur.fetchall()],
|
||||
['id','date','weight','note','source','created'])
|
||||
|
||||
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
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
# 5. data/caliper.csv
|
||||
cur.execute("SELECT id, date, sf_chest, sf_abdomen, sf_thigh, sf_triceps, sf_subscap, sf_suprailiac, sf_axilla, sf_method, body_fat_pct, notes, created FROM caliper_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||
rows = [r2d(r) for r in cur.fetchall()]
|
||||
for r in rows:
|
||||
r['chest'] = r.pop('sf_chest', None)
|
||||
r['abdomen'] = r.pop('sf_abdomen', None)
|
||||
r['thigh'] = r.pop('sf_thigh', None)
|
||||
r['tricep'] = r.pop('sf_triceps', None)
|
||||
r['subscapular'] = r.pop('sf_subscap', None)
|
||||
r['suprailiac'] = r.pop('sf_suprailiac', None)
|
||||
r['midaxillary'] = r.pop('sf_axilla', None)
|
||||
r['method'] = r.pop('sf_method', None)
|
||||
r['bf_percent'] = r.pop('body_fat_pct', None)
|
||||
r['note'] = r.pop('notes', None)
|
||||
write_csv(zf, "caliper.csv", rows,
|
||||
['id','date','chest','abdomen','thigh','tricep','subscapular','suprailiac','midaxillary','method','bf_percent','note','created'])
|
||||
|
||||
# 6. data/nutrition.csv
|
||||
cur.execute("SELECT id, date, kcal, protein_g, fat_g, carbs_g, source, created FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||
rows = [r2d(r) for r in cur.fetchall()]
|
||||
for r in rows:
|
||||
r['meal_name'] = '' # not tracked per meal
|
||||
r['protein'] = r.pop('protein_g', None)
|
||||
r['fat'] = r.pop('fat_g', None)
|
||||
r['carbs'] = r.pop('carbs_g', None)
|
||||
r['fiber'] = None # not tracked
|
||||
r['note'] = ''
|
||||
write_csv(zf, "nutrition.csv", rows,
|
||||
['id','date','meal_name','kcal','protein','fat','carbs','fiber','note','source','created'])
|
||||
|
||||
# 7. data/activity.csv
|
||||
cur.execute("SELECT id, date, activity_type, duration_min, kcal_active, hr_avg, hr_max, distance_km, notes, source, created FROM activity_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||
rows = [r2d(r) for r in cur.fetchall()]
|
||||
for r in rows:
|
||||
r['name'] = r['activity_type']
|
||||
r['type'] = r.pop('activity_type', None)
|
||||
r['kcal'] = r.pop('kcal_active', None)
|
||||
r['heart_rate_avg'] = r.pop('hr_avg', None)
|
||||
r['heart_rate_max'] = r.pop('hr_max', None)
|
||||
r['note'] = r.pop('notes', None)
|
||||
write_csv(zf, "activity.csv", rows,
|
||||
['id','date','name','type','duration_min','kcal','heart_rate_avg','heart_rate_max','distance_km','note','source','created'])
|
||||
|
||||
# 8. insights/ai_insights.json
|
||||
cur.execute("SELECT id, scope, content, created FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,))
|
||||
insights = []
|
||||
for r in cur.fetchall():
|
||||
rd = r2d(r)
|
||||
insights.append({
|
||||
"id": rd['id'],
|
||||
"scope": rd['scope'],
|
||||
"created": rd['created'].isoformat() if hasattr(rd['created'], 'isoformat') else str(rd['created']),
|
||||
"result": rd['content']
|
||||
})
|
||||
if insights:
|
||||
zf.writestr("insights/ai_insights.json", json.dumps(insights, indent=2, ensure_ascii=False).encode('utf-8'))
|
||||
|
||||
# 9. photos/
|
||||
cur.execute("SELECT * FROM photos WHERE profile_id=%s ORDER BY date", (pid,))
|
||||
photos = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
for i, photo in enumerate(photos):
|
||||
photo_path = Path(PHOTOS_DIR) / photo['path']
|
||||
if photo_path.exists():
|
||||
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)
|
||||
filename = f"mitai-export-{profile_name.replace(' ','-')}-{export_date}.zip"
|
||||
return StreamingResponse(
|
||||
iter([zip_buffer.getvalue()]),
|
||||
media_type="application/zip",
|
||||
headers={"Content-Disposition": f"attachment; filename=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'],
|
||||
}
|
||||
|
||||
# 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
|
||||
@@ -173,8 +179,17 @@ def migrate_table(pg_conn, table: str) -> Dict[str, int]:
|
||||
# Convert rows
|
||||
converted_rows = [convert_row(row, table) for row in sqlite_rows]
|
||||
|
||||
# Get column names
|
||||
columns = list(converted_rows[0].keys())
|
||||
# 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())
|
||||
cols_str = ', '.join(columns)
|
||||
placeholders = ', '.join(['%s'] * len(columns))
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""
|
||||
Pydantic Models for Mitai Jinkendo API
|
||||
|
||||
Data validation schemas for request/response bodies.
|
||||
"""
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
# ── Profile Models ────────────────────────────────────────────────────────────
|
||||
|
||||
class ProfileCreate(BaseModel):
|
||||
name: str
|
||||
avatar_color: Optional[str] = '#1D9E75'
|
||||
sex: Optional[str] = 'm'
|
||||
dob: Optional[str] = None
|
||||
height: Optional[float] = 178
|
||||
goal_weight: Optional[float] = None
|
||||
goal_bf_pct: Optional[float] = None
|
||||
|
||||
|
||||
class ProfileUpdate(BaseModel):
|
||||
name: Optional[str] = None
|
||||
avatar_color: Optional[str] = None
|
||||
sex: Optional[str] = None
|
||||
dob: Optional[str] = None
|
||||
height: Optional[float] = None
|
||||
goal_weight: Optional[float] = None
|
||||
goal_bf_pct: Optional[float] = None
|
||||
|
||||
|
||||
# ── Tracking Models ───────────────────────────────────────────────────────────
|
||||
|
||||
class WeightEntry(BaseModel):
|
||||
date: str
|
||||
weight: float
|
||||
note: Optional[str] = None
|
||||
|
||||
|
||||
class CircumferenceEntry(BaseModel):
|
||||
date: str
|
||||
c_neck: Optional[float] = None
|
||||
c_chest: Optional[float] = None
|
||||
c_waist: Optional[float] = None
|
||||
c_belly: Optional[float] = None
|
||||
c_hip: Optional[float] = None
|
||||
c_thigh: Optional[float] = None
|
||||
c_calf: Optional[float] = None
|
||||
c_arm: Optional[float] = None
|
||||
notes: Optional[str] = None
|
||||
photo_id: Optional[str] = None
|
||||
|
||||
|
||||
class CaliperEntry(BaseModel):
|
||||
date: str
|
||||
sf_method: Optional[str] = 'jackson3'
|
||||
sf_chest: Optional[float] = None
|
||||
sf_axilla: Optional[float] = None
|
||||
sf_triceps: Optional[float] = None
|
||||
sf_subscap: Optional[float] = None
|
||||
sf_suprailiac: Optional[float] = None
|
||||
sf_abdomen: Optional[float] = None
|
||||
sf_thigh: Optional[float] = None
|
||||
sf_calf_med: Optional[float] = None
|
||||
sf_lowerback: Optional[float] = None
|
||||
sf_biceps: Optional[float] = None
|
||||
body_fat_pct: Optional[float] = None
|
||||
lean_mass: Optional[float] = None
|
||||
fat_mass: Optional[float] = None
|
||||
notes: Optional[str] = None
|
||||
|
||||
|
||||
class ActivityEntry(BaseModel):
|
||||
date: str
|
||||
start_time: Optional[str] = None
|
||||
end_time: Optional[str] = None
|
||||
activity_type: str
|
||||
duration_min: Optional[float] = None
|
||||
kcal_active: Optional[float] = None
|
||||
kcal_resting: Optional[float] = None
|
||||
hr_avg: Optional[float] = None
|
||||
hr_max: Optional[float] = None
|
||||
distance_km: Optional[float] = None
|
||||
rpe: Optional[int] = None
|
||||
source: Optional[str] = 'manual'
|
||||
notes: Optional[str] = None
|
||||
|
||||
|
||||
class NutritionDay(BaseModel):
|
||||
date: str
|
||||
kcal: Optional[float] = None
|
||||
protein_g: Optional[float] = None
|
||||
fat_g: Optional[float] = None
|
||||
carbs_g: Optional[float] = None
|
||||
|
||||
|
||||
# ── Auth Models ───────────────────────────────────────────────────────────────
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
email: str
|
||||
password: str
|
||||
|
||||
|
||||
class PasswordResetRequest(BaseModel):
|
||||
email: str
|
||||
|
||||
|
||||
class PasswordResetConfirm(BaseModel):
|
||||
token: str
|
||||
new_password: str
|
||||
|
||||
|
||||
# ── Admin Models ──────────────────────────────────────────────────────────────
|
||||
|
||||
class AdminProfileUpdate(BaseModel):
|
||||
role: Optional[str] = None
|
||||
ai_enabled: Optional[int] = None
|
||||
ai_limit_day: Optional[int] = None
|
||||
export_enabled: Optional[int] = None
|
||||
+1
-3
@@ -1,7 +1,7 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: mitai-db
|
||||
container_name: mitai-db-prod
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: mitai_prod
|
||||
@@ -9,8 +9,6 @@ services:
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-change_me_in_production}
|
||||
volumes:
|
||||
- mitai_postgres_data:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "127.0.0.1:5432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U mitai_prod"]
|
||||
interval: 10s
|
||||
|
||||
@@ -150,8 +150,11 @@ export default function Analysis() {
|
||||
}
|
||||
|
||||
const savePrompt = async (promptId, data) => {
|
||||
const token = localStorage.getItem('bodytrack_token')||''
|
||||
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()
|
||||
}
|
||||
@@ -176,6 +179,10 @@ export default function Analysis() {
|
||||
|
||||
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 (
|
||||
<div>
|
||||
<h1 className="page-title">KI-Analyse</h1>
|
||||
@@ -218,36 +225,38 @@ export default function Analysis() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pipeline button */}
|
||||
<div className="card" style={{marginBottom:16,borderColor:'var(--accent)',borderWidth:2}}>
|
||||
<div style={{display:'flex',alignItems:'flex-start',gap:12}}>
|
||||
<div style={{flex:1}}>
|
||||
<div style={{fontWeight:700,fontSize:15,color:'var(--accent)'}}>🔬 Mehrstufige Gesamtanalyse</div>
|
||||
<div style={{fontSize:12,color:'var(--text2)',marginTop:3,lineHeight:1.5}}>
|
||||
3 spezialisierte KI-Calls parallel (Körper + Ernährung + Aktivität),
|
||||
dann Synthese + Zielabgleich. Detaillierteste Auswertung.
|
||||
</div>
|
||||
{allInsights.find(i=>i.scope==='pipeline') && (
|
||||
<div style={{fontSize:11,color:'var(--text3)',marginTop:3}}>
|
||||
Letzte Analyse: {dayjs(allInsights.find(i=>i.scope==='pipeline').created).format('DD.MM.YYYY, HH:mm')}
|
||||
{/* Pipeline button - only if all sub-prompts are active */}
|
||||
{pipelineAvailable && (
|
||||
<div className="card" style={{marginBottom:16,borderColor:'var(--accent)',borderWidth:2}}>
|
||||
<div style={{display:'flex',alignItems:'flex-start',gap:12}}>
|
||||
<div style={{flex:1}}>
|
||||
<div style={{fontWeight:700,fontSize:15,color:'var(--accent)'}}>🔬 Mehrstufige Gesamtanalyse</div>
|
||||
<div style={{fontSize:12,color:'var(--text2)',marginTop:3,lineHeight:1.5}}>
|
||||
3 spezialisierte KI-Calls parallel (Körper + Ernährung + Aktivität),
|
||||
dann Synthese + Zielabgleich. Detaillierteste Auswertung.
|
||||
</div>
|
||||
)}
|
||||
{allInsights.find(i=>i.scope==='pipeline') && (
|
||||
<div style={{fontSize:11,color:'var(--text3)',marginTop:3}}>
|
||||
Letzte Analyse: {dayjs(allInsights.find(i=>i.scope==='pipeline').created).format('DD.MM.YYYY, HH:mm')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<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>
|
||||
<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>}
|
||||
{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>
|
||||
{pipelineLoading && (
|
||||
<div style={{marginTop:10,padding:'8px 12px',background:'var(--accent-light)',
|
||||
borderRadius:8,fontSize:12,color:'var(--accent-dark)'}}>
|
||||
⚡ Stufe 1: 3 parallele Analyse-Calls… dann Synthese… dann Zielabgleich
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!canUseAI && (
|
||||
<div style={{padding:'14px 16px',background:'#FCEBEB',borderRadius:10,
|
||||
@@ -345,21 +354,26 @@ export default function Analysis() {
|
||||
Einzelanalysen
|
||||
</div>
|
||||
{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={{flex:1}}>
|
||||
<div style={{fontWeight:600,fontSize:14,display:'flex',alignItems:'center',gap:8}}>
|
||||
{SLUG_LABELS[p.slug]||p.name}
|
||||
{!p.active && <span style={{fontSize:10,color:'var(--text3)',
|
||||
background:'var(--surface2)',padding:'1px 6px',borderRadius:4}}>Inaktiv</span>}
|
||||
{!p.active && <span style={{fontSize:10,color:'#D85A30',
|
||||
background:'#FCEBEB',padding:'2px 8px',borderRadius:4,fontWeight:600}}>⏸ Deaktiviert</span>}
|
||||
</div>
|
||||
{p.description && <div style={{fontSize:12,color:'var(--text3)',marginTop:1}}>{p.description}</div>}
|
||||
</div>
|
||||
<button className="btn btn-secondary" style={{padding:'5px 8px',fontSize:12}}
|
||||
onClick={()=>fetch(`/api/prompts/${p.id}`,{method:'PUT',
|
||||
headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({active:p.active?0:1})}).then(loadAll)}>
|
||||
{p.active?'Deaktiv.':'Aktiv.'}
|
||||
onClick={()=>{
|
||||
const token = localStorage.getItem('bodytrack_token')||''
|
||||
fetch(`/api/prompts/${p.id}`,{
|
||||
method:'PUT',
|
||||
headers:{'Content-Type':'application/json','X-Auth-Token':token},
|
||||
body:JSON.stringify({active:!p.active})
|
||||
}).then(loadAll)
|
||||
}}>
|
||||
{p.active?'Deaktivieren':'Aktivieren'}
|
||||
</button>
|
||||
<button className="btn btn-secondary" style={{padding:'5px 8px'}}
|
||||
onClick={()=>setEditing(p)}><Pencil size={13}/></button>
|
||||
@@ -372,26 +386,60 @@ export default function Analysis() {
|
||||
))}
|
||||
|
||||
{/* Pipeline prompts */}
|
||||
<div style={{fontSize:12,fontWeight:700,color:'var(--text3)',
|
||||
textTransform:'uppercase',letterSpacing:'0.05em',margin:'20px 0 8px'}}>
|
||||
Mehrstufige Pipeline
|
||||
</div>
|
||||
<div style={{padding:'10px 12px',background:'var(--warn-bg)',borderRadius:8,
|
||||
fontSize:12,color:'var(--warn-text)',marginBottom:12,lineHeight:1.6}}>
|
||||
⚠️ <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.
|
||||
<div style={{display:'flex',alignItems:'center',justifyContent:'space-between',margin:'20px 0 8px'}}>
|
||||
<div style={{fontSize:12,fontWeight:700,color:'var(--text3)',
|
||||
textTransform:'uppercase',letterSpacing:'0.05em'}}>
|
||||
Mehrstufige Pipeline
|
||||
</div>
|
||||
{(() => {
|
||||
const pipelinePrompt = prompts.find(p=>p.slug==='pipeline')
|
||||
return pipelinePrompt && (
|
||||
<button className="btn btn-secondary" style={{padding:'5px 12px',fontSize:12}}
|
||||
onClick={()=>{
|
||||
const token = localStorage.getItem('bodytrack_token')||''
|
||||
fetch(`/api/prompts/${pipelinePrompt.id}`,{
|
||||
method:'PUT',
|
||||
headers:{'Content-Type':'application/json','X-Auth-Token':token},
|
||||
body:JSON.stringify({active:!pipelinePrompt.active})
|
||||
}).then(loadAll)
|
||||
}}>
|
||||
{pipelinePrompt.active ? 'Gesamte Pipeline deaktivieren' : 'Gesamte Pipeline aktivieren'}
|
||||
</button>
|
||||
)
|
||||
})()}
|
||||
</div>
|
||||
{(() => {
|
||||
const pipelinePrompt = prompts.find(p=>p.slug==='pipeline')
|
||||
const isPipelineActive = pipelinePrompt?.active ?? true
|
||||
return (
|
||||
<div style={{padding:'10px 12px',
|
||||
background: isPipelineActive ? 'var(--warn-bg)' : '#FCEBEB',
|
||||
borderRadius:8,fontSize:12,
|
||||
color: isPipelineActive ? 'var(--warn-text)' : '#D85A30',
|
||||
marginBottom:12,lineHeight:1.6}}>
|
||||
{isPipelineActive ? (
|
||||
<>⚠️ <strong>Hinweis:</strong> Pipeline-Stage-1-Prompts müssen valides JSON zurückgeben.
|
||||
Halte das JSON-Format im Prompt erhalten. Stage 2 + 3 können frei angepasst werden.</>
|
||||
) : (
|
||||
<>⏸ <strong>Pipeline deaktiviert:</strong> Die mehrstufige Gesamtanalyse ist aktuell nicht verfügbar.
|
||||
Aktiviere sie mit dem Schalter oben, um sie auf der Analyse-Seite zu nutzen.</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})()}
|
||||
{pipelinePrompts.map(p=>{
|
||||
const isJson = jsonSlugs.includes(p.slug)
|
||||
return (
|
||||
<div key={p.id} className="card section-gap"
|
||||
style={{borderLeft:`3px solid ${isJson?'var(--warn)':'var(--accent)'}`}}>
|
||||
style={{borderLeft:`3px solid ${isJson?'var(--warn)':'var(--accent)'}`,opacity:p.active?1:0.6}}>
|
||||
<div style={{display:'flex',alignItems:'center',gap:10}}>
|
||||
<div style={{flex:1}}>
|
||||
<div style={{fontWeight:600,fontSize:14,display:'flex',alignItems:'center',gap:8}}>
|
||||
{p.name}
|
||||
{isJson && <span style={{fontSize:10,background:'var(--warn-bg)',
|
||||
color:'var(--warn-text)',padding:'1px 6px',borderRadius:4}}>JSON-Output</span>}
|
||||
{!p.active && <span style={{fontSize:10,color:'#D85A30',
|
||||
background:'#FCEBEB',padding:'2px 8px',borderRadius:4,fontWeight:600}}>⏸ Deaktiviert</span>}
|
||||
</div>
|
||||
{p.description && <div style={{fontSize:12,color:'var(--text3)',marginTop:1}}>{p.description}</div>}
|
||||
</div>
|
||||
|
||||
@@ -147,7 +147,7 @@ function PeriodSelector({ value, onChange }) {
|
||||
}
|
||||
|
||||
// ── 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 sex = profile?.sex||'m'
|
||||
const height = profile?.height||178
|
||||
@@ -394,14 +394,14 @@ function BodySection({ weights, calipers, circs, profile, insights, onRequest, l
|
||||
</div>
|
||||
)}
|
||||
|
||||
<InsightBox insights={insights} slugs={['pipeline','koerper','gesundheit','ziele']}
|
||||
<InsightBox insights={insights} slugs={filterActiveSlugs(['pipeline','koerper','gesundheit','ziele'])}
|
||||
onRequest={onRequest} loading={loadingSlug}/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Nutrition Section ─────────────────────────────────────────────────────────
|
||||
function NutritionSection({ nutrition, weights, profile, insights, onRequest, loadingSlug }) {
|
||||
function NutritionSection({ nutrition, weights, profile, insights, onRequest, loadingSlug, filterActiveSlugs }) {
|
||||
const [period, setPeriod] = useState(30)
|
||||
if (!nutrition?.length) return (
|
||||
<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>
|
||||
{macroRules.map((item,i)=><RuleCard key={i} item={item}/>)}
|
||||
</div>
|
||||
<InsightBox insights={insights} slugs={['ernaehrung']} onRequest={onRequest} loading={loadingSlug}/>
|
||||
<InsightBox insights={insights} slugs={filterActiveSlugs(['ernaehrung'])} onRequest={onRequest} loading={loadingSlug}/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Activity Section ──────────────────────────────────────────────────────────
|
||||
function ActivitySection({ activities, insights, onRequest, loadingSlug }) {
|
||||
function ActivitySection({ activities, insights, onRequest, loadingSlug, filterActiveSlugs }) {
|
||||
const [period, setPeriod] = useState(30)
|
||||
if (!activities?.length) return (
|
||||
<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>
|
||||
{actRules.map((item,i)=><RuleCard key={i} item={item}/>)}
|
||||
</div>
|
||||
<InsightBox insights={insights} slugs={['aktivitaet']} onRequest={onRequest} loading={loadingSlug}/>
|
||||
<InsightBox insights={insights} slugs={filterActiveSlugs(['aktivitaet'])} onRequest={onRequest} loading={loadingSlug}/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── 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)
|
||||
if (filtered.length < 5) return (
|
||||
<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>
|
||||
)}
|
||||
|
||||
<InsightBox insights={insights} slugs={['gesamt','ziele']} onRequest={onRequest} loading={loadingSlug}/>
|
||||
<InsightBox insights={insights} slugs={filterActiveSlugs(['gesamt','ziele'])} onRequest={onRequest} loading={loadingSlug}/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -903,6 +903,7 @@ export default function History() {
|
||||
const [activities, setActivities] = useState([])
|
||||
const [corrData, setCorrData] = useState([])
|
||||
const [insights, setInsights] = useState([])
|
||||
const [prompts, setPrompts] = useState([])
|
||||
const [profile, setProfile] = useState(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [loadingSlug,setLoadingSlug]= useState(null)
|
||||
@@ -911,10 +912,12 @@ export default function History() {
|
||||
api.listWeight(365), api.listCaliper(), api.listCirc(),
|
||||
api.listNutrition(90), api.listActivity(200),
|
||||
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)
|
||||
setNutrition(n); setActivities(a); setCorrData(corr)
|
||||
setInsights(Array.isArray(ins)?ins:[]); setProfile(p)
|
||||
setPrompts(Array.isArray(pr)?pr:[])
|
||||
setLoading(false)
|
||||
})
|
||||
|
||||
@@ -923,17 +926,23 @@ export default function History() {
|
||||
const requestInsight = async (slug) => {
|
||||
setLoadingSlug(slug)
|
||||
try {
|
||||
const pid=localStorage.getItem('bodytrack_active_profile')||''
|
||||
const r=await api.runInsight(slug)
|
||||
if(!r.ok) throw new Error(await r.text())
|
||||
const ins=await api.latestInsights()
|
||||
const result = await api.runInsight(slug)
|
||||
// result is already JSON, not a Response object
|
||||
const ins = await api.latestInsights()
|
||||
setInsights(Array.isArray(ins)?ins:[])
|
||||
} catch(e){ alert('KI-Fehler: '+e.message) }
|
||||
} catch(e){
|
||||
alert('KI-Fehler: '+e.message)
|
||||
}
|
||||
finally{ setLoadingSlug(null) }
|
||||
}
|
||||
|
||||
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 (
|
||||
<div>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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 { useAuth } from '../context/AuthContext'
|
||||
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
|
||||
const [editingId, setEditingId] = useState(null)
|
||||
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 data = {}
|
||||
@@ -291,12 +358,12 @@ export default function SettingsPage() {
|
||||
)}
|
||||
{canExport && <>
|
||||
<button className="btn btn-primary btn-full"
|
||||
onClick={()=>window.open('/api/export/zip')}>
|
||||
onClick={()=>api.exportZip()}>
|
||||
<Download size={14}/> ZIP exportieren
|
||||
<span style={{fontSize:11,opacity:0.8,marginLeft:6}}>— je eine CSV pro Kategorie</span>
|
||||
</button>
|
||||
<button className="btn btn-secondary btn-full"
|
||||
onClick={()=>window.open('/api/export/json')}>
|
||||
onClick={()=>api.exportJson()}>
|
||||
<Download size={14}/> JSON exportieren
|
||||
<span style={{fontSize:11,opacity:0.8,marginLeft:6}}>— maschinenlesbar, alles in einer Datei</span>
|
||||
</button>
|
||||
@@ -307,6 +374,55 @@ export default function SettingsPage() {
|
||||
</p>
|
||||
</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 && (
|
||||
<div style={{position:'fixed',bottom:80,left:'50%',transform:'translateX(-50%)',
|
||||
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())
|
||||
},
|
||||
listPhotos: () => req('/photos'),
|
||||
photoUrl: (pid) => `${BASE}/photos/${pid}`,
|
||||
photoUrl: (pid) => {
|
||||
const token = getToken()
|
||||
return `${BASE}/photos/${pid}${token ? `?token=${token}` : ''}`
|
||||
},
|
||||
|
||||
// Nutrition
|
||||
importCsv: async(file)=>{
|
||||
@@ -88,9 +91,45 @@ export const api = {
|
||||
insightPipeline: () => req('/insights/pipeline',{method:'POST'}),
|
||||
listInsights: () => req('/insights'),
|
||||
latestInsights: () => req('/insights/latest'),
|
||||
exportZip: () => window.open(`${BASE}/export/zip`),
|
||||
exportJson: () => window.open(`${BASE}/export/json`),
|
||||
exportCsv: () => window.open(`${BASE}/export/csv`),
|
||||
exportZip: async () => {
|
||||
const res = await fetch(`${BASE}/export/zip`, {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]}.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
|
||||
adminListProfiles: () => req('/admin/profiles'),
|
||||
|
||||
Reference in new issue
Block a user