Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e6a542289 | ||
|
|
c7d283c0c9 | ||
|
|
d826524789 | ||
|
|
548d733048 | ||
|
|
6845397866 | ||
|
|
2df70b2a6b | ||
|
|
85f48907a4 | ||
|
|
c40b30737a | ||
|
|
961f905279 | ||
|
|
3f4ef75463 | ||
|
|
4886f00826 | ||
|
|
518e417b1d | ||
|
|
115d975335 | ||
|
|
e10e9d7eb9 | ||
|
|
b6f8b11685 | ||
|
|
64d1b9bf7b | ||
|
|
a0660e7a40 | ||
|
|
0797a8f55c | ||
|
|
47a268f426 | ||
|
|
f7f7f745b1 | ||
|
|
8e25b54cc2 | ||
|
|
1db780858b |
No files matched your search
@@ -10,7 +10,7 @@
|
||||
|-----------|-------------|---------|
|
||||
| Frontend | React 18 + Vite + PWA | Node 20 |
|
||||
| Backend | FastAPI (Python) | Python 3.12 |
|
||||
| Datenbank | SQLite (v9a) → PostgreSQL (v9b geplant) | - |
|
||||
| Datenbank | PostgreSQL 16 (Alpine) | v9b |
|
||||
| Container | Docker + Docker Compose | - |
|
||||
| Webserver | nginx (Reverse Proxy) | Alpine |
|
||||
| Auth | Token-basiert + bcrypt | - |
|
||||
@@ -53,36 +53,38 @@ mitai-jinkendo/
|
||||
└── CLAUDE.md # Diese Datei
|
||||
```
|
||||
|
||||
## Aktuelle Version: v9a
|
||||
## Aktuelle Version: v9b
|
||||
|
||||
### Was implementiert ist:
|
||||
- ✅ Multi-User mit E-Mail + Passwort Login (bcrypt)
|
||||
- ✅ Auth-Middleware auf ALLE Endpoints (44 Endpoints geschützt)
|
||||
- ✅ Auth-Middleware auf ALLE Endpoints (60+ Endpoints geschützt)
|
||||
- ✅ Rate Limiting (Login: 5/min, Reset: 3/min)
|
||||
- ✅ CORS konfigurierbar via ALLOWED_ORIGINS in .env
|
||||
- ✅ Admin/User Rollen, KI-Limits, Export-Berechtigungen
|
||||
- ✅ Gewicht, Umfänge, Caliper (4 Formeln), Ernährung, Aktivität
|
||||
- ✅ FDDB CSV-Import (Ernährung), Apple Health CSV-Import (Aktivität)
|
||||
- ✅ KI-Analyse: 6 Einzel-Prompts + 3-stufige Pipeline (parallel)
|
||||
- ✅ Konfigurierbare Prompts mit Template-Variablen
|
||||
- ✅ Konfigurierbare Prompts mit Template-Variablen (Admin kann bearbeiten)
|
||||
- ✅ Verlauf mit 5 Tabs + Zeitraumfilter + KI pro Sektion
|
||||
- ✅ Dashboard mit Kennzahlen, Zielfortschritt, Combo-Chart
|
||||
- ✅ Assistent-Modus (Schritt-für-Schritt Messung)
|
||||
- ✅ PWA (iPhone Home Screen), Jinkendo Ensō-Logo
|
||||
- ✅ E-Mail (SMTP) für Password-Recovery
|
||||
- ✅ Admin-Panel: User verwalten, KI-Limits, E-Mail-Test
|
||||
- ✅ Admin-Panel: User verwalten, KI-Limits, E-Mail-Test, PIN/Email setzen
|
||||
- ✅ Multi-Environment: Prod (mitai.jinkendo.de) + Dev (dev.mitai.jinkendo.de)
|
||||
- ✅ Gitea CI/CD mit Auto-Deploy auf Raspberry Pi 5
|
||||
- ✅ PostgreSQL 16 Migration (vollständig von SQLite migriert)
|
||||
- ✅ Export: CSV, JSON, ZIP (mit Fotos)
|
||||
- ✅ Automatische SQLite→PostgreSQL Migration bei Container-Start
|
||||
|
||||
### Was in v9b kommt:
|
||||
- 🔲 PostgreSQL Migration (aktuell noch SQLite)
|
||||
### Was in v9c kommt:
|
||||
- 🔲 Selbst-Registrierung mit E-Mail-Bestätigung
|
||||
- 🔲 Freemium Tier-System (free/basic/premium/selfhosted)
|
||||
- 🔲 14-Tage Trial automatisch
|
||||
- 🔲 Einladungslinks für Beta-Nutzer
|
||||
- 🔲 Admin kann Tiers manuell setzen
|
||||
|
||||
### Was in v9c kommt:
|
||||
### Was in v9d kommt:
|
||||
- 🔲 OAuth2-Grundgerüst für Fitness-Connectoren
|
||||
- 🔲 Strava Connector
|
||||
- 🔲 Withings Connector (Waage)
|
||||
@@ -116,20 +118,24 @@ docker compose -f docker-compose.dev-env.yml build --no-cache
|
||||
docker compose -f docker-compose.dev-env.yml up -d
|
||||
```
|
||||
|
||||
## Datenbank-Schema (SQLite, v9a)
|
||||
## Datenbank-Schema (PostgreSQL 16, v9b)
|
||||
### Wichtige Tabellen:
|
||||
- `profiles` – Nutzer (role, pin_hash/bcrypt, email, auth_type, ai_enabled)
|
||||
- `profiles` – Nutzer (role, pin_hash/bcrypt, email, auth_type, ai_enabled, tier)
|
||||
- `sessions` – Auth-Tokens mit Ablaufdatum
|
||||
- `weight_log` – Gewichtseinträge (profile_id, date, weight)
|
||||
- `circumference_log` – 8 Umfangspunkte
|
||||
- `caliper_log` – Hautfaltenmessung, 4 Methoden
|
||||
- `nutrition_log` – Kalorien + Makros (aus FDDB-CSV)
|
||||
- `activity_log` – Training (aus Apple Health oder manuell)
|
||||
- `photos` – Progress Photos
|
||||
- `ai_insights` – KI-Auswertungen (scope = prompt-slug)
|
||||
- `ai_prompts` – Konfigurierbare Prompts mit Templates (11 Prompts)
|
||||
- `ai_usage` – KI-Calls pro Tag pro Profil
|
||||
|
||||
## Auth-Flow (v9a)
|
||||
**Schema-Datei:** `backend/schema.sql` (vollständiges PostgreSQL-Schema)
|
||||
**Migration-Script:** `backend/migrate_to_postgres.py` (SQLite→PostgreSQL, automatisch)
|
||||
|
||||
## Auth-Flow (v9b)
|
||||
```
|
||||
Login-Screen → E-Mail + Passwort → Token im localStorage
|
||||
Token → X-Auth-Token Header → Backend require_auth()
|
||||
@@ -146,29 +152,44 @@ SHA256 Passwörter → automatisch zu bcrypt migriert beim Login
|
||||
|
||||
## Umgebungsvariablen (.env)
|
||||
```
|
||||
OPENROUTER_API_KEY= # KI-Calls
|
||||
# Database (PostgreSQL)
|
||||
DB_HOST=postgres
|
||||
DB_PORT=5432
|
||||
DB_NAME=mitai_prod
|
||||
DB_USER=mitai_prod
|
||||
DB_PASSWORD= # REQUIRED
|
||||
|
||||
# AI
|
||||
OPENROUTER_API_KEY= # KI-Calls (optional, alternativ ANTHROPIC_API_KEY)
|
||||
OPENROUTER_MODEL=anthropic/claude-sonnet-4
|
||||
SMTP_HOST= # E-Mail
|
||||
ANTHROPIC_API_KEY= # Direkte Anthropic API (optional)
|
||||
|
||||
# Email
|
||||
SMTP_HOST= # E-Mail (für Recovery)
|
||||
SMTP_PORT=587
|
||||
SMTP_USER=
|
||||
SMTP_PASS=
|
||||
SMTP_FROM=
|
||||
|
||||
# App
|
||||
APP_URL=https://mitai.jinkendo.de
|
||||
ALLOWED_ORIGINS=https://mitai.jinkendo.de
|
||||
DATA_DIR=/app/data
|
||||
PHOTOS_DIR=/app/photos
|
||||
ENVIRONMENT=production
|
||||
```
|
||||
|
||||
## Wichtige Hinweise für Claude Code
|
||||
1. **Ports immer 3002/8002 (Prod) oder 3099/8099 (Dev)** – nie ändern
|
||||
2. **npm install** (nicht npm ci) – kein package-lock.json vorhanden
|
||||
3. **SQLite safe_alters** – neue Spalten immer via safe_alters Liste
|
||||
3. **PostgreSQL-Migrations** – Schema-Änderungen in `backend/schema.sql`, dann Container neu bauen
|
||||
4. **Pipeline-Prompts** haben slug-Prefix `pipeline_` – nie als Einzelanalyse zeigen
|
||||
5. **dayjs.week()** braucht Plugin – stattdessen native JS ISO-Wochenberechnung
|
||||
6. **useNavigate()** nur in React-Komponenten, nicht in Helper-Functions
|
||||
7. **api.js nutzen** für alle API-Calls – injiziert Token automatisch
|
||||
8. **bcrypt** für alle neuen Passwort-Operationen verwenden
|
||||
9. **session=Depends(require_auth)** als separater Parameter – nie in Header() einbetten
|
||||
10. **RealDictCursor verwenden** – `get_cursor(conn)` statt `conn.cursor()` für dict-like row access
|
||||
|
||||
## Code-Style
|
||||
- React: Functional Components, Hooks
|
||||
@@ -437,10 +458,192 @@ def endpoint(x_profile_id: Optional[str] = Header(default=None),
|
||||
<Bar fill="#1D9E75"/>
|
||||
```
|
||||
|
||||
### SQLite neue Spalten hinzufügen
|
||||
### PostgreSQL Boolean-Syntax
|
||||
```python
|
||||
# In _safe_alters Liste hinzufügen (NICHT direkt ALTER TABLE):
|
||||
_safe_alters = [
|
||||
("profiles", "neue_spalte TEXT DEFAULT NULL"),
|
||||
# ❌ Falsch (SQLite-Syntax):
|
||||
cur.execute("SELECT * FROM ai_prompts WHERE active=1")
|
||||
|
||||
# ✅ Richtig (PostgreSQL):
|
||||
cur.execute("SELECT * FROM ai_prompts WHERE active=true")
|
||||
```
|
||||
|
||||
### RealDictCursor für dict-like row access
|
||||
```python
|
||||
# ❌ Falsch:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT COUNT(*) FROM weight_log")
|
||||
count = cur.fetchone()[0] # Tuple index
|
||||
|
||||
# ✅ Richtig:
|
||||
cur = get_cursor(conn) # Returns RealDictCursor
|
||||
cur.execute("SELECT COUNT(*) as count FROM weight_log")
|
||||
count = cur.fetchone()['count'] # Dict key
|
||||
```
|
||||
|
||||
## v9b Migration – Lessons Learned
|
||||
|
||||
### PostgreSQL Migration (SQLite → PostgreSQL)
|
||||
**Problem:** Docker Build hing 30+ Minuten bei `apt-get install postgresql-client`
|
||||
**Lösung:** Alle apt-get dependencies entfernt, reine Python-Lösung mit psycopg2-binary
|
||||
|
||||
**Problem:** Leere date-Strings (`''`) führten zu PostgreSQL-Fehlern
|
||||
**Lösung:** Migration-Script konvertiert leere Strings zu NULL für DATE-Spalten
|
||||
|
||||
**Problem:** Boolean-Felder (SQLite INTEGER 0/1 vs PostgreSQL BOOLEAN)
|
||||
**Lösung:** Migration konvertiert automatisch, Backend nutzt `active=true` statt `active=1`
|
||||
|
||||
### API Endpoint Consistency (März 2026)
|
||||
**Problem:** 11 kritische Endpoint-Mismatches zwischen Frontend und Backend gefunden
|
||||
**Gelöst:**
|
||||
- AI-Endpoints konsistent: `/api/insights/run/{slug}`, `/api/insights/pipeline`
|
||||
- Password-Reset: `/api/auth/forgot-password`, `/api/auth/reset-password`
|
||||
- Admin-Endpoints: `/permissions`, `/email`, `/pin` Sub-Routes
|
||||
- Export: JSON + ZIP Endpoints hinzugefügt
|
||||
- Prompt-Bearbeitung: PUT-Endpoint für Admins
|
||||
|
||||
**Tool:** Vollständiger Audit via Explore-Agent empfohlen bei größeren Änderungen
|
||||
|
||||
## Export/Import Spezifikation (v9c)
|
||||
|
||||
### ZIP-Export Struktur
|
||||
```
|
||||
mitai-export-{name}-{YYYY-MM-DD}.zip
|
||||
├── README.txt ← Erklärung des Formats + Versionsnummer
|
||||
├── profile.json ← Profildaten (ohne Passwort-Hash)
|
||||
├── data/
|
||||
│ ├── weight.csv ← Gewichtsverlauf
|
||||
│ ├── circumferences.csv ← Umfänge (8 Messpunkte)
|
||||
│ ├── caliper.csv ← Caliper-Messungen
|
||||
│ ├── nutrition.csv ← Ernährungsdaten
|
||||
│ └── activity.csv ← Aktivitäten
|
||||
├── insights/
|
||||
│ └── ai_insights.json ← KI-Auswertungen (alle gespeicherten)
|
||||
└── photos/
|
||||
├── {date}_{id}.jpg ← Progress-Fotos
|
||||
└── ...
|
||||
```
|
||||
|
||||
### CSV Format (alle Dateien)
|
||||
```
|
||||
- Trennzeichen: Semikolon (;) – Excel/LibreOffice kompatibel
|
||||
- Encoding: UTF-8 mit BOM (für Windows Excel)
|
||||
- Datumsformat: YYYY-MM-DD
|
||||
- Dezimaltrennzeichen: Punkt (.)
|
||||
- Erste Zeile: Header
|
||||
- Nullwerte: leer (nicht "null" oder "NULL")
|
||||
```
|
||||
|
||||
### weight.csv Spalten
|
||||
```
|
||||
id;date;weight;note;source;created
|
||||
```
|
||||
|
||||
### circumferences.csv Spalten
|
||||
```
|
||||
id;date;waist;hip;chest;neck;upper_arm;thigh;calf;forearm;note;created
|
||||
```
|
||||
|
||||
### caliper.csv Spalten
|
||||
```
|
||||
id;date;chest;abdomen;thigh;tricep;subscapular;suprailiac;midaxillary;method;bf_percent;note;created
|
||||
```
|
||||
|
||||
### nutrition.csv Spalten
|
||||
```
|
||||
id;date;meal_name;kcal;protein;fat;carbs;fiber;note;source;created
|
||||
```
|
||||
|
||||
### activity.csv Spalten
|
||||
```
|
||||
id;date;name;type;duration_min;kcal;heart_rate_avg;heart_rate_max;distance_km;note;source;created
|
||||
```
|
||||
|
||||
### profile.json Struktur
|
||||
```json
|
||||
{
|
||||
"export_version": "2",
|
||||
"export_date": "2026-03-18",
|
||||
"app": "Mitai Jinkendo",
|
||||
"profile": {
|
||||
"name": "Lars",
|
||||
"email": "lars@stommer.com",
|
||||
"sex": "m",
|
||||
"height": 178,
|
||||
"birth_year": 1980,
|
||||
"goal_weight": 82,
|
||||
"goal_bf_pct": 14,
|
||||
"avatar_color": "#1D9E75",
|
||||
"auth_type": "password",
|
||||
"session_days": 30,
|
||||
"ai_enabled": true,
|
||||
"tier": "selfhosted"
|
||||
},
|
||||
"stats": {
|
||||
"weight_entries": 150,
|
||||
"nutrition_entries": 300,
|
||||
"activity_entries": 45,
|
||||
"photos": 12
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### ai_insights.json Struktur
|
||||
```json
|
||||
[
|
||||
{
|
||||
"id": "uuid",
|
||||
"scope": "gesamt",
|
||||
"created": "2026-03-18T10:00:00",
|
||||
"result": "KI-Analyse Text..."
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
### README.txt Inhalt
|
||||
```
|
||||
Mitai Jinkendo – Datenexport
|
||||
Version: 2
|
||||
Exportiert am: YYYY-MM-DD
|
||||
Profil: {name}
|
||||
|
||||
Inhalt:
|
||||
- profile.json: Profildaten und Einstellungen
|
||||
- data/*.csv: Messdaten (Semikolon-getrennt, UTF-8)
|
||||
- insights/: KI-Auswertungen (JSON)
|
||||
- photos/: Progress-Fotos (JPEG)
|
||||
|
||||
Import:
|
||||
Dieser Export kann in Mitai Jinkendo unter
|
||||
Einstellungen → Import → "Mitai Backup importieren"
|
||||
wieder eingespielt werden.
|
||||
|
||||
Format-Version 2 (ab v9b):
|
||||
Alle CSV-Dateien sind UTF-8 mit BOM kodiert.
|
||||
Trennzeichen: Semikolon (;)
|
||||
Datumsformat: YYYY-MM-DD
|
||||
```
|
||||
|
||||
### Import-Funktion (zu implementieren)
|
||||
**Endpoint:** `POST /api/import/zip`
|
||||
**Verhalten:**
|
||||
- Akzeptiert ZIP-Datei (multipart/form-data)
|
||||
- Erkennt export_version aus profile.json
|
||||
- Importiert nur fehlende Einträge (kein Duplikat)
|
||||
- Fotos werden nicht überschrieben falls bereits vorhanden
|
||||
- Gibt Zusammenfassung zurück: wie viele Einträge je Kategorie importiert
|
||||
- Bei Fehler: vollständiger Rollback (alle oder nichts)
|
||||
|
||||
**Duplikat-Erkennung:**
|
||||
```python
|
||||
# INSERT ... ON CONFLICT (profile_id, date) DO NOTHING
|
||||
# weight: UNIQUE (profile_id, date)
|
||||
# nutrition: UNIQUE (profile_id, date, meal_name)
|
||||
# activity: UNIQUE (profile_id, date, name)
|
||||
# caliper: UNIQUE (profile_id, date)
|
||||
# circumferences: UNIQUE (profile_id, date)
|
||||
```
|
||||
|
||||
**Frontend:** Neuer Button in SettingsPage:
|
||||
```
|
||||
[ZIP exportieren] [JSON exportieren] [Backup importieren]
|
||||
```
|
||||
+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
|
||||
+685
-157
File diff suppressed because it is too large.
Load diff
@@ -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