docs: Struktur .claude/docs versionieren, working/, Gitea-Index, Regeln

- .gitignore: .claude/docs, rules, commands tracken; settings.local weiter ignorieren
- DOCUMENTATION.md: verbindliche Ablage functional/technical/working/issues
- .claude/README.md: Agent-Einstieg; GITEA_ISSUES_INDEX aus MCP (Stand 2026-04-08)
- Arbeitspapiere von docs/ nach .claude/docs/working/ verschoben
- docs/MEMBERSHIP_SYSTEM.md als Stub; kanonisch technical/MEMBERSHIP_SYSTEM.md
- CLAUDE.md Pflichtlektüre und Links angepasst; docs/README.md vereinfacht

Made-with: Cursor
This commit is contained in:
Lars committed 2026-04-08 13:01:49 +02:00
1 parent 24daeeb83c
commit 7940dc7560
115 files changed
+45622 -1063

No files matched your search

@@ -0,0 +1,387 @@
# Aggregation Methods – Goal Value Calculation
**Zweck:** Dokumentation für Entwicklung und Erweiterung von Aggregationsmethoden im Goal-System.
**Datum:** 2026-03-28
**Version:** 1.0
**Modul:** `backend/goal_utils.py` → `_fetch_by_aggregation_method()`
---
## Übersicht
Aggregationsmethoden berechnen den `current_value` von Goals aus Rohdaten (z.B. Trainings, Gewicht, Ernährung). Sie sind der Kern des dynamischen Goal-Tracking-Systems.
**Beispiel:**
```python
Goal: "Trainingshäufigkeit Krafttraining"
source_table: activity_log
source_column: id (nur für COUNT relevant)
aggregation_method: avg_per_week_30d
filter_conditions: {"training_category": "strength"}
→ Berechnet: Durchschnittliche Anzahl Krafttrainings pro Woche (über 30 Tage)
```
---
## Architektur
### 1. Wo sind Methoden definiert?
**Datei:** `backend/goal_utils.py`
**Funktion:** `_fetch_by_aggregation_method(conn, profile_id, table, column, method, filter_conditions)`
**Aufruf-Hierarchie:**
```
goal_utils.fetch_goal_value()
└─> _fetch_by_aggregation_method()
└─> SQL Query mit method-spezifischer Logik
```
### 2. Verfügbare Methoden (Stand: 2026-03-28)
| Methode | Beschreibung | SQL Aggregat | Zeitfenster | Use Case |
|---------|--------------|--------------|-------------|----------|
| `latest` | Aktuellster Wert | SELECT {column} ORDER BY date DESC LIMIT 1 | — | Gewicht, Körperfett, VO2max |
| `avg_7d` | 7-Tage-Durchschnitt | AVG({column}) | 7 Tage | Durchschn. Ruhepuls, HRV |
| `avg_30d` | 30-Tage-Durchschnitt | AVG({column}) | 30 Tage | Durchschn. Kalorien, Protein |
| `sum_30d` | 30-Tage-Summe | SUM({column}) | 30 Tage | Gesamtkalorien, Trainingsminuten |
| `count_7d` | Anzahl Einträge (7d) | COUNT(*) | 7 Tage | Trainings letzte Woche |
| `count_30d` | Anzahl Einträge (30d) | COUNT(*) | 30 Tage | Trainings letzter Monat |
| `min_30d` | Minimum (30d) | MIN({column}) | 30 Tage | Niedrigster Ruhepuls |
| `max_30d` | Maximum (30d) | MAX({column}) | 30 Tage | Höchster VO2max |
| `avg_per_week_30d` | Durchschn. pro Woche | COUNT(*) / 4.3 | 30 Tage | Trainingsfrequenz/Woche |
### 3. Filter-Mechanismus
Alle Methoden unterstützen **optionale Filter** via `filter_conditions` (JSON):
```python
filter_conditions = {"training_category": "strength"}
# Wird zu SQL:
# ... WHERE profile_id = %s AND training_category = %s
```
**Unterstützte Filter-Typen:**
- **Equality:** `{"column": "value"}` → `WHERE column = 'value'`
- **IN-Clause:** `{"column": ["val1", "val2"]}` → `WHERE column IN ('val1', 'val2')`
---
## Neue Aggregationsmethode hinzufügen
### Schritt 1: Anforderungen definieren
**Checkliste:**
- [ ] **Name:** Eindeutig, beschreibend (z.B. `avg_per_week_30d`)
- [ ] **SQL-Aggregat:** Welche Funktion? (COUNT, AVG, SUM, MIN, MAX, oder Custom)
- [ ] **Zeitfenster:** Fixed (7d, 30d) oder dynamisch?
- [ ] **Spaltentyp:** Numerisch (DECIMAL, INT) oder UUID/TEXT (nur COUNT)?
- [ ] **Filter-Support:** Ja/Nein?
- [ ] **Return-Typ:** `float` oder `None`
### Schritt 2: Code-Template
**Location:** `backend/goal_utils.py` → `_fetch_by_aggregation_method()`
```python
elif method == 'neue_methode':
# 1. Zeitfenster definieren (falls relevant)
days_ago = date.today() - timedelta(days=30)
# 2. Parameter vorbereiten (inkl. filter_params)
params = [profile_id, days_ago] + filter_params
# 3. SQL Query (mit date_col und filter_sql)
cur.execute(f"""
SELECT AGG_FUNCTION({column}) as result_value
FROM {table}
WHERE profile_id = %s
AND {date_col} >= %s
AND {column} IS NOT NULL{filter_sql}
""", params)
# 4. Result extrahieren und konvertieren
row = cur.fetchone()
return float(row['result_value']) if row and row['result_value'] is not None else None
```
### Schritt 3: Spaltentyp-Validierung
**Wichtig:** Nur numerische Aggregationen (AVG, SUM, MIN, MAX) auf numerischen Spalten!
**Spaltentypen:**
- ✅ **AVG/SUM/MIN/MAX:** DECIMAL, INT, FLOAT
- ❌ **AVG/SUM/MIN/MAX:** UUID, TEXT, VARCHAR
- ✅ **COUNT:** Beliebiger Typ (UUID, TEXT, etc.)
**Bei Fehlkonfiguration:**
```python
# Wird automatisch geloggt + None returned (siehe except-Block Zeile 414-430)
[ERROR] Failed to fetch value from activity_log.id using avg_7d:
function avg(uuid) does not exist
```
### Schritt 4: Testen
**Manueller Test:**
```python
from goal_utils import _fetch_by_aggregation_method
from db import get_db
with get_db() as conn:
result = _fetch_by_aggregation_method(
conn,
profile_id='...',
table='activity_log',
column='id',
method='avg_per_week_30d',
filter_conditions={"training_category": "strength"}
)
print(f"Result: {result}")
```
**Unit-Test (TODO):**
```python
# backend/tests/test_goal_utils.py
def test_avg_per_week_30d():
# Setup: Insert 12 activities in last 30 days
# Expected: 12 / 4.3 ≈ 2.79
assert result == pytest.approx(2.79, abs=0.1)
```
---
## Beispiel-Implementierung: avg_per_week_30d
**Use Case:** Trainingshäufigkeit pro Woche (geglättet über 30 Tage)
**Berechnung:** `(Anzahl Trainings in 30 Tagen) / 4.3 Wochen`
**Code:**
```python
elif method == 'avg_per_week_30d':
days_ago = date.today() - timedelta(days=30)
params = [profile_id, days_ago] + filter_params
cur.execute(f"""
SELECT COUNT(*) as count_value FROM {table}
WHERE profile_id = %s AND {date_col} >= %s{filter_sql}
""", params)
row = cur.fetchone()
if row and row['count_value'] is not None:
# 30 Tage = 4.285 Wochen (30/7)
return round(float(row['count_value']) / 4.285, 2)
return None
```
**Warum 4.285?**
- 30 Tage ÷ 7 Tage/Woche = 4.285 Wochen
- Alternativ: 4.3 (gerundet) für einfachere Rechnung
---
## Best Practices
### 1. Naming Conventions
**Pattern:** `{aggregat}_{spalte}_{zeitfenster}`
- ✅ `avg_hr_7d` – Average heart rate, 7 days
- ✅ `count_per_week_30d` – Count per week, averaged over 30 days
- ✅ `sum_calories_30d` – Sum of calories, 30 days
- ❌ `get_training_count` – Unklar, kein Zeitfenster
- ❌ `calc_average` – Zu generisch
### 2. Return-Werte
**Konsistenz:**
- **Erfolg:** `float` (auch bei 0.0)
- **Keine Daten:** `None` (nicht 0.0!)
- **Fehler:** `None` (geloggt im except-Block)
**Warum None statt 0.0?**
```python
# None = "Keine Daten vorhanden"
# 0.0 = "Gemessen, aber Wert ist tatsächlich 0"
```
### 3. Date-Columns
Nicht alle Tabellen nutzen `date` als Spaltenname:
```python
DATE_COLUMN_MAP = {
'blood_pressure_log': 'measured_at', # TIMESTAMP
'activity_log': 'date', # DATE
'fitness_tests': 'test_date', # DATE
# ... siehe goal_utils.py Zeile 289-300
}
```
**Nutzung:** `date_col = DATE_COLUMN_MAP.get(table, 'date')`
### 4. Filter-Safety
**SQL-Injection-Schutz:**
- ✅ **Parametrisierte Queries:** `WHERE col = %s` + `params`
- ❌ **String-Interpolation:** `WHERE col = '{value}'`
**Filter-Validierung:**
```python
try:
filters = json.loads(filter_conditions) if isinstance(filter_conditions, str) else filter_conditions
# ... build filter_sql
except (json.JSONDecodeError, TypeError, AttributeError) as e:
print(f"[WARNING] Invalid filter_conditions: {e}, ignoring filters")
```
### 5. Performance
**Query-Optimierung:**
- `WHERE profile_id = %s` ist **immer** erste Bedingung (Index)
- `AND {column} IS NOT NULL` vor Aggregation (reduziert NULL-Handling)
- `ORDER BY {date_col} DESC LIMIT 1` für `latest` (schneller als MAX)
---
## Erweiterte Methoden (Future)
### Statistische Analysen
**Median:**
```python
elif method == 'median_30d':
# PostgreSQL: PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY column)
cur.execute(f"""
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY {column}) as median_value
FROM {table}
WHERE profile_id = %s AND {date_col} >= %s{filter_sql}
""", params)
```
**Standard Deviation:**
```python
elif method == 'stddev_30d':
cur.execute(f"""
SELECT STDDEV({column}) as stddev_value FROM {table}
WHERE profile_id = %s AND {date_col} >= %s{filter_sql}
""", params)
```
**Trend (Linear Regression):**
```python
elif method == 'trend_30d':
# Slope via REGR_SLOPE(y, x)
cur.execute(f"""
SELECT REGR_SLOPE(
{column},
EXTRACT(EPOCH FROM {date_col})
) as slope FROM {table}
WHERE profile_id = %s AND {date_col} >= %s{filter_sql}
""", params)
```
### Kalenderwoche
```python
elif method == 'count_calendar_week':
# Montag der aktuellen Woche
today = date.today()
monday = today - timedelta(days=today.weekday())
cur.execute(f"""
SELECT COUNT(*) as count_value FROM {table}
WHERE profile_id = %s
AND {date_col} >= %s
AND {date_col} < %s + INTERVAL '7 days'{filter_sql}
""", [profile_id, monday] + filter_params)
```
---
## Fehlerbehandlung
### Exception-Handling
**Alle Methoden sind wrapped in try-except** (Zeile 329-430):
```python
try:
# ... method logic
except Exception as e:
print(f"[ERROR] Failed to fetch value from {table}.{column} using {method}: {e}")
print(f"[ERROR] Filter conditions: {filter_conditions}")
# CRITICAL: Rollback transaction
conn.rollback()
return None
```
**Warum Rollback?**
- PostgreSQL bleibt in `InFailedSqlTransaction` bis Rollback
- Ohne Rollback: Alle nachfolgenden Queries schlagen fehl
### Typische Fehler
| Fehler | Ursache | Lösung |
|--------|---------|--------|
| `function avg(uuid) does not exist` | AVG auf UUID-Spalte | Methode auf `count_*` ändern |
| `column "xyz" does not exist` | Falsche source_column | Schema prüfen, Spalte korrigieren |
| `division by zero` | Keine Daten für Durchschnitt | None-Check vor Division |
| `UndefinedColumn: training_category` | Filter-Spalte existiert nicht | Filter entfernen oder Spalte anlegen |
---
## Migration zu neuer Methode
**Szenario:** Bestehende Goal-Type-Definition ändern
**Beispiel:** `sport_pro_woche` von `avg_7d` zu `avg_per_week_30d`
**SQL:**
```sql
UPDATE goal_type_definitions
SET aggregation_method = 'avg_per_week_30d'
WHERE type_key = 'sport_pro_woche';
```
**Wichtig:**
- Bestehende Goals behalten ihre `current_value` (historisch)
- Nächste Berechnung nutzt neue Methode
- UI zeigt dann neuen Wert
---
## Dokumentations-Pflicht
**Bei jeder neuen Methode:**
1. ✅ Eintrag in dieser Datei (Tabelle "Verfügbare Methoden")
2. ✅ Docstring in `_fetch_by_aggregation_method()`
3. ✅ Beispiel-Anwendung (Use Case)
4. ✅ Unit-Test (wenn möglich)
5. ✅ Update in `goal_types.py` Schema-Info (falls relevant für Admin-UI)
---
## Zusammenfassung
**Aggregationsmethoden sind:**
- ✅ Zentral in `goal_utils.py`
- ✅ SQL-basiert (PostgreSQL-Funktionen)
- ✅ Filter-fähig (JSON-basiert)
- ✅ Error-safe (Rollback + None-Return)
- ✅ Erweiterbar (einfaches elif-Pattern)
**Für neue Methoden:**
1. Name definieren (`{aggregat}_{zeitfenster}`)
2. SQL Query schreiben (mit filter_sql)
3. Testen (manuell + Unit-Test)
4. Dokumentieren (diese Datei)
**Bei Fragen:**
- Siehe `backend/goal_utils.py` Zeile 259-430
- Siehe bestehende Methoden als Template
- Siehe `.claude/docs/working/GOALS_SYSTEM_UNIFIED_ANALYSIS.md` für Kontext
+575
View File
@@ -0,0 +1,575 @@
# API-Referenz
## Basis-URLs
| Umgebung | URL |
|----------|-----|
| **Production** | `https://mitai.jinkendo.de/api` |
| **Development** | `https://dev.mitai.jinkendo.de/api` |
| **Local** | `http://localhost:8000/api` (Backend direkt) |
---
## Authentifizierung
**Alle geschützten Endpoints** benötigen einen Auth-Token im Header:
```http
GET /api/weight
X-Auth-Token: jT9z3xK...pQ2vL
```
**Token-Beschaffung:** `POST /api/auth/login` → `{"token": "..."}`
**Storage:** `localStorage.bodytrack_token` (Frontend)
---
## Fehler-Codes
| Status | Bedeutung | Beispiel |
|--------|-----------|----------|
| **200** | Erfolg | `{"data": [...]}` |
| **201** | Erstellt | `{"id": "uuid", ...}` |
| **400** | Bad Request | `{"detail": "Ungültige Eingabe"}` |
| **401** | Unauthorized | `{"detail": "Nicht eingeloggt"}` |
| **403** | Forbidden | `{"detail": "Nur für Admins"}` oder `{"detail": "Feature-Limit erreicht"}` |
| **404** | Not Found | `{"detail": "Eintrag nicht gefunden"}` |
| **429** | Too Many Requests | `{"detail": "Rate limit exceeded: 5 per 1 minute"}` |
| **500** | Server Error | `{"detail": "Interner Fehler"}` |
**Standard-Fehler-Format:**
```json
{
"detail": "Fehlermeldung"
}
```
---
## Rate Limits
| Endpoint | Limit | Grund |
|----------|-------|-------|
| `POST /api/auth/login` | 5/minute | Brute-Force-Schutz |
| `POST /api/auth/register` | 3/hour | Spam-Prevention |
| `POST /api/auth/forgot-password` | 3/minute | E-Mail-Flooding-Schutz |
| `POST /api/auth/resend-verification` | 3/hour | E-Mail-Flooding-Schutz |
**Andere Endpoints:** Keine Rate-Limits (Feature-Limits via Membership-System)
---
## Endpoints nach Modul
### 1. Auth (`/api/auth/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `POST` | `/auth/login` | ❌ | `{email, password}` | `{token, profile_id, name, role, expires_at}` | Login mit E-Mail + Passwort |
| `POST` | `/auth/logout` | ✅ | – | `{ok: true}` | Logout (löscht Session) |
| `GET` | `/auth/me` | ✅ | – | `{id, name, email, role, tier, ...}` | Aktuelles Profil abrufen |
| `GET` | `/auth/status` | ❌ | – | `{status: "ok", version: "v9b"}` | Health Check |
| `PUT` | `/auth/pin` | ✅ | `{pin}` | `{ok: true}` | PIN/Passwort ändern |
| `POST` | `/auth/forgot-password` | ❌ | `{email}` | `{ok: true, message}` | Passwort-Reset anfordern |
| `POST` | `/auth/reset-password` | ❌ | `{token, new_password}` | `{ok: true, message}` | Passwort-Reset bestätigen |
| `POST` | `/auth/register` | ❌ | `{name, email, password}` | `{ok: true, message}` | Selbst-Registrierung |
| `GET` | `/auth/verify/{token}` | ❌ | – | `{ok: true, token, profile}` | E-Mail-Verifizierung |
| `POST` | `/auth/resend-verification` | ❌ | `{email}` | `{ok: true, message}` | Verifizierungs-E-Mail erneut senden |
**Rate Limits:** Siehe Tabelle oben
---
### 2. Profiles (`/api/profiles/*`, `/api/profile`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/profile` | ✅ | – | `{id, name, email, role, tier, ...}` | Aktives Profil |
| `PUT` | `/profile` | ✅ | `{name?, sex?, dob?, height?, goal_weight?, goal_bf_pct?, avatar_color?}` | `{ok: true}` | Profil aktualisieren |
| `GET` | `/profiles` | ✅ | – | `[{id, name, ...}, ...]` | Alle Profile (Multi-User, derzeit nicht genutzt) |
| `POST` | `/profiles` | ✅ | `{name, ...}` | `{id, ...}` | Profil erstellen (Multi-User) |
| `PUT` | `/profiles/{id}` | ✅ | `{name?, ...}` | `{ok: true}` | Profil bearbeiten |
| `DELETE` | `/profiles/{id}` | ✅ | – | `{ok: true}` | Profil löschen |
---
### 3. Weight (`/api/weight/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/weight` | ✅ | `?limit=365` | `[{id, date, weight, note, source, created}, ...]` | Gewichtseinträge abrufen |
| `POST` | `/weight` | ✅ | `{date, weight, note?}` | `{id, date, weight, ...}` | Gewicht eintragen (Upsert) |
| `PUT` | `/weight/{id}` | ✅ | `{date, weight, note?}` | `{ok: true}` | Eintrag bearbeiten |
| `DELETE` | `/weight/{id}` | ✅ | – | `{ok: true}` | Eintrag löschen |
| `GET` | `/weight/stats` | ✅ | – | `{latest, avg_7d, avg_30d, delta_7d, delta_30d, trend}` | Gewichts-Statistiken |
**Feature-Limits:** `weight_entries` (v9c Phase 4: Enforcement aktiv)
---
### 4. Circumferences (`/api/circumferences/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/circumferences` | ✅ | `?limit=100` | `[{id, date, c_neck, c_chest, c_waist, c_belly, c_hip, c_thigh, c_calf, c_arm, notes, photo_id}, ...]` | Umfangsmessungen |
| `POST` | `/circumferences` | ✅ | `{date, c_neck?, c_chest?, ...}` | `{id, ...}` | Messung eintragen (Upsert) |
| `PUT` | `/circumferences/{id}` | ✅ | `{date, ...}` | `{ok: true}` | Bearbeiten |
| `DELETE` | `/circumferences/{id}` | ✅ | – | `{ok: true}` | Löschen |
**Feature-Limits:** `circumference_entries`
---
### 5. Caliper (`/api/caliper/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/caliper` | ✅ | `?limit=100` | `[{id, date, sf_method, sf_chest, sf_abdomen, ..., body_fat_pct, lean_mass, fat_mass, notes}, ...]` | Hautfaltenmessungen |
| `POST` | `/caliper` | ✅ | `{date, sf_method, sf_chest?, ...}` | `{id, body_fat_pct, ...}` | Messung eintragen (berechnet KF% automatisch) |
| `PUT` | `/caliper/{id}` | ✅ | `{date, ...}` | `{ok: true}` | Bearbeiten |
| `DELETE` | `/caliper/{id}` | ✅ | – | `{ok: true}` | Löschen |
**Methoden:** `jackson3`, `jackson7`, `durnin`, `parrillo`
**Feature-Limits:** `caliper_entries`
---
### 6. Activity (`/api/activity/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/activity` | ✅ | `?limit=200` | `[{id, date, start_time, end_time, activity_type, duration_min, kcal_active, hr_avg, hr_max, distance_km, rpe, source, notes}, ...]` | Aktivitäten |
| `POST` | `/activity` | ✅ | `{date, activity_type, duration_min, ...}` | `{id, ...}` | Aktivität erstellen |
| `PUT` | `/activity/{id}` | ✅ | `{date, ...}` | `{ok: true}` | Bearbeiten |
| `DELETE` | `/activity/{id}` | ✅ | – | `{ok: true}` | Löschen |
| `GET` | `/activity/stats` | ✅ | – | `{total_activities, total_kcal, avg_duration, ...}` | Statistiken |
| `GET` | `/activity/uncategorized` | ✅ | – | `[{activity_type, count}, ...]` | Unkategorisierte Aktivitäten |
| `POST` | `/activity/bulk-categorize` | ✅ | `[{activity_type, training_type_id}, ...]` | `{ok: true, updated_count}` | Bulk-Kategorisierung (lernendes System) |
| `POST` | `/activity/import-csv` | ✅ | `FormData(file)` | `{imported, skipped, failed, errors}` | Apple Health CSV-Import |
**Feature-Limits:** `activity_entries`
---
### 7. Nutrition (`/api/nutrition/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/nutrition` | ✅ | `?limit=365` | `[{id, date, kcal, protein_g, fat_g, carbs_g, source}, ...]` | Ernährungsdaten |
| `GET` | `/nutrition/by-date/{date}` | ✅ | – | `{id, date, kcal, ...}` oder `null` | Eintrag für bestimmtes Datum |
| `POST` | `/nutrition` | ✅ | `?date=YYYY-MM-DD&kcal=2000&protein_g=150&fat_g=70&carbs_g=200` | `{id, ...}` | Eintrag erstellen (Upsert) |
| `PUT` | `/nutrition/{id}` | ✅ | `?kcal=2000&...` | `{ok: true}` | Bearbeiten |
| `DELETE` | `/nutrition/{id}` | ✅ | – | `{ok: true}` | Löschen |
| `GET` | `/nutrition/correlations` | ✅ | – | `{weight_vs_kcal: [...], bf_vs_protein: [...]}` | Korrelationen |
| `GET` | `/nutrition/weekly` | ✅ | `?weeks=16` | `[{week, year, avg_kcal, avg_protein, ...}, ...]` | Wochendaten |
| `GET` | `/nutrition/import-history` | ✅ | – | `[{date, count}, ...]` | Import-Historie |
| `POST` | `/nutrition/import-csv` | ✅ | `FormData(file)` | `{imported, skipped, failed, errors}` | CSV-Import (FDDB, MyFitnessPal) |
**Feature-Limits:** `nutrition_entries`, `data_import`
---
### 8. Photos (`/api/photos/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/photos` | ✅ | – | `[{id, date, path, created}, ...]` | Alle Fotos |
| `GET` | `/photos/{id}` | ✅ | `?token=...` (optional) | Binary (JPEG) | Foto abrufen (Token für <img> tag) |
| `POST` | `/photos` | ✅ | `FormData(file, date?)` | `{id, path, date}` | Foto hochladen |
| `DELETE` | `/photos/{id}` | ✅ | – | `{ok: true}` | Foto löschen |
**Feature-Limits:** `photos`
**Hinweis:** Token-Parameter für `GET /photos/{id}` erlaubt Zugriff via `<img>` tag (ohne Header-Support)
---
### 9. AI Insights (`/api/insights/*`, `/api/ai/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/insights` | ✅ | – | `[{id, scope, content, created}, ...]` | Alle Insights |
| `GET` | `/insights/latest` | ✅ | – | `{slug: content, ...}` | Neueste Insights pro Scope |
| `POST` | `/insights/trend` | ✅ | – | `{content, usage}` | Trend-Analyse (Gewicht) |
| `POST` | `/insights/run/{slug}` | ✅ | – | `{content, usage}` | Einzelnen Prompt ausführen |
| `POST` | `/insights/pipeline` | ✅ | – | `{content, usage}` | 3-stufige Pipeline |
**Feature-Limits:** `ai_calls` (pro Aufruf), `ai_pipeline` (für Pipeline)
**Prompts:** Konfigurierbar via `/api/prompts`
---
### 10. AI Prompts (`/api/prompts/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/prompts` | ✅ | – | `[{id, slug, name, description, template, active, sort_order}, ...]` | Alle Prompts |
| `PUT` | `/prompts/{id}` | 🔒 Admin | `{name?, description?, template?, active?, sort_order?}` | `{ok: true}` | Prompt bearbeiten |
**Standard-Prompts:**
- `weight-trend` – Gewichts-Trend-Analyse
- `nutrition-analysis` – Ernährungs-Auswertung
- `training-plan` – Trainings-Empfehlungen
- `body-composition` – Körperzusammensetzung
- `progress-summary` – Fortschritts-Zusammenfassung
- `pipeline` – Master-Schalter für Pipeline
---
### 11. Admin (`/api/admin/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/admin/profiles` | 🔒 Admin | – | `[{id, name, email, role, tier, ...}, ...]` | Alle Profile |
| `POST` | `/admin/profiles` | 🔒 Admin | `{name, email, password, role?}` | `{id, ...}` | Profil erstellen |
| `DELETE` | `/admin/profiles/{id}` | 🔒 Admin | – | `{ok: true}` | Profil löschen |
| `PUT` | `/admin/profiles/{id}/permissions` | 🔒 Admin | `{ai_enabled?, ai_limit_day?, export_enabled?}` | `{ok: true}` | Permissions setzen |
---
### 12. Stats (`/api/stats`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/stats` | ✅ | – | `{weight: {...}, nutrition: {...}, activity: {...}, body_comp: {...}}` | Dashboard-Stats |
**Response-Struktur:**
```json
{
"weight": {
"latest": 75.5,
"avg_7d": 75.8,
"avg_30d": 76.2,
"delta_7d": -0.3,
"delta_30d": -0.7
},
"nutrition": {
"avg_kcal_7d": 2100,
"avg_protein_7d": 150,
"days_logged_7d": 6
},
"activity": {
"total_activities_7d": 5,
"total_kcal_7d": 2500,
"avg_duration_7d": 45
},
"body_comp": {
"latest_bf_pct": 12.5,
"latest_lean_mass": 65.8
}
}
```
---
### 13. Export (`/api/export/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/export/csv` | ✅ | – | Binary (CSV) | Alle Daten als CSV |
| `GET` | `/export/json` | ✅ | – | Binary (JSON) | Alle Daten als JSON |
| `GET` | `/export/zip` | ✅ | – | Binary (ZIP) | Alle Daten + Fotos als ZIP |
**Feature-Limits:** `data_export`
**Dateiname:** `mitai-export-YYYY-MM-DD.[csv|json|zip]`
**ZIP-Struktur:**
```
mitai-export-2026-03-23.zip
├── data.json
├── photos/
│ ├── photo_uuid1.jpg
│ └── photo_uuid2.jpg
└── README.txt
```
---
### 14. Import (`/api/import/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `POST` | `/import/backup` | ✅ | `FormData(file)` | `{imported: {...}, skipped: {...}, failed: {...}}` | JSON-Backup importieren |
**Feature-Limits:** `data_import`
**Format:** JSON-Export von `/export/json`
**Hinweis:** Überschreibt keine existierenden Einträge (Upsert-Logik)
---
## Subscription System (v9c)
### 15. Subscription (`/api/subscription/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/subscription/me` | ✅ | – | `{tier, tier_expires_at, trial_ends_at, invited_by, ...}` | Abo-Status |
| `GET` | `/subscription/usage` | ✅ | – | `{feature_id: {used, limit, remaining, allowed}, ...}` | Feature-Usage |
| `GET` | `/subscription/limits` | ✅ | – | `{feature_id: limit, ...}` | Feature-Limits für aktuelles Tier |
---
### 16. Coupons (`/api/coupons/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `POST` | `/coupons/redeem` | ✅ | `{code}` | `{ok: true, tier_id, valid_days, message}` | Coupon einlösen |
| `GET` | `/coupons` | 🔒 Admin | – | `[{id, code, tier_id, valid_days, max_uses, ...}, ...]` | Alle Coupons |
| `POST` | `/coupons` | 🔒 Admin | `{code, tier_id, valid_days, max_uses?}` | `{id, ...}` | Coupon erstellen |
| `PUT` | `/coupons/{id}` | 🔒 Admin | `{...}` | `{ok: true}` | Bearbeiten |
| `DELETE` | `/coupons/{id}` | 🔒 Admin | – | `{ok: true}` | Löschen |
| `GET` | `/coupons/{id}/redemptions` | 🔒 Admin | – | `[{profile_id, redeemed_at}, ...]` | Einlösungen |
---
### 17. Features (`/api/features/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/features` | ✅ | – | `[{id, name, description, limit_type, reset_period, default_limit, active}, ...]` | Alle Features |
| `GET` | `/features/usage` | ✅ | – | `[{feature_id, feature_name, limit, used, remaining, allowed, reason}, ...]` | Feature-Usage für aktuellen User |
| `POST` | `/features` | 🔒 Admin | `{id, name, description, limit_type, reset_period, default_limit}` | `{id, ...}` | Feature erstellen |
| `PUT` | `/features/{id}` | 🔒 Admin | `{...}` | `{ok: true}` | Bearbeiten |
| `DELETE` | `/features/{id}` | 🔒 Admin | – | `{ok: true}` | Löschen |
**Limit-Types:** `count` (zählbar), `boolean` (on/off)
**Reset-Periods:** `never`, `daily`, `monthly`
---
### 18. Tiers (`/api/tiers/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/tiers` | 🔒 Admin | – | `[{id, name, description, price_monthly, active}, ...]` | Alle Tiers |
| `POST` | `/tiers` | 🔒 Admin | `{id, name, description, price_monthly}` | `{id, ...}` | Tier erstellen |
| `PUT` | `/tiers/{id}` | 🔒 Admin | `{...}` | `{ok: true}` | Bearbeiten |
| `DELETE` | `/tiers/{id}` | 🔒 Admin | – | `{ok: true}` | Löschen |
**Standard-Tiers:** `free`, `basic`, `premium`, `selfhosted`
---
### 19. Tier Limits (`/api/tier-limits/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/tier-limits` | 🔒 Admin | – | `{tiers: [...], features: [...], matrix: {...}}` | Tier-Limits-Matrix |
| `PUT` | `/tier-limits` | 🔒 Admin | `{tier_id, feature_id, limit_value}` | `{ok: true}` | Limit setzen |
| `PUT` | `/tier-limits/batch` | 🔒 Admin | `{updates: [{tier_id, feature_id, limit_value}, ...]}` | `{ok: true}` | Batch-Update |
**Matrix-Format:**
```json
{
"tiers": ["free", "basic", "premium", "selfhosted"],
"features": [
{"id": "weight_entries", "name": "Gewichtseinträge", ...},
...
],
"matrix": {
"weight_entries": {
"free": 100,
"basic": 1000,
"premium": null,
"selfhosted": null
},
...
}
}
```
---
### 20. User Restrictions (`/api/user-restrictions/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/user-restrictions` | 🔒 Admin | `?profile_id=...` | `[{id, profile_id, feature_id, limit_value}, ...]` | User-spezifische Limits |
| `POST` | `/user-restrictions` | 🔒 Admin | `{profile_id, feature_id, limit_value}` | `{id, ...}` | Limit setzen |
| `PUT` | `/user-restrictions/{id}` | 🔒 Admin | `{limit_value}` | `{ok: true}` | Bearbeiten |
| `DELETE` | `/user-restrictions/{id}` | 🔒 Admin | – | `{ok: true}` | Löschen |
**Verwendung:** Individuelle Limits überschreiben Tier-Limits
---
### 21. Access Grants (`/api/access-grants/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/access-grants` | 🔒 Admin | `?profile_id=...&active_only=true` | `[{id, profile_id, tier_id, valid_from, valid_until, source, is_active}, ...]` | Zeitlich begrenzte Tier-Zugriffe |
| `POST` | `/access-grants` | 🔒 Admin | `{profile_id, tier_id, valid_from, valid_until, source?}` | `{id, ...}` | Grant erstellen |
| `PUT` | `/access-grants/{id}` | 🔒 Admin | `{...}` | `{ok: true}` | Bearbeiten |
| `DELETE` | `/access-grants/{id}` | 🔒 Admin | – | `{ok: true}` | Revoke |
**Quellen:** `coupon`, `trial`, `manual`, `gift`
---
## Training Types (v9d)
### 22. Training Types (`/api/training-types/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/training-types` | ✅ | – | `{category: [{id, name, category, color, icon}, ...], ...}` | Gruppiert nach Kategorie |
| `GET` | `/training-types/flat` | ✅ | – | `[{id, name, category, ...}, ...]` | Flache Liste |
| `GET` | `/training-types/categories` | ✅ | – | `[{id, name, icon, color}, ...]` | Kategorien-Metadaten |
**Kategorien:** Kraft, Cardio, Flexibilität, Spiel & Sport, Alltag & Bewegung, Outdoor & Natur, Geist & Meditation
---
### 23. Admin Training Types (`/api/admin/training-types/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/admin/training-types` | 🔒 Admin | – | `[{id, name, category, color, icon, abilities}, ...]` | Alle Typen (inkl. abilities JSONB) |
| `GET` | `/admin/training-types/{id}` | 🔒 Admin | – | `{id, name, ...}` | Einzelner Typ |
| `POST` | `/admin/training-types` | 🔒 Admin | `{name, category, color?, icon?}` | `{id, ...}` | Typ erstellen |
| `PUT` | `/admin/training-types/{id}` | 🔒 Admin | `{name?, category?, color?, icon?, abilities?}` | `{ok: true}` | Bearbeiten |
| `DELETE` | `/admin/training-types/{id}` | 🔒 Admin | – | `{ok: true}` | Löschen |
| `GET` | `/admin/training-types/taxonomy/abilities` | 🔒 Admin | – | `{categories: [...], abilities: [...]}` | Abilities-Taxonomie (v9f) |
---
### 24. Activity Mappings (`/api/admin/activity-mappings/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/admin/activity-mappings` | 🔒 Admin | `?profile_id=...&global_only=true` | `[{id, activity_type, training_type_id, profile_id, is_global}, ...]` | Lernendes Mapping-System |
| `GET` | `/admin/activity-mappings/{id}` | 🔒 Admin | – | `{id, ...}` | Einzelnes Mapping |
| `POST` | `/admin/activity-mappings` | 🔒 Admin | `{activity_type, training_type_id, profile_id?, is_global?}` | `{id, ...}` | Mapping erstellen |
| `PUT` | `/admin/activity-mappings/{id}` | 🔒 Admin | `{training_type_id?, is_global?}` | `{ok: true}` | Bearbeiten |
| `DELETE` | `/admin/activity-mappings/{id}` | 🔒 Admin | – | `{ok: true}` | Löschen |
| `GET` | `/admin/activity-mappings/stats/coverage` | 🔒 Admin | – | `{total_activities, mapped, unmapped, coverage_pct}` | Mapping-Coverage |
**Auto-Learning:** Bulk-Kategorisierung in ActivityPage speichert neue Mappings automatisch
---
### 25. Training Profiles (`/api/evaluation/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/evaluation/parameters` | 🔒 Admin | – | `{categories: [...], abilities: [...]}` | Training-Parameter-Taxonomie |
| `POST` | `/evaluation/batch` | 🔒 Admin | – | `{evaluated, failed, errors}` | Batch-Evaluierung aller Aktivitäten (v9d #15) |
---
## Sleep & Vitals (v9d Phase 2)
### 26. Sleep (`/api/sleep/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/sleep` | ✅ | `?limit=90` | `[{id, date, bedtime, wakeup, duration_min, quality, sleep_segments, notes, source}, ...]` | Schlaf-Einträge |
| `GET` | `/sleep/by-date/{date}` | ✅ | – | `{id, date, ...}` oder `null` | Eintrag für Datum |
| `POST` | `/sleep` | ✅ | `{date, bedtime, wakeup, duration_min, quality?, sleep_segments?, notes?}` | `{id, ...}` | Eintrag erstellen (Upsert) |
| `PUT` | `/sleep/{id}` | ✅ | `{...}` | `{ok: true}` | Bearbeiten |
| `DELETE` | `/sleep/{id}` | ✅ | – | `{ok: true}` | Löschen |
| `GET` | `/sleep/stats` | ✅ | `?days=7` | `{avg_duration, avg_quality, total_deep, total_rem, ...}` | Stats |
| `GET` | `/sleep/debt` | ✅ | `?days=14` | `{sleep_debt_min, avg_duration, target_duration}` | Schlafschuld |
| `GET` | `/sleep/trend` | ✅ | `?days=30` | `[{date, duration_min, quality}, ...]` | Trend |
| `GET` | `/sleep/phases` | ✅ | `?days=30` | `[{date, deep_min, rem_min, light_min, awake_min}, ...]` | Schlafphasen |
| `POST` | `/sleep/import/apple-health` | ✅ | `FormData(file)` | `{imported, skipped, failed, errors}` | Apple Health CSV-Import |
**sleep_segments Format (JSONB):**
```json
[
{"phase": "deep", "start": "23:30", "end": "01:15"},
{"phase": "rem", "start": "01:15", "end": "02:45"},
{"phase": "light", "start": "02:45", "end": "06:00"},
{"phase": "awake", "start": "06:00", "end": "06:15"}
]
```
---
### 27. Rest Days (`/api/rest-days/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/rest-days` | ✅ | `?limit=90` | `[{id, date, rest_type, reason, notes}, ...]` | Ruhetage |
| `GET` | `/rest-days/{id}` | ✅ | – | `{id, ...}` | Einzelner Eintrag |
| `POST` | `/rest-days` | ✅ | `{date, rest_type, reason?, notes?}` | `{id, ...}` | Ruhetag eintragen |
| `PUT` | `/rest-days/{id}` | ✅ | `{...}` | `{ok: true}` | Bearbeiten |
| `DELETE` | `/rest-days/{id}` | ✅ | – | `{ok: true}` | Löschen |
| `GET` | `/rest-days/stats` | ✅ | `?weeks=4` | `{total_rest_days, kraft_days, cardio_days, entspannung_days}` | Stats |
| `POST` | `/rest-days/validate-activity` | ✅ | `{date, activity_type}` | `{conflicts: [{rest_type, reason}, ...]}` | Validierung gegen Ruhetage |
**rest_type:** `kraft`, `cardio`, `entspannung` (Multi-Dimensional Rest)
---
### 28. Vitals Baseline (`/api/vitals/baseline/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/vitals/baseline` | ✅ | `?limit=90` | `[{id, date, resting_hr, hrv, vo2_max, spo2, respiratory_rate, notes}, ...]` | Morgenmessungen |
| `GET` | `/vitals/baseline/by-date/{date}` | ✅ | – | `{id, ...}` oder `null` | Eintrag für Datum |
| `POST` | `/vitals/baseline` | ✅ | `{date, resting_hr?, hrv?, vo2_max?, spo2?, respiratory_rate?, notes?}` | `{id, ...}` | Eintrag erstellen (Upsert) |
| `PUT` | `/vitals/baseline/{id}` | ✅ | `{...}` | `{ok: true}` | Bearbeiten |
| `DELETE` | `/vitals/baseline/{id}` | ✅ | – | `{ok: true}` | Löschen |
| `GET` | `/vitals/baseline/stats` | ✅ | `?days=30` | `{avg_resting_hr, avg_hrv, trend_resting_hr, trend_hrv}` | Stats |
| `POST` | `/vitals/baseline/import/apple-health` | ✅ | `FormData(file)` | `{imported, skipped, failed, errors}` | Apple Health CSV-Import |
**Messung:** 1x täglich, morgens nüchtern
---
### 29. Blood Pressure (`/api/blood-pressure/*`)
| Methode | Pfad | Auth | Parameter | Response | Beschreibung |
|---------|------|------|-----------|----------|--------------|
| `GET` | `/blood-pressure` | ✅ | `?limit=90` | `[{id, date, time, systolic, diastolic, pulse, context, irregular_heartbeat, afib_warning, notes}, ...]` | Blutdruck-Messungen |
| `GET` | `/blood-pressure/by-date/{date}` | ✅ | – | `[{id, time, ...}, ...]` | Alle Messungen für Datum |
| `POST` | `/blood-pressure` | ✅ | `{date, time, systolic, diastolic, pulse?, context?, irregular_heartbeat?, afib_warning?, notes?}` | `{id, ...}` | Messung eintragen |
| `PUT` | `/blood-pressure/{id}` | ✅ | `{...}` | `{ok: true}` | Bearbeiten |
| `DELETE` | `/blood-pressure/{id}` | ✅ | – | `{ok: true}` | Löschen |
| `GET` | `/blood-pressure/stats` | ✅ | `?days=30` | `{avg_systolic, avg_diastolic, avg_pulse, classification, trend}` | Stats |
| `POST` | `/blood-pressure/import/omron` | ✅ | `FormData(file)` | `{imported, skipped, failed, errors}` | Omron CSV-Import (Deutsch) |
**Contexts:** `fasting`, `after_meal`, `exercise`, `stress`, `rest`, `before_sleep`, `after_sleep`, `medication`
**WHO/ISH-Klassifizierung:**
- Optimal: <120/<80
- Normal: 120-129/80-84
- Hoch-Normal: 130-139/85-89
- Hypertonie Grad 1: 140-159/90-99
- Hypertonie Grad 2: 160-179/100-109
- Hypertonie Grad 3: ≥180/≥110
---
## Zusammenfassung
**Gesamt:** 29 Router-Module, ~200 Endpoints
**Authentifizierung:** Token-basiert (X-Auth-Token Header)
**Fehlerformat:** `{"detail": "Fehlermeldung"}`
**Rate Limits:** Nur Auth-Endpoints (5/min Login, 3/hour Register)
**Feature-Limits:** Membership-basiert (v9c), enforcement via HTTP 403
**Import-Formate:** CSV (Apple Health, Omron, FDDB), JSON (Backup)
**Export-Formate:** CSV, JSON, ZIP (mit Fotos)
**Besonderheiten:**
- Upsert-Logik für viele Endpoints (Date-basiert)
- Inline-Editing-Support (GET by date, PUT by id)
- CSV-Import mit Duplikat-Erkennung
- Lernendes Mapping-System (Activity Types)
- JSONB für flexible Datenstrukturen (sleep_segments, abilities)
- Auto-Migration SHA256 → bcrypt
- E-Mail-Verifizierung + Passwort-Reset
+634
View File
@@ -0,0 +1,634 @@
# Architektur-Übersicht – Mitai Jinkendo
## System-Überblick
**Mitai Jinkendo** ist eine selbst-gehostete Progressive Web App (PWA) für Körper-Tracking mit KI-gestützter Auswertung. Die Architektur folgt einem klassischen **3-Tier-Modell** mit klarer Trennung von Präsentation, Business-Logik und Datenhaltung.
```
Internet
↓
Fritz!Box (privat.stommer.com)
↓
Synology NAS
↓
Raspberry Pi 5 (192.168.2.49)
↓
┌────────────────────────────────────┐
│ Docker Compose Environment │
├────────────────────────────────────┤
│ Frontend (React + Vite) │ Port 3002 (Prod) / 3099 (Dev)
│ Backend (FastAPI + Python) │ Port 8002 (Prod) / 8099 (Dev)
│ Database (PostgreSQL 16 Alpine) │ Port 5432 (internal)
└────────────────────────────────────┘
```
---
## Tech-Stack
| Komponente | Technologie | Version | Zweck |
|-----------|-------------|---------|-------|
| **Frontend** | React | 18 | UI Framework |
| | Vite | Latest | Build Tool + Dev Server |
| | React Router | 6 | Client-side Routing |
| | Lucide React | Latest | Icon Library |
| **Backend** | FastAPI | Latest | REST API Framework |
| | Python | 3.12 | Programmiersprache |
| | psycopg2-binary | Latest | PostgreSQL Driver |
| | bcrypt | Latest | Passwort-Hashing |
| | slowapi | Latest | Rate Limiting |
| **Database** | PostgreSQL | 16 Alpine | Primäre Datenbank |
| **Container** | Docker | Latest | Container Runtime |
| | Docker Compose | v2 | Multi-Container Orchestration |
| **KI** | OpenRouter API | - | Claude Sonnet 4 |
| | Anthropic API | - | Direkt-Integration (optional) |
| **Email** | SMTP | - | E-Mail-Versand (Verifikation, Reset) |
| **Infrastruktur** | Raspberry Pi 5 | - | Host-System |
| | Gitea | 3000 | Git Server + CI/CD |
| | Synology NAS | - | Reverse Proxy |
---
## Deployment-Architektur
### Umgebungen
| Umgebung | Domain | Branch | Ports | Deployment |
|----------|--------|--------|-------|-----------|
| **Production** | mitai.jinkendo.de | `main` | 3002/8002 | Auto-Deploy via Gitea |
| **Development** | dev.mitai.jinkendo.de | `develop` | 3099/8099 | Auto-Deploy via Gitea |
### Git-Workflow
```
develop → Push → Gitea Webhook → Runner → docker-compose.dev-env.yml → dev.mitai.jinkendo.de
main → Push → Gitea Webhook → Runner → docker-compose.yml → mitai.jinkendo.de
```
**Runner-Details:**
- Läuft auf Raspberry Pi 5 (`/home/lars/gitea-runner/`)
- Watchtower für automatische Updates
- Docker Compose Build + Restart bei neuen Commits
### Verzeichnisstruktur auf dem Server
```
/home/lars/docker/
├── bodytrack/ # Production
│ ├── docker-compose.yml
│ └── .env
└── bodytrack-dev/ # Development
├── docker-compose.dev-env.yml
└── .env
```
**Externe Volumes:**
- `bodytrack_bodytrack-data` → `/app/data` (Backend JSON-Daten, Legacy)
- `bodytrack_bodytrack-photos` → `/app/photos` (Progress-Fotos)
- `mitai_postgres_data` → PostgreSQL Datenbank
---
## Komponenten-Übersicht
### Backend-Module (26 Router)
| Router | Endpunkte | Beschreibung |
|--------|-----------|--------------|
| **auth** | `/api/auth/*` | Login, Register, Verify, Password Reset |
| **profiles** | `/api/profiles/*`, `/api/profile` | Nutzerverwaltung |
| **weight** | `/api/weight/*` | Gewichts-Tracking |
| **circumference** | `/api/circumferences/*` | Umfangsmessungen (8 Punkte) |
| **caliper** | `/api/caliper/*` | Hautfaltenmessungen (4 Methoden) |
| **activity** | `/api/activity/*` | Training & Aktivitäten |
| **nutrition** | `/api/nutrition/*` | Ernährungsdaten (Kalorien + Makros) |
| **photos** | `/api/photos/*` | Progress-Fotos |
| **insights** | `/api/insights/*`, `/api/ai/*` | KI-Auswertungen |
| **prompts** | `/api/prompts/*` | Konfigurierbare KI-Prompts |
| **admin** | `/api/admin/*` | Admin-Panel (Profile, Permissions) |
| **stats** | `/api/stats` | Statistiken für Dashboard |
| **exportdata** | `/api/export/*` | CSV/JSON/ZIP Export |
| **importdata** | `/api/import/*` | CSV Import |
| **subscription** | `/api/subscription/*` | Abo-Status (v9c) |
| **coupons** | `/api/coupons/*` | Coupon-System (v9c) |
| **features** | `/api/features/*` | Feature-Verwaltung (v9c) |
| **tiers_mgmt** | `/api/tiers/*` | Tier-Verwaltung (v9c) |
| **tier_limits** | `/api/tier-limits/*` | Tier-Limits Matrix (v9c) |
| **user_restrictions** | `/api/user-restrictions/*` | User-spezifische Limits (v9c) |
| **access_grants** | `/api/access-grants/*` | Zeitlich begrenzte Zugriffe (v9c) |
| **training_types** | `/api/training-types/*` | Trainingstypen (v9d) |
| **admin_training_types** | `/api/admin/training-types/*` | Trainingstypen-Admin (v9d) |
| **admin_activity_mappings** | `/api/admin/activity-mappings/*` | Activity Mapping Admin (v9d) |
| **sleep** | `/api/sleep/*` | Schlaf-Modul (v9d Phase 2b) |
| **rest_days** | `/api/rest-days/*` | Ruhetage (v9d Phase 2a) |
| **vitals_baseline** | `/api/vitals/baseline/*` | Morgenmessungen (RHR, HRV, VO2 Max) |
| **blood_pressure** | `/api/blood-pressure/*` | Blutdruck (mehrfach täglich) |
| **evaluation** | `/api/evaluation/*` | Training Type Profiling (v9d Phase 2 #15) |
**Registrierung in `main.py`:**
```python
app.include_router(auth.router)
app.include_router(profiles.router)
# ... alle 26 Router
```
### Frontend-Struktur
```
frontend/src/
├── App.jsx # Root-Komponente + Routing
├── app.css # Globales Design-System
├── context/
│ ├── AuthContext.jsx # Session-Management
│ └── ProfileContext.jsx # Aktives Profil
├── pages/ # 30+ Seiten
│ ├── LoginScreen.jsx # Login + Auto-Migration SHA256→bcrypt
│ ├── Register.jsx # Selbst-Registrierung (v9c)
│ ├── Verify.jsx # E-Mail-Verifizierung
│ ├── Dashboard.jsx # Übersicht mit Stats + Charts
│ ├── CaptureHub.jsx # Quick-Entry-Auswahl
│ ├── WeightScreen.jsx # Gewichts-Erfassung
│ ├── CircumScreen.jsx # Umfänge
│ ├── CaliperScreen.jsx # Caliper
│ ├── ActivityPage.jsx # Training (mit Trainingstypen v9d)
│ ├── NutritionPage.jsx # Ernährung (3-Tab: Entry/Import/Charts)
│ ├── SleepPage.jsx # Schlaf (v9d Phase 2b)
│ ├── RestDaysPage.jsx # Ruhetage (v9d Phase 2a)
│ ├── VitalsPage.jsx # Vitalwerte (3-Tab: Baseline/BP/Import)
│ ├── History.jsx # Verlauf-Charts
│ ├── Analysis.jsx # KI-Analyse + Pipeline
│ ├── SettingsPage.jsx # Einstellungen
│ ├── SubscriptionPage.jsx # Membership-UI (v9c)
│ └── Admin*.jsx # 9 Admin-Seiten
└── utils/
├── api.js # ALLE API-Calls (285 Zeilen)
├── calc.js # Body-Fat-Berechnungen
├── interpret.js # Daten-Interpretation
├── Markdown.jsx # Markdown-Renderer
└── guideData.js # Guide-Inhalte
```
---
## Datenfluss
### 1. User Request → Auth → API → Database
```
User Action (Frontend)
↓
api.js (Token injiziert via hdrs())
↓
FastAPI Endpoint
↓
require_auth() Dependency (auth.py)
↓ (validiert X-Auth-Token → session)
↓
get_session() → SELECT FROM sessions JOIN profiles
↓ (returns session dict mit profile_id, role, ai_enabled, ...)
↓
Router-Funktion
↓
db.py → get_db() Context Manager
↓
psycopg2 → PostgreSQL Query (RealDictCursor)
↓
Response (JSON)
```
### 2. Feature Access Control (v9c)
```
Endpoint (z.B. POST /api/insights/run)
↓
check_feature_access(profile_id, 'ai_calls')
↓
Prüf-Hierarchie:
1. user_feature_restrictions (user-spezifisch)
2. tier_limits (Tier-basiert)
3. features.default_limit (Fallback)
↓
get_effective_tier(profile_id)
→ access_grants (Coupon/Trial) ODER profiles.tier
↓
user_feature_usage (aktueller Zähler)
↓
Ergebnis: {allowed: bool, limit: int, used: int, remaining: int, reason: str}
↓
Falls allowed == false → HTTP 403
Falls allowed == true → increment_feature_usage() + execute
```
### 3. KI-Pipeline (3-stufig)
```
User: "Analyse starten"
↓
POST /api/insights/pipeline
↓
check_feature_access('ai_pipeline')
↓
Stufe 1: Gewicht-Trend → claude-sonnet-4 (OpenRouter)
Stufe 2: Ernährung → claude-sonnet-4
Stufe 3: Gesamtanalyse → claude-sonnet-4 (mit Ergebnissen aus 1+2)
↓
Jeder Call: increment_feature_usage('ai_calls')
↓
INSERT INTO ai_insights (scope='pipeline', content=...)
↓
Return: {content: "...", usage: {...}}
```
---
## Sicherheitsarchitektur
### 1. Passwort-Sicherheit
**Hash-Verfahren:**
- **Aktuell:** bcrypt (Salting + Work Factor)
- **Legacy:** SHA256 (wird beim Login automatisch zu bcrypt migriert)
**Passwort-Hashing (`auth.py`):**
```python
def hash_pin(pin: str) -> str:
return bcrypt.hashpw(pin.encode(), bcrypt.gensalt()).decode()
def verify_pin(pin: str, stored_hash: str) -> bool:
if stored_hash.startswith('$2'): # bcrypt
return bcrypt.checkpw(pin.encode(), stored_hash.encode())
# Legacy SHA256 → auto-upgrade beim nächsten Login
return stored_hash == hashlib.sha256(pin.encode()).hexdigest()
```
### 2. Session-Management
**Token-Format:**
- `secrets.token_urlsafe(32)` → 43 Zeichen Base64-URL-safe
- Gespeichert in `sessions` Tabelle mit `expires_at`
- Standard-Lebensdauer: 30 Tage (konfigurierbar pro Profil)
**Auth-Flow:**
```python
# Backend
@router.post("/api/auth/login")
def login(email, password):
profile = SELECT ... WHERE email=...
verify_pin(password, profile.pin_hash) # ✓
token = make_token()
INSERT INTO sessions (token, profile_id, expires_at)
return {"token": token, "profile": {...}}
# Frontend (AuthContext.jsx)
localStorage.setItem('mitai-jinkendo_token', token)
```
**Auth-Middleware (`auth.py`):**
```python
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 # dict mit profile_id, role, ai_enabled, ...
```
### 3. CORS-Konfiguration
**Produktion (`docker-compose.yml`):**
```yaml
ALLOWED_ORIGINS: https://mitai.jinkendo.de
```
**Development:**
```yaml
ALLOWED_ORIGINS: https://dev.mitai.jinkendo.de,http://localhost:3099
```
**FastAPI Setup (`main.py`):**
```python
app.add_middleware(
CORSMiddleware,
allow_origins=os.getenv("ALLOWED_ORIGINS", "*").split(","),
allow_credentials=True,
allow_methods=["GET","POST","PUT","DELETE","OPTIONS"],
allow_headers=["*"],
)
```
### 4. Rate Limiting
**Library:** slowapi (Redis-freie In-Memory Rate Limiting)
**Anwendung:**
```python
from slowapi import Limiter
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
@router.post("/auth/login")
@limiter.limit("5/minute") # Max 5 Login-Versuche pro Minute
def login(request: Request, ...):
...
```
**Geschützte Endpoints:**
- `/api/auth/login` → 5/minute
- `/api/auth/register` → 3/minute
- KI-Endpoints → via Feature-Limits (nicht Rate Limiting)
### 5. SQL Injection Protection
**Parameter-Binding:**
```python
# ✅ Sicher (psycopg2 escaped automatisch):
cur.execute("SELECT * FROM profiles WHERE id = %s", (profile_id,))
# ❌ NIEMALS:
cur.execute(f"SELECT * FROM profiles WHERE id = '{profile_id}'")
```
**RealDictCursor:**
- Automatisches Escaping
- Keine String-Konkatenation
---
## Versions-Historie
### v9c (Komplett) – Production seit 21.03.2026 ✅
**Features:**
- Membership-System (5 Tiers: free/basic/premium/selfhosted)
- Coupon-System + Trial (14 Tage)
- Feature-Enforcement (4 Phasen):
- Phase 1: Cleanup ✅
- Phase 2: Monitoring ✅
- Phase 3: Frontend Display ✅
- Phase 4: Enforcement (HTTP 403) ✅
- Selbst-Registrierung + E-Mail-Verifizierung
- Export: CSV/JSON/ZIP
- Ernährungs-Modul erweitert (3-Tab Layout)
### v9d – Phase 1b ✅
**Trainingstypen-System:**
- 29 Trainingstypen in 7 Kategorien
- Lernendes Mapping-System (DB-basiert)
- Apple Health Import (Deutsch + English)
- Bulk-Kategorisierung (selbstlernend)
### v9d – Phase 2 ✅ (Deployed 23.03.2026)
**Vitalwerte & Erholung:**
- **Schlaf-Modul (v9d Phase 2b):**
- Tabelle `sleep_log` mit JSONB sleep_segments
- Schlafphasen (Deep, REM, Light, Awake)
- Apple Health CSV Import
- **Ruhetage (v9d Phase 2a):**
- Multi-dimensionale Ruhetage (Kraft/Cardio/Entspannung)
- Quick Mode Presets + Custom Entry
- **Vitalwerte erweitert (v9d Phase 2d):**
- **3-Tab Architektur:** Baseline (morgens) / Blutdruck (mehrfach täglich) / Import
- **Baseline Vitals:** Ruhepuls, HRV, VO2 Max, SpO2, Atemfrequenz
- **Blutdruck:** Systolisch/Diastolisch + Puls, WHO/ISH-Klassifizierung
- **Context-Tagging:** 8 Kontexte (nüchtern, nach Essen, Training, Stress, etc.)
- **Inline-Editing:** Alle Messungen direkt in der Liste bearbeitbar
- CSV Import: Omron (Deutsch) + Apple Health (Deutsch/Englisch)
### v9b (PostgreSQL-Migration)
- Migration SQLite → PostgreSQL 16
- Connection Pooling (psycopg2)
- UUID statt Integer Primary Keys
- Trigger für auto-update timestamps
### v9a (Basis)
- Login + Auth-Middleware
- Gewicht, Umfänge, Caliper, Ernährung, Aktivität
- KI-Analyse (6 Prompts + 3-stufige Pipeline)
- PWA + Dashboard
- Admin-Panel
---
## Design-Entscheidungen
### Warum PostgreSQL statt SQLite?
**Vorteile:**
- Concurrent Writes (SQLite locked bei Writes)
- Native UUID Support
- JSONB für flexible Datenstrukturen (z.B. sleep_segments)
- Trigger + Stored Procedures
- Production-ready für Self-Hosting
**Migration:**
- Automatisches Migrations-System (`db_init.py`)
- Rollback-fähig via SQL-Dateien
- Tracking in `schema_migrations` Tabelle
### Warum FastAPI statt Flask/Django?
**Vorteile:**
- Async Support (für zukünftige WebSocket-Features)
- Automatic OpenAPI Docs
- Type Hints → automatische Validierung
- Dependency Injection (z.B. `require_auth`)
- Performance (ASGI statt WSGI)
### Warum React statt Vue/Svelte?
**Entscheidung:**
- Bekanntes Ecosystem
- Context API ausreichend (kein Redux nötig)
- Gute PWA-Integration
- React Router maturity
### Warum kein TypeScript?
**Entscheidung (bewusst):**
- Schnellere Prototyping-Geschwindigkeit
- Weniger Build-Komplexität
- Dokumentation via JSDoc-Kommentare
- Type Safety durch Backend (Pydantic)
### Warum Connection Pooling?
**Problem ohne Pooling:**
- Jeder API-Call → neue DB-Verbindung → Overhead
- PostgreSQL max_connections erreicht bei vielen gleichzeitigen Requests
**Lösung:**
```python
_pool = psycopg2.pool.SimpleConnectionPool(minconn=1, maxconn=10)
@contextmanager
def get_db():
conn = _pool.getconn()
try:
yield conn
conn.commit()
except:
conn.rollback()
raise
finally:
_pool.putconn(conn)
```
**Vorteil:**
- Max 10 gleichzeitige Verbindungen
- Automatisches Recycling
- Auto-Commit/Rollback
---
## Bekannte Limitationen & Workarounds
### 1. Docker Build auf Raspberry Pi
**Problem:** `apt-get install postgresql-client` hängt 30+ Minuten
**Lösung:** Reine Python-Lösung mit `psycopg2-binary` (keine System-Dependencies)
### 2. Apple Health CSV-Import
**Problem:** Dezimalwerte werden als String exportiert (`"65.0"` statt `65`)
**Lösung:**
```python
def safe_float(val):
try:
return float(val) if val else None
except:
return None
```
### 3. Bun Crash nach langen Claude Code Sessions
**Problem:** Bun (JS Runtime für Claude Code CLI) crashed bei >30 Min Sessions
**Workaround:** Bei komplexen Tasks früher committen + neue Session starten
### 4. dayjs.week() ohne Plugin
**Problem:** `dayjs().week()` existiert nicht ohne `isoWeek`-Plugin
**Lösung:** Native ISO-Wochenberechnung:
```javascript
const isoWeek = (d => Math.ceil(((new Date(d.setDate(d.getDate()+4-(d.getDay()||7)))-
new Date(d.getFullYear(),0,1))/86400000+1)/7))(new Date(date))
```
---
## Performance-Optimierungen
### 1. Frontend
- **Code Splitting:** React.lazy() für Admin-Seiten (nicht initial geladen)
- **Image Loading:** `loading="lazy"` für Photos
- **CSS:** Inline Critical CSS, kein CSS-in-JS Overhead
- **PWA Cache:** Service Worker cached statische Assets
### 2. Backend
- **Connection Pooling:** Max 10 Connections statt unlimited
- **Query Optimization:** Indizes auf häufig abgefragte Spalten
- **Lazy Loading:** KI-Analysen nur auf Abruf, nicht im Dashboard
### 3. Database
**Indizes:**
```sql
CREATE INDEX idx_weight_log_profile_date ON weight_log(profile_id, date DESC);
CREATE INDEX idx_sessions_expires_at ON sessions(expires_at);
CREATE INDEX idx_ai_insights_profile_scope ON ai_insights(profile_id, scope, created DESC);
```
**Unique Constraints:**
```sql
CREATE UNIQUE INDEX idx_weight_log_profile_date_unique ON weight_log(profile_id, date);
```
---
## Monitoring & Logging
### 1. Feature Usage Logging (v9c Phase 2)
**Format:** JSON Lines (JSONL)
**Speicherort:** `/app/logs/feature-usage.log`
**Beispiel:**
```json
{"timestamp":"2026-03-23T10:15:30Z","profile_id":"uuid-here","feature":"ai_calls","allowed":true,"limit":10,"used":3,"remaining":7}
{"timestamp":"2026-03-23T10:16:00Z","profile_id":"uuid-here","feature":"data_export","allowed":false,"limit":0,"used":0,"remaining":0,"reason":"limit_exceeded"}
```
**Auswertung:**
```bash
cat feature-usage.log | jq -s 'group_by(.feature) | map({feature: .[0].feature, total: length})'
```
### 2. Health Checks
**Database:**
```yaml
healthcheck:
test: ["CMD-SHELL", "pg_isready -U mitai_prod"]
interval: 10s
```
**API:**
```python
@app.get("/")
def root():
return {"status": "ok", "service": "mitai-jinkendo", "version": "v9c-dev"}
```
### 3. Error Handling
**Einheitliches Format:**
```python
raise HTTPException(status_code=404, detail="Eintrag nicht gefunden")
# → {"detail": "Eintrag nicht gefunden"}
```
**Frontend (`api.js`):**
```javascript
if (!res.ok) {
const err = await res.text()
try {
const parsed = JSON.parse(err)
throw new Error(parsed.detail || err)
} catch {
throw new Error(err)
}
}
```
---
## Zusammenfassung
**Architektur-Highlights:**
- ✅ Modulare Router-Struktur (26 Module, single responsibility)
- ✅ Connection Pooling (max 10 concurrent DB connections)
- ✅ Token-basiertes Auth + bcrypt
- ✅ Feature Access Control mit Tier-System
- ✅ Docker Compose für einfaches Deployment
- ✅ Auto-Deploy via Gitea Webhooks
- ✅ PostgreSQL mit Migrations-System
- ✅ PWA mit Service Worker
- ✅ API-First Prinzip (Backend = Single Source of Truth)
**Nächste Schritte (v9e+):**
- Ziele-Modul (Goal Tracking)
- HF-Zonen + Erholungsstatus
- Stripe-Integration
- Connectoren (Garmin, Withings, etc.)
- Meditation + Selbstwahrnehmung
+904
View File
@@ -0,0 +1,904 @@
# Auth-Flow & Sicherheit
## Übersicht
Mitai Jinkendo nutzt **Token-basiertes Session-Management** mit bcrypt-Passwort-Hashing. Die Authentifizierung ist als FastAPI Dependency implementiert (`require_auth()`), die automatisch auf alle geschützten Endpoints angewendet wird.
**Sicherheits-Features:**
- ✅ bcrypt-Hashing (Work Factor ~12 Rounds)
- ✅ Auto-Migration SHA256 → bcrypt
- ✅ Rate Limiting (slowapi)
- ✅ CORS-Konfiguration
- ✅ E-Mail-Verifizierung für Registrierung
- ✅ Passwort-Reset via E-Mail (1h Token)
- ✅ Session-Expiry (30 Tage Standard)
- ✅ Admin-Role-Check
---
## Login-Flow (Schritt für Schritt)
### 1. User-Eingabe (Frontend)
**LoginScreen.jsx:**
```javascript
const handleLogin = async () => {
const data = await login({ email: email.trim().toLowerCase(), password })
window.location.href = '/' // Hard-Redirect nach Login
}
```
### 2. POST /api/auth/login (Backend)
**Request:**
```json
{
"email": "user@example.com",
"password": "geheim123"
}
```
**Backend-Logik (`backend/routers/auth.py`):**
```python
@router.post("/login")
@limiter.limit("5/minute") # Rate Limiting
async def login(req: LoginRequest, request: Request):
# 1. E-Mail-Lookup
cur.execute("SELECT * FROM profiles WHERE email=%s", (req.email.lower().strip(),))
prof = cur.fetchone()
if not prof:
raise HTTPException(401, "Ungültige Zugangsdaten")
# 2. Passwort-Verifizierung
if not verify_pin(req.password, prof['pin_hash']):
raise HTTPException(401, "Ungültige Zugangsdaten")
# 3. Auto-Migration SHA256 → bcrypt
if not prof['pin_hash'].startswith('$2'): # bcrypt-Hash startet mit $2b$ oder $2a$
new_hash = hash_pin(req.password)
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, prof['id']))
# 4. Session erstellen
token = make_token() # secrets.token_urlsafe(32) → 43 Zeichen
session_days = prof.get('session_days', 30)
expires = datetime.now() + timedelta(days=session_days)
cur.execute("""
INSERT INTO sessions (token, profile_id, expires_at, created)
VALUES (%s, %s, %s, CURRENT_TIMESTAMP)
""", (token, prof['id'], expires))
return {
"token": token,
"profile_id": prof['id'],
"name": prof['name'],
"role": prof['role'],
"expires_at": expires.isoformat()
}
```
**Response:**
```json
{
"token": "jT9z3xK...(43 chars)...pQ2vL",
"profile_id": "550e8400-e29b-41d4-a716-446655440000",
"name": "Max Mustermann",
"role": "user",
"expires_at": "2026-04-22T14:30:00"
}
```
### 3. Token-Speicherung (Frontend)
**AuthContext.jsx:**
```javascript
const login = async (credentials) => {
const data = await api.login(credentials)
// Token speichern
localStorage.setItem('bodytrack_token', data.token)
localStorage.setItem('bodytrack_active_profile', data.profile_id)
// Volles Profil laden
const profile = await fetch('/api/auth/me', {
headers: { 'X-Auth-Token': data.token }
})
setSession({
token: data.token,
profile_id: data.profile_id,
role: data.role,
profile: await profile.json()
})
}
```
### 4. Nachfolgende Requests
**api.js:**
```javascript
function hdrs(extra={}) {
const h = {...extra}
const token = getToken() // localStorage.getItem('bodytrack_token')
if (token) h['X-Auth-Token'] = token
return h
}
async function req(path, opts={}) {
const res = await fetch(BASE+path, {...opts, headers:hdrs(opts.headers||{})})
// ...
}
```
**Jeder API-Call sendet automatisch:**
```
GET /api/weight
Headers:
X-Auth-Token: jT9z3xK...pQ2vL
```
### 5. Auth-Validierung (Backend)
**require_auth() Dependency:**
```python
def require_auth(x_auth_token: Optional[str] = Header(default=None)):
"""FastAPI Dependency - requires valid authentication."""
session = get_session(x_auth_token)
if not session:
raise HTTPException(401, "Nicht eingeloggt")
return session
def get_session(token: str):
"""Get session data for a given token."""
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()
```
**Endpoint-Beispiel:**
```python
@router.get("/api/weight")
def list_weight(session: dict = Depends(require_auth)):
profile_id = session['profile_id'] # Immer aus Session, nie aus Header!
# ... Query mit profile_id
```
**Session-Dict:**
```python
{
'profile_id': 'uuid-string',
'role': 'user' | 'admin',
'name': 'Max Mustermann',
'ai_enabled': True,
'ai_limit_day': 10,
'export_enabled': True,
'expires_at': datetime(2026, 4, 22, 14, 30, 0)
}
```
---
## Registrierung-Flow (v9c)
### 1. Selbst-Registrierung
**POST /api/auth/register:**
```json
{
"name": "Max Mustermann",
"email": "max@example.com",
"password": "sicheresPasswort123"
}
```
**Validierung:**
- E-Mail: Muss `@` enthalten
- Passwort: Mindestens 8 Zeichen
- Name: Mindestens 2 Zeichen
- E-Mail-Duplikat-Check
**Backend:**
```python
@router.post("/register")
@limiter.limit("3/hour") # Rate Limiting
async def register(req: RegisterRequest, request: Request):
email = req.email.lower().strip()
# Duplikat-Check
cur.execute("SELECT id FROM profiles WHERE email=%s", (email,))
if cur.fetchone():
raise HTTPException(400, "E-Mail-Adresse bereits registriert")
# Profil erstellen (inaktiv bis verifiziert)
profile_id = str(secrets.token_hex(16))
pin_hash = hash_pin(req.password)
verification_token = secrets.token_urlsafe(32)
verification_expires = datetime.now() + timedelta(hours=24)
trial_ends = datetime.now() + timedelta(days=14) # 14-Tage-Trial
cur.execute("""
INSERT INTO profiles (
id, name, email, pin_hash, auth_type, role, tier,
email_verified, verification_token, verification_expires,
trial_ends_at, created
) VALUES (%s, %s, %s, %s, 'email', 'user', 'free', FALSE, %s, %s, %s, CURRENT_TIMESTAMP)
""", (profile_id, req.name, email, pin_hash, verification_token, verification_expires, trial_ends))
# Verifizierungs-E-Mail senden
send_email(email, "Willkommen bei Mitai Jinkendo", f"Verify: {APP_URL}/verify?token={verification_token}")
```
**Response:**
```json
{
"ok": true,
"message": "Registrierung erfolgreich! Bitte prüfe dein E-Mail-Postfach."
}
```
### 2. E-Mail-Verifizierung
**User klickt Link in E-Mail:**
```
https://mitai.jinkendo.de/verify?token=jT9z3xK...pQ2vL
```
**GET /api/auth/verify/{token}:**
```python
@router.get("/verify/{token}")
async def verify_email(token: str):
# Token-Lookup
cur.execute("""
SELECT id, name, email, email_verified, verification_expires
FROM profiles
WHERE verification_token=%s
""", (token,))
prof = cur.fetchone()
if not prof:
raise HTTPException(400, "Verifikations-Link ungültig")
if prof['email_verified']:
raise HTTPException(400, "E-Mail bereits bestätigt")
if datetime.now() > prof['verification_expires']:
raise HTTPException(400, "Link abgelaufen")
# Verifizierung
cur.execute("""
UPDATE profiles
SET email_verified=TRUE, verification_token=NULL, verification_expires=NULL
WHERE id=%s
""", (prof['id'],))
# Auto-Login (Session erstellen)
session_token = make_token()
expires = datetime.now() + timedelta(days=30)
cur.execute("""
INSERT INTO sessions (token, profile_id, expires_at, created)
VALUES (%s, %s, %s, CURRENT_TIMESTAMP)
""", (session_token, prof['id'], expires))
return {
"ok": True,
"token": session_token,
"profile": {"id": prof['id'], "name": prof['name'], "email": prof['email']}
}
```
**Frontend (Verify.jsx):**
```javascript
const verifyToken = urlParams.get('token')
const data = await api.verifyEmail(verifyToken)
// Auto-Login nach Verifizierung
setAuthFromToken(data.token, data.profile)
window.location.href = '/'
```
### 3. Resend Verification
**POST /api/auth/resend-verification:**
```json
{
"email": "max@example.com"
}
```
**Backend:**
- Generiert neuen Token (24h Gültigkeit)
- Sendet erneut E-Mail
- Rate Limit: 3/hour
---
## Passwort-Reset-Flow
### 1. Passwort vergessen
**POST /api/auth/forgot-password:**
```json
{
"email": "max@example.com"
}
```
**Backend:**
```python
@router.post("/forgot-password")
@limiter.limit("3/minute")
async def password_reset_request(req: PasswordResetRequest, request: Request):
email = req.email.lower().strip()
cur.execute("SELECT id, name FROM profiles WHERE email=%s", (email,))
prof = cur.fetchone()
if not prof:
# Don't reveal if email exists (Anti-Enumeration)
return {"ok": True, "message": "Falls die E-Mail existiert, wurde ein Link gesendet."}
# Reset-Token erstellen
token = secrets.token_urlsafe(32)
expires = datetime.now() + timedelta(hours=1) # 1 Stunde gültig
# In sessions-Tabelle speichern (mit Präfix "reset_")
cur.execute("""
INSERT INTO sessions (token, profile_id, expires_at, created)
VALUES (%s, %s, %s, CURRENT_TIMESTAMP)
""", (f"reset_{token}", prof['id'], expires))
# E-Mail senden
send_email(prof['email'], "Passwort zurücksetzen", f"Reset: {APP_URL}/reset-password?token={token}")
```
### 2. Neues Passwort setzen
**User klickt Link in E-Mail:**
```
https://mitai.jinkendo.de/reset-password?token=jT9z3xK...pQ2vL
```
**POST /api/auth/reset-password:**
```json
{
"token": "jT9z3xK...pQ2vL",
"new_password": "neuesPasswort123"
}
```
**Backend:**
```python
@router.post("/reset-password")
def password_reset_confirm(req: PasswordResetConfirm):
cur.execute("""
SELECT profile_id FROM sessions
WHERE token=%s AND expires_at > CURRENT_TIMESTAMP
""", (f"reset_{req.token}",))
sess = cur.fetchone()
if not sess:
raise HTTPException(400, "Ungültiger oder abgelaufener Reset-Link")
# Passwort ändern
new_hash = hash_pin(req.new_password)
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, sess['profile_id']))
# Reset-Token löschen
cur.execute("DELETE FROM sessions WHERE token=%s", (f"reset_{req.token}",))
return {"ok": True, "message": "Passwort erfolgreich zurückgesetzt"}
```
---
## Session-Management
### Session-Struktur (Datenbank)
**Tabelle: `sessions`**
```sql
CREATE TABLE sessions (
token VARCHAR(64) PRIMARY KEY, -- secrets.token_urlsafe(32)
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
created TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_sessions_profile_id ON sessions(profile_id);
CREATE INDEX idx_sessions_expires_at ON sessions(expires_at);
```
### Token-Format
**`secrets.token_urlsafe(32)`**
- 32 Bytes Zufallsdaten
- Base64-URL-safe-kodiert
- Resultierende Länge: 43 Zeichen
- Charset: `A-Za-z0-9_-`
**Beispiel:** `jT9z3xKpLmN8vQrStUwXyZ1aB2cD3eF4gH5iJ6kL7mN8oP9qR`
### Session-Lebensdauer
**Standard:** 30 Tage (konfigurierbar pro Profil via `profiles.session_days`)
**Nach Login:**
```python
session_days = prof.get('session_days', 30)
expires = datetime.now() + timedelta(days=session_days)
```
**Automatische Bereinigung:**
- Abgelaufene Sessions werden bei Login automatisch gelöscht (via `WHERE expires_at > CURRENT_TIMESTAMP`)
- Geplant: Cron-Job für Cleanup alter Sessions (v10+)
### Logout
**POST /api/auth/logout:**
```python
@router.post("/logout")
def logout(x_auth_token: Optional[str]=Header(default=None)):
if x_auth_token:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("DELETE FROM sessions WHERE token=%s", (x_auth_token,))
return {"ok": True}
```
**Frontend:**
```javascript
const logout = async () => {
await fetch('/api/auth/logout', {
method: 'POST',
headers: { 'X-Auth-Token': token }
})
localStorage.removeItem('bodytrack_token')
setSession(null)
}
```
---
## Passwort-Sicherheit
### 1. bcrypt-Hashing
**Verwendete Bibliothek:** `bcrypt` (Python)
**Konfiguration:**
- Work Factor: Default (~12 Rounds)
- Automatisches Salting (integriert in bcrypt)
**Hash-Format:**
```
$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz3/yDZL1AJ.zCBU8fKWChSrW8GZF1a
│ │ │ │ │
│ │ │ └─ Salt (22 Zeichen) └─ Hash (31 Zeichen)
│ │ └─ Cost-Faktor (12 = 2^12 = 4096 Iterationen)
│ └─ bcrypt-Variante ('a' oder 'b')
└─ Präfix
```
**Hashing-Funktion (`auth.py`):**
```python
import bcrypt
def hash_pin(pin: str) -> str:
"""Hash password with bcrypt."""
return bcrypt.hashpw(pin.encode(), bcrypt.gensalt()).decode()
```
**Verifizierung:**
```python
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()
```
### 2. SHA256 → bcrypt Auto-Migration
**Problem:** Alte Accounts hatten SHA256-Hashes (unsicher, kein Salting)
**Lösung:** Automatische Migration beim Login
**Logik:**
```python
# Beim Login
if prof['pin_hash'] and not prof['pin_hash'].startswith('$2'):
# Passwort verifiziert erfolgreich (via SHA256)
# → Upgrade zu bcrypt
new_hash = hash_pin(req.password)
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, prof['id']))
```
**Ablauf:**
1. User loggt sich mit altem Passwort ein
2. Backend verifiziert gegen SHA256-Hash (erfolgreich)
3. Backend erstellt bcrypt-Hash vom Klartext-Passwort
4. SHA256-Hash wird in DB durch bcrypt-Hash ersetzt
5. Nächster Login → bcrypt-Verifizierung
**Vorteil:** Keine Passwort-Resets nötig, Migration transparent
### 3. Passwort-Anforderungen
**Minimum:**
- Länge: 8 Zeichen (bei Registrierung)
- Länge: 4 Zeichen (bei PIN-Change, für Abwärtskompatibilität)
**Empfohlen (nicht erzwungen):**
- Groß- und Kleinbuchstaben
- Zahlen
- Sonderzeichen
**Keine Komplexitäts-Prüfung:** Bewusst nicht implementiert (Fokus auf Länge statt Komplexität)
---
## Rate Limiting
**Bibliothek:** slowapi (Redis-freie In-Memory Rate Limiting)
### Konfiguration
**main.py:**
```python
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
```
### Rate Limits
| Endpoint | Limit | Grund |
|----------|-------|-------|
| `/api/auth/login` | 5/minute | Brute-Force-Schutz |
| `/api/auth/register` | 3/hour | Spam-Prevention |
| `/api/auth/forgot-password` | 3/minute | E-Mail-Flooding-Schutz |
| `/api/auth/resend-verification` | 3/hour | E-Mail-Flooding-Schutz |
**Verwendung:**
```python
from slowapi import Limiter
@router.post("/login")
@limiter.limit("5/minute")
async def login(req: LoginRequest, request: Request):
# Request-Objekt muss übergeben werden für IP-Extraktion
pass
```
**Response bei Überschreitung:**
```
HTTP 429 Too Many Requests
{
"detail": "Rate limit exceeded: 5 per 1 minute"
}
```
**Key-Funktion:** `get_remote_address` → IP-basiert (nicht User-basiert)
**Hinweis:** In-Memory = Reset bei Server-Neustart
---
## CORS-Konfiguration
### Produktion
**docker-compose.yml:**
```yaml
ALLOWED_ORIGINS: https://mitai.jinkendo.de
```
**main.py:**
```python
app.add_middleware(
CORSMiddleware,
allow_origins=os.getenv("ALLOWED_ORIGINS", "*").split(","),
allow_credentials=True,
allow_methods=["GET","POST","PUT","DELETE","OPTIONS"],
allow_headers=["*"],
)
```
### Development
**docker-compose.dev-env.yml:**
```yaml
ALLOWED_ORIGINS: https://dev.mitai.jinkendo.de,http://localhost:3099
```
**Wichtig:** Keine Wildcards (`*`) in Produktion!
---
## Öffentliche vs. geschützte Endpoints
### Öffentliche Endpoints (kein Auth)
| Endpoint | Methode | Zweck |
|----------|---------|-------|
| `/` | GET | Health Check |
| `/api/auth/status` | GET | Status-Check (First-Run-Detection) |
| `/api/auth/login` | POST | Login |
| `/api/auth/register` | POST | Registrierung |
| `/api/auth/verify/{token}` | GET | E-Mail-Verifizierung |
| `/api/auth/forgot-password` | POST | Passwort-Reset anfordern |
| `/api/auth/reset-password` | POST | Passwort-Reset bestätigen |
| `/api/auth/resend-verification` | POST | Verifizierungs-E-Mail erneut senden |
### Geschützte Endpoints (require_auth)
**Alle anderen Endpoints** benötigen `X-Auth-Token` Header.
**Beispiel:**
```python
@router.get("/api/weight")
def list_weight(session: dict = Depends(require_auth)):
profile_id = session['profile_id']
# ...
```
### Admin-Only Endpoints (require_admin)
| Endpoint | Zweck |
|----------|-------|
| `/api/admin/*` | Admin-Panel |
| `/api/features` | Feature-Verwaltung (POST/PUT/DELETE) |
| `/api/tiers` | Tier-Verwaltung (POST/PUT/DELETE) |
| `/api/tier-limits` | Tier-Limits-Matrix (PUT) |
| `/api/coupons` | Coupon-Verwaltung (POST/PUT/DELETE) |
| `/api/user-restrictions` | User-Restrictions (POST/PUT/DELETE) |
| `/api/access-grants` | Access-Grants (POST/PUT/DELETE) |
| `/api/admin/training-types` | Trainingstypen-Admin (POST/PUT/DELETE) |
| `/api/admin/activity-mappings` | Activity-Mappings (POST/PUT/DELETE) |
**require_admin() Dependency:**
```python
def require_admin(x_auth_token: Optional[str] = Header(default=None)):
"""FastAPI dependency - requires admin authentication."""
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
```
---
## E-Mail-System
### SMTP-Konfiguration
**Umgebungsvariablen:**
```env
SMTP_HOST=smtp.strato.de
SMTP_PORT=587
SMTP_USER=noreply@jinkendo.de
SMTP_PASS=*****
SMTP_FROM=noreply@jinkendo.de
APP_URL=https://mitai.jinkendo.de
```
### E-Mail-Versand
**Helper-Funktion (`backend/routers/auth.py`):**
```python
def send_email(to_email: str, subject: str, body: str):
"""Send email via SMTP (reusable helper)."""
try:
smtp_host = os.getenv("SMTP_HOST")
smtp_port = int(os.getenv("SMTP_PORT", 587))
smtp_user = os.getenv("SMTP_USER")
smtp_pass = os.getenv("SMTP_PASS")
smtp_from = os.getenv("SMTP_FROM", "noreply@jinkendo.de")
if not smtp_host or not smtp_user or not smtp_pass:
print("SMTP not configured, skipping email")
return False
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = smtp_from
msg['To'] = to_email
with smtplib.SMTP(smtp_host, smtp_port) as server:
server.starttls()
server.login(smtp_user, smtp_pass)
server.send_message(msg)
return True
except Exception as e:
print(f"Email error: {e}")
return False
```
### E-Mail-Templates
**Registrierung (Verifizierung):**
```
Betreff: Willkommen bei Mitai Jinkendo – E-Mail bestätigen
Hallo {name},
willkommen bei Mitai Jinkendo!
Bitte bestätige deine E-Mail-Adresse um die Registrierung abzuschließen:
https://mitai.jinkendo.de/verify?token={verification_token}
Der Link ist 24 Stunden gültig.
Dein Mitai Jinkendo Team
```
**Passwort-Reset:**
```
Betreff: Passwort zurücksetzen – Mitai Jinkendo
Hallo {name},
du hast einen Passwort-Reset angefordert.
Reset-Link: https://mitai.jinkendo.de/reset-password?token={token}
Der Link ist 1 Stunde gültig.
Falls du diese Anfrage nicht gestellt hast, ignoriere diese E-Mail.
Dein Mitai Jinkendo Team
```
---
## Bekannte Sicherheitsentscheidungen
### 1. Profile-ID aus Session, nie aus Header
**❌ Falsch (Sicherheitslücke):**
```python
@router.get("/weight")
def list_weight(x_profile_id: str = Header(default=None), session=Depends(require_auth)):
profile_id = x_profile_id # User könnte beliebige ID senden!
```
**✅ Richtig:**
```python
@router.get("/weight")
def list_weight(session: dict = Depends(require_auth)):
profile_id = session['profile_id'] # Immer aus validierter Session
```
**Grund:** Session ist an Token gebunden → User kann nur eigene Daten abrufen
### 2. E-Mail-Enumeration-Schutz
**Problem:** Registrierung könnte verraten ob E-Mail bereits existiert
**Lösung:**
```python
if cur.fetchone():
raise HTTPException(400, "E-Mail-Adresse bereits registriert")
```
**Passwort-Reset:**
```python
if not prof:
# Don't reveal if email exists
return {"ok": True, "message": "Falls die E-Mail existiert, wurde ein Link gesendet."}
```
**Trade-off:** Registrierung gibt Info preis (UX > Sicherheit), Reset nicht (Sicherheit > UX)
### 3. Reset-Token-Präfix
**Problem:** Reset-Token könnte mit regulären Session-Token kollidieren
**Lösung:**
```python
cur.execute("INSERT INTO sessions (token, ...) VALUES (%s, ...)", (f"reset_{token}", ...))
```
**Vorteil:** Eindeutige Identifikation, kein Risiko von Kollisionen
### 4. Keine Passwort-Komplexitäts-Prüfung
**Entscheidung:** Nur Mindestlänge (8 Zeichen), keine Sonderzeichen-Pflicht
**Grund:**
- Länge > Komplexität (NIST-Empfehlung)
- Komplexitäts-Anforderungen führen zu schlechteren Passwörtern (z.B. `Password123!`)
- Benutzerfreundlichkeit
**Alternative:** Passwort-Strength-Meter im Frontend (geplant)
### 5. In-Memory Rate Limiting
**Problem:** Rate Limits resetten bei Server-Neustart
**Akzeptiert weil:**
- Redis-Overhead für Self-Hosting zu hoch
- Server-Neustarts selten (<1x pro Woche)
- Bei Neustart = Attack-Vektoren resetten sich auch (DDoS-Protection)
**Geplant (v10+):** Redis-Integration optional
---
## Zusammenfassung: Auth-Flow
```
┌─────────────────────────────────────────────────────────────┐
│ 1. Login (POST /api/auth/login) │
│ ↓ E-Mail + Passwort │
│ ↓ verify_pin(password, pin_hash) │
│ ↓ SHA256 → bcrypt Migration (falls nötig) │
│ ↓ Token generieren (secrets.token_urlsafe(32)) │
│ ↓ INSERT INTO sessions (token, profile_id, expires_at) │
│ → Return {token, profile_id, role, expires_at} │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 2. Frontend speichert Token │
│ localStorage.setItem('bodytrack_token', token) │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 3. Nachfolgende Requests │
│ GET /api/weight │
│ Headers: X-Auth-Token: {token} │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 4. Backend validiert Token (require_auth) │
│ ↓ SELECT FROM sessions WHERE token=... AND expires_at>NOW│
│ ↓ JOIN profiles ON profile_id │
│ → Return session dict {profile_id, role, ai_enabled, ...}│
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 5. Endpoint-Logik │
│ profile_id = session['profile_id'] │
│ data = SELECT FROM weight_log WHERE profile_id=... │
│ → Return data │
└─────────────────────────────────────────────────────────────┘
```
**Sicherheits-Highlights:**
- ✅ bcrypt mit Auto-Salting
- ✅ SHA256 → bcrypt Migration (transparent)
- ✅ Rate Limiting (5/min Login, 3/hour Register)
- ✅ E-Mail-Verifizierung (24h Token)
- ✅ Passwort-Reset (1h Token via E-Mail)
- ✅ Session-Expiry (30 Tage)
- ✅ Admin-Role-Check (require_admin)
- ✅ Profile-ID-Isolation (immer aus Session)
- ✅ CORS-Whitelisting (Production)
**Bekannte Limitationen:**
- In-Memory Rate Limiting (Reset bei Server-Neustart)
- Keine 2FA (geplant für v10+)
- Keine Passwort-Strength-Meter (geplant)
- Keine Session-Revocation-UI (nur via DB)
@@ -0,0 +1,205 @@
# Zentrales Abo-System (Zukunft)
## Vision
**Ein zentrales Abo-System für alle Jinkendo Apps:**
- mitai.jinkendo.de (Körper-Tracking) 身体
- miken.jinkendo.de (Meditation) 眉間
- ikigai.jinkendo.de (Lebenssinn) 生き甲斐
- shinkan.jinkendo.de (Kampfsport) 真観
## Konzept
### Zentrale Webseite: jinkendo.de
- Zentrale Landing-Page mit allen Apps
- **Zentrale Abo-Verwaltung** (Stripe-Integration)
- User-Account übergreifend für alle Apps
- Single Sign-On (SSO) zwischen Apps
### Abo-Modelle (Ideen)
#### Option 1: App-spezifische Abos
```
mitai Basic: €5/Monat → Nur Mitai Premium
miken Basic: €5/Monat → Nur Miken Premium
```
#### Option 2: Kombinierte Abos
```
Jinkendo Basic: €8/Monat → 2 Apps
Jinkendo Premium: €12/Monat → Alle 4 Apps
Jinkendo Family: €20/Monat → Alle Apps + 3 Profile
```
#### Option 3: Feature-basiert
```
Free: Basis-Features alle Apps
Basic: Erweiterte Features (KI, Export, etc.)
Premium: Unlimited + Priority Support
```
---
## Technische Umsetzung
### Backend
#### Zentrale Auth-API
```
auth.jinkendo.de
POST /register → User-Account erstellen
POST /login → JWT Token für alle Apps
POST /refresh → Token erneuern
GET /me → User-Info mit Abo-Status
```
#### Subscription-API
```
subscriptions.jinkendo.de
GET /plans → Verfügbare Abos
POST /subscribe → Stripe Checkout Session
GET /my-subscription → Aktuelles Abo + Features
POST /cancel → Abo kündigen
POST /webhook → Stripe Webhook
```
#### App-Integration
Jede App prüft beim Start:
```javascript
const subscription = await fetch('https://subscriptions.jinkendo.de/my-subscription', {
headers: { 'Authorization': `Bearer ${jwt_token}` }
})
// subscription.features: ['mitai_premium', 'miken_basic', ...]
// App aktiviert entsprechende Features
```
### Frontend
#### Zentrale Webseite (jinkendo.de)
- Next.js oder React + Vite
- Stripe Elements für Payment
- Dashboard: Übersicht alle Apps + Abo-Status
- Rechnung-Historie
#### App-Anpassungen
**TrialBanner:**
```jsx
<a href="https://jinkendo.de/upgrade?app=mitai">
Jetzt upgraden
</a>
```
**Settings → Abo:**
- Link zu `https://jinkendo.de/account/subscription`
- Oder Embedded iFrame
---
## Datenbank-Schema (zentral)
### users
```sql
CREATE TABLE users (
id UUID PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
name VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
### subscriptions
```sql
CREATE TABLE subscriptions (
id SERIAL PRIMARY KEY,
user_id UUID REFERENCES users(id),
stripe_customer_id VARCHAR(100),
stripe_subscription_id VARCHAR(100),
plan VARCHAR(50), -- 'basic', 'premium', 'family'
status VARCHAR(20), -- 'active', 'canceled', 'past_due'
current_period_end TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
canceled_at TIMESTAMP
);
```
### subscription_features
```sql
CREATE TABLE subscription_features (
subscription_id INT REFERENCES subscriptions(id),
app VARCHAR(50), -- 'mitai', 'miken', 'ikigai', 'shinkan'
tier VARCHAR(50), -- 'basic', 'premium'
PRIMARY KEY (subscription_id, app)
);
```
### app_access_tokens
```sql
-- Mapping: Zentrale User → App-spezifische Profile
CREATE TABLE app_access_tokens (
user_id UUID REFERENCES users(id),
app VARCHAR(50),
app_profile_id VARCHAR(100), -- ID in der jeweiligen App-DB
PRIMARY KEY (user_id, app)
);
```
---
## Migration: Bestehende Apps
### Schritt 1: Zentrale Auth aufbauen
1. `auth.jinkendo.de` API deployen
2. User aus `mitai` DB migrieren zu zentraler DB
3. Mapping erstellen: zentrale User ID → mitai Profile ID
### Schritt 2: Apps auf zentrale Auth umstellen
1. Login/Register in Apps deaktivieren
2. "Mit Jinkendo anmelden" Button → SSO-Flow
3. JWT von `auth.jinkendo.de` verwenden
4. Profile-ID Mapping bei jedem Request
### Schritt 3: Subscription-System
1. `subscriptions.jinkendo.de` API deployen
2. Stripe-Integration
3. Apps prüfen Abo-Status bei jedem Feature-Zugriff
### Schritt 4: Zentrale Webseite
1. `jinkendo.de` Landing Page
2. Account-Dashboard
3. Abo-Verwaltung
---
## Status (März 2026)
🔲 **Noch nicht gestartet**
**Aktuell:**
- Jede App hat eigene User-Verwaltung
- `mitai` hat Membership-System (v9c)
- TrialBanner Link → `mailto:mitai@jinkendo.de`
**Nächste Schritte:**
1. Weitere Apps entwickeln (miken, ikigai, shinkan)
2. Zentrale Infrastruktur planen
3. Migration vorbereiten
---
## Offene Fragen
- **Pricing:** Welche Preise pro App / kombiniert?
- **Stripe vs. Paddle:** Welcher Payment Provider?
- **Single DB vs. Separate:** Eine PostgreSQL-DB für alles oder separate?
- **Hosting:** Eigener Server oder Cloud (Vercel, Railway, Fly.io)?
- **Domain-Strategie:** Subdomains (api.jinkendo.de) oder Paths (jinkendo.de/api)?
---
## Related
- `MEMBERSHIP_SYSTEM.md` - Aktuelles System in mitai (v9c)
- `FEATURE_ENFORCEMENT.md` - Feature-Limiting Mechanismus
- Backlog: v9h (Connectoren & Stripe)
@@ -0,0 +1,163 @@
# Dashboard-Lab-Widgets – Anleitung für Coding-Agenten
Ziel: Ein neues Dashboard-Widget **end-to-end** korrekt einbinden (Backend-Katalog, Validierung, API-Layout, Frontend-Registrierung, optional Lab-Editor für `config`).
Kontext: **Dashboard-Lab** unter geschützten Endpoints `GET/PUT /api/app/...` (siehe `backend/routers/app_dashboard.py`). Layout liegt pro Profil in `profiles.dashboard_layout` (JSON).
---
## 0. Architekturanforderung: Subscription / Feature-System vs. Widget-Katalog
### 0.1 Ist-Stand (Verifikation)
- **Bereits vorhanden:** Membership- und Feature-Modell (`features`, `tier_limits`, `user_feature_restrictions`, `check_feature_access` in `backend/auth.py`). Siehe `.claude/docs/architecture/FEATURE_ENFORCEMENT.md`.
- **Umgesetzt:** `GET /api/app/widgets/catalog` liefert pro Widget **`allowed`** (aus `requires_feature` im Katalog + `check_feature_access`). `GET/PUT /api/app/dashboard-layout` wendet **`apply_entitlements_to_layout_dict`** an (nicht erlaubte Einträge: `enabled: false`; Standard-Layout ebenfalls bereinigt). Implementierung: `backend/dashboard_widget_entitlements.py`.
- Optional pro Katalogzeile: **`requires_feature`** (`features.id`) in `widget_catalog.py`; fehlt der Key → Widget für alle authentifizierten Nutzer katalog-sichtbar (ohne zusätzliches Feature-Gate).
### 0.2 Soll: eine Wahrheit für „darf angezeigt werden“
- **Komplexität** (Module aus, Cluster, Stufen: z. B. Ernährung an, aber bestimmte Auswertungen nur in höherem Tier) gehört in die **Feature-/Subscription-Schicht** (inkl. späterer Feature-Cluster), nicht in einzelne React-Widgets.
- **Widgets** sollen das Ergebnis nur **abrufen** (z. B. `allowed` / sichtbar im Katalog), nicht die Tier-Logik duplizieren.
### 0.3 Bindende Anforderungen (wenn Feature-Gating umgesetzt wird)
| Anforderung | Beschreibung |
|-------------|--------------|
| **A1 – Zentrale Auflösung** | Backend ermittelt pro Profil (effektiver Tier + Restrictions), welche Widget-IDs **erlaubt** sind – idealerweise in **einer** Stelle (Erweiterung des Katalog-Endpoints oder dedizierter Entitlements-Teil der Response). Intern: `check_feature_access` und später ggf. Mapping Widget-ID → Feature-ID(n) / Cluster. |
| **A2 – Nutzer-Konfigurator** | Im Dashboard-Lab (und jedem späteren Layout-Konfigurator): Widgets **ohne Berechtigung nicht anbieten** (ausgeblendet oder gar nicht in der Liste). Alle **erlaubten** Widgets bleiben wie heute wählbar. |
| **A3 – Layout-Persistenz** | `PUT /api/app/dashboard-layout`: Layout darf **keine** nicht erlaubten Widgets dauerhaft speichern – entweder **ablehnen** (422) oder **beim Speichern entfernen/deaktivieren** (Policy festlegen und dokumentieren). Verhindert „gespeichert, aber nie sichtbar“-Zombies. |
| **A4 – API-/Datenschutz** | Sichtbarkeit im UI reicht nicht: Endpoints, die **Inhalte** für gated Widgets liefern (Charts, KI, …), müssen weiterhin wie heute **eigenständig** über Features abgesichert sein (`check_feature_access`, 403). |
### 0.4 Katalog-Erweiterung (Vorbereitung ohne feste Tier-Namen)
- Tiers bleiben **in der DB konfigurierbar**; im Code keine Annahme „free vs. pro“.
- Pro Widget-Eintrag (oder separater Mapping-Layer) kann später **`required_feature_id`** (ein Key aus `features.id`) oder ein **Cluster-Key** ergänzt werden, der auf **eine oder mehrere** `check_feature_access`-Abfragen abgebildet wird – Details bei Implementierung festlegen.
- Neue Widget-Doku: Wenn ein Widget an ein Feature hängt, in `widget_catalog`-`description` und in dieser Anleitung vermerken.
**Verweis:** Verbindliche Regel auf Projektebene: `.claude/rules/ARCHITECTURE.md` § 9.
---
## 1. Datenfluss (kurz)
1. **`backend/widget_catalog.py`** – `WIDGET_CATALOG`: erlaubte Widget-IDs, Reihenfolge, Titel/Beschreibung für API und Default-Layout.
2. **`backend/dashboard_layout_schema.py`** – `DashboardLayoutPayload`: jede Zeile hat `id`, `enabled`, optional `config`. IDs müssen in `ALLOWED_WIDGET_IDS` sein (aus dem Katalog abgeleitet).
3. **`backend/dashboard_widget_config.py`** – `validate_widget_entry_config`: **nur** Widgets in `WIDGETS_ALLOWING_CONFIG` dürfen **nicht-leere** `config` haben; Keys werden streng validiert (unbekannte Keys → Fehler).
4. **Frontend** – `ensurePilotLabWidgetsRegistered()` in `frontend/src/widgetSystem/registerPilotLabWidgets.js`: verbindet jede Katalog-ID mit einer React-Komponente und mappt `ctx.layoutEntry.config` auf Props.
5. **Dashboard-Lab-UI** – `frontend/src/pages/DashboardLabPage.jsx`: Umsortieren, Ein/Aus, Speichern; **zusätzliche** UI nur nötig, wenn das Widget konfigurierbare Felder braucht.
---
## 2. Checkliste: neues Widget ohne Konfiguration
| Schritt | Datei | Aktion |
|--------|--------|--------|
| A | `backend/widget_catalog.py` | Neuen Eintrag `{ "id", "title", "description" }` in `WIDGET_CATALOG` einfügen (Reihenfolge = Default-Reihenfolge im Layout). Optional `"requires_feature": "<features.id>"` für Tarif-Gating (`dashboard_widget_entitlements`). |
| B | `backend/widget_catalog.py` | Optional: ID zu `DEFAULT_LAB_WIDGET_IDS` hinzufügen, wenn es im Standard-Lab **aktiv** sein soll. |
| C | `frontend/src/components/dashboard-widgets/MyWidget.jsx` (oder Pilot-Komponente) | React-Komponente implementieren; typischerweise `refreshTick` aus `mapProps` nutzen, um Daten neu zu laden. |
| D | `frontend/src/widgetSystem/registerPilotLabWidgets.js` | `import` + `registerDashboardWidget({ id, Component, mapProps })` – `id` **exakt** wie im Katalog. |
| E | `backend/tests/test_widget_catalog.py` | Läuft implizit mit; bei Strukturänderungen Katalog-Tests beachten. |
| F | `backend/version.py` | `MODULE_VERSIONS["app_dashboard"]` MINOR erhöhen und kurz kommentieren. |
| G | Build/Tests | `pytest` (z. B. `tests/test_dashboard_layout_schema.py`, `test_widget_catalog.py`); `npm run build` im `frontend`. |
**Nicht nötig:** `WIDGETS_ALLOWING_CONFIG` oder `validate_widget_entry_config`-Zweig, solange `config` immer `{}` bleibt.
**Wichtig:** Widget-IDs im Frontend-Registry **ohne** Registrierung führen im UI zu „Unbekanntes Widget“ (`dashboardWidgetRegistry.jsx`).
---
## 3. Checkliste: Widget mit konfigurierbaren Einstellungen (`config`)
### 3.1 Backend
1. **`WIDGETS_ALLOWING_CONFIG`** in `backend/dashboard_widget_config.py` um die neue `widget_id` ergänzen.
2. In **`validate_widget_entry_config`** einen eigenen Zweig oder Aufruf einer Hilfsfunktion hinzufügen (siehe bestehende Muster unten).
3. **`MAX_WIDGET_CONFIG_JSON_BYTES`** (3072): keine großen Blobs in `config`.
4. Regeln konsistent halten:
- Unbekannte Keys **ablehnen** (wie bei `kpi_board`, `quick_capture`, `chart_days`-only).
- Leeres Objekt `{}` erlauben, wenn alle Keys optional sind (Validator entscheidet).
**Referenz-Muster im Code:**
| Muster | Verwendung | Implementierung |
|--------|------------|-----------------|
| Nur `chart_days` (7–90) | Chart-Kacheln | `_validate_chart_days_only(raw, label="...")` |
| KPI-Kacheln | `tiles`-Liste, max. 9 | `_validate_kpi_board_config` |
| Booleans + Mindestens eines true | Schnelleingabe-Sichtbarkeit | `_validate_quick_capture_config` |
Neue komplexe Config: eigene `_validate_my_widget_config` schreiben, Keys als `frozenset` whitelisten, Typen prüfen, sinnvoll normalisieren/abrunden.
5. **Tests** in `backend/tests/test_dashboard_widget_config.py`: Happy-Path, ein ungültiger Wert, unbekannter Key, ggf. Größe/Limits.
### 3.2 Katalog-Beschreibung
In `widget_catalog.py` bei `description` die **konfigurierbaren Keys** kurz nennen (hilft Admin/API-Nutzern). Einheitliche Benennung mit dem Backend (z. B. `chart_days 7–90`).
### 3.3 Frontend: Props aus Layout
`registerDashboardWidget` erhält `mapProps(ctx)`:
- **`ctx.layoutEntry`**: `{ id, enabled, config? }` – hierher kommt die gespeicherte Konfiguration.
- **`ctx.refreshTick`** / **`ctx.requestRefresh()`**: Datenaktualisierung nach Aktionen.
Typische Zuordnung:
```javascript
mapProps: (ctx) => ({
refreshTick: ctx.refreshTick,
myOption: ctx.layoutEntry?.config?.my_option,
})
```
**Abgleich mit Chart-Zeitraum:** Für `chart_days` existiert `frontend/src/widgetSystem/bodyChartDays.js` (`BODY_CHART_DAYS_MIN/MAX`, `normalizeBodyChartDays`). Entweder in `mapProps` normalisieren (wie `body_overview`) oder rohen Wert durchreichen und in der Widget-Komponente normalisieren (wie `nutrition_detail_charts` / `TrendKcalWeightWidget`) – **beides** ist im Projekt vertreten; wichtig ist Konsistenz mit der Backend-Grenze 7–90.
### 3.4 Dashboard-Lab-Editor (`DashboardLabPage.jsx`)
Ohne UI-Änderung bleibt `config` beim Nutzer `{}` – konfigurierbare Widgets brauchen **Editor-Controls**:
- **Einfaches Zahlfeld `chart_days`:** Eintrag in `CHART_DAYS_WIDGET_IDS` (Set oben in der Datei) + bestehendes Label/`aria-label`-Pattern für die Zeitraum-Zeile erweitern (siehe `body_overview`, `nutrition_detail_charts`).
- **Strukturierte Config (Listen, mehrere Booleans):** Eigenes Editor-Komponenten-File nach Vorbild `KpiBoardConfigEditor.jsx` / `QuickCaptureConfigEditor.jsx` einbinden und `setLayout` + `normalizeLayoutForEditor` wie bei den bestehenden Blöcken verwenden.
Nach Speichern ruft die Seite `api.putAppDashboardLayout(layout)` auf; das Backend validiert über `DashboardLayoutPayload` → `validate_widget_entry_config`.
---
## 4. Grenzen und Fehlerbilder
| Thema | Detail |
|--------|--------|
| Erlaubte IDs | Nur IDs aus `WIDGET_CATALOG`. `ALLOWED_WIDGET_IDS` wird daraus abgeleitet – nicht manuell duplizieren. |
| Doppelte IDs | Im Layout sind **keine** doppelten `widget.id` erlaubt (`DashboardLayoutPayload`). |
| Max. Widgets | `widgets` max. 32 Einträge (`DashboardLayoutPayload`). |
| Config verboten | Widget **nicht** in `WIDGETS_ALLOWING_CONFIG` → jede nicht-leere `config` → Validierungsfehler beim Speichern. |
| Frontend ≠ Katalog | Komponente registriert, ID fehlt im Katalog → PUT schlägt fehl. |
| Katalog ohne Registry | GET Layout ok, Render zeigt „Unbekanntes Widget“. |
---
## 5. API zum Prüfen
- `GET /api/app/widgets/catalog` – Katalog inkl. `allowed` je Widget (Auth + `X-Profile-Id` wie andere App-Endpoints).
- `GET /api/app/dashboard-layout` – `layout` (effektiv, bereinigt), `custom`, `product_default_layout` (Übersichts-Standard), `lab_default_layout` (Dashboard-Lab-Standard).
- `PUT /api/app/dashboard-layout` – Body `{ "version": 1, "widgets": [ ... ] }` (unerlaubte Widgets werden auf `enabled: false` gesetzt).
---
## 6. Nach getaner Arbeit
- `pytest` für `dashboard_widget_config` und `widget_catalog` / `dashboard_layout_schema`.
- `npm run build`.
- `MODULE_VERSIONS["app_dashboard"]` in `backend/version.py` anheben.
---
## 7. Verwandte Dateien (Referenz)
| Zweck | Pfad |
|--------|------|
| Katalog | `backend/widget_catalog.py` |
| Config-Validierung | `backend/dashboard_widget_config.py` |
| Layout-Pydantic | `backend/dashboard_layout_schema.py` |
| HTTP | `backend/routers/app_dashboard.py` |
| Registry + Render | `frontend/src/widgetSystem/dashboardWidgetRegistry.jsx` |
| Pilot/Lab-Registrierung | `frontend/src/widgetSystem/registerPilotLabWidgets.js` |
| Lab-UI | `frontend/src/pages/DashboardLabPage.jsx` |
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,780 @@
# Data Layer Extension Guide
**Version:** 1.0
**Erstellt:** 28. März 2026
**Zielgruppe:** Entwickler, Claude Code
**Phase:** Post Phase 0c
---
## Überblick
Dieser Guide beschreibt, wie man das Data Layer System erweitert mit:
- Neuen Modulen
- Neuen Funktionen in bestehenden Modulen
- Neuen Berechnungslogiken
- Neuen Aggregationsmethoden
**Voraussetzung:** Phase 0c abgeschlossen (Multi-Layer Architecture implementiert)
---
## Modul-Struktur
### Bestehende Module (Phase 0c)
```
backend/data_layer/
├── __init__.py # Exports all functions
├── body_metrics.py # Gewicht, FM, LBM, Umfänge
├── nutrition_metrics.py # Kalorien, Protein, Makros
├── activity_metrics.py # Training, Volumen, Abilities
├── recovery_metrics.py # Sleep, RHR, HRV, Recovery Score
├── health_metrics.py # BP, VO2Max, Health Stability
├── goals.py # Active goals, progress
├── correlations.py # Lag-analysis, plateau detection
└── utils.py # Shared: confidence, baseline, outliers
```
### Modul-Namenskonventionen
- **Singular:** `body_metrics.py` (nicht `bodies_metrics.py`)
- **Domain-focused:** Ein Modul pro fachlichem Bereich
- **Max ~500 Zeilen:** Bei >500 Zeilen → Split erwägen
---
## Neue Funktion hinzufügen
### Template
```python
# backend/data_layer/<module>.py
def get_<metric>_data(
profile_id: str,
days: int = 28,
**kwargs
) -> dict:
"""
[Eine Zeile: Was liefert diese Funktion?]
[Optional: Ausführliche Beschreibung der Berechnung]
Args:
profile_id: User profile ID
days: Analysis window (default 28)
**kwargs: Additional parameters (z.B., goal_mode)
Returns:
{
"<field>": <type>, # Main result
"confidence": str, # REQUIRED: "high"/"medium"/"low"/"insufficient"
"data_points": int, # REQUIRED: Number of data points used
"<additional>": <type> # Any additional data
}
Confidence Rules:
- "high": >= X points
- "medium": >= Y points
- "low": >= Z points
- "insufficient": < Z points
Example:
>>> data = get_<metric>_data("profile_123", days=28)
>>> print(data['<field>'])
42.0
"""
with get_db() as conn:
cur = get_cursor(conn)
# 1. DATA RETRIEVAL
cur.execute("""
SELECT ...
FROM ...
WHERE profile_id = %s
AND date >= NOW() - INTERVAL '%s days'
ORDER BY date
""", (profile_id, days))
rows = cur.fetchall()
# 2. CONFIDENCE CALCULATION
from data_layer.utils import calculate_confidence
confidence = calculate_confidence(
data_points=len(rows),
days_requested=days,
metric_type="general" # or "correlation" or "trend"
)
# 3. EARLY RETURN IF INSUFFICIENT
if confidence == 'insufficient':
return {
"confidence": "insufficient",
"data_points": len(rows),
# Include all fields with safe defaults
"<field>": 0.0,
}
# 4. CALCULATION
# ... your logic here ...
# 5. RETURN STRUCTURED DATA
return {
"<field>": result,
"confidence": confidence,
"data_points": len(rows),
# Additional fields as needed
}
```
### Pflicht-Felder
**Jede Funktion MUSS zurückgeben:**
```python
{
"confidence": str, # "high" | "medium" | "low" | "insufficient"
"data_points": int, # Anzahl verwendeter Datenpunkte
}
```
**Warum?**
- Confidence: UI kann User warnen bei niedriger Datenqualität
- Data Points: Debugging + Monitoring
### Optionale Felder (Best Practices)
```python
{
"first_date": date, # Ältester Datenpunkt
"last_date": date, # Neuester Datenpunkt
"avg": float, # Durchschnitt
"std_dev": float, # Standardabweichung
"min": float, # Minimum
"max": float, # Maximum
"outliers": list[int], # Indices von Ausreißern
}
```
---
## Neue Berechnungslogik hinzufügen
### 1. Statistik-Funktionen (utils.py)
**Wenn du eine neue statistische Berechnung brauchst:**
```python
# backend/data_layer/utils.py
def calculate_<statistic>(
values: list[float],
**kwargs
) -> float:
"""
[Beschreibung der Statistik]
Args:
values: List of measurements
**kwargs: Additional parameters
Returns:
Calculated statistic (float)
Example:
>>> calculate_<statistic>([1.0, 2.0, 3.0])
2.0
"""
# Implementation
...
```
**Beispiele:**
```python
def calculate_median_absolute_deviation(values: list[float]) -> float:
"""
MAD = median(|xi - median(x)|)
More robust than standard deviation for outlier detection.
"""
import statistics
median = statistics.median(values)
deviations = [abs(x - median) for x in values]
return statistics.median(deviations)
def calculate_coefficient_of_variation(values: list[float]) -> float:
"""
CV = (std_dev / mean) * 100
Measures relative variability.
"""
import statistics
mean = statistics.mean(values)
std_dev = statistics.stdev(values)
return (std_dev / mean) * 100 if mean != 0 else 0.0
def calculate_z_score(value: float, mean: float, std_dev: float) -> float:
"""
Z = (x - μ) / σ
Standardized score.
"""
return (value - mean) / std_dev if std_dev != 0 else 0.0
```
### 2. Aggregations-Funktionen (utils.py)
**Neue Aggregationsmethoden für Goal Types:**
```python
# backend/data_layer/utils.py
def aggregate_data(
values: list[tuple], # [(date, value), ...]
method: str,
**kwargs
) -> float:
"""
Aggregate data points using specified method.
Args:
values: List of (date, value) tuples
method: Aggregation method (see below)
**kwargs: Method-specific parameters
Returns:
Aggregated value (float)
Supported Methods:
- "latest": Most recent value
- "avg_7d": Average last 7 days
- "avg_30d": Average last 30 days
- "avg_90d": Average last 90 days
- "sum_7d": Sum last 7 days
- "sum_30d": Sum last 30 days
- "count_7d": Count last 7 days
- "count_30d": Count last 30 days
- "min_30d": Minimum last 30 days
- "max_30d": Maximum last 30 days
- "median_7d": Median last 7 days
- "median_30d": Median last 30 days
- "rolling_avg": Rolling average (window from kwargs)
- "percentile": Nth percentile (n from kwargs)
Example:
>>> values = [(date1, 85.0), (date2, 84.5), ...]
>>> aggregate_data(values, "avg_7d")
84.7
"""
from datetime import date, timedelta
import statistics
if not values:
return 0.0
# Sort by date (most recent first)
sorted_values = sorted(values, key=lambda x: x[0], reverse=True)
if method == "latest":
return float(sorted_values[0][1])
elif method.startswith("avg_"):
days = int(method.split("_")[1].replace("d", ""))
cutoff = date.today() - timedelta(days=days)
recent = [v for d, v in sorted_values if d >= cutoff]
return statistics.mean(recent) if recent else 0.0
elif method.startswith("sum_"):
days = int(method.split("_")[1].replace("d", ""))
cutoff = date.today() - timedelta(days=days)
recent = [v for d, v in sorted_values if d >= cutoff]
return sum(recent)
elif method.startswith("count_"):
days = int(method.split("_")[1].replace("d", ""))
cutoff = date.today() - timedelta(days=days)
return len([v for d, v in sorted_values if d >= cutoff])
elif method.startswith("min_") or method.startswith("max_"):
func_name, days_str = method.split("_")
days = int(days_str.replace("d", ""))
cutoff = date.today() - timedelta(days=days)
recent = [v for d, v in sorted_values if d >= cutoff]
if not recent:
return 0.0
return min(recent) if func_name == "min" else max(recent)
elif method.startswith("median_"):
days = int(method.split("_")[1].replace("d", ""))
cutoff = date.today() - timedelta(days=days)
recent = [v for d, v in sorted_values if d >= cutoff]
return statistics.median(recent) if recent else 0.0
elif method == "rolling_avg":
window = kwargs.get("window", 7)
if len(sorted_values) < window:
return statistics.mean([v for _, v in sorted_values])
recent = sorted_values[:window]
return statistics.mean([v for _, v in recent])
elif method == "percentile":
n = kwargs.get("n", 50) # Default: median
values_only = [v for _, v in sorted_values]
return statistics.quantiles(values_only, n=100)[n - 1] if len(values_only) > 1 else values_only[0]
else:
raise ValueError(f"Unknown aggregation method: {method}")
```
### 3. Korrelations-Funktionen (correlations.py)
**Neue Korrelations-Analysen:**
```python
# backend/data_layer/correlations.py
def get_<metric_a>_<metric_b>_correlation(
profile_id: str,
days: int = 90,
max_lag: int = 7
) -> dict:
"""
Correlation between <metric_a> and <metric_b> with lag analysis.
Args:
profile_id: User profile ID
days: Analysis window
max_lag: Maximum lag in days to test
Returns:
{
"correlation": float, # Pearson r at best lag
"best_lag": int, # Days of lag
"p_value": float, # Statistical significance
"confidence": str,
"paired_points": int,
"interpretation": str # "strong"/"moderate"/"weak"/"none"
}
Interpretation:
|r| > 0.7: "strong"
|r| > 0.5: "moderate"
|r| > 0.3: "weak"
|r| <= 0.3: "none"
"""
# Implementation using scipy.stats or numpy
...
```
---
## Neues Modul erstellen
### Wann ein neues Modul?
**Erstelle ein neues Modul wenn:**
- ✅ Neue fachliche Domäne (z.B., `stress_metrics.py`, `hormone_metrics.py`)
- ✅ Bestehendes Modul >500 Zeilen
- ✅ Klare thematische Trennung möglich
**KEIN neues Modul wenn:**
- ❌ Nur 1-2 Funktionen (füge zu bestehendem Modul hinzu)
- ❌ Starke Abhängigkeit zu bestehendem Modul (merge statt split)
### Modul-Template
```python
# backend/data_layer/<new_module>.py
"""
<Module Name> - <Brief description>
This module provides data functions for <domain>.
Functions:
- get_<metric1>_data()
- get_<metric2>_data()
- ...
Usage:
from data_layer.<new_module> import get_<metric>_data
data = get_<metric>_data(profile_id="123", days=28)
"""
from typing import Optional, List, Dict, Tuple
from datetime import date, timedelta
from db import get_db, get_cursor
# ── PUBLIC FUNCTIONS ─────────────────────────────────────────────
def get_<metric>_data(
profile_id: str,
days: int = 28,
**kwargs
) -> dict:
"""
[Docstring as per template above]
"""
...
# ── PRIVATE HELPERS ──────────────────────────────────────────────
def _calculate_<internal_metric>(values: list[float]) -> float:
"""
Internal helper for <module>.
NOT exported from module.
"""
...
def _validate_<data>(data: dict) -> bool:
"""
Internal validation helper.
"""
...
```
### Exports in __init__.py
```python
# backend/data_layer/__init__.py
# Existing modules
from .body_metrics import *
from .nutrition_metrics import *
from .activity_metrics import *
from .recovery_metrics import *
from .health_metrics import *
from .goals import *
from .correlations import *
from .utils import *
# NEW MODULE
from .<new_module> import *
__all__ = [
# Existing exports...
# NEW MODULE exports
'get_<metric1>_data',
'get_<metric2>_data',
]
```
---
## Integration mit Goal Types
### Goal Type mit neuer Aggregationsmethode
**Scenario:** Du hast eine neue Aggregationsmethode `avg_per_week_30d` implementiert.
#### 1. In utils.py implementieren
```python
# backend/data_layer/utils.py
def aggregate_data(values, method, **kwargs):
# ... existing methods ...
elif method == "avg_per_week_30d":
# Group by week, calculate average per week
from collections import defaultdict
weeks = defaultdict(list)
for d, v in values:
week_start = d - timedelta(days=d.weekday())
weeks[week_start].append(v)
week_avgs = [sum(vals) / len(vals) for vals in weeks.values()]
return sum(week_avgs) / len(week_avgs) if week_avgs else 0.0
# ...
```
#### 2. In goal_utils.py nutzen
```python
# backend/goal_utils.py
def _fetch_by_aggregation_method(
cur,
profile_id: str,
source_table: str,
source_column: str,
aggregation_method: str,
date_column: str = 'date',
filter_conditions: dict = None
) -> Optional[float]:
"""
Fetch current value using aggregation method.
Now supports:
- latest, avg_7d, avg_30d, sum_30d, count_7d, etc.
- avg_per_week_30d (NEW)
"""
# Fetch data
cur.execute(f"""
SELECT {date_column}, {source_column}
FROM {source_table}
WHERE profile_id = %s
ORDER BY {date_column} DESC
LIMIT 100
""", (profile_id,))
rows = cur.fetchall()
if not rows:
return None
# Use aggregate_data from utils
from data_layer.utils import aggregate_data
return aggregate_data(rows, aggregation_method)
```
#### 3. In Frontend verfügbar machen
```javascript
// frontend/src/pages/AdminGoalTypesPage.jsx
const AGGREGATION_METHODS = [
{ value: 'latest', label: 'Aktuellster Wert' },
{ value: 'avg_7d', label: 'Durchschnitt 7 Tage' },
{ value: 'avg_30d', label: 'Durchschnitt 30 Tage' },
{ value: 'sum_30d', label: 'Summe 30 Tage' },
{ value: 'avg_per_week_30d', label: 'Durchschnitt pro Woche (30d)' }, // NEW
// ...
]
```
---
## Testing-Strategie
### Unit Tests für neue Funktionen
```python
# backend/tests/test_data_layer.py
import pytest
from data_layer.<module> import get_<metric>_data
@pytest.fixture
def test_profile_with_data(db_connection):
"""Create test profile with sample data"""
# Setup
profile_id = "test_profile_123"
# Insert test data into relevant tables
...
yield profile_id
# Teardown
...
def test_get_metric_data_sufficient(test_profile_with_data):
"""Test with sufficient data points"""
data = get_<metric>_data(test_profile_with_data, days=28)
assert data['confidence'] in ['high', 'medium', 'low']
assert data['data_points'] >= 18
assert '<field>' in data
assert isinstance(data['<field>'], float)
def test_get_metric_data_insufficient():
"""Test with insufficient data"""
data = get_<metric>_data("no_data_profile", days=28)
assert data['confidence'] == 'insufficient'
assert data['data_points'] == 0
def test_get_metric_data_edge_cases(test_profile_with_data):
"""Test edge cases: outliers, missing values, etc."""
# Test with extreme values
# Test with gaps in data
# Test with all same values
...
def test_get_metric_data_parameters(test_profile_with_data):
"""Test different parameter combinations"""
# Test different days values
for days in [7, 28, 90]:
data = get_<metric>_data(test_profile_with_data, days=days)
assert data is not None
# Test additional parameters
data = get_<metric>_data(test_profile_with_data, days=28, goal_mode="strength")
assert data is not None
```
### Integration Tests
```python
# backend/tests/test_charts_integration.py
def test_chart_uses_data_layer(client, auth_token):
"""Test that chart endpoint uses data layer correctly"""
response = client.get(
"/api/charts/<metric>",
headers={"X-Auth-Token": auth_token}
)
assert response.status_code == 200
data = response.json()
# Verify Chart.js structure
assert 'chart_type' in data
assert 'data' in data
assert 'metadata' in data
# Verify metadata includes confidence
assert 'confidence' in data['metadata']
```
---
## Performance Considerations
### 1. Query Optimization
**Problem:** N+1 Queries
```python
# ❌ BAD:
for goal_id in goal_ids:
cur.execute("SELECT * FROM goals WHERE id = %s", (goal_id,))
# ... process each goal ...
# ✅ GOOD:
cur.execute("SELECT * FROM goals WHERE id = ANY(%s)", (goal_ids,))
```
**Problem:** Unindexed Columns
```sql
-- Add index if querying frequently by date range
CREATE INDEX IF NOT EXISTS idx_weight_log_profile_date
ON weight_log(profile_id, date DESC);
```
### 2. Caching
**For expensive calculations:**
```python
from functools import lru_cache
@lru_cache(maxsize=128)
def get_expensive_calculation(profile_id: str, days: int) -> dict:
"""Cache results for 128 most recent calls"""
...
```
**Note:** In-memory cache resets on restart. For persistent cache → Redis (later).
### 3. Pagination
**For large datasets:**
```python
def get_<metric>_data(
profile_id: str,
days: int = 28,
limit: int = 1000,
offset: int = 0
) -> dict:
"""
Paginated data retrieval.
"""
cur.execute("""
SELECT ...
FROM ...
WHERE profile_id = %s
ORDER BY date DESC
LIMIT %s OFFSET %s
""", (profile_id, limit, offset))
```
---
## Checkliste: Neue Funktion
```
[ ] Richtiges Modul gewählt (oder neues Modul erstellt)
[ ] Funktion implementiert mit korrekter Signatur
[ ] Docstring vollständig (Args, Returns, Example)
[ ] Confidence calculation included
[ ] Returns structured data (dict with primitives)
[ ] NO formatting (no strings with units)
[ ] Decimal → Float conversion wo nötig
[ ] Safe dict access (.get() mit defaults)
[ ] SQL parameter binding (keine String-Concatenation)
[ ] Unit tests geschrieben (sufficient/insufficient/edge cases)
[ ] Integration test geschrieben (wenn Chart/API endpoint)
[ ] Performance geprüft (< 500ms)
[ ] In __init__.py exportiert
[ ] Dokumentation aktualisiert (CLAUDE.md)
[ ] Commit mit aussagekräftiger Message
```
---
## Häufige Fehler
### 1. Vergessen Confidence zu berechnen
```python
# ❌ WRONG:
return {"value": result}
# ✅ CORRECT:
from data_layer.utils import calculate_confidence
confidence = calculate_confidence(len(rows), days, "general")
return {"value": result, "confidence": confidence, "data_points": len(rows)}
```
### 2. Formatierung im Data Layer
```python
# ❌ WRONG (Data Layer):
return {"slope": f"{slope:.2f} kg/Woche"}
# ✅ CORRECT (Data Layer):
return {"slope": 0.23} # Just the number
# ✅ FORMATTING (KI Layer):
return f"{data['slope']:.2f} kg/Woche"
```
### 3. Hardcoded Thresholds
```python
# ❌ WRONG:
if len(rows) < 18: # Magic number
return {"confidence": "insufficient"}
# ✅ CORRECT:
confidence = calculate_confidence(len(rows), days, "general")
if confidence == "insufficient":
return {"confidence": "insufficient", ...}
```
---
## Support & Hilfe
**Bei Fragen:**
1. Lies PLACEHOLDER_DEVELOPMENT_GUIDE.md
2. Prüfe bestehende Funktionen als Beispiel
3. Frag im Team oder erstelle Gitea Issue
**Debugging:**
1. Unit Test schreiben
2. Print intermediate results
3. Check SQL query mit `EXPLAIN ANALYZE`
4. Profile mit `cProfile` wenn Performance-Problem
---
**Autor:** Claude Sonnet 4.5
**Version:** 1.0
**Letzte Aktualisierung:** 28. März 2026
@@ -0,0 +1,337 @@
# Feature Enforcement Mapping
**Version:** v9c Phase 2
**Status:** Planning
**Datum:** 20. März 2026
---
## Übersicht
Dieses Dokument definiert, welche API-Endpoints welche Features prüfen müssen.
---
## Feature-Katalog (nach Cleanup)
### Data Features (count, never)
1. `weight_entries` - Gewichtseinträge
2. `circumference_entries` - Umfangsmessungen
3. `caliper_entries` - Hautfaltenmessungen
4. `nutrition_entries` - Ernährungseinträge
5. `activity_entries` - Trainingseinträge
6. `photos` - Progress-Fotos
### AI Features
7. `ai_calls` - KI-Einzelanalysen (count, monthly)
8. `ai_pipeline` - KI-Pipeline-Analyse (boolean, never)
### Export/Import Features
9. `data_export` - Daten exportieren (count, monthly)
10. `data_import` - Daten importieren (count, monthly)
---
## Endpoint → Feature Mapping
### Weight Router (`/api/weight`)
| Endpoint | Method | Feature | Action |
|----------|--------|---------|--------|
| `/api/weight` | POST | `weight_entries` | Check before create, increment after |
| `/api/weight` | GET | - | No check (reading is always allowed) |
| `/api/weight/{id}` | PUT | - | No check (editing existing is allowed) |
| `/api/weight/{id}` | DELETE | - | No check (deleting is allowed) |
**Rationale:** Limit bezieht sich auf Gesamtanzahl Einträge (COUNT), nicht auf API-Calls.
---
### Circumference Router (`/api/circumference`)
| Endpoint | Method | Feature | Action |
|----------|--------|---------|--------|
| `/api/circumference` | POST | `circumference_entries` | Check before, increment after |
| `/api/circumference` | GET | - | No check |
| `/api/circumference/{id}` | PUT | - | No check |
| `/api/circumference/{id}` | DELETE | - | No check |
---
### Caliper Router (`/api/caliper`)
| Endpoint | Method | Feature | Action |
|----------|--------|---------|--------|
| `/api/caliper` | POST | `caliper_entries` | Check before, increment after |
| `/api/caliper` | GET | - | No check |
| `/api/caliper/{id}` | PUT | - | No check |
| `/api/caliper/{id}` | DELETE | - | No check |
---
### Nutrition Router (`/api/nutrition`)
| Endpoint | Method | Feature | Action |
|----------|--------|---------|--------|
| `/api/nutrition` | POST | `nutrition_entries` | Check before, increment after |
| `/api/nutrition` | GET | - | No check |
| `/api/nutrition/{id}` | PUT | - | No check |
| `/api/nutrition/{id}` | DELETE | - | No check |
---
### Activity Router (`/api/activity`)
| Endpoint | Method | Feature | Action |
|----------|--------|---------|--------|
| `/api/activity` | POST | `activity_entries` | Check before, increment after |
| `/api/activity` | GET | - | No check |
| `/api/activity/{id}` | PUT | - | No check |
| `/api/activity/{id}` | DELETE | - | No check |
---
### Photos Router (`/api/photos`)
| Endpoint | Method | Feature | Action |
|----------|--------|---------|--------|
| `/api/photos/upload` | POST | `photos` | Check before, increment after |
| `/api/photos` | GET | - | No check |
| `/api/photos/{id}` | DELETE | - | No check (deleting is allowed) |
---
### Insights Router (`/api/insights`)
| Endpoint | Method | Feature | Action |
|----------|--------|---------|--------|
| `/api/insights/run/{slug}` | POST | `ai_calls` | Check before, increment after |
| `/api/insights/pipeline` | POST | `ai_pipeline` (boolean) | Check before (no increment for boolean) |
| `/api/insights` | GET | - | No check |
| `/api/insights/{id}` | GET | - | No check |
**Rationale:**
- `ai_calls` = count-based, monthly reset
- `ai_pipeline` = boolean (enabled/disabled), no usage tracking
---
### Export Router (`/api/export`)
| Endpoint | Method | Feature | Action |
|----------|--------|---------|--------|
| `/api/export/csv` | GET | `data_export` | Check before, increment after |
| `/api/export/json` | GET | `data_export` | Check before, increment after |
| `/api/export/zip` | GET | `data_export` | Check before, increment after |
**Rationale:** Ein Feature für alle 3 Export-Typen (konsolidiert).
---
### Import Router (`/api/import`)
| Endpoint | Method | Feature | Action |
|----------|--------|---------|--------|
| `/api/nutrition/import/fddb` | POST | `data_import` | Check before, increment after |
| `/api/activity/import/csv` | POST | `data_import` | Check before, increment after |
| `/api/import/zip` | POST | `data_import` | Check before, increment after |
**Rationale:** Ein Feature für alle Import-Typen.
---
## Implementation Pattern (Phase 2: Non-Blocking Logging)
### Pattern für count-based Features
```python
from auth import require_auth, check_feature_access, increment_feature_usage
import logging
logger = logging.getLogger(__name__)
@router.post("/api/weight")
def create_weight(data: dict, session: dict = Depends(require_auth)):
profile_id = session['profile_id']
# Phase 2: Check access (log only, don't block)
access = check_feature_access(profile_id, 'weight_entries')
if not access['allowed']:
logger.warning(
f"[FEATURE-LIMIT] User {profile_id} would be blocked: "
f"weight_entries limit_exceeded ({access['used']}/{access['limit']})"
)
# NOTE: Phase 2 does NOT raise HTTPException - just logs!
# Actual logic
# ... create weight entry ...
# Phase 2: Increment usage (even if limit would be exceeded)
increment_feature_usage(profile_id, 'weight_entries')
return {"ok": True, "id": entry_id}
```
### Pattern für boolean Features
```python
@router.post("/api/insights/pipeline")
def run_pipeline(session: dict = Depends(require_auth)):
profile_id = session['profile_id']
# Phase 2: Check access (log only)
access = check_feature_access(profile_id, 'ai_pipeline')
if not access['allowed']:
logger.warning(
f"[FEATURE-LIMIT] User {profile_id} would be blocked: "
f"ai_pipeline disabled"
)
# NOTE: Phase 2 does NOT raise HTTPException!
# Actual logic
# ... run pipeline ...
# No increment for boolean features
return {"ok": True}
```
---
## Phase 3: Frontend Display (ohne Gates)
### Usage-Counter anzeigen
```jsx
// Example: WeightPage.jsx
import { useEffect, useState } from 'react'
import api from '../utils/api'
function WeightPage() {
const [usage, setUsage] = useState(null)
useEffect(() => {
// Fetch usage info
api.get('/api/features/weight_entries/check-access')
.then(res => setUsage(res))
}, [])
return (
<div>
<h1>Gewicht</h1>
{/* Phase 3: Display usage (non-blocking) */}
{usage && usage.limit !== null && (
<div className="usage-badge">
{usage.used} / {usage.limit} Einträge
{usage.remaining !== null && usage.remaining < 5 && (
<span className="warning">
Nur noch {usage.remaining} Einträge verfügbar
</span>
)}
</div>
)}
{/* Button is NOT disabled in Phase 3 */}
<button onClick={createEntry}>
Gewicht hinzufügen
</button>
</div>
)
}
```
---
## Phase 4: Enforcement aktivieren (opt-in)
### Feature-Flag System
```python
# In app_settings table
INSERT INTO app_settings (key, value, description)
VALUES ('feature_enforcement_enabled', 'false', 'Enable/disable feature limit enforcement');
```
### Modified Pattern (mit Enforcement)
```python
def create_weight(data: dict, session: dict = Depends(require_auth)):
profile_id = session['profile_id']
# Check if enforcement is enabled
enforcement_enabled = get_app_setting('feature_enforcement_enabled', False)
# Check access
access = check_feature_access(profile_id, 'weight_entries')
if not access['allowed']:
if enforcement_enabled:
# Phase 4: BLOCK
raise HTTPException(
status_code=429,
detail=f"Limit erreicht: {access['used']}/{access['limit']} Gewichtseinträge. Upgrade für mehr."
)
else:
# Phase 2/3: LOG ONLY
logger.warning(
f"[FEATURE-LIMIT] User {profile_id} would be blocked: "
f"weight_entries limit_exceeded ({access['used']}/{access['limit']})"
)
# Actual logic
# ...
```
---
## Rollout-Strategie
### Phase 2: Log-Only (1-2 Wochen)
- Alle Checks implementiert
- Nur Logging, keine Blocks
- **Monitoring**: Wie oft würde blockiert?
- **Analyse**: Gibt es falsche Limits?
### Phase 3: Display-Only (1 Woche)
- Frontend zeigt Usage an
- Buttons NICHT disabled
- **User-Feedback**: Ist Usage-Anzeige klar?
- **Testing**: Funktioniert Counter korrekt?
### Phase 4: Enforcement (schrittweise)
1. Admin-Account testen (enforcement=true nur für Admin)
2. Test-User (1-2 Accounts)
3. Rollout an alle (feature_enforcement_enabled=true)
### Rollback-Plan
- `UPDATE app_settings SET value='false' WHERE key='feature_enforcement_enabled'`
- Sofortiger Rollback ohne Code-Deploy
---
## Testing-Checklist
### Unit-Tests (Backend)
- [ ] `check_feature_access()` mit allen Hierarchien
- [ ] `increment_feature_usage()` mit Reset-Logik
- [ ] Count-based Features (limit erreicht)
- [ ] Boolean Features (enabled/disabled)
- [ ] Monthly reset funktioniert
### Integration-Tests
- [ ] POST weight-entry bis Limit erreicht
- [ ] Limit wird korrekt in Response angezeigt
- [ ] Reset nach Monatswechsel
- [ ] User-Override überschreibt Tier-Limit
- [ ] Access-Grant überschreibt Base-Tier
### Frontend-Tests
- [ ] Usage-Counter aktualisiert nach Create
- [ ] Warning bei < 5 remaining
- [ ] Unlimited zeigt "∞"
- [ ] Disabled-Features zeigen Upgrade-Hinweis
---
**Letzte Aktualisierung:** 20. März 2026
**Autor:** Lars Stommer + Claude Opus 4.6
+923
View File
@@ -0,0 +1,923 @@
# Frontend-Dokumentation
## Übersicht
Das Frontend ist eine **Progressive Web App (PWA)** gebaut mit React 18, Vite und React Router. Die Architektur folgt einem **Component-based Pattern** mit Context-basiertem State Management (kein Redux).
**Technologien:**
- React 18 (ohne TypeScript)
- Vite (Build Tool + Dev Server)
- React Router v6 (Client-side Routing)
- Recharts (Chart-Bibliothek)
- Lucide React (Icon Library)
- Day.js (Datum-Handling)
**Bundle-Größe:** ~450 KB (gzip), PWA-Cache für Offline-Nutzung
---
## Seiten-Übersicht
| Seite | Route | Beschreibung | Auth | Admin |
|-------|-------|--------------|------|-------|
| **LoginScreen** | `/` (ohne Auth) | E-Mail + Passwort Login, SHA256→bcrypt Auto-Migration | ❌ | ❌ |
| **Register** | `/register` | Selbst-Registrierung + E-Mail-Verifizierung | ❌ | ❌ |
| **Verify** | `/verify?token=...` | E-Mail-Verifizierung nach Registrierung | ❌ | ❌ |
| **SetupScreen** | `/` (First Run) | Initiales Setup (erster Admin-Account) | ❌ | ❌ |
| **Dashboard** | `/` | Übersicht: Quick Weight, Stats, Charts, Widgets | ✅ | ❌ |
| **CaptureHub** | `/capture` | Quick-Entry-Auswahl (Gewicht/Umfänge/Caliper/Fotos/Aktivität/Schlaf) | ✅ | ❌ |
| **WeightScreen** | `/weight` | Gewichts-Tracking mit Inline-Edit | ✅ | ❌ |
| **CircumScreen** | `/circum` | Umfänge (8 Punkte) | ✅ | ❌ |
| **CaliperScreen** | `/caliper` | Hautfaltenmessungen (4 Methoden) | ✅ | ❌ |
| **MeasureWizard** | `/wizard` | Geführte Messung (Schritt-für-Schritt) | ✅ | ❌ |
| **ActivityPage** | `/activity` | Training + Trainingstypen (v9d) | ✅ | ❌ |
| **NutritionPage** | `/nutrition` | 3-Tab Layout: Entry / Import / Charts | ✅ | ❌ |
| **SleepPage** | `/sleep` | Schlaf-Tracking + Phasen + Apple Health Import | ✅ | ❌ |
| **RestDaysPage** | `/rest-days` | Ruhetage (Kraft/Cardio/Entspannung) | ✅ | ❌ |
| **VitalsPage** | `/vitals` | 3-Tab: Baseline / Blutdruck / Import | ✅ | ❌ |
| **History** | `/history` | Verlauf mit Charts (Gewicht, KF%, Umfänge, etc.) | ✅ | ❌ |
| **Analysis** | `/analysis` | KI-Auswertung + Pipeline | ✅ | ❌ |
| **SettingsPage** | `/settings` | Profil, PIN-Change, Export, Feature-Usage-Übersicht | ✅ | ❌ |
| **SubscriptionPage** | `/subscription` | Membership-Status (v9c) | ✅ | ❌ |
| **GuidePage** | `/guide` | Anleitungen (Caliper, Umfänge) | ✅ | ❌ |
| **AdminPanel** | `/admin/*` (in Settings) | Admin-Übersicht | ✅ | ✅ |
| **AdminTierLimitsPage** | `/admin/tier-limits` | Tier-Limits Matrix (v9c) | ✅ | ✅ |
| **AdminFeaturesPage** | `/admin/features` | Feature-Verwaltung (v9c) | ✅ | ✅ |
| **AdminTiersPage** | `/admin/tiers` | Tier-Verwaltung (v9c) | ✅ | ✅ |
| **AdminCouponsPage** | `/admin/coupons` | Coupon-System (v9c) | ✅ | ✅ |
| **AdminUserRestrictionsPage** | `/admin/user-restrictions` | User-spezifische Limits (v9c) | ✅ | ✅ |
| **AdminTrainingTypesPage** | `/admin/training-types` | Trainingstypen-CRUD (v9d) | ✅ | ✅ |
| **AdminActivityMappingsPage** | `/admin/activity-mappings` | Activity Mapping-Verwaltung (v9d) | ✅ | ✅ |
| **AdminTrainingProfiles** | `/admin/training-profiles` | Training Type Profiling (v9d #15) | ✅ | ✅ |
**Gesamt:** 31 Seiten (22 User-facing, 9 Admin)
---
## Komponenten
### Wiederverwendbare Komponenten
| Komponente | Props | Beschreibung |
|-----------|-------|--------------|
| **Avatar** | `profile, size` | Runder Avatar mit Initialen + Farbe |
| **Markdown** | `text` | Lightweight Markdown-Renderer (## Headings, **bold**, Listen) |
| **TrialBanner** | – | Trial-Countdown-Banner (3 Urgency-Level) |
| **EmailVerificationBanner** | – | E-Mail-Verifizierungs-Hinweis |
| **FeatureUsageOverview** | – | Tabelle mit allen Feature-Limits + Usage (v9c Phase 3) |
| **UsageBadge** | `feature` | Inline-Badge mit Limit-Status (z.B. "3/10") |
| **TrainingTypeDistribution** | `days` | Pie-Chart für Trainingstypen-Verteilung |
| **SleepWidget** | `days` | Dashboard-Widget mit Schlaf-Stats |
| **RestDaysWidget** | `weeks` | Dashboard-Widget mit aktuellen Ruhetagen |
**Location:** `frontend/src/components/`
### Inline-Komponenten (in Seiten definiert)
**Dashboard.jsx:**
- `QuickWeight` – Schnelle Gewichts-Eingabe mit Feature-Limit-Check
- `StatCard` – Statistik-Karte mit Delta-Anzeige
- `Pill` – Status-Pill mit Tooltip (WHR, WHtR, KF, Protein Ø7T)
**SettingsPage.jsx:**
- `ProfileForm` – Formular für Profil-Bearbeitung
**NutritionPage.jsx:**
- `EntryTab` – Manuelle Eingabe + CSV-Import
- `ImportHistoryTab` – Import-Historie mit Gruppierung
- `ChartsTab` – Korrelationen + Wochendaten
**VitalsPage.jsx:**
- `BaselineTab` – Morgenmessungen (RHR, HRV, VO2 Max, SpO2)
- `BloodPressureTab` – Blutdruck mehrfach täglich + Context-Tagging
- `ImportTab` – CSV-Import (Omron Deutsch, Apple Health)
---
## Context / State Management
### 1. AuthContext (`frontend/src/context/AuthContext.jsx`)
**Verantwortlichkeit:** Session-Management + Login/Logout
**State:**
```javascript
{
session: {
token: string,
profile_id: string,
role: 'user' | 'admin',
profile: { id, name, email, tier, ... }
},
loading: boolean,
needsSetup: boolean, // First-run detection
}
```
**Methods:**
- `login(credentials)` – Login mit E-Mail + Passwort (oder Legacy profile_id + PIN)
- `setup(formData)` – Initial Setup (First Run)
- `logout()` – Logout + Token-Löschung
- `setAuthFromToken(token, profile)` – Direkt-Login (für E-Mail-Verifizierung)
- `checkStatus()` – Auth-Status prüfen (beim App-Start)
**Computed:**
- `isAdmin` – `session.role === 'admin'`
- `canUseAI` – `session.profile.ai_enabled !== 0`
- `canExport` – `session.profile.export_enabled !== 0`
**Storage:**
- `localStorage.bodytrack_token` – Auth-Token
- `localStorage.bodytrack_active_profile` – Aktive Profile-ID
**Flow:**
```
App-Start → checkStatus()
↓
GET /api/auth/status → {needs_setup: true/false}
↓ (wenn needs_setup = false)
GET /api/auth/me (mit Token aus localStorage)
↓
Session gesetzt → App.jsx zeigt Dashboard
```
### 2. ProfileContext (`frontend/src/context/ProfileContext.jsx`)
**Verantwortlichkeit:** Aktives Profil + Profil-Liste
**State:**
```javascript
{
profiles: Array<Profile>, // Alle Profile
activeProfile: Profile, // Aktuelles Profil
loading: boolean,
}
```
**Methods:**
- `setActiveProfile(profile)` – Profil wechseln (speichert in localStorage)
- `refreshProfiles()` – Profile neu laden (nach Update)
**Flow:**
```
session.profile_id ändert sich
↓
GET /api/profiles (mit X-Auth-Token)
↓
profiles gesetzt, activeProfile = match(session.profile_id)
```
**Hinweis:** Profile-Wechsel ist derzeit Single-User-optimiert (Multi-User-Support in Planung).
---
## API-Integration (`frontend/src/utils/api.js`)
**Zweck:** Zentrale API-Schnittstelle – **ALLE** API-Calls gehen über `api.js`
**Features:**
- Automatisches Token-Injection (`X-Auth-Token` Header)
- Automatisches Profile-ID-Injection (`X-Profile-Id` Header, derzeit deprecated)
- Einheitliche Fehlerbehandlung (parst `{detail: "..."}` aus Backend)
- Typed-like API (alle Methoden dokumentiert)
**Beispiel:**
```javascript
import { api } from '../utils/api'
// GET-Request
const weights = await api.listWeight(365) // limit=365
// POST-Request
await api.upsertWeight('2026-03-23', 75.5, 'Morgens nüchtern')
// DELETE-Request
await api.deleteWeight(entryId)
// File-Upload
const result = await api.importCsv(file)
```
**Headers-Injection:**
```javascript
function hdrs(extra={}) {
const h = {...extra}
if (_profileId) h['X-Profile-Id'] = _profileId // Deprecated, bleibt für Legacy
const token = getToken()
if (token) h['X-Auth-Token'] = token
return h
}
```
**Error-Handling:**
```javascript
if (!res.ok) {
const err = await res.text()
try {
const parsed = JSON.parse(err)
throw new Error(parsed.detail || err)
} catch {
throw new Error(err)
}
}
```
**API-Methoden (285 Zeilen):**
- **Profiles:** `getActiveProfile, listProfiles, createProfile, updateProfile, deleteProfile`
- **Weight:** `listWeight, upsertWeight, updateWeight, deleteWeight, weightStats`
- **Circumferences:** `listCirc, upsertCirc, updateCirc, deleteCirc`
- **Caliper:** `listCaliper, upsertCaliper, updateCaliper, deleteCaliper`
- **Activity:** `listActivity, createActivity, updateActivity, deleteActivity, activityStats, bulkCategorizeActivities, importActivityCsv`
- **Nutrition:** `importCsv, listNutrition, nutritionCorrelations, nutritionWeekly, nutritionImportHistory, createNutrition, updateNutrition, deleteNutrition`
- **Photos:** `uploadPhoto, listPhotos, photoUrl`
- **AI:** `insightTrend, listPrompts, runInsight, insightPipeline, listInsights, latestInsights`
- **Export:** `exportZip, exportJson, exportCsv` (Download-Handling inkludiert)
- **Admin:** `adminListProfiles, adminCreateProfile, adminDeleteProfile, adminSetPermissions, changePin`
- **Auth:** `register, verifyEmail, resendVerification`
- **Subscription (v9c):** `getMySubscription, getMyUsage, getMyLimits, redeemCoupon, getFeatureUsage`
- **Admin Features (v9c):** `listFeatures, createFeature, updateFeature, deleteFeature`
- **Admin Tiers (v9c):** `listTiers, createTier, updateTier, deleteTier, getTierLimitsMatrix, updateTierLimit, updateTierLimitsBatch`
- **Admin User Restrictions (v9c):** `listUserRestrictions, createUserRestriction, updateUserRestriction, deleteUserRestriction`
- **Admin Coupons (v9c):** `listCoupons, createCoupon, updateCoupon, deleteCoupon, getCouponRedemptions`
- **Admin Access Grants (v9c):** `listAccessGrants, createAccessGrant, updateAccessGrant, revokeAccessGrant`
- **Training Types (v9d):** `listTrainingTypes, listTrainingTypesFlat, getTrainingCategories, adminListTrainingTypes, adminCreateTrainingType, adminUpdateTrainingType, adminDeleteTrainingType, getAbilitiesTaxonomy`
- **Training Profiles (v9d #15):** `getProfileStats, getProfileTemplates, getProfileTemplate, applyProfileTemplate, getTrainingParameters, batchEvaluateActivities`
- **Activity Mappings (v9d):** `adminListActivityMappings, adminCreateActivityMapping, adminUpdateActivityMapping, adminDeleteActivityMapping, adminGetMappingCoverage`
- **Sleep (v9d):** `listSleep, getSleepByDate, createSleep, updateSleep, deleteSleep, getSleepStats, getSleepDebt, getSleepTrend, getSleepPhases, importAppleHealthSleep`
- **Rest Days (v9d):** `listRestDays, createRestDay, getRestDay, updateRestDay, deleteRestDay, getRestDaysStats, validateActivity`
- **Vitals Baseline (v9d):** `listBaseline, getBaselineByDate, createBaseline, updateBaseline, deleteBaseline, getBaselineStats, importBaselineAppleHealth`
- **Blood Pressure (v9d):** `listBloodPressure, getBPByDate, createBloodPressure, updateBloodPressure, deleteBloodPressure, getBPStats, importBPOmron`
---
## Berechnungs-Utils
### 1. calc.js (`frontend/src/utils/calc.js`)
**Zweck:** Körperfett-Berechnungen + Derived Metrics
**Funktionen:**
**`calcBodyFat(method, skinfolds, sex, age)`**
- Berechnet Körperfett-% nach 4 Methoden:
- `jackson3` – Jackson-Pollock 3-Punkt (Standard)
- `jackson7` – Jackson-Pollock 7-Punkt
- `durnin` – Durnin-Womersley 4-Punkt
- `parrillo` – Parrillo 9-Punkt (linear)
- Nutzt Siri-Formel: `BF% = (495 / D) - 450`
- Parameter:
- `method`: String ('jackson3', 'jackson7', 'durnin', 'parrillo')
- `skinfolds`: Object mit Hautfalten in mm (z.B. `{chest: 12, abdomen: 24, thigh: 18}`)
- `sex`: 'm' | 'f'
- `age`: Number
**`getBfCategory(pct, sex)`**
- Kategorisiert Körperfett-% in Bereiche:
- Männer: Essenziell (<6%), Athletisch (6-14%), Fit (14-18%), Durchschnitt (18-25%), Übergewicht (>25%)
- Frauen: Essenziell (<14%), Athletisch (14-21%), Fit (21-25%), Durchschnitt (25-32%), Übergewicht (>32%)
- Returns: `{max, label, color, desc}`
**`calcDerived(measurement, height)`**
- Berechnet abgeleitete Metriken:
- **WHR** (Waist-Hip-Ratio): `waist / hip` (Ziel: <0.90 M / <0.85 F)
- **WHtR** (Waist-to-Height-Ratio): `waist / height` (Ziel: <0.50)
- **FFMI** (Fat-Free Mass Index): `lean_mass / (height_m²)` (Natural Limit: ~25 M / ~22 F)
- Returns: `{whr, whtr, ffmi}`
**`getRuleBasedAssessment(current, previous, profile)`**
- Generiert automatische Interpretationen basierend auf:
- Körperfett-Kategorie
- Änderungen seit letzter Messung
- FFMI (Muskel-Index)
- WHR / WHtR (Fettverteilung)
- Taillenumfang (WHO-Grenzwerte)
- Returns: `{findings: Array, summary: string, summaryType: 'good'|'warn'|'bad'}`
**Guide-Daten:**
- `CIRCUMFERENCE_GUIDE` – Messanleitung für 8 Umfangspunkte (wo, wie, Posture, Tipps)
- `CALIPER_GUIDE` – Messanleitung für Hautfalten-Punkte
### 2. interpret.js (`frontend/src/utils/interpret.js`)
**Zweck:** Interpretation von Messwerten
**`getInterpretation(measurement, profile, prevMeasurement)`**
- Analysiert Messung und generiert strukturierte Interpretation:
- Körperfett-Status (mit Kategorie + Farbe)
- WHR-Status
- WHtR-Status
- FFMI-Status
- BMI-Status
- Vergleich zur letzten Messung (Deltas)
- Returns: Array von Interpretations-Objects:
```javascript
{
category: 'Körperfett',
icon: '🫧',
status: 'good' | 'warn' | 'bad',
title: 'Athletischer Körperfettanteil',
detail: 'Ausgezeichnet. Typisch für aktive Sportler...',
value: '12.5%',
badge: 'Athletisch',
color: '#1D9E75',
}
```
**`getStatusColor(status)`** – Farbe für Status ('good'→Grün, 'warn'→Orange, 'bad'→Rot)
**`getStatusBg(status)`** – Background-Farbe für Status
### 3. Markdown.jsx (`frontend/src/utils/Markdown.jsx`)
**Zweck:** Leichtgewichtiger Markdown-Renderer für KI-Texte
**Unterstützte Syntax:**
- `# Heading 1`, `## Heading 2`, `### Heading 3`
- `**bold**`, `*italic*`
- `- Bullet List`, `1. Numbered List`
- `---` (Horizontal Rule)
- Line Breaks
**Verwendung:**
```jsx
<Markdown text={aiInsight.content} />
```
**Vorteil:** Kein remark/rehype-Dependency – nur 134 Zeilen pures React
---
## CSS-System (`frontend/src/app.css`)
### CSS-Variablen (Light + Dark Mode)
**Farben:**
```css
:root {
--bg: #f4f3ef; /* Hintergrund */
--surface: #ffffff; /* Cards */
--surface2: #f9f8f5; /* Inputs, Secondary */
--border: rgba(0,0,0,0.09); /* Standard-Border */
--border2: rgba(0,0,0,0.16);/* Input-Border */
--text1: #1c1b18; /* Primär-Text */
--text2: #5a5955; /* Sekundär-Text */
--text3: #9a9892; /* Muted */
--accent: #1D9E75; /* Primär-Farbe */
--accent-light: #E1F5EE; /* Accent-Background */
--accent-dark: #0a5c43; /* Hover */
--danger: #D85A30; /* Fehler/Löschen */
--warn: #EF9F27; /* Warnung */
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #181816;
--surface: #222220;
--surface2: #1e1e1c;
--border: rgba(255,255,255,0.08);
--text1: #eeecea;
--text2: #aaa9a4;
--text3: #686762;
--accent-light: #04342C;
--accent-dark: #5DCAA5;
}
}
```
**Layout:**
```css
--nav-h: 64px; /* Bottom Navigation Höhe */
--header-h: 52px; /* App-Header Höhe */
```
### Utility Classes
**Cards:**
```css
.card /* Standard-Card (white background, border, rounded) */
.card-title /* Card-Überschrift (uppercase, small, muted) */
```
**Stats:**
```css
.stats-grid /* 2-Column Grid für Stats */
.stat-card /* Einzelne Stat-Card */
.stat-val /* Wert (groß, bold) */
.stat-label /* Label (klein, muted) */
.stat-delta /* Delta (z.B. "+2.5 kg") */
.delta-pos /* Positive Änderung (grün) */
.delta-neg /* Negative Änderung (rot) */
```
**Forms:**
```css
.form-section /* Formular-Sektion mit Abstand */
.form-section-title /* Sektions-Titel (uppercase, border-bottom) */
.form-row /* Zeile mit Label + Input + Unit */
.form-label /* Label (links, flex:1) */
.form-input /* Input (90px breit, text-align:right) */
.form-unit /* Einheit (z.B. "kg", 24px breit) */
.form-select /* Select-Dropdown */
.form-sub /* Sub-Label (klein, muted) */
```
**Buttons:**
```css
.btn /* Base Button */
.btn-primary /* Primär-Button (accent) */
.btn-secondary /* Sekundär-Button (grau) */
.btn-danger /* Löschen-Button (rot) */
.btn-full /* Full-Width Button */
```
**Tabs:**
```css
.tabs /* Tab-Container (segmented control) */
.tab /* Einzelner Tab */
.tab.active /* Aktiver Tab (white background, shadow) */
```
**Misc:**
```css
.badge /* Inline-Badge (klein, rounded) */
.spinner /* Loading-Spinner (CSS-Animation) */
.empty-state /* Leerer Zustand (zentriert, muted) */
.muted /* Muted-Text (text3) */
```
### Responsive Design
**Mobile-First Approach:**
- Standard-Layout für 375px–600px (Mobile)
- Max-Width: 600px (zentriert auf Desktop)
- Bottom-Navigation für Mobile (64px hoch)
- Touch-optimierte Button-Größen (min 44px)
**Bottom Navigation:**
```css
.bottom-nav {
position: fixed;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 100%;
max-width: 600px;
height: var(--nav-h);
z-index: 20;
}
```
**Safe Area (iPhone):**
```css
padding-bottom: env(safe-area-inset-bottom, 0); /* Notch-Handling */
```
**Desktop-Optimierung:**
- App zentriert mit max-width: 600px
- Kein responsives Layout für >600px (bewusst Mobile-optimiert)
---
## PWA-Konfiguration
### Service Worker
**Location:** `frontend/public/service-worker.js`
**Cache-Strategie:**
- **Static Assets:** Cache-First (HTML, CSS, JS, Icons)
- **API-Calls:** Network-First mit Fallback
- **Photos:** Cache-First mit Expiry
**Registrierung:**
```javascript
// frontend/src/main.jsx
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
}
```
### Manifest
**Location:** `frontend/public/manifest.json`
**Wichtige Felder:**
```json
{
"name": "Mitai Jinkendo",
"short_name": "Mitai",
"theme_color": "#1D9E75",
"background_color": "#f4f3ef",
"display": "standalone",
"icons": [
{ "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" }
]
}
```
**Installation:**
- iOS: "Zum Home-Bildschirm"
- Android: "Installieren"-Prompt
- Desktop: Chrome/Edge Install-Button
---
## Chart-Bibliothek (Recharts)
**Verwendete Charts:**
| Chart-Typ | Verwendung | Seite |
|-----------|-----------|-------|
| **LineChart** | Gewicht, Körperfett, Umfänge, Vitalwerte | Dashboard, History |
| **BarChart** | Wöchentliche Ernährung, Aktivität | NutritionPage, History |
| **PieChart** | Trainingstypen-Verteilung | Dashboard, ActivityPage |
| **ScatterChart** | Korrelationen (Gewicht vs. Kalorien) | NutritionPage |
| **ComposedChart** | Multi-Axis (Gewicht + KF% kombiniert) | History |
**Standard-Konfiguration:**
```jsx
<ResponsiveContainer width="100%" height={240}>
<LineChart data={data}>
<CartesianGrid strokeDasharray="3 3" stroke="var(--border)" />
<XAxis dataKey="date" tick={{ fontSize: 11 }} stroke="var(--text3)" />
<YAxis tick={{ fontSize: 11 }} stroke="var(--text3)" />
<Tooltip contentStyle={{ background: 'var(--surface)', border: '1px solid var(--border)' }} />
<Line type="monotone" dataKey="weight" stroke="var(--accent)" strokeWidth={2} dot={false} />
</LineChart>
</ResponsiveContainer>
```
**Farb-Schema:**
- Gewicht: `var(--accent)` (#1D9E75)
- Körperfett: `#D85A30` (Danger)
- Umfänge: Individual Colors (siehe `CIRCUMFERENCE_GUIDE`)
- 7-Tage-Durchschnitt: `var(--accent-dark)` (#0a5c43, gestrichelt)
---
## Feature Usage Badges (v9c Phase 3)
**Zweck:** Sichtbarkeit der Feature-Limits direkt in der UI
**Komponenten:**
### 1. UsageBadge (`components/UsageBadge.jsx`)
**Inline-Badge mit Limit-Status:**
```jsx
<UsageBadge feature="weight_entries" />
// Rendert: "5/10" (grün) oder "10/10 🔒" (rot)
```
**Logik:**
```javascript
const { allowed, used, limit, remaining } = await api.getFeatureUsage()
const color = allowed ? 'var(--accent)' : 'var(--danger)'
const text = limit === null ? '∞' : `${used}/${limit}`
```
**Verwendung:** In Buttons (z.B. "Speichern 5/10")
### 2. FeatureUsageOverview (`components/FeatureUsageOverview.jsx`)
**Tabelle mit allen Features:**
```jsx
<FeatureUsageOverview />
```
**Darstellung:**
| Feature | Genutzt | Limit | Verbleibend | Status |
|---------|---------|-------|-------------|--------|
| Gewichtseinträge | 45 | 100 | 55 | ✓ OK |
| KI-Aufrufe | 10 | 10 | 0 | 🔒 Limit erreicht |
| Daten-Export | 1 | 5 | 4 | ✓ OK |
**Farbcodierung:**
- Grün: `allowed === true`
- Rot: `allowed === false`
- Gelb: `remaining < 10% && allowed`
**Location:** Settings-Seite (Tab "Quota")
---
## Routing-Architektur
### App-Struktur (`App.jsx`)
```
AuthProvider
↓
ProfileProvider
↓
BrowserRouter
↓
AppShell
├── Public Routes (ohne Auth)
│ ├── /register → Register
│ ├── /verify?token=... → Verify
│ └── /reset-password?token=... → ResetPassword
│
├── Auth Gates
│ ├── authLoading → Spinner
│ ├── needsSetup → SetupScreen
│ └── !session → LoginScreen
│
└── Authenticated Routes
├── Header (Logo + Logout + Avatar)
├── Main (Scrollable Content)
│ └── Routes (31 Seiten)
└── Nav (Bottom Navigation, 5 Items)
```
### Navigation-Items
```javascript
const links = [
{ to: '/', icon: <LayoutDashboard/>, label: 'Übersicht' },
{ to: '/capture', icon: <PlusSquare/>, label: 'Erfassen' },
{ to: '/history', icon: <TrendingUp/>, label: 'Verlauf' },
{ to: '/analysis', icon: <BarChart2/>, label: 'Analyse' },
{ to: '/settings', icon: <Settings/>, label: 'Einst.' },
]
```
**Besonderheit:** Active-State via React Router `NavLink` (`isActive` prop)
### Route-Guards
**Auth-Schutz:**
```jsx
if (!session) return <LoginScreen/>
```
**Admin-Schutz:**
```jsx
// In AdminPanel-Seiten:
const { isAdmin } = useAuth()
if (!isAdmin) return <div>Nur für Admins</div>
```
**Setup-Check:**
```jsx
if (needsSetup) return <SetupScreen/>
```
---
## Performance-Optimierungen
### 1. Code Splitting
**React.lazy() für Admin-Seiten:**
```javascript
const AdminPanel = React.lazy(() => import('./pages/AdminPanel'))
```
**Vorteil:** Admin-Code nicht im Initial Bundle (~80 KB gespart)
### 2. Memoization
**useMemo für teure Berechnungen:**
```javascript
const stats = useMemo(() => {
return calculateStats(data)
}, [data])
```
**Verwendung:** Chart-Daten-Transformation, Aggregationen
### 3. Lazy Loading
**Images:**
```jsx
<img src={photoUrl} loading="lazy" />
```
**Charts:**
- Nur sichtbare Charts rendern (Intersection Observer in Planung)
### 4. API-Call-Batching
**Parallel-Loading:**
```javascript
const [stats, insights, weights] = await Promise.all([
api.getStats(),
api.latestInsights(),
api.listWeight(30),
])
```
**Verwendung:** Dashboard initial load
---
## Error-Handling
### 1. API-Fehler
**Pattern in allen Seiten:**
```javascript
const [error, setError] = useState(null)
try {
const data = await api.someEndpoint()
setData(data)
} catch(e) {
setError(e.message) // api.js parsed bereits {detail: "..."}
} finally {
setLoading(false)
}
```
**Anzeige:**
```jsx
{error && (
<div style={{
background: 'rgba(216,90,48,0.1)',
color: 'var(--danger)',
padding: '10px 14px',
borderRadius: 8,
border: '1px solid rgba(216,90,48,0.2)'
}}>
{error}
</div>
)}
```
### 2. Network-Fehler
**Offline-Detection:**
```javascript
useEffect(() => {
const handleOnline = () => setOnline(true)
const handleOffline = () => setOnline(false)
window.addEventListener('online', handleOnline)
window.addEventListener('offline', handleOffline)
return () => {
window.removeEventListener('online', handleOnline)
window.removeEventListener('offline', handleOffline)
}
}, [])
```
**Anzeige:** Banner "Keine Internetverbindung – Änderungen werden gespeichert sobald Online"
### 3. Form-Validierung
**Client-Side:**
```javascript
if (!weight || weight < 20 || weight > 300) {
setError('Gewicht zwischen 20 und 300 kg')
return
}
```
**Server-Side:**
- Backend wirft `HTTPException(400, detail="...")` → Frontend zeigt `detail`
---
## Besonderheiten & Design-Entscheidungen
### 1. Warum kein TypeScript?
**Entscheidung:** Bewusst auf TypeScript verzichtet
**Gründe:**
- Schnellere Prototyping-Geschwindigkeit
- Weniger Build-Komplexität
- JSDoc-Kommentare für Dokumentation ausreichend
- Type Safety durch Backend (Pydantic validiert alle Inputs)
### 2. Warum Context statt Redux?
**Entscheidung:** Context API ausreichend für diesen Use-Case
**Gründe:**
- Nur 2 globale States (Auth + Profile)
- Kein komplexes State-Update-Pattern nötig
- Weniger Boilerplate
- Performance ausreichend (keine häufigen Re-Renders)
**Hinweis:** Bei >5 Contexts würde Redux Sinn machen
### 3. Warum Custom Markdown statt remark/rehype?
**Entscheidung:** Eigener Markdown-Renderer (134 Zeilen)
**Gründe:**
- Nur Subset von Markdown benötigt (Headings, Bold, Listen)
- remark + rehype + plugins = ~200 KB Bundle-Size
- Custom-Renderer = 0 Dependencies
- Full Control über Styling
### 4. Warum Recharts statt Chart.js?
**Entscheidung:** Recharts für alle Charts
**Gründe:**
- React-native (kein Canvas, sondern SVG)
- Declarative API passt zu React
- Responsive by default
- Kleineres Bundle als Chart.js
### 5. Inline-Editing statt Modal-Forms
**Entscheidung:** Inline-Edit für alle Listen (Gewicht, Ernährung, Vitalwerte)
**Pattern:**
```javascript
const [editingId, setEditingId] = useState(null)
{entries.map(e => (
editingId === e.id
? <EditForm entry={e} onSave={...} onCancel={...} />
: <ViewRow entry={e} onEdit={() => setEditingId(e.id)} />
))}
```
**Vorteil:**
- Keine Modal-Komponente nötig
- Besserer Mobile-UX (kein Overlay)
- Schnelleres Editing (kein Dialog öffnen)
---
## Bekannte Limitationen
### 1. Desktop-Optimierung
**Problem:** App ist Mobile-First, Desktop-Layout nicht optimiert
**Aktuell:** Max-Width 600px, zentriert auf Desktop
**Geplant (v10+):** Responsive Grid-Layout für Desktop (Sidebar + Multi-Column)
### 2. Offline-Modus
**Problem:** Service Worker cached nur Static Assets, nicht API-Responses
**Aktuell:** Offline = Keine Daten-Eingabe möglich
**Geplant (v10+):** IndexedDB für Offline-Queue
### 3. Multi-Profil-Support
**Problem:** Profile-Wechsel funktioniert, aber Session ist Single-User
**Aktuell:** Logout + Login für Profil-Wechsel
**Geplant (v9f+):** Multi-Session-Support (Switch ohne Logout)
### 4. Accessibility
**Problem:** ARIA-Labels fehlen, Keyboard-Navigation unvollständig
**Aktuell:** Maus/Touch-optimiert
**Geplant (v10+):** WCAG 2.1 AA Compliance
---
## Testing
**Aktueller Stand:** Kein automatisiertes Testing implementiert
**Geplant (v10+):**
- Unit-Tests: Vitest für utils (calc.js, interpret.js)
- Component-Tests: React Testing Library
- E2E-Tests: Playwright für kritische Flows (Login, Gewicht-Eingabe, KI-Analyse)
**Manual Testing:**
- Alle Features manuell auf iOS Safari, Android Chrome, Desktop Firefox getestet
- Regression-Tests bei jedem Deploy
---
## Zusammenfassung
**Architektur-Highlights:**
- ✅ 31 Seiten (22 User, 9 Admin)
- ✅ Context-basiertes State Management (Auth + Profile)
- ✅ Zentrale API-Schnittstelle (api.js)
- ✅ Berechnungs-Utils für Body-Metrics (calc.js, interpret.js)
- ✅ CSS-Variablen für Light/Dark Mode
- ✅ PWA mit Service Worker
- ✅ Recharts für alle Charts
- ✅ Feature Usage Badges (v9c Phase 3)
- ✅ Mobile-First Design (max-width 600px)
- ✅ Inline-Editing statt Modals
- ✅ Custom Markdown-Renderer (0 Dependencies)
**Performance:**
- Initial Bundle: ~450 KB (gzip)
- Code Splitting: Admin-Seiten lazy-loaded
- API-Call-Batching: Parallel-Loading für Dashboard
**Nächste Schritte:**
- Testing (Vitest + React Testing Library)
- Desktop-Responsive-Layout
- Offline-Modus (IndexedDB)
- Accessibility (WCAG 2.1 AA)
@@ -0,0 +1,212 @@
# Internal API Reference
**Purpose:** Prevent guessing function signatures and module exports.
Last updated: 2026-03-28
---
## goal_utils.py
### Focus Area Functions
```python
def get_focus_weights(conn, profile_id: str) -> Dict[str, float]
```
Returns user's focus area weights as `{area_key: weight_percent}`.
Keys are **English** (weight_loss, muscle_gain, etc.).
```python
def get_focus_weights_v2(conn, profile_id: str) -> Dict[str, float]
```
Newer version with auto-normalization. Use this for new code.
```python
def get_primary_focus(conn, profile_id: str) -> str
```
Returns area_key of highest weighted focus area.
```python
def get_focus_description(focus_area: str) -> str
```
Returns German description for a focus area key.
---
### Goal Functions
```python
def get_active_goals(profile_id: str) -> List[Dict]
```
Returns ALL active goals for a profile.
Each dict has: id, type_key, current_value, target_value, is_primary, etc.
**To filter by type:**
```python
goals = get_active_goals(profile_id)
weight_goals = [g for g in goals if g.get('type_key') == 'weight']
```
```python
def get_goal_by_id(goal_id: str) -> Optional[Dict]
```
Returns single goal by UUID.
```python
def get_goal_type_config(conn, type_key: str) -> Optional[Dict[str, Any]]
```
Returns goal type metadata from `goal_type_definitions` table:
- source_table, source_column, aggregation_method, unit
```python
def get_current_value_for_goal(conn, profile_id: str, goal_type: str) -> Optional[float]
```
Calculates current value for a goal type using its aggregation method.
---
### Aggregation Functions
```python
def calculate_current_value(
profile_id: str,
table: str,
column: str,
method: str,
date_column: str = 'date',
filter_conditions: Optional[List[Tuple[str, Any]]] = None
) -> Optional[float]
```
**Available methods:**
- `latest` - Most recent value
- `avg_7d` - 7-day average (numeric values only)
- `avg_30d` - 30-day average
- `max_30d` - Maximum in 30 days
- `avg_per_week_30d` - Count per week over 30 days (for frequency tracking)
**Filter conditions format:**
```python
[("training_type", "strength"), ("quality", "good")]
```
---
## calculations/body_metrics.py
### Score Functions
```python
def calculate_body_progress_score(profile_id: str, focus_weights: Dict[str, float] = None) -> Optional[int]
```
Returns 0-100 score for body composition progress.
Weighted by focus areas: weight_loss, muscle_gain, body_recomposition.
**Sub-functions (private):**
- `_score_weight_trend(profile_id)` - Alignment with weight goal
- `_score_body_composition(profile_id)` - BF% + lean mass progress
---
## calculations/nutrition_metrics.py
### Score Functions
```python
def calculate_nutrition_score(profile_id: str, focus_weights: Dict[str, float] = None) -> Optional[int]
```
Returns 0-100 score for nutrition adherence.
Weighted by: protein_intake, calorie_balance, macro_consistency, meal_timing, hydration.
**Sub-functions (private):**
- `_score_calorie_adherence(profile_id)` - Energy balance vs goal
- `_score_protein_adequacy(profile_id)` - Protein target adherence
---
## calculations/activity_metrics.py
### Score Functions
```python
def calculate_activity_score(profile_id: str, focus_weights: Dict[str, float] = None) -> Optional[int]
```
Returns 0-100 score for training quality.
Weighted by: strength, endurance (aerobic+anaerobic+cardiovascular), mobility/coordination.
**Sub-functions (private):**
- `_score_training_quality(profile_id)` - Session quality %
- `_score_training_consistency(profile_id)` - Frequency adherence
---
## calculations/scores.py
### Main Score Aggregator
```python
def calculate_goal_progress_score(profile_id: str) -> Optional[int]
```
Master score aggregating body, nutrition, activity progress.
Weighted by user's category weights from focus areas.
```python
def calculate_category_progress(profile_id: str, category: str) -> Optional[int]
```
Maps category name to appropriate score function.
Categories: körper, ernährung, aktivität, erholung, vitalwerte, mental, lebensstil
---
## Common Patterns
### Getting Goals for a Specific Type
```python
# ❌ DON'T (function doesn't exist):
from goal_utils import get_goals_by_type
goals = get_goals_by_type(profile_id, 'weight')
# ✅ DO:
from goal_utils import get_active_goals
goals = get_active_goals(profile_id)
weight_goals = [g for g in goals if g.get('type_key') == 'weight']
```
### Accessing Focus Area Weights
```python
# ❌ DON'T (German keys don't exist in DB):
weight_focus = focus_weights.get('körpergewicht', 0)
# ✅ DO (English keys from Migration 031):
weight_loss = focus_weights.get('weight_loss', 0)
muscle_gain = focus_weights.get('muscle_gain', 0)
```
### Querying Sleep Data
```python
# ❌ DON'T:
SELECT duration FROM sleep_log
# ✅ DO:
SELECT duration_minutes, deep_minutes, rem_minutes FROM sleep_log
```
---
## Verification Checklist
Before using any function:
1. ✅ Verify function exists: `grep "^def function_name" backend/module.py`
2. ✅ Check signature: `Read module.py` to see parameters
3. ✅ Check what it returns: Read docstring or implementation
4. ✅ Verify imported correctly: Check module path
Before writing SQL:
1. ✅ Check table schema: `grep "CREATE TABLE" backend/schema.sql`
2. ✅ Verify column names: Check migration files
3. ✅ Test query logic: Use actual data, not assumptions
File diff suppressed because it is too large. Load diff
+392
View File
@@ -0,0 +1,392 @@
# Database Migrations System
**Version:** v9c
**Implementiert:** 2026-03-21
**Dokumentiert:** 2026-03-21
---
## Übersicht
Mitai Jinkendo verwendet ein automatisches Migrations-System für strukturierte Schema-Änderungen. Alle Migrationen werden beim Container-Start automatisch ausgeführt.
## Architektur
### Migration-Tracking
**Tabelle:** `schema_migrations`
```sql
CREATE TABLE schema_migrations (
id SERIAL PRIMARY KEY,
filename VARCHAR(255) UNIQUE NOT NULL,
applied_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)
```
Diese Tabelle trackt, welche Migrationen bereits angewendet wurden.
### Ablauf beim Container-Start
1. **PostgreSQL Connection Check** (`db_init.py`)
2. **Schema-Initialisierung** (falls `profiles` Tabelle nicht existiert)
- Lädt `backend/schema.sql` (Basis-Schema)
3. **Migrations-System** (`run_migrations()`)
- Erstellt `schema_migrations` Tabelle (falls nicht vorhanden)
- Scannt `backend/migrations/` nach `.sql` Dateien
- Filtert nur nummerierte Dateien: `\d{3}_*.sql` (z.B. `001_feature.sql`)
- Sortiert alphabetisch (aufsteigende Reihenfolge)
- Wendet nur noch nicht angewendete Migrationen an
- Trackt jede erfolgreich angewendete Migration
4. **SQLite-zu-PostgreSQL Migration** (falls vorhanden)
## Datei-Konventionen
### Naming-Pattern
**Format:** `XXX_descriptive_name.sql`
- `XXX` = Dreistellige Nummer (001, 002, 003, ...)
- Unterstrich `_` als Trennzeichen
- Kleinbuchstaben, keine Leerzeichen
- `.sql` Extension
**Beispiele:**
```
✅ 001_subscription_system.sql
✅ 002_fix_features.sql
✅ 003_add_email_verification.sql
❌ v9c_subscription_system.sql # Keine Nummer
❌ check_features.sql # Keine Nummer
❌ 1_feature.sql # Nur eine Ziffer
❌ 001-feature.sql # Bindestrich statt Unterstrich
```
### Datei-Struktur
Jede Migration sollte folgende Struktur haben:
```sql
-- ================================================================
-- Migration XXX: Beschreibung
-- Version: vX.X
-- Date: YYYY-MM-DD
-- ================================================================
-- Beschreibung der Änderung
ALTER TABLE table_name ...
-- Weitere SQL-Statements
-- Kommentare für Dokumentation
COMMENT ON COLUMN table.column IS 'Beschreibung';
```
### SQL-Einschränkungen
**Erlaubt:**
- Standard SQL DDL (CREATE, ALTER, DROP)
- Standard SQL DML (INSERT, UPDATE, DELETE)
- CREATE INDEX, CREATE FUNCTION, etc.
- Multi-Statement-Scripts (durch `;` getrennt)
**Nicht erlaubt:**
- psql Meta-Kommandos (`\echo`, `\set`, `\connect`, etc.)
- Interactive Commands (`\i`, `\include`)
- Transaktions-Kontrolle (automatisch gehandhabt)
## Anwendung
### Automatisch (Production/Dev)
Migrationen werden **automatisch** beim Container-Start angewendet:
```bash
# Container startet
docker compose up -d
# db_init.py wird ausgeführt:
# 1. PostgreSQL ready check
# 2. Schema initialisiert (falls nötig)
# 3. Migrationen ausgeführt
# 4. SQLite-Migration (falls nötig)
```
**Log-Output:**
```
═══════════════════════════════════════════════════════════
MITAI JINKENDO - Database Initialization (v9c)
═══════════════════════════════════════════════════════════
Checking PostgreSQL connection...
✓ PostgreSQL ready
Checking database schema...
✓ Schema already exists
Running database migrations...
Found 2 pending migration(s)...
✓ Applied: 001_subscription_system.sql
✓ Applied: 003_add_email_verification.sql
✓ Database initialization complete
```
### Manuell (Entwicklung)
Für Testing während der Entwicklung:
```bash
# Im laufenden Container
docker exec -it dev-mitai-api python3 /app/db_init.py
# Oder direkt mit psql (für einzelne Migrationen)
docker exec -it dev-mitai-db psql -U mitai_dev -d mitai_dev \
-f /path/to/migration.sql
```
## Migration erstellen
### Schritt 1: Datei erstellen
```bash
# Nächste freie Nummer ermitteln
ls backend/migrations/ | grep -E '^\d{3}_' | sort | tail -1
# → 003_add_email_verification.sql
# Neue Migration mit Nummer 004
touch backend/migrations/004_add_new_feature.sql
```
### Schritt 2: SQL schreiben
```sql
-- ================================================================
-- Migration 004: Add New Feature
-- Version: v9d
-- Date: 2026-03-22
-- ================================================================
-- Add new column
ALTER TABLE profiles
ADD COLUMN IF NOT EXISTS new_feature_enabled BOOLEAN DEFAULT TRUE;
-- Create index if needed
CREATE INDEX IF NOT EXISTS idx_profiles_new_feature
ON profiles(new_feature_enabled)
WHERE new_feature_enabled = TRUE;
-- Update existing data if needed
UPDATE profiles
SET new_feature_enabled = TRUE
WHERE tier = 'premium';
COMMENT ON COLUMN profiles.new_feature_enabled IS 'Feature flag for new feature';
```
### Schritt 3: Testen
```bash
# Lokal testen (Dev-Container)
git add backend/migrations/004_add_new_feature.sql
git commit -m "feat: add migration for new feature"
git push origin develop
# Container wird neu gebaut und Migration automatisch angewendet
```
### Schritt 4: Verifizieren
```bash
# Prüfen ob Migration angewendet wurde
docker exec -it dev-mitai-db psql -U mitai_dev -d mitai_dev \
-c "SELECT * FROM schema_migrations ORDER BY applied_at DESC LIMIT 5;"
# Output:
# id | filename | applied_at
# ---+------------------------------+------------------------
# 4 | 004_add_new_feature.sql | 2026-03-22 10:30:15+00
# 3 | 003_add_email_verification.sql| 2026-03-21 15:20:10+00
# 2 | 002_fix_features.sql | 2026-03-20 12:10:05+00
# 1 | 001_subscription_system.sql | 2026-03-20 12:10:00+00
```
## Rollback-Strategie
**Automatischer Rollback:** Nicht implementiert
**Manueller Rollback:**
1. **Identifizieren der problematischen Migration:**
```bash
docker logs dev-mitai-api | grep "Failed to apply"
```
2. **Migration aus Tracking entfernen:**
```sql
DELETE FROM schema_migrations
WHERE filename = '004_broken_migration.sql';
```
3. **Änderungen manuell rückgängig machen:**
```sql
-- Beispiel: Spalte entfernen
ALTER TABLE profiles DROP COLUMN new_feature_enabled;
```
4. **Migration-Datei korrigieren**
```bash
vim backend/migrations/004_broken_migration.sql
```
5. **Container neu starten** (Migration wird erneut ausgeführt)
```bash
docker compose restart api
```
## Best Practices
### ✅ DO
- **Immer `IF NOT EXISTS` / `IF EXISTS` verwenden:**
```sql
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS email_verified BOOLEAN;
CREATE INDEX IF NOT EXISTS idx_profiles_email ON profiles(email);
```
- **Idempotente Migrationen schreiben:** Migration kann mehrfach ausgeführt werden ohne Fehler
- **Daten-Migrationen mit Bedacht:**
```sql
UPDATE profiles
SET email_verified = TRUE
WHERE email IS NOT NULL AND email_verified IS NULL;
```
- **Kommentare für Dokumentation:**
```sql
COMMENT ON COLUMN profiles.email_verified IS 'Whether email has been verified';
```
- **Indices für Performance:**
```sql
CREATE INDEX IF NOT EXISTS idx_profiles_verification_token
ON profiles(verification_token)
WHERE verification_token IS NOT NULL; -- Partial index
```
### ❌ DON'T
- **Keine psql Meta-Kommandos:**
```sql
\echo "Starting migration" -- ❌ Funktioniert nicht
SELECT 'Starting migration'; -- ✅ Funktioniert
```
- **Keine Breaking Changes ohne Staging:**
```sql
ALTER TABLE profiles DROP COLUMN tier; -- ❌ App wird brechen
```
- **Keine Hardcoded Values für produktive Daten:**
```sql
INSERT INTO profiles (id, email, ...) VALUES (1, 'admin@example.com', ...); -- ❌
```
- **Keine Foreign Keys ohne Fallback:**
```sql
-- ❌ Ohne ON DELETE Behavior
ALTER TABLE subscriptions
ADD CONSTRAINT fk_profile FOREIGN KEY (profile_id) REFERENCES profiles(id);
-- ✅ Mit Cascade
ALTER TABLE subscriptions
ADD CONSTRAINT fk_profile FOREIGN KEY (profile_id)
REFERENCES profiles(id) ON DELETE CASCADE;
```
## Troubleshooting
### Migration schlägt fehl
**Symptom:** Container startet nicht, Logs zeigen `✗ Failed to apply XXX.sql`
**Lösung:**
1. Logs prüfen: `docker logs dev-mitai-api | tail -50`
2. Fehlerhafte Migration identifizieren
3. Aus Tracking entfernen + Schema manuell korrigieren
4. Migration-Datei fixen
5. Container neu starten
### Migration wurde nicht angewendet
**Symptom:** Neue Migration-Datei wird ignoriert
**Ursachen:**
- Datei entspricht nicht dem Pattern `\d{3}_*.sql`
- Datei wurde bereits in `schema_migrations` getrackt
- Datei ist nicht im Container (`backend/migrations/` Volume gemountet?)
**Lösung:**
```bash
# Prüfen ob Datei gemountet ist
docker exec -it dev-mitai-api ls -la /app/migrations/
# Prüfen ob bereits getrackt
docker exec -it dev-mitai-db psql -U mitai_dev -d mitai_dev \
-c "SELECT * FROM schema_migrations WHERE filename = '004_feature.sql';"
# Falls fälschlich getrackt, entfernen
docker exec -it dev-mitai-db psql -U mitai_dev -d mitai_dev \
-c "DELETE FROM schema_migrations WHERE filename = '004_feature.sql';"
# Container neu starten
docker compose restart api
```
### Datenbank-Schema inkonsistent
**Symptom:** `schema_migrations` zeigt Migration als angewendet, aber Änderungen fehlen
**Ursachen:**
- Migration wurde manuell ausgeführt, aber Tracking war kaputt
- Datenbank wurde zurückgesetzt, aber Tracking-Tabelle nicht
**Lösung:**
```bash
# Schema neu aufbauen (ACHTUNG: Datenverlust!)
docker compose down -v # Löscht Volumes
docker compose up -d # Baut alles neu auf
# ODER: Tracking-Tabelle manuell korrigieren
docker exec -it dev-mitai-db psql -U mitai_dev -d mitai_dev \
-c "TRUNCATE schema_migrations; -- Alle Tracking-Einträge löschen"
# Container neu starten → Alle Migrationen werden erneut angewendet
docker compose restart api
```
## Migrations-Historie
| Nr. | Datei | Version | Datum | Beschreibung |
|-----|-------|---------|-------|--------------|
| 003 | `003_add_email_verification.sql` | v9c | 2026-03-21 | Email-Verifizierung (verification_token, email_verified, verification_expires) |
| 002 | `002_fix_features.sql` (manuell) | v9c | 2026-03-20 | Feature-System Fixes |
| 001 | `001_subscription_system.sql` (manuell) | v9c | 2026-03-20 | Membership-System (tiers, subscriptions, coupons, access_grants) |
**Hinweis:** Migrationen 001 und 002 wurden vor Einführung des automatischen Systems manuell angewendet und sind nicht nummeriert. Ab Migration 003 läuft alles automatisch.
---
## Referenzen
- **Code:** `backend/db_init.py` (Zeilen 94-200)
- **Migrations-Ordner:** `backend/migrations/`
- **Tracking-Tabelle:** `schema_migrations`
- **Startup-Script:** `backend/startup.sh` (ruft `db_init.py` auf)
- **Dokumentation:** `.claude/docs/technical/MIGRATIONS.md` (diese Datei)
---
**Dokumentiert:** 2026-03-21
**Letzte Änderung:** 2026-03-21
@@ -0,0 +1,799 @@
# Placeholder Development Guide
**Version:** 1.0
**Erstellt:** 28. März 2026
**Zielgruppe:** Entwickler, Claude Code
---
## Überblick
Dieses Dokument beschreibt, wie neue KI-Platzhalter hinzugefügt, getestet und dokumentiert werden.
**Wichtig für Phase 0c:** Nach dem Refactoring zu Multi-Layer Architecture nutzen alle Platzhalter das Data Layer. Dieser Guide beschreibt beide Architekturen.
---
## Phase 0b Architektur (Aktuell - bis Phase 0c)
### Anatomie eines Platzhalters
```python
# backend/placeholder_resolver.py
def resolve_weight_28d_trend_slope(profile_id: str) -> str:
"""
Returns kg/week slope for 28-day weight trend.
This function:
1. Retrieves data from database
2. Performs calculation
3. Formats result for KI consumption
Args:
profile_id: User profile ID
Returns:
Formatted string (e.g., "0.23 kg/Woche")
or "Nicht genug Daten" if insufficient data
"""
with get_db() as conn:
cur = get_cursor(conn)
# 1. DATA RETRIEVAL
cur.execute("""
SELECT date, weight
FROM weight_log
WHERE profile_id = %s
AND date >= NOW() - INTERVAL '28 days'
ORDER BY date
""", (profile_id,))
rows = cur.fetchall()
# 2. VALIDATION
if len(rows) < 18: # Confidence threshold
return "Nicht genug Daten"
# 3. CALCULATION
x = [(row[0] - rows[0][0]).days for row in rows]
y = [row[1] for row in rows]
# Linear regression
n = len(x)
sum_x = sum(x)
sum_y = sum(y)
sum_xy = sum(xi * yi for xi, yi in zip(x, y))
sum_x2 = sum(xi ** 2 for xi in x)
slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x ** 2)
slope_per_week = slope * 7
# 4. FORMATTING
return f"{slope_per_week:.2f} kg/Woche"
```
### Schritte zum Hinzufügen eines neuen Platzhalters (Phase 0b)
#### 1. Funktion implementieren
**Datei:** `backend/placeholder_resolver.py`
**Namenskonvention:**
- `resolve_<placeholder_name>(profile_id: str) -> str`
- Snake_case
- Immer `profile_id` als Parameter
- Immer `str` als Return-Type
**Template:**
```python
def resolve_my_new_metric(profile_id: str) -> str:
"""
[Beschreibung was der Platzhalter zurückgibt]
Args:
profile_id: User profile ID
Returns:
[Beschreibung des Return-Formats]
"""
with get_db() as conn:
cur = get_cursor(conn)
# 1. DATA RETRIEVAL
cur.execute("""
SELECT ...
FROM ...
WHERE profile_id = %s
""", (profile_id,))
# 2. VALIDATION
if <insufficient_data_condition>:
return "Nicht genug Daten"
# 3. CALCULATION
result = ...
# 4. FORMATTING
return f"{result}"
```
#### 2. In Mapping registrieren
**Datei:** `backend/placeholder_resolver.py`
**Finde `PLACEHOLDER_FUNCTIONS` Dictionary:**
```python
PLACEHOLDER_FUNCTIONS = {
# ... existing placeholders ...
# Add your new placeholder:
"my_new_metric": resolve_my_new_metric,
}
```
**Naming:**
- Key = Platzhalter-Name (snake_case)
- Value = Funktions-Referenz (ohne Klammern!)
#### 3. In Katalog dokumentieren
**Datei:** `backend/placeholder_resolver.py`
**Finde `get_placeholder_catalog()` Funktion:**
```python
def get_placeholder_catalog(profile_id: str) -> Dict[str, List[Dict[str, str]]]:
placeholders = {
'Körper': [
# ... existing ...
('my_new_metric', 'Beschreibung des Platzhalters'),
],
# ...
}
```
**Kategorien:**
- `Profil`
- `Körper`
- `Ernährung`
- `Training`
- `Schlaf & Erholung`
- `Vitalwerte`
- `Scores (Phase 0b)`
- `Focus Areas`
- `Zeitraum`
#### 4. Testen
**Manueller Test:**
```python
# In Python REPL oder test script:
from placeholder_resolver import resolve_my_new_metric
result = resolve_my_new_metric("test_profile_id")
print(result) # Should return formatted string
```
**Integration Test:**
```python
# Test in actual prompt
from placeholder_resolver import resolve_placeholders
template = "Dein {{my_new_metric}} ist ..."
result = resolve_placeholders(template, "test_profile_id")
print(result) # Should have placeholder replaced
```
---
## Phase 0c Architektur (Nach Refactoring)
### Anatomie eines Platzhalters (3-Layer)
```python
# Layer 1: DATA LAYER
# backend/data_layer/body_metrics.py
def get_weight_trend_data(profile_id: str, days: int = 90) -> dict:
"""
Returns weight trend data with slopes and projections.
This is pure data retrieval and calculation.
NO FORMATTING. NO STRINGS.
Args:
profile_id: User profile ID
days: Analysis window
Returns:
{
"raw_values": [(date, weight), ...],
"rolling_median_7d": [(date, value), ...],
"slope_7d": float,
"slope_28d": float,
"slope_90d": float,
"confidence": str,
...
}
"""
with get_db() as conn:
cur = get_cursor(conn)
# DATA RETRIEVAL
cur.execute("""...""", (profile_id, days))
rows = cur.fetchall()
# VALIDATION + CONFIDENCE
from data_layer.utils import calculate_confidence
confidence = calculate_confidence(len(rows), days, "trend")
if confidence == 'insufficient':
return {
"confidence": "insufficient",
"slope_28d": 0.0,
# ... minimal data
}
# CALCULATION
# ... (same logic as before)
# RETURN STRUCTURED DATA (not formatted!)
return {
"raw_values": rows,
"slope_7d": slope_7d,
"slope_28d": slope_28d,
"confidence": confidence,
# ... all data as dict/list/float
}
# Layer 2a: KI LAYER
# backend/placeholder_resolver.py
from data_layer.body_metrics import get_weight_trend_data
def resolve_weight_28d_trend_slope(profile_id: str) -> str:
"""
Formats weight trend slope for KI consumption.
This function is now THIN - just calls data layer and formats.
"""
data = get_weight_trend_data(profile_id, days=28)
if data['confidence'] == 'insufficient':
return "Nicht genug Daten"
return f"{data['slope_28d']:.2f} kg/Woche"
```
### Schritte zum Hinzufügen eines neuen Platzhalters (Phase 0c)
#### 1. Data Layer Funktion implementieren
**Datei:** Passendes Modul in `backend/data_layer/`
- Body metrics → `body_metrics.py`
- Nutrition → `nutrition_metrics.py`
- Activity → `activity_metrics.py`
- Recovery → `recovery_metrics.py`
- Health → `health_metrics.py`
- Goals → `goals.py`
- Correlations → `correlations.py`
**Template:**
```python
# backend/data_layer/<module>.py
def get_<metric>_data(
profile_id: str,
days: int = 28,
**kwargs
) -> dict:
"""
[Beschreibung der Daten]
Args:
profile_id: User profile ID
days: Analysis window
**kwargs: Additional parameters
Returns:
{
"<field>": <value>,
"confidence": str, # ALWAYS include!
"data_points": int, # ALWAYS include!
}
"""
with get_db() as conn:
cur = get_cursor(conn)
# 1. DATA RETRIEVAL
cur.execute("""...""", (profile_id,))
rows = cur.fetchall()
# 2. CONFIDENCE CALCULATION
from data_layer.utils import calculate_confidence
confidence = calculate_confidence(
len(rows),
days,
"general" # or "correlation" or "trend"
)
# 3. VALIDATION
if confidence == 'insufficient':
return {
"confidence": "insufficient",
"data_points": len(rows),
# Return minimal safe data
}
# 4. CALCULATION
# ... your logic here ...
# 5. RETURN STRUCTURED DATA
return {
# All data as primitives: dict, list, float, int, str, bool
# NO FORMATTING (no "0.23 kg/Woche" - just 0.23)
"result": result_value,
"confidence": confidence,
"data_points": len(rows),
}
```
**WICHTIG:**
- ❌ Keine Strings mit Einheiten: `"0.23 kg/Woche"`
- ✅ Nur Zahlen: `0.23`
- ❌ Keine Formatierung für Menschen
- ✅ Strukturierte Daten für Maschinen
#### 2. KI Layer Wrapper erstellen
**Datei:** `backend/placeholder_resolver.py`
```python
from data_layer.<module> import get_<metric>_data
def resolve_<placeholder_name>(profile_id: str) -> str:
"""
[Beschreibung was zurückgegeben wird]
Phase 0c: Uses data_layer.<module>.get_<metric>_data()
"""
data = get_<metric>_data(profile_id)
if data['confidence'] == 'insufficient':
return "Nicht genug Daten"
# FORMAT for KI consumption
return f"{data['<field>']:.2f} <unit>"
```
#### 3. In Mapping registrieren
**UNVERÄNDERT - gleich wie Phase 0b:**
```python
PLACEHOLDER_FUNCTIONS = {
"my_new_metric": resolve_my_new_metric,
}
```
#### 4. In Katalog dokumentieren
**UNVERÄNDERT - gleich wie Phase 0b:**
```python
def get_placeholder_catalog(profile_id: str):
placeholders = {
'Körper': [
('my_new_metric', 'Beschreibung'),
],
}
```
#### 5. Testen
**Unit Test für Data Layer:**
```python
# backend/tests/test_data_layer.py
def test_get_metric_data_sufficient():
data = get_<metric>_data("test_profile_1", days=28)
assert data['confidence'] in ['high', 'medium', 'low', 'insufficient']
assert 'data_points' in data
assert isinstance(data['<field>'], float)
def test_get_metric_data_insufficient():
data = get_<metric>_data("profile_no_data", days=28)
assert data['confidence'] == 'insufficient'
```
**Integration Test für KI Layer:**
```python
# backend/tests/test_placeholders.py
def test_resolve_placeholder():
result = resolve_<placeholder_name>("test_profile_1")
assert isinstance(result, str)
assert result != "Nicht genug Daten"
```
---
## Best Practices
### 1. Confidence Scoring
**IMMER `calculate_confidence()` verwenden:**
```python
from data_layer.utils import calculate_confidence
confidence = calculate_confidence(
data_points=len(rows),
days_requested=days,
metric_type="general" # or "correlation" or "trend"
)
```
**Confidence Thresholds:**
- General (28d): high >= 18, medium >= 12, low >= 8
- Correlation: high >= 28, medium >= 21, low >= 14
- Trend: high >= (days * 0.7), medium >= (days * 0.5)
### 2. Decimal → Float Conversion
**PostgreSQL gibt Decimal zurück - immer zu float konvertieren:**
```python
# ❌ WRONG:
value = row['column']
# ✅ CORRECT:
value = float(row['column']) if row['column'] else 0.0
```
### 3. Safe Dict Access
**Nie direkter Key-Zugriff ohne Fallback:**
```python
# ❌ WRONG:
value = data['key'] # KeyError if missing
# ✅ CORRECT:
value = data.get('key', default_value)
```
### 4. Date Serialization
**Python date objects sind nicht JSON-serializable:**
```python
from data_layer.utils import serialize_dates
data = {
"date": date(2026, 3, 28),
"values": [...]
}
# Serialize before returning from API
return serialize_dates(data)
```
### 5. SQL Parameter Binding
**IMMER Parameter-Binding, NIE String-Concatenation:**
```python
# ✅ CORRECT:
cur.execute("SELECT * FROM t WHERE id = %s", (id,))
# ❌ WRONG (SQL Injection Risk):
cur.execute(f"SELECT * FROM t WHERE id = {id}")
```
### 6. Column Name Consistency
**Prüfe Schema BEVOR du Column-Namen verwendest:**
```python
# ❌ WRONG (assumed name):
SELECT bf_jpl FROM caliper_log
# ✅ CORRECT (check schema first):
SELECT body_fat_pct FROM caliper_log
```
**Schema prüfen:**
```sql
\d caliper_log -- in psql
-- oder
SELECT column_name FROM information_schema.columns
WHERE table_name = 'caliper_log';
```
---
## Fehler-Handling
### 1. Insufficient Data
**Return-Value bei zu wenig Daten:**
```python
# Data Layer:
return {
"confidence": "insufficient",
"data_points": 0,
# Alle anderen Felder mit safe defaults (0.0, [], etc.)
}
# KI Layer:
if data['confidence'] == 'insufficient':
return "Nicht genug Daten"
```
### 2. Missing Optional Data
**Wenn optionale Daten fehlen (z.B. keine Vitals):**
```python
# Data Layer:
return {
"hrv": None, # or 0.0, depending on semantic
"confidence": "low", # downgrade confidence
}
# KI Layer:
if data['hrv'] is None:
return "Keine HRV-Daten verfügbar"
```
### 3. Calculation Errors
**Bei Math-Errors (Division by Zero, etc.):**
```python
try:
result = numerator / denominator
except ZeroDivisionError:
result = 0.0 # or None, depending on semantic
```
---
## Dokumentations-Pflicht
### 1. Docstring
**Jede Funktion braucht Docstring:**
```python
def get_metric_data(profile_id: str, days: int = 28) -> dict:
"""
[Eine Zeile Zusammenfassung]
[Ausführliche Beschreibung wenn nötig]
Args:
profile_id: User profile ID
days: Analysis window (default 28)
Returns:
{
"field": value,
"confidence": str,
"data_points": int
}
Confidence Rules:
- high: >= X points
- medium: >= Y points
- low: >= Z points
- insufficient: < Z points
"""
```
### 2. Inline Comments
**Nur bei nicht-offensichtlicher Logik:**
```python
# Calculate trimmed mean (remove top/bottom 10%)
sorted_values = sorted(values)
trim_count = len(values) // 10
trimmed = sorted_values[trim_count:-trim_count]
result = sum(trimmed) / len(trimmed)
```
### 3. Type Hints
**IMMER Type Hints verwenden:**
```python
from typing import Optional, List, Dict, Tuple
def get_data(
profile_id: str,
days: int = 28,
include_raw: bool = False
) -> Dict[str, any]:
...
```
---
## Testing-Strategie
### 1. Unit Tests (Data Layer)
**Teste jede Data Layer Funktion isoliert:**
```python
# backend/tests/test_data_layer.py
import pytest
from data_layer.body_metrics import get_weight_trend_data
@pytest.fixture
def test_profile():
# Setup test data in database
...
yield profile_id
# Teardown
...
def test_weight_trend_sufficient_data(test_profile):
data = get_weight_trend_data(test_profile, days=28)
assert data['confidence'] in ['high', 'medium']
assert data['slope_28d'] != 0.0
assert len(data['raw_values']) >= 18
def test_weight_trend_insufficient_data():
data = get_weight_trend_data("no_data_profile", days=28)
assert data['confidence'] == 'insufficient'
```
### 2. Integration Tests (KI Layer)
**Teste Placeholder-Resolution:**
```python
# backend/tests/test_placeholders.py
def test_placeholder_resolution(test_profile):
result = resolve_weight_28d_trend_slope(test_profile)
assert isinstance(result, str)
assert "kg/Woche" in result or "Nicht genug Daten" in result
def test_placeholder_in_template(test_profile):
template = "Trend: {{weight_28d_trend_slope}}"
result = resolve_placeholders(template, test_profile)
assert "{{" not in result # All placeholders resolved
assert result.startswith("Trend:")
```
### 3. Manual Testing Checklist
```
[ ] Funktion mit verschiedenen days-Parametern testen
[ ] Mit vollständigen Daten testen
[ ] Mit unvollständigen Daten testen
[ ] Mit NO DATA testen
[ ] Edge Cases: Extreme Werte, Outliers
[ ] Performance: < 500ms für typische Queries
[ ] Memory: Kein Leak bei großen Datasets
```
---
## Checkliste: Neuer Platzhalter
### Phase 0b (Aktuell):
```
[ ] Funktion in placeholder_resolver.py implementiert
[ ] resolve_<name>(profile_id: str) -> str Signatur
[ ] Docstring vollständig
[ ] Confidence-Check implementiert
[ ] In PLACEHOLDER_FUNCTIONS registriert
[ ] In get_placeholder_catalog() dokumentiert
[ ] Manuell getestet
[ ] In echtem Prompt getestet
```
### Phase 0c (Nach Refactoring):
```
[ ] Data Layer Funktion implementiert
[ ] Richtiges Modul gewählt
[ ] get_<metric>_data(profile_id, ...) -> dict Signatur
[ ] Returns structured data (dict/list/primitives)
[ ] NO formatting, NO strings with units
[ ] Confidence calculation included
[ ] Docstring vollständig
[ ] KI Layer Wrapper implementiert
[ ] resolve_<name>(profile_id: str) -> str Signatur
[ ] Calls data_layer function
[ ] Formats result for KI
[ ] In PLACEHOLDER_FUNCTIONS registriert
[ ] In get_placeholder_catalog() dokumentiert
[ ] Unit Test für Data Layer geschrieben
[ ] Integration Test für KI Layer geschrieben
[ ] Manual Testing durchgeführt
```
---
## Häufige Fehler (Learnings from Phase 0b)
### 1. Vergessen float() Conversion
```python
# SYMPTOM: "Object of type Decimal is not JSON serializable"
# FIX:
value = float(row['column']) if row['column'] else 0.0
```
### 2. Hardcoded Column Names
```python
# SYMPTOM: "column bf_jpl does not exist"
# FIX: Check schema first
SELECT column_name FROM information_schema.columns
WHERE table_name = 'caliper_log';
```
### 3. KeyError bei fehlenden Daten
```python
# SYMPTOM: "KeyError: 'hrv'"
# FIX: Use .get() with default
hrv = data.get('hrv', 0.0)
```
### 4. Confidence nicht berechnet
```python
# SYMPTOM: Platzhalter liefert Daten bei <3 Punkten
# FIX: calculate_confidence() verwenden
from data_layer.utils import calculate_confidence
confidence = calculate_confidence(len(rows), days, "general")
```
### 5. Date nicht serialized
```python
# SYMPTOM: "Object of type date is not JSON serializable"
# FIX:
from data_layer.utils import serialize_dates
return serialize_dates(data)
```
### 6. SQL Injection Risk
```python
# SYMPTOM: Security Scanner warnt
# FIX: ALWAYS use parameter binding
cur.execute("SELECT * FROM t WHERE id = %s", (id,))
```
---
## Nächste Schritte
### Nach Implementierung eines neuen Platzhalters:
1. **Commit Message:**
```
feat: add {{my_new_metric}} placeholder
- Implements resolve_my_new_metric() in placeholder_resolver.py
- Adds entry to PLACEHOLDER_FUNCTIONS
- Documents in get_placeholder_catalog()
- Tested with profile XYZ
Category: <Körper/Ernährung/Training/etc.>
Returns: <description>
```
2. **Dokumentation aktualisieren:**
- `CLAUDE.md` - Neue Platzhalter auflisten
- `docs/api/PLACEHOLDERS.md` - API-Dokumentation
3. **Testing:**
- Mindestens 1 manueller Test mit echtem Profil
- Optional: Unit Test hinzufügen
4. **Review:**
- Prüfe ob Platzhalter in Prompt-Bibliothek sinnvoll
- Teste mit verschiedenen Prompts
- Performance-Check (< 500ms)
---
**Autor:** Claude Sonnet 4.5
**Version:** 1.0
**Letzte Aktualisierung:** 28. März 2026
@@ -0,0 +1,504 @@
# Placeholder Registry Framework - Verbindliche Dokumentation
**Status:** VERBINDLICH (ab 2026-04-02)
**Version:** 1.0
**Geltungsbereich:** Alle Placeholder/Metrics im System
---
## 1. Zweck
Das **Placeholder Registry Framework** ist die zentrale, verbindliche Metadaten-Verwaltung für alle Placeholder und Metrics im System.
**Kernprinzip:** Single Source of Truth
**Ziele:**
1. Einheitliche Metadaten-Struktur für alle Placeholder
2. Vermeidung von Duplikation und Inkonsistenzen
3. Zentrale Verwaltung für alle Konsumenten
4. Evidence-basierte Transparenz
5. Erweiterbarkeit und Wartbarkeit
---
## 2. Verbindlichkeit
### 2.1 Pflicht zur Nutzung
**ALLE neuen Placeholder/Metrics MÜSSEN über das Registry Framework registriert werden.**
Keine Ausnahmen ohne explizite technische Begründung und Freigabe.
### 2.2 Betroffene Systeme
Folgende Systeme MÜSSEN die Registry als Single Source of Truth nutzen:
1. **Backend Prompt-Injektion** (Layer 2a)
- Placeholder-Resolver
- Prompt-Template-Engine
2. **GUI Auswahllisten**
- Placeholder-Picker
- Kategorie-Filter
- Metadata-Anzeige
3. **Extended Export**
- `/api/prompts/placeholders/export-values-extended`
- Catalog-Generierung
- ZIP-Export
4. **Validierung** (zukünftig)
- Metadata-Completeness-Checks
- Evidence-Quality-Assurance
- Compliance-Reports
5. **Diagramm-Zuordnung** (zukünftig)
- Chart-Metadata-Mapping
- Layer-2b-Integration
### 2.3 Verbotene Praktiken
**VERBOTEN:**
- Hardcoded Metadaten außerhalb der Registry
- Duplizierte Metadaten-Definitionen
- Placeholder ohne Registry-Registrierung
- Direkte Manipulation von Metadaten im Export-Code
- Inkonsistente Metadaten zwischen Systemen
---
## 3. Framework-Architektur
### 3.1 Kernkomponenten
**Modul:** `backend/placeholder_registry.py`
**Klassen:**
- `PlaceholderMetadata` - Metadata-Dataclass (22 Pflichtfelder)
- `MissingValuePolicy` - Strukturierte Missing-Value-Behandlung
- `PlaceholderRegistry` - Zentrale Registry (Singleton)
- `EvidenceType` - Enum für Evidenz-Tagging
- `OutputType` - Enum für Output-Typen
- `PlaceholderType` - Enum für Placeholder-Typen
**Singleton-Instanz:**
```python
from placeholder_registry import get_registry
registry = get_registry()
```
### 3.2 Registrierungs-Package
**Package:** `backend/placeholder_registrations/`
**Struktur:**
```
placeholder_registrations/
├── __init__.py # Auto-Import aller Registrations
├── nutrition_part_a.py # Nutrition Basis-Metriken (4 Placeholder)
├── nutrition_part_b.py # Protein-Ziele (5 Placeholder) - TODO
├── body_metrics.py # Körper-Metriken - TODO
├── activity_metrics.py # Aktivitäts-Metriken - TODO
└── ... # Weitere Cluster
```
**Auto-Registration:**
- Import des Package triggert automatische Registrierung aller Placeholder
- Keine manuelle Registrierung erforderlich
### 3.3 Export-Integration
**Modul:** `backend/placeholder_registry_export.py`
**Funktionen:**
- `get_registry_metadata_for_export()` - Metadata aus Registry
- `merge_registry_with_legacy_export()` - Backward-Compatibility
- `get_enhanced_export_with_registry()` - Vollständiger Export
**Endpoint-Integration:**
```python
# backend/routers/prompts.py
import placeholder_registrations # Auto-registers
from placeholder_registry_export import get_registry_metadata_for_export
registry_data = get_registry_metadata_for_export(profile_id)
export_data['registry_metadata'] = registry_data
```
---
## 4. Metadata-Schema
### 4.1 Pflichtfelder (22 Felder)
**Core Identification (3):**
- `key` - Placeholder-Schlüssel (z.B. "kcal_avg")
- `category` - Kategorie (z.B. "Ernährung")
- `description` - Kurzbeschreibung
**Technical (6):**
- `resolver_module` - Modul-Pfad des Resolvers
- `resolver_function` - Funktionsname des Resolvers
- `data_layer_module` - Data Layer Modul (optional)
- `data_layer_function` - Data Layer Funktion (optional)
- `source_tables` - Liste der Quelltabellen
- `_resolver_func` - Runtime-Resolver (nicht exportiert)
**Semantic (8):**
- `semantic_contract` - Semantische Definition
- `business_meaning` - Fachliche Bedeutung
- `unit` - Einheit (z.B. "kcal/day")
- `time_window` - Zeitfenster (z.B. "30d")
- `output_type` - Output-Typ (Enum)
- `placeholder_type` - Placeholder-Typ (Enum)
- `format_hint` - Format-Information
- `example_output` - Beispiel-Ausgabe
**Quality (5):**
- `minimum_data_requirements` - Mindestanforderungen (optional)
- `quality_filter_policy` - Qualitätsfilter (optional)
- `confidence_logic` - Confidence-Berechnung (optional)
- `missing_value_policy` - Missing-Value-Handling
- `known_limitations` - Bekannte Einschränkungen (optional)
**Architecture (5):**
- `layer_1_decision` - Layer-1-Zuordnung (optional)
- `layer_2a_decision` - Layer-2a-Zuordnung (optional)
- `layer_2b_reuse_possible` - Chart-Reuse möglich (optional)
- `architecture_alignment` - Architektur-Konformität (optional)
- `issue_53_alignment` - Issue #53 Konformität (optional)
**Evidence Tracking (1):**
- `evidence` - Dict mapping Feldname → EvidenceType
### 4.2 Evidence-Typen
**Enum:** `EvidenceType`
**Werte:**
- `CODE_DERIVED` - Aus Code belegt (z.B. aus Import-Statement, SQL-Query)
- `DRAFT_DERIVED` - Aus Canonical Requirements Draft übernommen
- `MIXED` - Teilweise Code, teilweise Draft/abgeleitet
- `UNRESOLVED` - Nicht explizit dokumentiert, offen
- `TO_VERIFY` - Behauptung, muss noch verifiziert werden
**Verwendung:**
```python
metadata.set_evidence("unit", EvidenceType.CODE_DERIVED)
metadata.set_evidence("semantic_contract", EvidenceType.DRAFT_DERIVED)
metadata.set_evidence("layer_2b_reuse_possible", EvidenceType.TO_VERIFY)
```
---
## 5. Registrierungs-Workflow
### 5.1 Neuen Placeholder registrieren
**Schritt 1: Metadata-Objekt erstellen**
```python
# backend/placeholder_registrations/my_cluster.py
from placeholder_registry import (
PlaceholderMetadata,
MissingValuePolicy,
EvidenceType,
OutputType,
PlaceholderType,
register_placeholder
)
metadata = PlaceholderMetadata(
key="my_placeholder",
category="Meine Kategorie",
description="Kurzbeschreibung",
# Technical (CODE_DERIVED)
resolver_module="backend/placeholder_resolver.py",
resolver_function="get_my_placeholder",
data_layer_module="backend/data_layer/my_metrics.py",
data_layer_function="get_my_data",
source_tables=["my_table"],
# Semantic
semantic_contract="Was liefert dieser Placeholder?",
business_meaning="Fachliche Bedeutung",
unit="einheit",
time_window="30d",
output_type=OutputType.NUMERIC,
placeholder_type=PlaceholderType.INTERPRETED,
format_hint="Ganzzahl",
example_output="42",
# Quality
confidence_logic="Wie wird Verlässlichkeit berechnet?",
missing_value_policy=MissingValuePolicy(
available=False,
value_raw=None,
missing_reason="insufficient_data",
legacy_display="nicht genug Daten"
),
known_limitations="Einschränkungen dokumentieren",
# Architecture
layer_1_decision="Data Layer (my_metrics.get_my_data)",
layer_2a_decision="Placeholder Resolver (formatting only)",
architecture_alignment="Phase 0c conform"
)
```
**Schritt 2: Evidence setzen**
```python
# Code-derived Felder
metadata.set_evidence("resolver_module", EvidenceType.CODE_DERIVED)
metadata.set_evidence("resolver_function", EvidenceType.CODE_DERIVED)
metadata.set_evidence("data_layer_module", EvidenceType.CODE_DERIVED)
metadata.set_evidence("source_tables", EvidenceType.CODE_DERIVED)
metadata.set_evidence("unit", EvidenceType.CODE_DERIVED)
metadata.set_evidence("time_window", EvidenceType.CODE_DERIVED)
# Draft-derived Felder
metadata.set_evidence("semantic_contract", EvidenceType.DRAFT_DERIVED)
metadata.set_evidence("business_meaning", EvidenceType.DRAFT_DERIVED)
metadata.set_evidence("known_limitations", EvidenceType.DRAFT_DERIVED)
# Unresolved Felder
metadata.set_evidence("minimum_data_requirements", EvidenceType.UNRESOLVED)
```
**Schritt 3: Registrieren**
```python
register_placeholder(metadata)
```
**Schritt 4: Auto-Import sicherstellen**
```python
# backend/placeholder_registrations/__init__.py
from . import my_cluster
__all__ = ['nutrition_part_a', 'my_cluster']
```
### 5.2 Resolver-Funktion bereitstellen (optional)
Wenn der Placeholder runtime-resolved werden soll:
```python
from placeholder_resolver import get_my_placeholder
register_placeholder(
metadata,
resolver_func=lambda pid: get_my_placeholder(pid)
)
```
---
## 6. API-Nutzung
### 6.1 Metadata abrufen
```python
from placeholder_registry import get_registry
registry = get_registry()
# Einzelner Placeholder
meta = registry.get("kcal_avg")
print(meta.unit) # "kcal/day"
print(meta.time_window) # "30d"
# Alle Placeholder
all_metadata = registry.get_all() # Dict[str, PlaceholderMetadata]
# Nach Kategorie
ernaehrung = registry.get_by_category("Ernährung") # List[PlaceholderMetadata]
```
### 6.2 Export
```python
# Für Extended Export
export_data = registry.get_all_for_export() # List[Dict]
# Mit Runtime-Werten
from placeholder_registry_export import get_registry_metadata_for_export
registry_data = get_registry_metadata_for_export(profile_id)
# Returns: {flat, by_category, evidence_report, validation_report}
```
### 6.3 Validierung
```python
# Alle Placeholder validieren
issues = registry.validate_all() # Dict[str, List[str]]
if issues:
for key, problems in issues.items():
print(f"{key}: {problems}")
```
### 6.4 QA / Evidence-Tracking
```python
# Placeholder mit unresolved Fields finden
unresolved = registry.get_by_evidence_type(EvidenceType.UNRESOLVED)
# Returns: Dict[placeholder_key, List[field_names]]
# Placeholder die verifiziert werden müssen
to_verify = registry.get_by_evidence_type(EvidenceType.TO_VERIFY)
```
---
## 7. Best Practices
### 7.1 Evidence-Tagging
**DO:**
- Jedes Feld mit Evidence-Tag versehen
- `CODE_DERIVED` nur wenn direkt aus Code ableitbar
- `TO_VERIFY` für Behauptungen, die noch geprüft werden müssen
- `UNRESOLVED` für fehlende/unklare Informationen
**DON'T:**
- Felder ohne Evidence lassen
- Evidence halluzinieren (wenn nicht belegt, `UNRESOLVED` nutzen)
- `CODE_DERIVED` für Draft-Informationen nutzen
### 7.2 Metadata-Vollständigkeit
**Minimum Required:**
- `key`, `category`, `description`
- `resolver_module`, `resolver_function`
- `semantic_contract`
- `unit`, `time_window`
- `output_type`, `placeholder_type`
**Optional but Recommended:**
- `data_layer_module`, `data_layer_function`
- `source_tables`
- `confidence_logic`, `missing_value_policy`
- `layer_1_decision`, `layer_2a_decision`
### 7.3 Modularisierung
**Registrations nach Cluster gruppieren:**
- `nutrition_part_a.py` - Nutrition Basis (4 Placeholder)
- `nutrition_part_b.py` - Nutrition Protein (5 Placeholder)
- `body_metrics.py` - Körper-Metriken (N Placeholder)
**Nicht:**
- Alle Placeholder in eine riesige Datei
- Placeholder ohne thematische Gruppierung
### 7.4 Backward-Compatibility
**Export-Endpoint MUSS:**
- Legacy-Export beibehalten (`export_data['legacy']`)
- Graceful degradation bei Registry-Fehler
- Registry-Metadata als separate Sektion (`export_data['registry_metadata']`)
---
## 8. Migration bestehender Placeholder
### 8.1 Priorität
**Part A (erledigt):** Nutrition Basis (kcal_avg, protein_avg, carb_avg, fat_avg)
**Nächste Priorität:**
1. Part B - Nutrition Protein (5 Placeholder)
2. Part C - Nutrition Balance (4 Placeholder)
3. Part D - Nutrition Meta (1 Placeholder)
4. Body Metrics (ca. 15 Placeholder)
5. Activity Metrics (ca. 20 Placeholder)
### 8.2 Migration-Workflow
**Für jeden Placeholder:**
1. Code inspizieren (Resolver, Data Layer, SQL)
2. Evidence ableiten (was ist code-derived, was draft-derived?)
3. Metadata-Objekt erstellen
4. Registrieren
5. Export testen
6. Werte-Identität bestätigen
**Keine Logikänderung während Migration!**
---
## 9. Compliance & Enforcement
### 9.1 Code-Review-Checkliste
**Für neue Placeholder:**
- [ ] Registry-Registrierung vorhanden?
- [ ] Evidence-Tags gesetzt?
- [ ] Metadata-Vollständigkeit (minimum required)?
- [ ] Auto-Import in `__init__.py`?
- [ ] Export getestet?
### 9.2 CI/CD-Integration (zukünftig)
**Geplante Checks:**
- Alle Placeholder in PLACEHOLDER_MAP sind in Registry registriert
- Keine Placeholder ohne Evidence-Tags
- Keine doppelten Registrierungen
- Metadata-Vollständigkeit für production-ready Placeholder
---
## 10. Support & Weiterentwicklung
### 10.1 Fragen & Issues
**Bei Unklarheiten:**
1. Diese Dokumentation prüfen
2. Bestehende Registrations als Vorlage nutzen (`nutrition_part_a.py`)
3. Code-Review anfragen
### 10.2 Framework-Erweiterungen
**Geplante Features:**
- GUI-Integration (Placeholder-Picker mit Registry-Metadata)
- Validation-Dashboard (QA-Monitoring)
- Evidence-Report-Endpoint (Metadata-Qualität)
- Resolver-Test-Framework (Automatisierte Werteänderungs-Detektion)
- Chart-Metadata-Mapping (Layer-2b-Integration)
### 10.3 Versions-History
**v1.0 (2026-04-02):**
- Initial Release
- Part A Implementation (4 Nutrition Placeholders)
- Core Framework + Export-Integration
---
## 11. Referenzen
**Code:**
- `backend/placeholder_registry.py` - Core Framework
- `backend/placeholder_registrations/nutrition_part_a.py` - Part A Implementation
- `backend/placeholder_registry_export.py` - Export-Integration
- `backend/routers/prompts.py` - Export-Endpoint
**Dokumentation:**
- `.claude/task/rework_0b_placeholder/NUTRITION_PART_A_CHANGE_PLAN.md`
- `.claude/task/rework_0b_placeholder/NUTRITION_PART_A_IMPLEMENTATION_REPORT.md`
**Beispiel-Export:**
```bash
curl "https://dev.mitai.jinkendo.de/api/prompts/placeholders/export-values-extended?token=XXX"
```
---
**Ende Verbindliche Dokumentation**
@@ -0,0 +1,53 @@
# Persönliche Referenzwerte (Profil)
## Überblick
Nutzer-spezifische, **historische** Kennwerte (z. B. HF-Schwellen, Trainingshäufigkeit), die **nicht** zur Admin-/Focus-Area-Konfiguration gehören, sondern zum **aktiven Profil** wie Größe oder Ziele.
## Tabellen
| Tabelle | Zweck |
|--------|--------|
| `reference_value_types` | System-seedete Typdefinitionen: stabiler `key`, Anzeige-`label`, optional `default_unit`, `sort_order`, `active`, `metadata` (JSONB). |
| `profile_reference_values` | Historische Einträge: `profile_id`, `reference_value_type_id`, `effective_date`, `value_numeric` und/oder `value_text`, `unit`, optionale Felder `source`, `confidence`, `method`, `notes`, `extra` (JSONB). |
**Kein** Überschreiben eines einzelnen „aktuellen“ Werts: jede Messung ist eine eigene Zeile.
## Seed-Typen (Migration 037)
- `max_heart_rate` (bpm)
- `resting_heart_rate` (bpm)
- `anaerobic_threshold_hr` (bpm)
- `aerobic_threshold_hr` (bpm)
- `training_frequency_weekly` (Sessions/Woche)
- `fitness_level` (Stufe)
Es werden **keine** Benutzerwerte automatisch angelegt.
## Admin (nur Rolle `admin`)
- `GET/POST/PUT/DELETE /api/admin/reference-value-types` — vollständiger CRUD auf `reference_value_types` (inkl. inaktiver Typen).
- Löschen nur, wenn keine Zeilen in `profile_reference_values` zu diesem Typ existieren (sonst HTTP 409).
- UI: **Admin → Ziele & Fokus → Referenz-Kennwerte** (`/admin/reference-value-types`).
## API (Prefix `/api`)
- `GET /reference-value-types` — aktive Typen (dynamische UI)
- `GET /profile-reference-values?type_key=…` — Liste pro Typ, neueste zuerst
- `POST /profile-reference-values` — neuer Eintrag
- `PUT /profile-reference-values/{id}` — Aktualisierung
- `DELETE /profile-reference-values/{id}` — Löschen
Authentifizierung wie üblich; Profil über `X-Profile-Id` / `get_pid` wie andere Module.
## UI
**Einstellungen → Karte „Referenzwerte“ → „Referenzwerte verwalten“** (`/settings/reference-values`).
Typauswahl per Dropdown (aus API); Verlauf als Tabelle mit Bearbeiten/Löschen; Formular für neue Einträge bzw. Bearbeitung.
## Erweiterbarkeit
- Neue Messgrößen: nur **INSERT** in `reference_value_types` (Migration oder Admin-Skript), kein Schema-Wechsel für Nutzerdaten.
- Zusatzmetadaten: Spalten `source`, `confidence`, `method`, `notes`, `extra` bereits vorhanden; UI kann später erweitert werden.
- Platzierung **profilorientiert**, damit klar ist: Nutzerdaten, keine systemweite Semantik wie Focus Areas.
@@ -0,0 +1,148 @@
# Training Profile Resolver (Layer 1) — technisches Scaffold
**Stand:** 2026-04-06
**Zweck:** Erweiterbare technische Basis für spätere trainingsprofil-basierte Auswertungen, ohne freie Formel-/Skript-Engine und ohne Kopplung an KI oder Charts.
---
## 1. Einordnung in Layer 1
| Aspekt | Beschreibung |
|--------|----------------|
| Ort | `backend/data_layer/training_profile/` |
| Rolle | Reine Orchestrierung: Templates → registrierte Built-in-Algorithmen → strukturiertes Ergebnis inkl. Focus-Area-Beiträge |
| Single Source of Truth | Berechnungslogik der Algorithmen lebt in Python-Modulen; Templates wählen nur **Algorithmus-ID + Parameter + Dimensionen + FA-Mapping** |
| Rückwärtskompatibel | Keine Änderungen an bestehenden Data-Layer-Metriken, Placeholdern oder Chart-Routern |
---
## 2. Modulübersicht
| Pfad | Inhalt |
|------|--------|
| `models.py` | `CalculationTemplate`, `DimensionSpec`, `FocusAreaMapping`, `TrainingBaseProfile`, `TrainingEvaluationResult`, `AlgorithmRunResult` |
| `resolver.py` | `resolve_training_evaluation()`, `resolve_for_base_profile()` |
| `algorithms/registry.py` | `register_algorithm`, `get_algorithm`, `list_algorithm_ids` |
| `algorithms/builtin/threshold_band.py` | Beispiel: Schwellen-Bänder → Score 0–1 |
| `algorithms/builtin/linear_range.py` | Beispiel: lineare Abbildung [min,max] → [0,1] |
| `templates/registry.py` | Beispiel-Templates (deklarativ, in-code) |
| `profiles/registry.py` | Beispiel-Trainings-Basisprofile (Default-Template, optionale Dimensions-Whitelist) |
---
## 3. Built-in-Algorithmen
- Algorithmen sind **fest im Code** implementiert und über eine **ID** referenzierbar.
- Neue Algorithmen: Funktion mit Signatur `(*, inputs, params) -> AlgorithmRunResult` und `register_algorithm(id, fn)` (Start-up-Registrierung in `registry.py` oder Import eines Moduls, das registriert).
- **Nicht** vorgesehen: Nutzerdefinierte Ausdrücke, DSL, `eval`, externe Skripte.
Implementiert (Beispiele):
- `threshold_band` — `params.value_key`, `params.bands` (Liste mit `max` / `score`)
- `linear_range` — `params.value_key`, `min_value`, `max_value`, optional `invert`
---
## 4. Templates (deklarativ)
Ein `CalculationTemplate` besteht aus:
- `id`, `version`, `label`
- `dimensions`: Liste von `DimensionSpec` mit:
- `key` — Dimensionsname
- `algorithm_id` — referenziert registrierten Algorithmus
- `inputs` — erwartete Schlüssel im flachen `activity_inputs`-Dict des Aufrufers
- `params` — JSON-serialisierbare Parameter für den Algorithmus
- `maps_to` — Tupel `(focus_area_key, weight)` — gewichteter Anteil der **normalisierten** Dimension am jeweiligen Focus Area
Aggregation: Pro Dimension wird `normalized_score * weight` pro Focus Area addiert (`focus_area_contributions`).
---
## 5. Trainings-Basisprofile (Scaffold)
`TrainingBaseProfile`:
- `key`, `label`
- `default_template_id` — verweist auf ein `CalculationTemplate`
- optional `allowed_dimension_keys` — nur diese Dimensionen aus dem Template werden ausgeführt (Filter)
Aktuell **nur In-Code-Registry**; später denkbar: DB-Verknüpfung Trainingstyp → Profil-Key.
---
## 6. Ergebnisstruktur (`TrainingEvaluationResult`)
- `template_id`, `template_version`, `base_profile_key`
- `dimension_results[]` — pro Dimension: Scores, fehlende Inputs, Evidence
- `focus_area_contributions` — `dict[str, float]` (Focus-Area-Key → aggregierter Beitrag)
- `confidence` — `high` | `medium` | `low` | `insufficient` (heuristisch aus fehlenden Pflicht-Inputs)
- `evidence` — Metadaten (z. B. Anzahl Dimensionen, Input-Keys)
- optional `trace` — bei `include_trace=True` für Debugging
`to_serializable()` liefert ein JSON-taugliches Dict für APIs/Persistenz.
---
## 7. Öffentliche API (Import)
```python
from data_layer.training_profile import (
resolve_training_evaluation,
resolve_for_base_profile,
TrainingEvaluationResult,
CalculationTemplate,
)
```
Registries:
```python
from data_layer.training_profile.templates.registry import get_calculation_template
from data_layer.training_profile.profiles.registry import get_training_base_profile
from data_layer.training_profile.algorithms.registry import get_algorithm, list_algorithm_ids
```
---
## 8. Erweiterungspunkte (für spätere Produktlogik)
1. **Neue Algorithmen** — neue Datei unter `algorithms/builtin/`, in `registry.py` registrieren.
2. **Templates** — weitere `CalculationTemplate`-Instanzen in `templates/registry.py` oder später aus DB laden (Loader baut dieselben Dataclasses).
3. **Profile** — weitere `TrainingBaseProfile`-Einträge; Anbindung an `training_types` / Aktivität.
4. **Confidence/Evidence** — feinere Regeln (Datenqualität, Mindestkriterien) im Resolver oder in den Algorithmen.
5. **Normalisierung der FA-Beiträge** — optional globale Skalierung/Cap (aktuell rein additive Gewichtung).
---
## 9. Was absichtlich offen ist
- Finale Domänenregeln (welche Dimensionen für welchen Sport)
- Vollständige Liste Basisprofile und Templates
- Persistenz von Evaluationsergebnissen
- Integration in Placeholder-Resolver, Charts, Admin-UI
- Validierung gegen `focus_area_definitions` (DB-Keys)
---
## 10. Kritische Einschätzung
| Bereich | Bewertung |
|---------|-----------|
| Registry + Algorithmus-Schnittstelle | Robust, testbar, erweiterbar |
| Template-Modelle (frozen dataclasses) | Stabil, typsicher, serialisierbar |
| Beispiel-Algorithmen | Minimal, nur zur Demonstration der Pipeline |
| Confidence | Heuristik — für Produktion noch abzustimmen |
| Focus-Area-Gewichte | Additiv, nicht normiert — Domänenentscheidung für später |
---
## 11. Tests
`backend/tests/test_training_profile_resolver.py` — Registry, Resolver, Profil-Filter, Serialisierung, unbekannter Algorithmus.
Ausführen (aus `backend/`):
```bash
python -m pytest tests/test_training_profile_resolver.py -v
```
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff