Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
272c123952 | ||
|
|
91c8a5332f | ||
|
|
a849d5db9e | ||
|
|
ae9743d6ed | ||
|
|
ae47652d0c | ||
|
|
c002cb1e54 | ||
|
|
9387670a7b | ||
|
|
a8df7f8359 | ||
|
|
2f302b26af | ||
|
|
26f8bcf86d | ||
|
|
95c57de8d0 | ||
|
|
d4a8401a6a | ||
|
|
b4a1856f79 | ||
|
|
9e6a542289 | ||
|
|
aaf88a6f12 | ||
|
|
b789c1bd44 | ||
|
|
5062aa8068 | ||
|
|
8a042589e7 | ||
|
|
3898b5ad45 | ||
|
|
9d15336144 |
No files matched your search
+2
-1
@@ -60,4 +60,5 @@ tmp/
|
|||||||
*.tmp
|
*.tmp
|
||||||
|
|
||||||
#.claude Konfiguration
|
#.claude Konfiguration
|
||||||
.claude/
|
.claude/
|
||||||
|
.claude/settings.local.json
|
||||||
@@ -26,7 +26,25 @@
|
|||||||
```
|
```
|
||||||
mitai-jinkendo/
|
mitai-jinkendo/
|
||||||
├── backend/
|
├── backend/
|
||||||
│ ├── main.py # FastAPI App, alle Endpoints (~2000 Zeilen)
|
│ ├── main.py # FastAPI App Setup + Router Registration (~75 Zeilen)
|
||||||
|
│ ├── db.py # PostgreSQL Connection Pool + Helpers
|
||||||
|
│ ├── auth.py # Auth Functions (hash, verify, sessions)
|
||||||
|
│ ├── models.py # Pydantic Models (11 Models)
|
||||||
|
│ ├── routers/ # Modular Endpoint Structure (14 Router)
|
||||||
|
│ │ ├── auth.py # Login, Logout, Password Reset (7 Endpoints)
|
||||||
|
│ │ ├── profiles.py # Profile CRUD + Current User (7 Endpoints)
|
||||||
|
│ │ ├── weight.py # Weight Tracking (5 Endpoints)
|
||||||
|
│ │ ├── circumference.py # Body Measurements (4 Endpoints)
|
||||||
|
│ │ ├── caliper.py # Skinfold Tracking (4 Endpoints)
|
||||||
|
│ │ ├── activity.py # Workout Logging + CSV Import (6 Endpoints)
|
||||||
|
│ │ ├── nutrition.py # Nutrition + FDDB Import (4 Endpoints)
|
||||||
|
│ │ ├── photos.py # Progress Photos (3 Endpoints)
|
||||||
|
│ │ ├── insights.py # AI Analysis + Pipeline (8 Endpoints)
|
||||||
|
│ │ ├── prompts.py # AI Prompt Management (2 Endpoints)
|
||||||
|
│ │ ├── admin.py # User Management (7 Endpoints)
|
||||||
|
│ │ ├── stats.py # Dashboard Stats (1 Endpoint)
|
||||||
|
│ │ ├── exportdata.py # CSV/JSON/ZIP Export (3 Endpoints)
|
||||||
|
│ │ └── importdata.py # ZIP Import (1 Endpoint)
|
||||||
│ ├── requirements.txt
|
│ ├── requirements.txt
|
||||||
│ └── Dockerfile
|
│ └── Dockerfile
|
||||||
├── frontend/
|
├── frontend/
|
||||||
@@ -76,20 +94,481 @@ mitai-jinkendo/
|
|||||||
- ✅ PostgreSQL 16 Migration (vollständig von SQLite migriert)
|
- ✅ PostgreSQL 16 Migration (vollständig von SQLite migriert)
|
||||||
- ✅ Export: CSV, JSON, ZIP (mit Fotos)
|
- ✅ Export: CSV, JSON, ZIP (mit Fotos)
|
||||||
- ✅ Automatische SQLite→PostgreSQL Migration bei Container-Start
|
- ✅ Automatische SQLite→PostgreSQL Migration bei Container-Start
|
||||||
|
- ✅ **Modulare Backend-Architektur**: 14 Router-Module, main.py von 1878→75 Zeilen (-96%)
|
||||||
|
|
||||||
### Was in v9c kommt:
|
### Was in v9c kommt: Subscription & Coupon Management System
|
||||||
- 🔲 Selbst-Registrierung mit E-Mail-Bestätigung
|
**Phase 1 (DB-Schema): ✅ DONE**
|
||||||
- 🔲 Freemium Tier-System (free/basic/premium/selfhosted)
|
**Phase 2 (Backend API): ✅ DONE**
|
||||||
- 🔲 14-Tage Trial automatisch
|
**Phase 3 (Frontend UI): 🔲 TODO**
|
||||||
- 🔲 Einladungslinks für Beta-Nutzer
|
|
||||||
- 🔲 Admin kann Tiers manuell setzen
|
**Core Features (Backend):**
|
||||||
|
- ✅ DB-Schema (11 neue Tabellen, Feature-Registry Pattern)
|
||||||
|
- ✅ Feature-Access Middleware (check_feature_access, increment_feature_usage)
|
||||||
|
- ✅ Flexibles Tier-System (free/basic/premium/selfhosted) - Admin-editierbar via API
|
||||||
|
- ✅ **Coupon-System** (3 Typen: single_use, period, wellpass)
|
||||||
|
- ✅ Coupon-Stacking-Logik (Pause + Resume bei Wellpass-Override)
|
||||||
|
- ✅ Access-Grant-System (zeitlich begrenzte Zugriffe mit Quelle-Tracking)
|
||||||
|
- ✅ User-Activity-Log (JSONB details)
|
||||||
|
- ✅ User-Stats (Aggregierte Statistiken)
|
||||||
|
- ✅ Individuelle User-Restrictions (Admin kann Limits pro User setzen)
|
||||||
|
- ✅ 7 neue Router, 30+ neue Endpoints (subscription, coupons, features, tiers, tier-limits, user-restrictions, access-grants)
|
||||||
|
|
||||||
|
**Frontend TODO (Phase 3):**
|
||||||
|
- 🔲 Selbst-Registrierung mit E-Mail-Verifizierung (Pflicht)
|
||||||
|
- 🔲 Trial-System UI (Dauer konfigurierbar, auto-start nach E-Mail-Verifikation)
|
||||||
|
- 🔲 Admin Matrix-Editor (Tier x Feature Limits)
|
||||||
|
- 🔲 Admin Coupon-Manager (CRUD, Redemption-Historie)
|
||||||
|
- 🔲 Admin User-Restrictions UI
|
||||||
|
- 🔲 User Subscription-Info Page
|
||||||
|
- 🔲 User Coupon-Einlösung UI
|
||||||
|
- 🔲 App-Settings Admin-Panel (globale Konfiguration)
|
||||||
|
|
||||||
|
**E-Mail Templates (v9c):**
|
||||||
|
- 🔲 Registrierung + E-Mail-Verifizierung
|
||||||
|
- 🔲 Einladungslink
|
||||||
|
- 🔲 Passwort-Reset (bereits vorhanden)
|
||||||
|
|
||||||
|
**Spätere Features (v9d/v9e):**
|
||||||
|
- 🔲 Bonus-System (Login-Streaks → Punkte → Geschenk-Coupons)
|
||||||
|
- 🔲 Trial-Reminder-E-Mails (3 Tage vor Ablauf)
|
||||||
|
- 🔲 Monatliches Nutzungs-Summary per E-Mail
|
||||||
|
- 🔲 Self-Service Upgrade (Stripe-Integration)
|
||||||
|
- 🔲 Partner-Verwaltung (Wellpass, Hansefit, etc.)
|
||||||
|
- 🔲 Admin-Benachrichtigungen (neue Registrierungen, etc.)
|
||||||
|
|
||||||
### Was in v9d kommt:
|
### Was in v9d kommt:
|
||||||
|
- 🔲 Bonus-System & Gamification (Streaks, Achievements)
|
||||||
|
- 🔲 Stripe-Integration (Self-Service Upgrade, Subscriptions)
|
||||||
- 🔲 OAuth2-Grundgerüst für Fitness-Connectoren
|
- 🔲 OAuth2-Grundgerüst für Fitness-Connectoren
|
||||||
- 🔲 Strava Connector
|
- 🔲 Strava Connector
|
||||||
- 🔲 Withings Connector (Waage)
|
- 🔲 Withings Connector (Waage)
|
||||||
- 🔲 Garmin Connector
|
- 🔲 Garmin Connector
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## v9c Architektur-Details: Subscription & Coupon System
|
||||||
|
|
||||||
|
### Datenbank-Schema (Neue Tabellen)
|
||||||
|
|
||||||
|
#### **app_settings** - Globale Konfiguration
|
||||||
|
```sql
|
||||||
|
key, value, value_type, description, updated_at, updated_by
|
||||||
|
|
||||||
|
Beispiele:
|
||||||
|
- trial_days: 14
|
||||||
|
- trial_behavior: 'downgrade' | 'lock'
|
||||||
|
- allow_registration: true/false
|
||||||
|
- default_tier_trial: 'premium'
|
||||||
|
- gift_coupons_per_month: 3
|
||||||
|
```
|
||||||
|
|
||||||
|
#### **tiers** - Tier-Konfiguration (vereinfacht)
|
||||||
|
```sql
|
||||||
|
id, slug, name, description, sort_order, active
|
||||||
|
|
||||||
|
Initial Tiers:
|
||||||
|
- free, basic, premium, selfhosted
|
||||||
|
|
||||||
|
Limits sind jetzt in tier_limits Tabelle (siehe unten)!
|
||||||
|
```
|
||||||
|
|
||||||
|
#### **features** - Feature-Registry (alle limitierbaren Features)
|
||||||
|
```sql
|
||||||
|
id, slug, name, category, description, unit
|
||||||
|
default_limit (NULL = unbegrenzt)
|
||||||
|
reset_period ('monthly' | 'daily' | 'never')
|
||||||
|
visible_in_admin, sort_order, active
|
||||||
|
|
||||||
|
Initial Features:
|
||||||
|
- weight_entries: Gewichtseinträge, default: 30, never
|
||||||
|
- circumference_entries: Umfangsmessungen, default: 30, never
|
||||||
|
- caliper_entries: Caliper-Messungen, default: 30, never
|
||||||
|
- nutrition_entries: Ernährungseinträge, default: 30, never
|
||||||
|
- activity_entries: Aktivitäten, default: 30, never
|
||||||
|
- photos: Progress-Fotos, default: 5, never
|
||||||
|
- ai_calls: KI-Analysen, default: 0, monthly
|
||||||
|
- ai_pipeline: KI-Pipeline, default: 0, monthly
|
||||||
|
- csv_import: CSV-Importe, default: 0, monthly
|
||||||
|
- data_export: Daten-Exporte, default: 0, monthly
|
||||||
|
- fitness_connectors: Fitness-Connectoren, default: 0, never
|
||||||
|
|
||||||
|
Neue Features einfach per INSERT hinzufügen - kein Schema-Change!
|
||||||
|
```
|
||||||
|
|
||||||
|
#### **tier_limits** - Limits pro Tier + Feature
|
||||||
|
```sql
|
||||||
|
id, tier_slug, feature_slug, limit_value, enabled
|
||||||
|
|
||||||
|
Beispiel Free Tier:
|
||||||
|
- ('free', 'weight_entries', 30, true)
|
||||||
|
- ('free', 'ai_calls', 0, false) -- KI deaktiviert
|
||||||
|
- ('free', 'data_export', 0, false)
|
||||||
|
|
||||||
|
Beispiel Premium:
|
||||||
|
- ('premium', 'weight_entries', NULL, true) -- unbegrenzt
|
||||||
|
- ('premium', 'ai_calls', NULL, true) -- unbegrenzt
|
||||||
|
|
||||||
|
Admin kann in UI Matrix bearbeiten: Tier x Feature
|
||||||
|
```
|
||||||
|
|
||||||
|
#### **user_feature_restrictions** - Individuelle User-Limits
|
||||||
|
```sql
|
||||||
|
id, profile_id, feature_slug, limit_value, enabled
|
||||||
|
reason, set_by (admin_id)
|
||||||
|
|
||||||
|
Überschreibt Tier-Limits für spezifische User.
|
||||||
|
Admin kann jeden User individuell einschränken oder erweitern.
|
||||||
|
```
|
||||||
|
|
||||||
|
#### **user_feature_usage** - Nutzungs-Tracking
|
||||||
|
```sql
|
||||||
|
id, profile_id, feature_slug, period_start, usage_count, last_used
|
||||||
|
|
||||||
|
Für Features mit reset_period (z.B. ai_calls monthly).
|
||||||
|
Wird automatisch zurückgesetzt am Monatsanfang.
|
||||||
|
```
|
||||||
|
|
||||||
|
#### **coupons** - Coupon-Verwaltung
|
||||||
|
```sql
|
||||||
|
code, type ('single_use' | 'multi_use_period' | 'gift')
|
||||||
|
valid_from, valid_until, grants_tier, duration_days
|
||||||
|
max_redemptions, current_redemptions
|
||||||
|
created_by, created_for, notes, active
|
||||||
|
|
||||||
|
Beispiel Single-Use:
|
||||||
|
Code: FRIEND-GIFT-XYZ, 30 Tage Premium, max 1x
|
||||||
|
|
||||||
|
Beispiel Multi-Use Period:
|
||||||
|
Code: WELLPASS-2026-03, gültig 01.03-31.03, unbegrenzte Einlösungen
|
||||||
|
```
|
||||||
|
|
||||||
|
#### **coupon_redemptions** - Einlösungs-Historie
|
||||||
|
```sql
|
||||||
|
coupon_id, profile_id, redeemed_at, access_grant_id
|
||||||
|
UNIQUE(coupon_id, profile_id) - User kann denselben Coupon nur 1x einlösen
|
||||||
|
```
|
||||||
|
|
||||||
|
#### **access_grants** - Zeitlich begrenzte Zugriffe
|
||||||
|
```sql
|
||||||
|
profile_id, granted_tier, valid_from, valid_until
|
||||||
|
source ('coupon' | 'admin_grant' | 'trial')
|
||||||
|
active (false wenn pausiert durch Wellpass-Override)
|
||||||
|
paused_at, paused_by (access_grant_id das pausiert hat)
|
||||||
|
|
||||||
|
Stacking-Logik:
|
||||||
|
- Multi-Use Period Coupon (Wellpass): pausiert andere grants
|
||||||
|
- Single-Use Coupon: stackt zeitlich (Resume nach Ablauf)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### **user_activity_log** - Aktivitäts-Tracking
|
||||||
|
```sql
|
||||||
|
profile_id, activity_type, details (JSONB), ip_address, user_agent, created
|
||||||
|
|
||||||
|
Activity Types:
|
||||||
|
- login, password_change, email_change, coupon_redeemed
|
||||||
|
- tier_change, export, ai_analysis, registration
|
||||||
|
```
|
||||||
|
|
||||||
|
#### **user_stats** - Aggregierte Statistiken
|
||||||
|
```sql
|
||||||
|
profile_id, first_login, last_login, total_logins
|
||||||
|
current_streak_days, longest_streak_days, last_streak_date
|
||||||
|
total_weight_entries, total_ai_analyses, total_exports
|
||||||
|
bonus_points (später), gift_coupons_available (später)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### **profiles** - Erweiterte Spalten
|
||||||
|
```sql
|
||||||
|
tier, tier_locked (Admin kann Tier festnageln)
|
||||||
|
trial_ends_at, email_verified, email_verify_token
|
||||||
|
invited_by, contract_type, contract_valid_until
|
||||||
|
stripe_customer_id (vorbereitet für v9d)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Backend-Erweiterungen
|
||||||
|
|
||||||
|
#### Neue Router (v9c):
|
||||||
|
```
|
||||||
|
routers/tiers.py - Tier-Verwaltung (List, Edit, Create)
|
||||||
|
routers/features.py - Feature-Registry (List, Add, Edit, Delete) ⭐ NEU
|
||||||
|
routers/tier_limits.py - Tier-Limits-Matrix (Admin bearbeitet Tier x Feature) ⭐ NEU
|
||||||
|
routers/coupons.py - Coupon-System (Redeem, Admin CRUD)
|
||||||
|
routers/access_grants.py - Zugriffs-Verwaltung (Current, Grant, Revoke)
|
||||||
|
routers/user_admin.py - Erweiterte User-Verwaltung (Activity, Stats, Feature-Restrictions)
|
||||||
|
routers/settings.py - App-Einstellungen (Admin)
|
||||||
|
routers/registration.py - Registrierung + E-Mail-Verifizierung
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Neue Middleware:
|
||||||
|
```python
|
||||||
|
check_feature_access(profile_id, feature_slug, action='use')
|
||||||
|
"""
|
||||||
|
Zentrale Feature-Access-Prüfung.
|
||||||
|
Hierarchie:
|
||||||
|
1. User-Restriction (höchste Priorität)
|
||||||
|
2. Tier-Limit
|
||||||
|
3. Feature-Default
|
||||||
|
|
||||||
|
Returns: {'allowed': bool, 'limit': int, 'used': int, 'remaining': int, 'reason': str}
|
||||||
|
"""
|
||||||
|
|
||||||
|
increment_feature_usage(profile_id, feature_slug)
|
||||||
|
"""
|
||||||
|
Inkrementiert Nutzungszähler.
|
||||||
|
Berücksichtigt reset_period (monthly, daily, never).
|
||||||
|
"""
|
||||||
|
|
||||||
|
log_activity(profile_id, activity_type, details=None)
|
||||||
|
"""
|
||||||
|
Loggt User-Aktivitäten in user_activity_log.
|
||||||
|
"""
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Hintergrund-Tasks (Cron):
|
||||||
|
```python
|
||||||
|
check_expired_access() # Täglich 00:00 - Trial/Coupon-Ablauf prüfen
|
||||||
|
reset_monthly_limits() # 1. jeden Monats - AI-Calls zurücksetzen
|
||||||
|
update_user_streaks() # Täglich 23:59 - Login-Streaks aktualisieren
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Zugriffs-Hierarchie
|
||||||
|
|
||||||
|
```
|
||||||
|
Effektiver Tier wird ermittelt durch (Priorität absteigend):
|
||||||
|
1. Admin-Override (tier_locked=true) → nutzt profiles.tier
|
||||||
|
2. Aktiver access_grant (nicht pausiert, valid_until > now)
|
||||||
|
3. Trial (trial_ends_at > now)
|
||||||
|
4. Base tier (profiles.tier)
|
||||||
|
|
||||||
|
Wellpass-Override-Logik:
|
||||||
|
- User hat Single-Use Coupon (20 Tage verbleibend)
|
||||||
|
- User löst Wellpass-Coupon ein (gültig bis 31.03)
|
||||||
|
- Single-Use access_grant wird pausiert (active=false, paused_by=wellpass_grant_id)
|
||||||
|
- Nach Wellpass-Ablauf: Single-Use wird reaktiviert (noch 20 Tage)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Tier-Limits & Feature-Gates
|
||||||
|
|
||||||
|
**Daten-Sichtbarkeit bei Downgrade:**
|
||||||
|
- Frontend: Buttons/Features ausblenden (Export, KI, Import)
|
||||||
|
- Backend: API limitiert Rückgabe (z.B. nur letzte 30 Gewichtseinträge bei free)
|
||||||
|
- Daten bleiben erhalten, werden nur versteckt
|
||||||
|
- Bei Upgrade wieder sichtbar
|
||||||
|
|
||||||
|
**Feature-Checks:**
|
||||||
|
```python
|
||||||
|
# Beispiel: Gewicht-Eintrag erstellen
|
||||||
|
@check_feature_limit('weight', 'create')
|
||||||
|
def create_weight_entry():
|
||||||
|
# Prüft: Hat User max_weight_entries erreicht?
|
||||||
|
# Falls ja: HTTPException 403 "Limit erreicht - Upgrade erforderlich"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Frontend-Erweiterungen
|
||||||
|
|
||||||
|
#### Neue Seiten:
|
||||||
|
```
|
||||||
|
RegisterPage.jsx - Registrierung (Name, E-Mail, Passwort)
|
||||||
|
VerifyEmailPage.jsx - E-Mail-Verifizierung (Token aus URL)
|
||||||
|
RedeemCouponPage.jsx - Coupon-Eingabe (oder Modal)
|
||||||
|
AdminCouponsPage.jsx - Coupon-Verwaltung (Admin)
|
||||||
|
AdminTiersPage.jsx - Tier-Verwaltung (CRUD) (Admin)
|
||||||
|
AdminFeaturesPage.jsx - Feature-Registry (List, Add, Edit) ⭐ NEU
|
||||||
|
AdminTierLimitsPage.jsx - Tier x Feature Matrix (bearbeiten) ⭐ NEU
|
||||||
|
AdminUserRestrictionsPage.jsx - User-spezifische Limits (bearbeiten) ⭐ NEU
|
||||||
|
AdminSettingsPage.jsx - App-Einstellungen (Admin)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Neue Komponenten:
|
||||||
|
```jsx
|
||||||
|
<TierBadge tier="premium" /> // Tier-Anzeige mit Icon
|
||||||
|
<FeatureGate feature="ai_calls">...</> // Feature-basierte Sichtbarkeit ⭐ GEÄNDERT
|
||||||
|
<AccessStatus /> // "Trial endet in 5 Tagen" Banner
|
||||||
|
<CouponInput onRedeem={...} /> // Coupon-Eingabefeld
|
||||||
|
<ActivityTimeline activities={...} /> // User-Activity-Log
|
||||||
|
<FeatureLimitBadge feature="ai_calls" /> // "5/10 verwendet" Anzeige ⭐ NEU
|
||||||
|
<TierLimitsMatrix tiers={...} features={...}/> // Matrix-Editor ⭐ NEU
|
||||||
|
<StreakCounter days={7} /> // Login-Streak (später)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Erweiterte Admin-Seiten:
|
||||||
|
```
|
||||||
|
AdminUsersPage.jsx erweitert um:
|
||||||
|
- Activity-Log Button → zeigt user_activity_log
|
||||||
|
- Stats Button → zeigt user_stats
|
||||||
|
- Access-Grants Button → zeigt aktive/abgelaufene Zugriffe
|
||||||
|
- Feature-Restrictions Button → individuelle Feature-Limits setzen ⭐ GEÄNDERT
|
||||||
|
- Grant Access Button → manuell Tier-Zugriff gewähren
|
||||||
|
- Usage-Overview → zeigt user_feature_usage für alle Features ⭐ NEU
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Admin-Interface-Details:
|
||||||
|
|
||||||
|
**AdminFeaturesPage.jsx** - Feature-Registry verwalten
|
||||||
|
```jsx
|
||||||
|
// Alle Features auflisten + neue hinzufügen
|
||||||
|
<FeatureList>
|
||||||
|
{features.map(f => (
|
||||||
|
<FeatureRow>
|
||||||
|
<Name>{f.name}</Name>
|
||||||
|
<Category>{f.category}</Category>
|
||||||
|
<Unit>{f.unit}</Unit>
|
||||||
|
<ResetPeriod>{f.reset_period}</ResetPeriod>
|
||||||
|
<DefaultLimit>{f.default_limit ?? '∞'}</DefaultLimit>
|
||||||
|
<Actions>
|
||||||
|
<EditButton />
|
||||||
|
<DeleteButton />
|
||||||
|
</Actions>
|
||||||
|
</FeatureRow>
|
||||||
|
))}
|
||||||
|
</FeatureList>
|
||||||
|
<AddFeatureButton />
|
||||||
|
```
|
||||||
|
|
||||||
|
**AdminTierLimitsPage.jsx** - Matrix-Editor
|
||||||
|
```jsx
|
||||||
|
// Matrix-View: Tiers (Spalten) x Features (Zeilen)
|
||||||
|
<TierLimitsMatrix>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Feature</th>
|
||||||
|
<th>Free</th>
|
||||||
|
<th>Basic</th>
|
||||||
|
<th>Premium</th>
|
||||||
|
<th>Selfhosted</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td>Gewichtseinträge</td>
|
||||||
|
<td><Input value="30" /></td>
|
||||||
|
<td><Input value="" placeholder="∞" /></td>
|
||||||
|
<td><Input value="" placeholder="∞" /></td>
|
||||||
|
<td><Input value="" placeholder="∞" /></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>KI-Analysen/Monat</td>
|
||||||
|
<td><Checkbox disabled /> 0</td>
|
||||||
|
<td><Checkbox checked /> <Input value="10" /></td>
|
||||||
|
<td><Checkbox checked /> ∞</td>
|
||||||
|
<td><Checkbox checked /> ∞</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</TierLimitsMatrix>
|
||||||
|
```
|
||||||
|
|
||||||
|
**AdminUserRestrictionsPage.jsx** - Individuelle User-Limits
|
||||||
|
```jsx
|
||||||
|
<UserSelect onChange={loadUser} />
|
||||||
|
|
||||||
|
<CurrentTier badge={user.tier} />
|
||||||
|
<CurrentUsage>
|
||||||
|
{features.map(f => (
|
||||||
|
<FeatureUsageRow key={f.slug}>
|
||||||
|
<Name>{f.name}</Name>
|
||||||
|
<TierLimit>{getTierLimit(user.tier, f.slug)}</TierLimit>
|
||||||
|
<CurrentUsage>{getUsage(user.id, f.slug)}</CurrentUsage>
|
||||||
|
<Override>
|
||||||
|
<Input
|
||||||
|
value={getUserRestriction(user.id, f.slug)}
|
||||||
|
placeholder="Tier-Standard"
|
||||||
|
/>
|
||||||
|
</Override>
|
||||||
|
<SaveButton />
|
||||||
|
</FeatureUsageRow>
|
||||||
|
))}
|
||||||
|
</CurrentUsage>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### E-Mail Templates (v9c)
|
||||||
|
|
||||||
|
**1. Registrierung + E-Mail-Verifizierung:**
|
||||||
|
```
|
||||||
|
Betreff: Willkommen bei Mitai Jinkendo - E-Mail bestätigen
|
||||||
|
|
||||||
|
Hallo {name},
|
||||||
|
|
||||||
|
vielen Dank für deine Registrierung bei Mitai Jinkendo!
|
||||||
|
|
||||||
|
Bitte bestätige deine E-Mail-Adresse:
|
||||||
|
{app_url}/verify-email?token={token}
|
||||||
|
|
||||||
|
Nach der Bestätigung startet dein 14-Tage Premium Trial automatisch.
|
||||||
|
|
||||||
|
Viel Erfolg bei deinem Training!
|
||||||
|
Dein Mitai Jinkendo Team
|
||||||
|
```
|
||||||
|
|
||||||
|
**2. Einladungslink (Admin):**
|
||||||
|
```
|
||||||
|
Betreff: Du wurdest zu Mitai Jinkendo eingeladen
|
||||||
|
|
||||||
|
Hallo,
|
||||||
|
|
||||||
|
{admin_name} hat dich zu Mitai Jinkendo eingeladen!
|
||||||
|
|
||||||
|
Registriere dich jetzt:
|
||||||
|
{app_url}/register?invite={token}
|
||||||
|
|
||||||
|
Du erhältst {tier} Zugriff.
|
||||||
|
|
||||||
|
Dein Mitai Jinkendo Team
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Migrations-Reihenfolge (v9c)
|
||||||
|
|
||||||
|
```
|
||||||
|
Phase 1 - DB Schema:
|
||||||
|
1. app_settings Tabelle + Initialdaten
|
||||||
|
2. tiers Tabelle + 4 Standard-Tiers
|
||||||
|
3. coupons Tabelle
|
||||||
|
4. coupon_redemptions Tabelle
|
||||||
|
5. access_grants Tabelle
|
||||||
|
6. user_activity_log Tabelle
|
||||||
|
7. user_stats Tabelle
|
||||||
|
8. user_restrictions Tabelle
|
||||||
|
9. profiles Spalten erweitern
|
||||||
|
10. Bestehende Profile migrieren (Lars → tier='selfhosted', email_verified=true)
|
||||||
|
|
||||||
|
Phase 2 - Backend:
|
||||||
|
11. Tier-System Router + Middleware
|
||||||
|
12. Registrierungs-Flow
|
||||||
|
13. Coupon-System
|
||||||
|
14. Access-Grant-Logik
|
||||||
|
15. Activity-Logging
|
||||||
|
16. Erweiterte Admin-Endpoints
|
||||||
|
|
||||||
|
Phase 3 - Frontend:
|
||||||
|
17. Registrierungs-Seiten
|
||||||
|
18. Tier-System UI-Komponenten
|
||||||
|
19. Coupon-Eingabe
|
||||||
|
20. Erweiterte Admin-Panels
|
||||||
|
21. Feature-Gates in bestehende Seiten einbauen
|
||||||
|
|
||||||
|
Phase 4 - Cron-Jobs:
|
||||||
|
22. Expired-Access-Checker
|
||||||
|
23. Monthly-Reset
|
||||||
|
24. Streak-Updater
|
||||||
|
|
||||||
|
Phase 5 - Testing & Deployment:
|
||||||
|
25. Dev-Testing
|
||||||
|
26. Prod-Deployment
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Deployment
|
## Deployment
|
||||||
|
|
||||||
### Infrastruktur
|
### Infrastruktur
|
||||||
@@ -424,6 +903,12 @@ Dev: dev-mitai-api, dev-mitai-ui
|
|||||||
|
|
||||||
## Bekannte Probleme & Lösungen
|
## Bekannte Probleme & Lösungen
|
||||||
|
|
||||||
|
### Admin User-Erstellung – Email fehlt (v9c TODO)
|
||||||
|
**Problem:** Bei Admin-CRUD `/api/profiles` (POST) wird keine Email-Adresse abgefragt.
|
||||||
|
**Impact:** Neue User können sich nicht einloggen (Login erfordert Email).
|
||||||
|
**Workaround:** Email manuell via `/api/admin/profiles/{pid}/email` setzen.
|
||||||
|
**Fix-TODO:** POST `/api/profiles` sollte Email als optionales Feld akzeptieren.
|
||||||
|
|
||||||
### dayjs.week() – NIEMALS verwenden
|
### dayjs.week() – NIEMALS verwenden
|
||||||
```javascript
|
```javascript
|
||||||
// ❌ Falsch:
|
// ❌ Falsch:
|
||||||
|
|||||||
@@ -0,0 +1,117 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Apply v9c Subscription System Migration
|
||||||
|
|
||||||
|
This script checks if v9c migration is needed and applies it.
|
||||||
|
Run automatically on container startup via main.py startup event.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import psycopg2
|
||||||
|
from psycopg2.extras import RealDictCursor
|
||||||
|
|
||||||
|
|
||||||
|
def get_db_connection():
|
||||||
|
"""Get PostgreSQL connection."""
|
||||||
|
return psycopg2.connect(
|
||||||
|
host=os.getenv("DB_HOST", "postgres"),
|
||||||
|
port=int(os.getenv("DB_PORT", 5432)),
|
||||||
|
database=os.getenv("DB_NAME", "mitai_prod"),
|
||||||
|
user=os.getenv("DB_USER", "mitai_prod"),
|
||||||
|
password=os.getenv("DB_PASSWORD", ""),
|
||||||
|
cursor_factory=RealDictCursor
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def migration_needed(conn):
|
||||||
|
"""Check if v9c migration is needed."""
|
||||||
|
cur = conn.cursor()
|
||||||
|
|
||||||
|
# Check if tiers table exists
|
||||||
|
cur.execute("""
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT FROM information_schema.tables
|
||||||
|
WHERE table_name = 'tiers'
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
tiers_exists = cur.fetchone()['exists']
|
||||||
|
|
||||||
|
# Check if features table exists
|
||||||
|
cur.execute("""
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT FROM information_schema.tables
|
||||||
|
WHERE table_name = 'features'
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
features_exists = cur.fetchone()['exists']
|
||||||
|
|
||||||
|
cur.close()
|
||||||
|
|
||||||
|
# Migration needed if either table is missing
|
||||||
|
return not (tiers_exists and features_exists)
|
||||||
|
|
||||||
|
|
||||||
|
def apply_migration():
|
||||||
|
"""Apply v9c migration if needed."""
|
||||||
|
print("[v9c Migration] Checking if migration is needed...")
|
||||||
|
|
||||||
|
try:
|
||||||
|
conn = get_db_connection()
|
||||||
|
|
||||||
|
if not migration_needed(conn):
|
||||||
|
print("[v9c Migration] Already applied, skipping.")
|
||||||
|
conn.close()
|
||||||
|
return
|
||||||
|
|
||||||
|
print("[v9c Migration] Applying subscription system migration...")
|
||||||
|
|
||||||
|
# Read migration SQL
|
||||||
|
migration_path = os.path.join(
|
||||||
|
os.path.dirname(__file__),
|
||||||
|
"migrations",
|
||||||
|
"v9c_subscription_system.sql"
|
||||||
|
)
|
||||||
|
|
||||||
|
with open(migration_path, 'r', encoding='utf-8') as f:
|
||||||
|
migration_sql = f.read()
|
||||||
|
|
||||||
|
# Execute migration
|
||||||
|
cur = conn.cursor()
|
||||||
|
cur.execute(migration_sql)
|
||||||
|
conn.commit()
|
||||||
|
cur.close()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
print("[v9c Migration] ✅ Migration completed successfully!")
|
||||||
|
|
||||||
|
# Verify tables created
|
||||||
|
conn = get_db_connection()
|
||||||
|
cur = conn.cursor()
|
||||||
|
cur.execute("""
|
||||||
|
SELECT table_name FROM information_schema.tables
|
||||||
|
WHERE table_schema = 'public'
|
||||||
|
AND table_name IN ('tiers', 'features', 'tier_limits', 'access_grants', 'coupons')
|
||||||
|
ORDER BY table_name
|
||||||
|
""")
|
||||||
|
tables = [r['table_name'] for r in cur.fetchall()]
|
||||||
|
print(f"[v9c Migration] Created tables: {', '.join(tables)}")
|
||||||
|
|
||||||
|
# Verify initial data
|
||||||
|
cur.execute("SELECT COUNT(*) as count FROM tiers")
|
||||||
|
tier_count = cur.fetchone()['count']
|
||||||
|
cur.execute("SELECT COUNT(*) as count FROM features")
|
||||||
|
feature_count = cur.fetchone()['count']
|
||||||
|
cur.execute("SELECT COUNT(*) as count FROM tier_limits")
|
||||||
|
limit_count = cur.fetchone()['count']
|
||||||
|
|
||||||
|
print(f"[v9c Migration] Initial data: {tier_count} tiers, {feature_count} features, {limit_count} tier limits")
|
||||||
|
|
||||||
|
cur.close()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[v9c Migration] ❌ Error: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
apply_migration()
|
||||||
+235
@@ -7,6 +7,7 @@ for FastAPI endpoints.
|
|||||||
import hashlib
|
import hashlib
|
||||||
import secrets
|
import secrets
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
from datetime import datetime, timedelta
|
||||||
from fastapi import Header, Query, HTTPException
|
from fastapi import Header, Query, HTTPException
|
||||||
import bcrypt
|
import bcrypt
|
||||||
|
|
||||||
@@ -114,3 +115,237 @@ def require_admin(x_auth_token: Optional[str] = Header(default=None)):
|
|||||||
if session['role'] != 'admin':
|
if session['role'] != 'admin':
|
||||||
raise HTTPException(403, "Nur für Admins")
|
raise HTTPException(403, "Nur für Admins")
|
||||||
return session
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Feature Access Control (v9c)
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
def get_effective_tier(profile_id: str) -> str:
|
||||||
|
"""
|
||||||
|
Get the effective tier for a profile.
|
||||||
|
|
||||||
|
Checks for active access_grants first (from coupons, trials, etc.),
|
||||||
|
then falls back to profile.tier.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
tier_id (str): 'free', 'basic', 'premium', or 'selfhosted'
|
||||||
|
"""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Check for active access grants (highest priority)
|
||||||
|
cur.execute("""
|
||||||
|
SELECT tier_id
|
||||||
|
FROM access_grants
|
||||||
|
WHERE profile_id = %s
|
||||||
|
AND is_active = true
|
||||||
|
AND valid_from <= CURRENT_TIMESTAMP
|
||||||
|
AND valid_until > CURRENT_TIMESTAMP
|
||||||
|
ORDER BY valid_until DESC
|
||||||
|
LIMIT 1
|
||||||
|
""", (profile_id,))
|
||||||
|
|
||||||
|
grant = cur.fetchone()
|
||||||
|
if grant:
|
||||||
|
return grant['tier_id']
|
||||||
|
|
||||||
|
# Fall back to profile tier
|
||||||
|
cur.execute("SELECT tier FROM profiles WHERE id = %s", (profile_id,))
|
||||||
|
profile = cur.fetchone()
|
||||||
|
return profile['tier'] if profile else 'free'
|
||||||
|
|
||||||
|
|
||||||
|
def check_feature_access(profile_id: str, feature_id: str) -> dict:
|
||||||
|
"""
|
||||||
|
Check if a profile has access to a feature.
|
||||||
|
|
||||||
|
Access hierarchy:
|
||||||
|
1. User-specific restriction (user_feature_restrictions)
|
||||||
|
2. Tier limit (tier_limits)
|
||||||
|
3. Feature default (features.default_limit)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: {
|
||||||
|
'allowed': bool,
|
||||||
|
'limit': int | None, # NULL = unlimited
|
||||||
|
'used': int,
|
||||||
|
'remaining': int | None, # NULL = unlimited
|
||||||
|
'reason': str # 'unlimited', 'within_limit', 'limit_exceeded', 'feature_disabled'
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Get feature info
|
||||||
|
cur.execute("""
|
||||||
|
SELECT limit_type, reset_period, default_limit
|
||||||
|
FROM features
|
||||||
|
WHERE id = %s AND active = true
|
||||||
|
""", (feature_id,))
|
||||||
|
feature = cur.fetchone()
|
||||||
|
|
||||||
|
if not feature:
|
||||||
|
return {
|
||||||
|
'allowed': False,
|
||||||
|
'limit': None,
|
||||||
|
'used': 0,
|
||||||
|
'remaining': None,
|
||||||
|
'reason': 'feature_not_found'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Priority 1: Check user-specific restriction
|
||||||
|
cur.execute("""
|
||||||
|
SELECT limit_value
|
||||||
|
FROM user_feature_restrictions
|
||||||
|
WHERE profile_id = %s AND feature_id = %s
|
||||||
|
""", (profile_id, feature_id))
|
||||||
|
restriction = cur.fetchone()
|
||||||
|
|
||||||
|
if restriction is not None:
|
||||||
|
limit = restriction['limit_value']
|
||||||
|
else:
|
||||||
|
# Priority 2: Check tier limit
|
||||||
|
tier_id = get_effective_tier(profile_id)
|
||||||
|
cur.execute("""
|
||||||
|
SELECT limit_value
|
||||||
|
FROM tier_limits
|
||||||
|
WHERE tier_id = %s AND feature_id = %s
|
||||||
|
""", (tier_id, feature_id))
|
||||||
|
tier_limit = cur.fetchone()
|
||||||
|
|
||||||
|
if tier_limit is not None:
|
||||||
|
limit = tier_limit['limit_value']
|
||||||
|
else:
|
||||||
|
# Priority 3: Feature default
|
||||||
|
limit = feature['default_limit']
|
||||||
|
|
||||||
|
# For boolean features (limit 0 = disabled, 1 = enabled)
|
||||||
|
if feature['limit_type'] == 'boolean':
|
||||||
|
allowed = limit == 1
|
||||||
|
return {
|
||||||
|
'allowed': allowed,
|
||||||
|
'limit': limit,
|
||||||
|
'used': 0,
|
||||||
|
'remaining': None,
|
||||||
|
'reason': 'enabled' if allowed else 'feature_disabled'
|
||||||
|
}
|
||||||
|
|
||||||
|
# For count-based features
|
||||||
|
# Check current usage
|
||||||
|
cur.execute("""
|
||||||
|
SELECT usage_count, reset_at
|
||||||
|
FROM user_feature_usage
|
||||||
|
WHERE profile_id = %s AND feature_id = %s
|
||||||
|
""", (profile_id, feature_id))
|
||||||
|
usage = cur.fetchone()
|
||||||
|
|
||||||
|
used = usage['usage_count'] if usage else 0
|
||||||
|
|
||||||
|
# Check if reset is needed
|
||||||
|
if usage and usage['reset_at'] and datetime.now() > usage['reset_at']:
|
||||||
|
# Reset usage
|
||||||
|
used = 0
|
||||||
|
next_reset = _calculate_next_reset(feature['reset_period'])
|
||||||
|
cur.execute("""
|
||||||
|
UPDATE user_feature_usage
|
||||||
|
SET usage_count = 0, reset_at = %s, updated = CURRENT_TIMESTAMP
|
||||||
|
WHERE profile_id = %s AND feature_id = %s
|
||||||
|
""", (next_reset, profile_id, feature_id))
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
# NULL limit = unlimited
|
||||||
|
if limit is None:
|
||||||
|
return {
|
||||||
|
'allowed': True,
|
||||||
|
'limit': None,
|
||||||
|
'used': used,
|
||||||
|
'remaining': None,
|
||||||
|
'reason': 'unlimited'
|
||||||
|
}
|
||||||
|
|
||||||
|
# 0 limit = disabled
|
||||||
|
if limit == 0:
|
||||||
|
return {
|
||||||
|
'allowed': False,
|
||||||
|
'limit': 0,
|
||||||
|
'used': used,
|
||||||
|
'remaining': 0,
|
||||||
|
'reason': 'feature_disabled'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Check if within limit
|
||||||
|
allowed = used < limit
|
||||||
|
remaining = limit - used if limit else None
|
||||||
|
|
||||||
|
return {
|
||||||
|
'allowed': allowed,
|
||||||
|
'limit': limit,
|
||||||
|
'used': used,
|
||||||
|
'remaining': remaining,
|
||||||
|
'reason': 'within_limit' if allowed else 'limit_exceeded'
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def increment_feature_usage(profile_id: str, feature_id: str) -> None:
|
||||||
|
"""
|
||||||
|
Increment usage counter for a feature.
|
||||||
|
|
||||||
|
Creates usage record if it doesn't exist, with reset_at based on
|
||||||
|
feature's reset_period.
|
||||||
|
"""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Get feature reset period
|
||||||
|
cur.execute("""
|
||||||
|
SELECT reset_period
|
||||||
|
FROM features
|
||||||
|
WHERE id = %s
|
||||||
|
""", (feature_id,))
|
||||||
|
feature = cur.fetchone()
|
||||||
|
|
||||||
|
if not feature:
|
||||||
|
return
|
||||||
|
|
||||||
|
reset_period = feature['reset_period']
|
||||||
|
next_reset = _calculate_next_reset(reset_period)
|
||||||
|
|
||||||
|
# Upsert usage
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO user_feature_usage (profile_id, feature_id, usage_count, reset_at)
|
||||||
|
VALUES (%s, %s, 1, %s)
|
||||||
|
ON CONFLICT (profile_id, feature_id)
|
||||||
|
DO UPDATE SET
|
||||||
|
usage_count = user_feature_usage.usage_count + 1,
|
||||||
|
updated = CURRENT_TIMESTAMP
|
||||||
|
""", (profile_id, feature_id, next_reset))
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def _calculate_next_reset(reset_period: str) -> Optional[datetime]:
|
||||||
|
"""
|
||||||
|
Calculate next reset timestamp based on reset period.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
reset_period: 'never', 'daily', 'monthly'
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
datetime or None (for 'never')
|
||||||
|
"""
|
||||||
|
if reset_period == 'never':
|
||||||
|
return None
|
||||||
|
elif reset_period == 'daily':
|
||||||
|
# Reset at midnight
|
||||||
|
tomorrow = datetime.now().date() + timedelta(days=1)
|
||||||
|
return datetime.combine(tomorrow, datetime.min.time())
|
||||||
|
elif reset_period == 'monthly':
|
||||||
|
# Reset at start of next month
|
||||||
|
now = datetime.now()
|
||||||
|
if now.month == 12:
|
||||||
|
return datetime(now.year + 1, 1, 1)
|
||||||
|
else:
|
||||||
|
return datetime(now.year, now.month + 1, 1)
|
||||||
|
else:
|
||||||
|
return None
|
||||||
+59
-1845
File diff suppressed because it is too large.
Load diff
+1878
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,352 @@
|
|||||||
|
-- ============================================================================
|
||||||
|
-- Mitai Jinkendo v9c: Subscription & Coupon System Migration
|
||||||
|
-- ============================================================================
|
||||||
|
-- Created: 2026-03-19
|
||||||
|
-- Purpose: Add flexible tier system with Feature-Registry Pattern
|
||||||
|
--
|
||||||
|
-- Tables added:
|
||||||
|
-- 1. app_settings - Global configuration
|
||||||
|
-- 2. tiers - Subscription tiers (simplified)
|
||||||
|
-- 3. features - Feature registry (all limitable features)
|
||||||
|
-- 4. tier_limits - Tier x Feature matrix
|
||||||
|
-- 5. user_feature_restrictions - Individual user overrides
|
||||||
|
-- 6. user_feature_usage - Usage tracking
|
||||||
|
-- 7. coupons - Coupon management
|
||||||
|
-- 8. coupon_redemptions - Redemption history
|
||||||
|
-- 9. access_grants - Time-limited access grants
|
||||||
|
-- 10. user_activity_log - Activity tracking
|
||||||
|
-- 11. user_stats - Aggregated statistics
|
||||||
|
--
|
||||||
|
-- Feature-Registry Pattern:
|
||||||
|
-- Instead of hardcoded columns (max_weight_entries, max_ai_calls),
|
||||||
|
-- all limits are defined in features table and configured via tier_limits.
|
||||||
|
-- This allows adding new limitable features without schema changes.
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- 1. app_settings - Global configuration
|
||||||
|
-- ============================================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS app_settings (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- 2. tiers - Subscription tiers (simplified)
|
||||||
|
-- ============================================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS tiers (
|
||||||
|
id TEXT PRIMARY KEY, -- 'free', 'basic', 'premium', 'selfhosted'
|
||||||
|
name TEXT NOT NULL, -- Display name
|
||||||
|
description TEXT, -- Marketing description
|
||||||
|
price_monthly_cents INTEGER, -- NULL for free/selfhosted
|
||||||
|
price_yearly_cents INTEGER, -- NULL for free/selfhosted
|
||||||
|
stripe_price_id_monthly TEXT, -- Stripe Price ID (for v9d)
|
||||||
|
stripe_price_id_yearly TEXT, -- Stripe Price ID (for v9d)
|
||||||
|
active BOOLEAN DEFAULT true, -- Can new users subscribe?
|
||||||
|
sort_order INTEGER DEFAULT 0,
|
||||||
|
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- 3. features - Feature registry (all limitable features)
|
||||||
|
-- ============================================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS features (
|
||||||
|
id TEXT PRIMARY KEY, -- 'weight_entries', 'ai_calls', 'photos', etc.
|
||||||
|
name TEXT NOT NULL, -- Display name
|
||||||
|
description TEXT, -- What is this feature?
|
||||||
|
category TEXT, -- 'data', 'ai', 'export', 'integration'
|
||||||
|
limit_type TEXT DEFAULT 'count', -- 'count', 'boolean', 'quota'
|
||||||
|
reset_period TEXT DEFAULT 'never', -- 'never', 'monthly', 'daily'
|
||||||
|
default_limit INTEGER, -- Fallback if no tier_limit defined
|
||||||
|
active BOOLEAN DEFAULT true, -- Is this feature currently used?
|
||||||
|
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- 4. tier_limits - Tier x Feature matrix
|
||||||
|
-- ============================================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS tier_limits (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
tier_id TEXT NOT NULL REFERENCES tiers(id) ON DELETE CASCADE,
|
||||||
|
feature_id TEXT NOT NULL REFERENCES features(id) ON DELETE CASCADE,
|
||||||
|
limit_value INTEGER, -- NULL = unlimited, 0 = disabled
|
||||||
|
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
UNIQUE(tier_id, feature_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- 5. user_feature_restrictions - Individual user overrides
|
||||||
|
-- ============================================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS user_feature_restrictions (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||||
|
feature_id TEXT NOT NULL REFERENCES features(id) ON DELETE CASCADE,
|
||||||
|
limit_value INTEGER, -- NULL = unlimited, 0 = disabled
|
||||||
|
reason TEXT, -- Why was this override applied?
|
||||||
|
created_by UUID, -- Admin profile_id
|
||||||
|
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
UNIQUE(profile_id, feature_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- 6. user_feature_usage - Usage tracking
|
||||||
|
-- ============================================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS user_feature_usage (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||||
|
feature_id TEXT NOT NULL REFERENCES features(id) ON DELETE CASCADE,
|
||||||
|
usage_count INTEGER DEFAULT 0,
|
||||||
|
reset_at TIMESTAMP, -- When does this counter reset?
|
||||||
|
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
UNIQUE(profile_id, feature_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- 7. coupons - Coupon management
|
||||||
|
-- ============================================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS coupons (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
code TEXT UNIQUE NOT NULL,
|
||||||
|
type TEXT NOT NULL, -- 'single_use', 'period', 'wellpass'
|
||||||
|
tier_id TEXT REFERENCES tiers(id) ON DELETE SET NULL,
|
||||||
|
duration_days INTEGER, -- For period/wellpass coupons
|
||||||
|
max_redemptions INTEGER, -- NULL = unlimited
|
||||||
|
redemption_count INTEGER DEFAULT 0,
|
||||||
|
valid_from TIMESTAMP,
|
||||||
|
valid_until TIMESTAMP,
|
||||||
|
active BOOLEAN DEFAULT true,
|
||||||
|
created_by UUID, -- Admin profile_id
|
||||||
|
description TEXT, -- Internal note
|
||||||
|
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- 8. coupon_redemptions - Redemption history
|
||||||
|
-- ============================================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS coupon_redemptions (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
coupon_id UUID NOT NULL REFERENCES coupons(id) ON DELETE CASCADE,
|
||||||
|
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||||
|
redeemed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
access_grant_id UUID, -- FK to access_grants (created as result)
|
||||||
|
UNIQUE(coupon_id, profile_id) -- One redemption per user per coupon
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- 9. access_grants - Time-limited access grants
|
||||||
|
-- ============================================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS access_grants (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||||
|
tier_id TEXT NOT NULL REFERENCES tiers(id) ON DELETE CASCADE,
|
||||||
|
granted_by TEXT, -- 'coupon', 'admin', 'trial', 'subscription'
|
||||||
|
coupon_id UUID REFERENCES coupons(id) ON DELETE SET NULL,
|
||||||
|
valid_from TIMESTAMP NOT NULL,
|
||||||
|
valid_until TIMESTAMP NOT NULL,
|
||||||
|
is_active BOOLEAN DEFAULT true, -- Can be paused by Wellpass logic
|
||||||
|
paused_by UUID, -- access_grant.id that paused this
|
||||||
|
paused_at TIMESTAMP, -- When was it paused?
|
||||||
|
remaining_days INTEGER, -- Days left when paused (for resume)
|
||||||
|
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- 10. user_activity_log - Activity tracking
|
||||||
|
-- ============================================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS user_activity_log (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||||
|
action TEXT NOT NULL, -- 'login', 'logout', 'coupon_redeemed', 'tier_changed'
|
||||||
|
details JSONB, -- Flexible metadata
|
||||||
|
ip_address TEXT,
|
||||||
|
user_agent TEXT,
|
||||||
|
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_activity_log_profile ON user_activity_log(profile_id, created DESC);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_activity_log_action ON user_activity_log(action, created DESC);
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- 11. user_stats - Aggregated statistics
|
||||||
|
-- ============================================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS user_stats (
|
||||||
|
profile_id UUID PRIMARY KEY REFERENCES profiles(id) ON DELETE CASCADE,
|
||||||
|
last_login TIMESTAMP,
|
||||||
|
login_count INTEGER DEFAULT 0,
|
||||||
|
weight_entries_count INTEGER DEFAULT 0,
|
||||||
|
ai_calls_count INTEGER DEFAULT 0,
|
||||||
|
photos_count INTEGER DEFAULT 0,
|
||||||
|
total_data_points INTEGER DEFAULT 0,
|
||||||
|
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- Extend profiles table with subscription fields
|
||||||
|
-- ============================================================================
|
||||||
|
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS tier TEXT DEFAULT 'free';
|
||||||
|
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS trial_ends_at TIMESTAMP;
|
||||||
|
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS email_verified BOOLEAN DEFAULT false;
|
||||||
|
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS email_verify_token TEXT;
|
||||||
|
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS invited_by UUID REFERENCES profiles(id) ON DELETE SET NULL;
|
||||||
|
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS invitation_token TEXT;
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- Insert initial data
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
-- App settings
|
||||||
|
INSERT INTO app_settings (key, value, description) VALUES
|
||||||
|
('trial_duration_days', '14', 'Default trial duration for new registrations'),
|
||||||
|
('post_trial_tier', 'free', 'Tier after trial expires (free/disabled)'),
|
||||||
|
('require_email_verification', 'true', 'Require email verification before activation'),
|
||||||
|
('self_registration_enabled', 'true', 'Allow self-registration')
|
||||||
|
ON CONFLICT (key) DO NOTHING;
|
||||||
|
|
||||||
|
-- Tiers
|
||||||
|
INSERT INTO tiers (id, name, description, price_monthly_cents, price_yearly_cents, active, sort_order) VALUES
|
||||||
|
('free', 'Free', 'Eingeschränkte Basis-Funktionen', NULL, NULL, true, 1),
|
||||||
|
('basic', 'Basic', 'Kernfunktionen ohne KI', 499, 4990, true, 2),
|
||||||
|
('premium', 'Premium', 'Alle Features inkl. KI und Connectoren', 999, 9990, true, 3),
|
||||||
|
('selfhosted', 'Self-Hosted', 'Unbegrenzt (für Heimserver)', NULL, NULL, false, 4)
|
||||||
|
ON CONFLICT (id) DO NOTHING;
|
||||||
|
|
||||||
|
-- Features (11 initial features)
|
||||||
|
INSERT INTO features (id, name, description, category, limit_type, reset_period, default_limit, active) VALUES
|
||||||
|
('weight_entries', 'Gewichtseinträge', 'Anzahl Gewichtsmessungen', 'data', 'count', 'never', NULL, true),
|
||||||
|
('circumference_entries', 'Umfangs-Einträge', 'Anzahl Umfangsmessungen', 'data', 'count', 'never', NULL, true),
|
||||||
|
('caliper_entries', 'Caliper-Einträge', 'Anzahl Hautfaltenmessungen', 'data', 'count', 'never', NULL, true),
|
||||||
|
('nutrition_entries', 'Ernährungs-Einträge', 'Anzahl Ernährungslogs', 'data', 'count', 'never', NULL, true),
|
||||||
|
('activity_entries', 'Aktivitäts-Einträge', 'Anzahl Trainings/Aktivitäten', 'data', 'count', 'never', NULL, true),
|
||||||
|
('photos', 'Progress-Fotos', 'Anzahl hochgeladene Fotos', 'data', 'count', 'never', NULL, true),
|
||||||
|
('ai_calls', 'KI-Analysen', 'KI-Auswertungen pro Monat', 'ai', 'count', 'monthly', 0, true),
|
||||||
|
('ai_pipeline', 'KI-Pipeline', 'Vollständige Pipeline-Analyse', 'ai', 'boolean', 'never', 0, true),
|
||||||
|
('export_csv', 'CSV-Export', 'Daten als CSV exportieren', 'export', 'boolean', 'never', 0, true),
|
||||||
|
('export_json', 'JSON-Export', 'Daten als JSON exportieren', 'export', 'boolean', 'never', 0, true),
|
||||||
|
('export_zip', 'ZIP-Export', 'Vollständiger Backup-Export', 'export', 'boolean', 'never', 0, true)
|
||||||
|
ON CONFLICT (id) DO NOTHING;
|
||||||
|
|
||||||
|
-- Tier x Feature Matrix (tier_limits)
|
||||||
|
-- Format: (tier, feature, limit) - NULL = unlimited, 0 = disabled
|
||||||
|
|
||||||
|
-- FREE tier (sehr eingeschränkt)
|
||||||
|
INSERT INTO tier_limits (tier_id, feature_id, limit_value) VALUES
|
||||||
|
('free', 'weight_entries', 30),
|
||||||
|
('free', 'circumference_entries', 10),
|
||||||
|
('free', 'caliper_entries', 10),
|
||||||
|
('free', 'nutrition_entries', 30),
|
||||||
|
('free', 'activity_entries', 30),
|
||||||
|
('free', 'photos', 5),
|
||||||
|
('free', 'ai_calls', 0), -- Keine KI
|
||||||
|
('free', 'ai_pipeline', 0), -- Keine Pipeline
|
||||||
|
('free', 'export_csv', 0), -- Kein Export
|
||||||
|
('free', 'export_json', 0),
|
||||||
|
('free', 'export_zip', 0)
|
||||||
|
ON CONFLICT (tier_id, feature_id) DO NOTHING;
|
||||||
|
|
||||||
|
-- BASIC tier (Kernfunktionen)
|
||||||
|
INSERT INTO tier_limits (tier_id, feature_id, limit_value) VALUES
|
||||||
|
('basic', 'weight_entries', NULL), -- Unbegrenzt
|
||||||
|
('basic', 'circumference_entries', NULL),
|
||||||
|
('basic', 'caliper_entries', NULL),
|
||||||
|
('basic', 'nutrition_entries', NULL),
|
||||||
|
('basic', 'activity_entries', NULL),
|
||||||
|
('basic', 'photos', 50),
|
||||||
|
('basic', 'ai_calls', 3), -- 3 KI-Calls/Monat
|
||||||
|
('basic', 'ai_pipeline', 0), -- Keine Pipeline
|
||||||
|
('basic', 'export_csv', 1), -- Export erlaubt
|
||||||
|
('basic', 'export_json', 1),
|
||||||
|
('basic', 'export_zip', 1)
|
||||||
|
ON CONFLICT (tier_id, feature_id) DO NOTHING;
|
||||||
|
|
||||||
|
-- PREMIUM tier (alles unbegrenzt)
|
||||||
|
INSERT INTO tier_limits (tier_id, feature_id, limit_value) VALUES
|
||||||
|
('premium', 'weight_entries', NULL),
|
||||||
|
('premium', 'circumference_entries', NULL),
|
||||||
|
('premium', 'caliper_entries', NULL),
|
||||||
|
('premium', 'nutrition_entries', NULL),
|
||||||
|
('premium', 'activity_entries', NULL),
|
||||||
|
('premium', 'photos', NULL),
|
||||||
|
('premium', 'ai_calls', NULL), -- Unbegrenzt KI
|
||||||
|
('premium', 'ai_pipeline', 1), -- Pipeline erlaubt
|
||||||
|
('premium', 'export_csv', 1),
|
||||||
|
('premium', 'export_json', 1),
|
||||||
|
('premium', 'export_zip', 1)
|
||||||
|
ON CONFLICT (tier_id, feature_id) DO NOTHING;
|
||||||
|
|
||||||
|
-- SELFHOSTED tier (alles unbegrenzt)
|
||||||
|
INSERT INTO tier_limits (tier_id, feature_id, limit_value) VALUES
|
||||||
|
('selfhosted', 'weight_entries', NULL),
|
||||||
|
('selfhosted', 'circumference_entries', NULL),
|
||||||
|
('selfhosted', 'caliper_entries', NULL),
|
||||||
|
('selfhosted', 'nutrition_entries', NULL),
|
||||||
|
('selfhosted', 'activity_entries', NULL),
|
||||||
|
('selfhosted', 'photos', NULL),
|
||||||
|
('selfhosted', 'ai_calls', NULL),
|
||||||
|
('selfhosted', 'ai_pipeline', 1),
|
||||||
|
('selfhosted', 'export_csv', 1),
|
||||||
|
('selfhosted', 'export_json', 1),
|
||||||
|
('selfhosted', 'export_zip', 1)
|
||||||
|
ON CONFLICT (tier_id, feature_id) DO NOTHING;
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- Migrate existing profiles
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
-- Lars' Profile → selfhosted tier with email verified
|
||||||
|
UPDATE profiles
|
||||||
|
SET
|
||||||
|
tier = 'selfhosted',
|
||||||
|
email_verified = true
|
||||||
|
WHERE
|
||||||
|
email = 'lars@stommer.com'
|
||||||
|
OR role = 'admin';
|
||||||
|
|
||||||
|
-- Other existing profiles → free tier, unverified
|
||||||
|
UPDATE profiles
|
||||||
|
SET
|
||||||
|
tier = 'free',
|
||||||
|
email_verified = false
|
||||||
|
WHERE
|
||||||
|
tier IS NULL
|
||||||
|
OR tier = '';
|
||||||
|
|
||||||
|
-- Initialize user_stats for existing profiles
|
||||||
|
INSERT INTO user_stats (profile_id, weight_entries_count, photos_count)
|
||||||
|
SELECT
|
||||||
|
p.id,
|
||||||
|
(SELECT COUNT(*) FROM weight_log WHERE profile_id = p.id),
|
||||||
|
(SELECT COUNT(*) FROM photos WHERE profile_id = p.id)
|
||||||
|
FROM profiles p
|
||||||
|
ON CONFLICT (profile_id) DO NOTHING;
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- Create indexes for performance
|
||||||
|
-- ============================================================================
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_tier_limits_tier ON tier_limits(tier_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_tier_limits_feature ON tier_limits(feature_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_restrictions_profile ON user_feature_restrictions(profile_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_usage_profile ON user_feature_usage(profile_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_access_grants_profile ON access_grants(profile_id, valid_until DESC);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_access_grants_active ON access_grants(profile_id, is_active, valid_until DESC);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_coupons_code ON coupons(code);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_coupon_redemptions_profile ON coupon_redemptions(profile_id);
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- Migration complete
|
||||||
|
-- ============================================================================
|
||||||
|
-- Run this migration with:
|
||||||
|
-- psql -h localhost -U mitai_prod -d mitai_prod < backend/migrations/v9c_subscription_system.sql
|
||||||
|
--
|
||||||
|
-- Or via Docker:
|
||||||
|
-- docker exec -i mitai-postgres psql -U mitai_prod -d mitai_prod < backend/migrations/v9c_subscription_system.sql
|
||||||
|
-- ============================================================================
|
||||||
Whitespace-only changes.
@@ -0,0 +1,192 @@
|
|||||||
|
"""
|
||||||
|
Access Grants Management Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Admin-only access grants history and manual grant creation.
|
||||||
|
"""
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from fastapi import APIRouter, HTTPException, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_admin
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/access-grants", tags=["access-grants"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def list_access_grants(
|
||||||
|
profile_id: str = None,
|
||||||
|
active_only: bool = False,
|
||||||
|
session: dict = Depends(require_admin)
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Admin: List access grants.
|
||||||
|
|
||||||
|
Query params:
|
||||||
|
- profile_id: Filter by user
|
||||||
|
- active_only: Only show currently active grants
|
||||||
|
"""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
query = """
|
||||||
|
SELECT
|
||||||
|
ag.*,
|
||||||
|
t.name as tier_name,
|
||||||
|
p.name as profile_name,
|
||||||
|
p.email as profile_email
|
||||||
|
FROM access_grants ag
|
||||||
|
JOIN tiers t ON t.id = ag.tier_id
|
||||||
|
JOIN profiles p ON p.id = ag.profile_id
|
||||||
|
"""
|
||||||
|
|
||||||
|
conditions = []
|
||||||
|
params = []
|
||||||
|
|
||||||
|
if profile_id:
|
||||||
|
conditions.append("ag.profile_id = %s")
|
||||||
|
params.append(profile_id)
|
||||||
|
|
||||||
|
if active_only:
|
||||||
|
conditions.append("ag.is_active = true")
|
||||||
|
conditions.append("ag.valid_until > CURRENT_TIMESTAMP")
|
||||||
|
|
||||||
|
if conditions:
|
||||||
|
query += " WHERE " + " AND ".join(conditions)
|
||||||
|
|
||||||
|
query += " ORDER BY ag.valid_until DESC"
|
||||||
|
|
||||||
|
cur.execute(query, params)
|
||||||
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("")
|
||||||
|
def create_access_grant(data: dict, session: dict = Depends(require_admin)):
|
||||||
|
"""
|
||||||
|
Admin: Manually create access grant.
|
||||||
|
|
||||||
|
Body:
|
||||||
|
{
|
||||||
|
"profile_id": "uuid",
|
||||||
|
"tier_id": "premium",
|
||||||
|
"duration_days": 30,
|
||||||
|
"reason": "Compensation for bug"
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
profile_id = data.get('profile_id')
|
||||||
|
tier_id = data.get('tier_id')
|
||||||
|
duration_days = data.get('duration_days')
|
||||||
|
reason = data.get('reason', '')
|
||||||
|
|
||||||
|
if not profile_id or not tier_id or not duration_days:
|
||||||
|
raise HTTPException(400, "profile_id, tier_id und duration_days fehlen")
|
||||||
|
|
||||||
|
valid_from = datetime.now()
|
||||||
|
valid_until = valid_from + timedelta(days=duration_days)
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Create grant
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO access_grants (
|
||||||
|
profile_id, tier_id, granted_by, valid_from, valid_until
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, 'admin', %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""", (profile_id, tier_id, valid_from, valid_until))
|
||||||
|
|
||||||
|
grant_id = cur.fetchone()['id']
|
||||||
|
|
||||||
|
# Log activity
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO user_activity_log (profile_id, action, details)
|
||||||
|
VALUES (%s, 'access_grant_created', %s)
|
||||||
|
""", (
|
||||||
|
profile_id,
|
||||||
|
f'{{"tier": "{tier_id}", "duration_days": {duration_days}, "reason": "{reason}"}}'
|
||||||
|
))
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"id": grant_id,
|
||||||
|
"valid_until": valid_until.isoformat()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{grant_id}")
|
||||||
|
def update_access_grant(grant_id: str, data: dict, session: dict = Depends(require_admin)):
|
||||||
|
"""
|
||||||
|
Admin: Update access grant (e.g., extend duration, pause/resume).
|
||||||
|
|
||||||
|
Body:
|
||||||
|
{
|
||||||
|
"is_active": false, // Pause grant
|
||||||
|
"valid_until": "2026-12-31T23:59:59" // Extend
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
updates = []
|
||||||
|
values = []
|
||||||
|
|
||||||
|
if 'is_active' in data:
|
||||||
|
updates.append('is_active = %s')
|
||||||
|
values.append(data['is_active'])
|
||||||
|
|
||||||
|
if not data['is_active']:
|
||||||
|
# Pausing - calculate remaining days
|
||||||
|
cur.execute("SELECT valid_until FROM access_grants WHERE id = %s", (grant_id,))
|
||||||
|
grant = cur.fetchone()
|
||||||
|
if grant:
|
||||||
|
remaining = (grant['valid_until'] - datetime.now()).days
|
||||||
|
updates.append('remaining_days = %s')
|
||||||
|
values.append(remaining)
|
||||||
|
updates.append('paused_at = CURRENT_TIMESTAMP')
|
||||||
|
|
||||||
|
if 'valid_until' in data:
|
||||||
|
updates.append('valid_until = %s')
|
||||||
|
values.append(data['valid_until'])
|
||||||
|
|
||||||
|
if not updates:
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
updates.append('updated = CURRENT_TIMESTAMP')
|
||||||
|
values.append(grant_id)
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
f"UPDATE access_grants SET {', '.join(updates)} WHERE id = %s",
|
||||||
|
values
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{grant_id}")
|
||||||
|
def revoke_access_grant(grant_id: str, session: dict = Depends(require_admin)):
|
||||||
|
"""Admin: Revoke access grant (hard delete)."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Get grant info for logging
|
||||||
|
cur.execute("SELECT profile_id, tier_id FROM access_grants WHERE id = %s", (grant_id,))
|
||||||
|
grant = cur.fetchone()
|
||||||
|
|
||||||
|
if grant:
|
||||||
|
# Log revocation
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO user_activity_log (profile_id, action, details)
|
||||||
|
VALUES (%s, 'access_grant_revoked', %s)
|
||||||
|
""", (
|
||||||
|
grant['profile_id'],
|
||||||
|
f'{{"grant_id": "{grant_id}", "tier": "{grant["tier_id"]}"}}'
|
||||||
|
))
|
||||||
|
|
||||||
|
# Delete grant
|
||||||
|
cur.execute("DELETE FROM access_grants WHERE id = %s", (grant_id,))
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {"ok": True}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
"""
|
||||||
|
Activity Tracking Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Handles workout/activity logging, statistics, and Apple Health CSV import.
|
||||||
|
"""
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
|
import uuid
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, UploadFile, File, Header, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth
|
||||||
|
from models import ActivityEntry
|
||||||
|
from routers.profiles import get_pid
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/activity", tags=["activity"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def list_activity(limit: int=200, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Get activity entries for current profile."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"SELECT * FROM activity_log WHERE profile_id=%s ORDER BY date DESC, start_time DESC LIMIT %s", (pid,limit))
|
||||||
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("")
|
||||||
|
def create_activity(e: ActivityEntry, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Create new activity entry."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
eid = str(uuid.uuid4())
|
||||||
|
d = e.model_dump()
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("""INSERT INTO activity_log
|
||||||
|
(id,profile_id,date,start_time,end_time,activity_type,duration_min,kcal_active,kcal_resting,
|
||||||
|
hr_avg,hr_max,distance_km,rpe,source,notes,created)
|
||||||
|
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,CURRENT_TIMESTAMP)""",
|
||||||
|
(eid,pid,d['date'],d['start_time'],d['end_time'],d['activity_type'],d['duration_min'],
|
||||||
|
d['kcal_active'],d['kcal_resting'],d['hr_avg'],d['hr_max'],d['distance_km'],
|
||||||
|
d['rpe'],d['source'],d['notes']))
|
||||||
|
return {"id":eid,"date":e.date}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{eid}")
|
||||||
|
def update_activity(eid: str, e: ActivityEntry, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Update existing activity entry."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
d = e.model_dump()
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(f"UPDATE activity_log SET {', '.join(f'{k}=%s' for k in d)} WHERE id=%s AND profile_id=%s",
|
||||||
|
list(d.values())+[eid,pid])
|
||||||
|
return {"id":eid}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{eid}")
|
||||||
|
def delete_activity(eid: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Delete activity entry."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("DELETE FROM activity_log WHERE id=%s AND profile_id=%s", (eid,pid))
|
||||||
|
return {"ok":True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/stats")
|
||||||
|
def activity_stats(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Get activity statistics (last 30 entries)."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"SELECT * FROM activity_log WHERE profile_id=%s ORDER BY date DESC LIMIT 30", (pid,))
|
||||||
|
rows = [r2d(r) for r in cur.fetchall()]
|
||||||
|
if not rows: return {"count":0,"total_kcal":0,"total_min":0,"by_type":{}}
|
||||||
|
total_kcal=sum(float(r.get('kcal_active') or 0) for r in rows)
|
||||||
|
total_min=sum(float(r.get('duration_min') or 0) for r in rows)
|
||||||
|
by_type={}
|
||||||
|
for r in rows:
|
||||||
|
t=r['activity_type']; by_type.setdefault(t,{'count':0,'kcal':0,'min':0})
|
||||||
|
by_type[t]['count']+=1
|
||||||
|
by_type[t]['kcal']+=float(r.get('kcal_active') or 0)
|
||||||
|
by_type[t]['min']+=float(r.get('duration_min') or 0)
|
||||||
|
return {"count":len(rows),"total_kcal":round(total_kcal),"total_min":round(total_min),"by_type":by_type}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/import-csv")
|
||||||
|
async def import_activity_csv(file: UploadFile=File(...), x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Import Apple Health workout CSV."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
raw = await file.read()
|
||||||
|
try: text = raw.decode('utf-8')
|
||||||
|
except: text = raw.decode('latin-1')
|
||||||
|
if text.startswith('\ufeff'): text = text[1:]
|
||||||
|
if not text.strip(): raise HTTPException(400,"Leere Datei")
|
||||||
|
reader = csv.DictReader(io.StringIO(text))
|
||||||
|
inserted = skipped = 0
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
for row in reader:
|
||||||
|
wtype = row.get('Workout Type','').strip()
|
||||||
|
start = row.get('Start','').strip()
|
||||||
|
if not wtype or not start: continue
|
||||||
|
try: date = start[:10]
|
||||||
|
except: continue
|
||||||
|
dur = row.get('Duration','').strip()
|
||||||
|
duration_min = None
|
||||||
|
if dur:
|
||||||
|
try:
|
||||||
|
p = dur.split(':')
|
||||||
|
duration_min = round(int(p[0])*60+int(p[1])+int(p[2])/60,1)
|
||||||
|
except: pass
|
||||||
|
def kj(v):
|
||||||
|
try: return round(float(v)/4.184) if v else None
|
||||||
|
except: return None
|
||||||
|
def tf(v):
|
||||||
|
try: return round(float(v),1) if v else None
|
||||||
|
except: return None
|
||||||
|
try:
|
||||||
|
cur.execute("""INSERT INTO activity_log
|
||||||
|
(id,profile_id,date,start_time,end_time,activity_type,duration_min,kcal_active,kcal_resting,
|
||||||
|
hr_avg,hr_max,distance_km,source,created)
|
||||||
|
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,'apple_health',CURRENT_TIMESTAMP)""",
|
||||||
|
(str(uuid.uuid4()),pid,date,start,row.get('End',''),wtype,duration_min,
|
||||||
|
kj(row.get('Aktive Energie (kJ)','')),kj(row.get('Ruheeinträge (kJ)','')),
|
||||||
|
tf(row.get('Durchschn. Herzfrequenz (count/min)','')),
|
||||||
|
tf(row.get('Max. Herzfrequenz (count/min)','')),
|
||||||
|
tf(row.get('Distanz (km)',''))))
|
||||||
|
inserted+=1
|
||||||
|
except: skipped+=1
|
||||||
|
return {"inserted":inserted,"skipped":skipped,"message":f"{inserted} Trainings importiert"}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
"""
|
||||||
|
Admin Management Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Handles user management, permissions, and email testing (admin-only).
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import smtplib
|
||||||
|
from email.mime.text import MIMEText
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_admin, hash_pin
|
||||||
|
from models import AdminProfileUpdate
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/profiles")
|
||||||
|
def admin_list_profiles(session: dict=Depends(require_admin)):
|
||||||
|
"""Admin: List all profiles with stats."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT * FROM profiles ORDER BY created")
|
||||||
|
profs = [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
for p in profs:
|
||||||
|
pid = p['id']
|
||||||
|
cur.execute("SELECT COUNT(*) as count FROM weight_log WHERE profile_id=%s", (pid,))
|
||||||
|
p['weight_count'] = cur.fetchone()['count']
|
||||||
|
cur.execute("SELECT COUNT(*) as count FROM ai_insights WHERE profile_id=%s", (pid,))
|
||||||
|
p['ai_insights_count'] = cur.fetchone()['count']
|
||||||
|
|
||||||
|
today = datetime.now().date().isoformat()
|
||||||
|
cur.execute("SELECT call_count FROM ai_usage WHERE profile_id=%s AND date=%s", (pid, today))
|
||||||
|
usage = cur.fetchone()
|
||||||
|
p['ai_usage_today'] = usage['call_count'] if usage else 0
|
||||||
|
|
||||||
|
return profs
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/profiles/{pid}")
|
||||||
|
def admin_update_profile(pid: str, data: AdminProfileUpdate, session: dict=Depends(require_admin)):
|
||||||
|
"""Admin: Update profile settings."""
|
||||||
|
with get_db() as conn:
|
||||||
|
updates = {k:v for k,v in data.model_dump().items() if v is not None}
|
||||||
|
if not updates:
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(f"UPDATE profiles SET {', '.join(f'{k}=%s' for k in updates)} WHERE id=%s",
|
||||||
|
list(updates.values()) + [pid])
|
||||||
|
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/profiles/{pid}/permissions")
|
||||||
|
def admin_set_permissions(pid: str, data: dict, session: dict=Depends(require_admin)):
|
||||||
|
"""Admin: Set profile permissions."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
updates = []
|
||||||
|
values = []
|
||||||
|
if 'ai_enabled' in data:
|
||||||
|
updates.append('ai_enabled=%s')
|
||||||
|
values.append(data['ai_enabled'])
|
||||||
|
if 'ai_limit_day' in data:
|
||||||
|
updates.append('ai_limit_day=%s')
|
||||||
|
values.append(data['ai_limit_day'])
|
||||||
|
if 'export_enabled' in data:
|
||||||
|
updates.append('export_enabled=%s')
|
||||||
|
values.append(data['export_enabled'])
|
||||||
|
if 'role' in data:
|
||||||
|
updates.append('role=%s')
|
||||||
|
values.append(data['role'])
|
||||||
|
|
||||||
|
if updates:
|
||||||
|
cur.execute(f"UPDATE profiles SET {', '.join(updates)} WHERE id=%s", values + [pid])
|
||||||
|
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/profiles/{pid}/email")
|
||||||
|
def admin_set_email(pid: str, data: dict, session: dict=Depends(require_admin)):
|
||||||
|
"""Admin: Set profile email."""
|
||||||
|
email = data.get('email', '').strip().lower()
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("UPDATE profiles SET email=%s WHERE id=%s", (email if email else None, pid))
|
||||||
|
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/profiles/{pid}/pin")
|
||||||
|
def admin_set_pin(pid: str, data: dict, session: dict=Depends(require_admin)):
|
||||||
|
"""Admin: Set profile PIN/password."""
|
||||||
|
new_pin = data.get('pin', '')
|
||||||
|
if len(new_pin) < 4:
|
||||||
|
raise HTTPException(400, "PIN/Passwort muss mind. 4 Zeichen haben")
|
||||||
|
|
||||||
|
new_hash = hash_pin(new_pin)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, pid))
|
||||||
|
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/email/status")
|
||||||
|
def admin_email_status(session: dict=Depends(require_admin)):
|
||||||
|
"""Admin: Check email configuration status."""
|
||||||
|
smtp_host = os.getenv("SMTP_HOST")
|
||||||
|
smtp_user = os.getenv("SMTP_USER")
|
||||||
|
smtp_pass = os.getenv("SMTP_PASS")
|
||||||
|
app_url = os.getenv("APP_URL", "http://localhost:3002")
|
||||||
|
|
||||||
|
configured = bool(smtp_host and smtp_user and smtp_pass)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"configured": configured,
|
||||||
|
"smtp_host": smtp_host or "",
|
||||||
|
"smtp_user": smtp_user or "",
|
||||||
|
"app_url": app_url
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/email/test")
|
||||||
|
def admin_test_email(data: dict, session: dict=Depends(require_admin)):
|
||||||
|
"""Admin: Send test email."""
|
||||||
|
email = data.get('to', '')
|
||||||
|
if not email:
|
||||||
|
raise HTTPException(400, "E-Mail-Adresse fehlt")
|
||||||
|
|
||||||
|
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")
|
||||||
|
|
||||||
|
if not smtp_host or not smtp_user or not smtp_pass:
|
||||||
|
raise HTTPException(500, "SMTP nicht konfiguriert")
|
||||||
|
|
||||||
|
msg = MIMEText("Dies ist eine Test-E-Mail von Mitai Jinkendo.")
|
||||||
|
msg['Subject'] = "Test-E-Mail"
|
||||||
|
msg['From'] = smtp_from
|
||||||
|
msg['To'] = email
|
||||||
|
|
||||||
|
with smtplib.SMTP(smtp_host, smtp_port) as server:
|
||||||
|
server.starttls()
|
||||||
|
server.login(smtp_user, smtp_pass)
|
||||||
|
server.send_message(msg)
|
||||||
|
|
||||||
|
return {"ok": True, "message": f"Test-E-Mail an {email} gesendet"}
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(500, f"Fehler beim Senden: {str(e)}")
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
"""
|
||||||
|
Authentication Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Handles login, logout, password reset, and profile authentication.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
import smtplib
|
||||||
|
from typing import Optional
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from email.mime.text import MIMEText
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Header, Depends
|
||||||
|
from starlette.requests import Request
|
||||||
|
from slowapi import Limiter
|
||||||
|
from slowapi.util import get_remote_address
|
||||||
|
|
||||||
|
from db import get_db, get_cursor
|
||||||
|
from auth import hash_pin, verify_pin, make_token, require_auth
|
||||||
|
from models import LoginRequest, PasswordResetRequest, PasswordResetConfirm
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||||
|
limiter = Limiter(key_func=get_remote_address)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/login")
|
||||||
|
@limiter.limit("5/minute")
|
||||||
|
async def login(req: LoginRequest, request: Request):
|
||||||
|
"""Login with email + password."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT * FROM profiles WHERE email=%s", (req.email.lower().strip(),))
|
||||||
|
prof = cur.fetchone()
|
||||||
|
if not prof:
|
||||||
|
raise HTTPException(401, "Ungültige Zugangsdaten")
|
||||||
|
|
||||||
|
# Verify password
|
||||||
|
if not verify_pin(req.password, prof['pin_hash']):
|
||||||
|
raise HTTPException(401, "Ungültige Zugangsdaten")
|
||||||
|
|
||||||
|
# Auto-upgrade from SHA256 to bcrypt
|
||||||
|
if prof['pin_hash'] and not prof['pin_hash'].startswith('$2'):
|
||||||
|
new_hash = hash_pin(req.password)
|
||||||
|
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, prof['id']))
|
||||||
|
|
||||||
|
# Create session
|
||||||
|
token = make_token()
|
||||||
|
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.isoformat()))
|
||||||
|
|
||||||
|
return {
|
||||||
|
"token": token,
|
||||||
|
"profile_id": prof['id'],
|
||||||
|
"name": prof['name'],
|
||||||
|
"role": prof['role'],
|
||||||
|
"expires_at": expires.isoformat()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/logout")
|
||||||
|
def logout(x_auth_token: Optional[str]=Header(default=None)):
|
||||||
|
"""Logout (delete session)."""
|
||||||
|
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}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/me")
|
||||||
|
def get_me(session: dict=Depends(require_auth)):
|
||||||
|
"""Get current user info."""
|
||||||
|
pid = session['profile_id']
|
||||||
|
# Import here to avoid circular dependency
|
||||||
|
from routers.profiles import get_profile
|
||||||
|
return get_profile(pid, session)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/status")
|
||||||
|
def auth_status():
|
||||||
|
"""Health check endpoint."""
|
||||||
|
return {"status": "ok", "service": "mitai-jinkendo", "version": "v9b"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/pin")
|
||||||
|
def change_pin(req: dict, session: dict=Depends(require_auth)):
|
||||||
|
"""Change PIN/password for current user."""
|
||||||
|
pid = session['profile_id']
|
||||||
|
new_pin = req.get('pin', '')
|
||||||
|
if len(new_pin) < 4:
|
||||||
|
raise HTTPException(400, "PIN/Passwort muss mind. 4 Zeichen haben")
|
||||||
|
|
||||||
|
new_hash = hash_pin(new_pin)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, pid))
|
||||||
|
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/forgot-password")
|
||||||
|
@limiter.limit("3/minute")
|
||||||
|
async def password_reset_request(req: PasswordResetRequest, request: Request):
|
||||||
|
"""Request password reset email."""
|
||||||
|
email = req.email.lower().strip()
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT id, name FROM profiles WHERE email=%s", (email,))
|
||||||
|
prof = cur.fetchone()
|
||||||
|
if not prof:
|
||||||
|
# Don't reveal if email exists
|
||||||
|
return {"ok": True, "message": "Falls die E-Mail existiert, wurde ein Reset-Link gesendet."}
|
||||||
|
|
||||||
|
# Generate reset token
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
expires = datetime.now() + timedelta(hours=1)
|
||||||
|
|
||||||
|
# Store in sessions table (reuse mechanism)
|
||||||
|
cur.execute("INSERT INTO sessions (token, profile_id, expires_at, created) VALUES (%s,%s,%s,CURRENT_TIMESTAMP)",
|
||||||
|
(f"reset_{token}", prof['id'], expires.isoformat()))
|
||||||
|
|
||||||
|
# Send email
|
||||||
|
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")
|
||||||
|
app_url = os.getenv("APP_URL", "https://mitai.jinkendo.de")
|
||||||
|
|
||||||
|
if smtp_host and smtp_user and smtp_pass:
|
||||||
|
msg = MIMEText(f"""Hallo {prof['name']},
|
||||||
|
|
||||||
|
Du hast einen Passwort-Reset angefordert.
|
||||||
|
|
||||||
|
Reset-Link: {app_url}/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
|
||||||
|
""")
|
||||||
|
msg['Subject'] = "Passwort zurücksetzen – Mitai Jinkendo"
|
||||||
|
msg['From'] = smtp_from
|
||||||
|
msg['To'] = email
|
||||||
|
|
||||||
|
with smtplib.SMTP(smtp_host, smtp_port) as server:
|
||||||
|
server.starttls()
|
||||||
|
server.login(smtp_user, smtp_pass)
|
||||||
|
server.send_message(msg)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Email error: {e}")
|
||||||
|
|
||||||
|
return {"ok": True, "message": "Falls die E-Mail existiert, wurde ein Reset-Link gesendet."}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/reset-password")
|
||||||
|
def password_reset_confirm(req: PasswordResetConfirm):
|
||||||
|
"""Confirm password reset with token."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
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")
|
||||||
|
|
||||||
|
pid = sess['profile_id']
|
||||||
|
new_hash = hash_pin(req.new_password)
|
||||||
|
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, pid))
|
||||||
|
cur.execute("DELETE FROM sessions WHERE token=%s", (f"reset_{req.token}",))
|
||||||
|
|
||||||
|
return {"ok": True, "message": "Passwort erfolgreich zurückgesetzt"}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"""
|
||||||
|
Caliper/Skinfold Tracking Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Handles body fat measurements via skinfold caliper (4 methods supported).
|
||||||
|
"""
|
||||||
|
import uuid
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Header, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth
|
||||||
|
from models import CaliperEntry
|
||||||
|
from routers.profiles import get_pid
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/caliper", tags=["caliper"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def list_caliper(limit: int=100, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Get caliper entries for current profile."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"SELECT * FROM caliper_log WHERE profile_id=%s ORDER BY date DESC LIMIT %s", (pid,limit))
|
||||||
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("")
|
||||||
|
def upsert_caliper(e: CaliperEntry, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Create or update caliper entry (upsert by date)."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT id FROM caliper_log WHERE profile_id=%s AND date=%s", (pid,e.date))
|
||||||
|
ex = cur.fetchone()
|
||||||
|
d = e.model_dump()
|
||||||
|
if ex:
|
||||||
|
eid = ex['id']
|
||||||
|
sets = ', '.join(f"{k}=%s" for k in d if k!='date')
|
||||||
|
cur.execute(f"UPDATE caliper_log SET {sets} WHERE id=%s",
|
||||||
|
[v for k,v in d.items() if k!='date']+[eid])
|
||||||
|
else:
|
||||||
|
eid = str(uuid.uuid4())
|
||||||
|
cur.execute("""INSERT INTO caliper_log
|
||||||
|
(id,profile_id,date,sf_method,sf_chest,sf_axilla,sf_triceps,sf_subscap,sf_suprailiac,
|
||||||
|
sf_abdomen,sf_thigh,sf_calf_med,sf_lowerback,sf_biceps,body_fat_pct,lean_mass,fat_mass,notes,created)
|
||||||
|
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,CURRENT_TIMESTAMP)""",
|
||||||
|
(eid,pid,d['date'],d['sf_method'],d['sf_chest'],d['sf_axilla'],d['sf_triceps'],
|
||||||
|
d['sf_subscap'],d['sf_suprailiac'],d['sf_abdomen'],d['sf_thigh'],d['sf_calf_med'],
|
||||||
|
d['sf_lowerback'],d['sf_biceps'],d['body_fat_pct'],d['lean_mass'],d['fat_mass'],d['notes']))
|
||||||
|
return {"id":eid,"date":e.date}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{eid}")
|
||||||
|
def update_caliper(eid: str, e: CaliperEntry, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Update existing caliper entry."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
d = e.model_dump()
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(f"UPDATE caliper_log SET {', '.join(f'{k}=%s' for k in d)} WHERE id=%s AND profile_id=%s",
|
||||||
|
list(d.values())+[eid,pid])
|
||||||
|
return {"id":eid}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{eid}")
|
||||||
|
def delete_caliper(eid: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Delete caliper entry."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("DELETE FROM caliper_log WHERE id=%s AND profile_id=%s", (eid,pid))
|
||||||
|
return {"ok":True}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
"""
|
||||||
|
Circumference Tracking Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Handles body circumference measurements (8 measurement points).
|
||||||
|
"""
|
||||||
|
import uuid
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Header, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth
|
||||||
|
from models import CircumferenceEntry
|
||||||
|
from routers.profiles import get_pid
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/circumferences", tags=["circumference"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def list_circs(limit: int=100, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Get circumference entries for current profile."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"SELECT * FROM circumference_log WHERE profile_id=%s ORDER BY date DESC LIMIT %s", (pid,limit))
|
||||||
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("")
|
||||||
|
def upsert_circ(e: CircumferenceEntry, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Create or update circumference entry (upsert by date)."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT id FROM circumference_log WHERE profile_id=%s AND date=%s", (pid,e.date))
|
||||||
|
ex = cur.fetchone()
|
||||||
|
d = e.model_dump()
|
||||||
|
if ex:
|
||||||
|
eid = ex['id']
|
||||||
|
sets = ', '.join(f"{k}=%s" for k in d if k!='date')
|
||||||
|
cur.execute(f"UPDATE circumference_log SET {sets} WHERE id=%s",
|
||||||
|
[v for k,v in d.items() if k!='date']+[eid])
|
||||||
|
else:
|
||||||
|
eid = str(uuid.uuid4())
|
||||||
|
cur.execute("""INSERT INTO circumference_log
|
||||||
|
(id,profile_id,date,c_neck,c_chest,c_waist,c_belly,c_hip,c_thigh,c_calf,c_arm,notes,photo_id,created)
|
||||||
|
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,CURRENT_TIMESTAMP)""",
|
||||||
|
(eid,pid,d['date'],d['c_neck'],d['c_chest'],d['c_waist'],d['c_belly'],
|
||||||
|
d['c_hip'],d['c_thigh'],d['c_calf'],d['c_arm'],d['notes'],d['photo_id']))
|
||||||
|
return {"id":eid,"date":e.date}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{eid}")
|
||||||
|
def update_circ(eid: str, e: CircumferenceEntry, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Update existing circumference entry."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
d = e.model_dump()
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(f"UPDATE circumference_log SET {', '.join(f'{k}=%s' for k in d)} WHERE id=%s AND profile_id=%s",
|
||||||
|
list(d.values())+[eid,pid])
|
||||||
|
return {"id":eid}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{eid}")
|
||||||
|
def delete_circ(eid: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Delete circumference entry."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("DELETE FROM circumference_log WHERE id=%s AND profile_id=%s", (eid,pid))
|
||||||
|
return {"ok":True}
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
"""
|
||||||
|
Coupon Management Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Handles coupon CRUD (admin) and redemption (users).
|
||||||
|
"""
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Optional
|
||||||
|
from fastapi import APIRouter, HTTPException, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth, require_admin
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/coupons", tags=["coupons"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def list_coupons(session: dict = Depends(require_admin)):
|
||||||
|
"""Admin: List all coupons with redemption stats."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("""
|
||||||
|
SELECT
|
||||||
|
c.*,
|
||||||
|
t.name as tier_name,
|
||||||
|
(SELECT COUNT(*) FROM coupon_redemptions WHERE coupon_id = c.id) as redemptions
|
||||||
|
FROM coupons c
|
||||||
|
LEFT JOIN tiers t ON t.id = c.tier_id
|
||||||
|
ORDER BY c.created DESC
|
||||||
|
""")
|
||||||
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("")
|
||||||
|
def create_coupon(data: dict, session: dict = Depends(require_admin)):
|
||||||
|
"""
|
||||||
|
Admin: Create new coupon.
|
||||||
|
|
||||||
|
Required fields:
|
||||||
|
- code: Unique coupon code
|
||||||
|
- type: 'single_use', 'period', or 'wellpass'
|
||||||
|
- tier_id: Target tier
|
||||||
|
- duration_days: For period/wellpass coupons
|
||||||
|
|
||||||
|
Optional fields:
|
||||||
|
- max_redemptions: NULL = unlimited
|
||||||
|
- valid_from, valid_until: Validity period
|
||||||
|
- description: Internal note
|
||||||
|
"""
|
||||||
|
code = data.get('code', '').strip().upper()
|
||||||
|
coupon_type = data.get('type')
|
||||||
|
tier_id = data.get('tier_id')
|
||||||
|
duration_days = data.get('duration_days')
|
||||||
|
max_redemptions = data.get('max_redemptions')
|
||||||
|
valid_from = data.get('valid_from')
|
||||||
|
valid_until = data.get('valid_until')
|
||||||
|
description = data.get('description', '')
|
||||||
|
|
||||||
|
if not code:
|
||||||
|
raise HTTPException(400, "Coupon-Code fehlt")
|
||||||
|
if coupon_type not in ['single_use', 'period', 'wellpass']:
|
||||||
|
raise HTTPException(400, "Ungültiger Coupon-Typ")
|
||||||
|
if not tier_id:
|
||||||
|
raise HTTPException(400, "Tier fehlt")
|
||||||
|
if coupon_type in ['period', 'wellpass'] and not duration_days:
|
||||||
|
raise HTTPException(400, "duration_days fehlt für period/wellpass Coupons")
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Check if code already exists
|
||||||
|
cur.execute("SELECT id FROM coupons WHERE code = %s", (code,))
|
||||||
|
if cur.fetchone():
|
||||||
|
raise HTTPException(400, f"Coupon-Code '{code}' existiert bereits")
|
||||||
|
|
||||||
|
# Create coupon
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO coupons (
|
||||||
|
code, type, tier_id, duration_days, max_redemptions,
|
||||||
|
valid_from, valid_until, description, created_by
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""", (
|
||||||
|
code, coupon_type, tier_id, duration_days, max_redemptions,
|
||||||
|
valid_from, valid_until, description, session['profile_id']
|
||||||
|
))
|
||||||
|
|
||||||
|
coupon_id = cur.fetchone()['id']
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {"ok": True, "id": coupon_id, "code": code}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{coupon_id}")
|
||||||
|
def update_coupon(coupon_id: str, data: dict, session: dict = Depends(require_admin)):
|
||||||
|
"""Admin: Update coupon."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
updates = []
|
||||||
|
values = []
|
||||||
|
|
||||||
|
if 'active' in data:
|
||||||
|
updates.append('active = %s')
|
||||||
|
values.append(data['active'])
|
||||||
|
if 'max_redemptions' in data:
|
||||||
|
updates.append('max_redemptions = %s')
|
||||||
|
values.append(data['max_redemptions'])
|
||||||
|
if 'valid_until' in data:
|
||||||
|
updates.append('valid_until = %s')
|
||||||
|
values.append(data['valid_until'])
|
||||||
|
if 'description' in data:
|
||||||
|
updates.append('description = %s')
|
||||||
|
values.append(data['description'])
|
||||||
|
|
||||||
|
if not updates:
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
updates.append('updated = CURRENT_TIMESTAMP')
|
||||||
|
values.append(coupon_id)
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
f"UPDATE coupons SET {', '.join(updates)} WHERE id = %s",
|
||||||
|
values
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{coupon_id}")
|
||||||
|
def delete_coupon(coupon_id: str, session: dict = Depends(require_admin)):
|
||||||
|
"""Admin: Delete coupon (soft-delete: set active=false)."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("UPDATE coupons SET active = false WHERE id = %s", (coupon_id,))
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{coupon_id}/redemptions")
|
||||||
|
def get_coupon_redemptions(coupon_id: str, session: dict = Depends(require_admin)):
|
||||||
|
"""Admin: Get all redemptions for a coupon."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("""
|
||||||
|
SELECT
|
||||||
|
cr.id,
|
||||||
|
cr.redeemed_at,
|
||||||
|
p.name as profile_name,
|
||||||
|
p.email as profile_email,
|
||||||
|
ag.valid_from,
|
||||||
|
ag.valid_until,
|
||||||
|
ag.is_active
|
||||||
|
FROM coupon_redemptions cr
|
||||||
|
JOIN profiles p ON p.id = cr.profile_id
|
||||||
|
LEFT JOIN access_grants ag ON ag.id = cr.access_grant_id
|
||||||
|
WHERE cr.coupon_id = %s
|
||||||
|
ORDER BY cr.redeemed_at DESC
|
||||||
|
""", (coupon_id,))
|
||||||
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/redeem")
|
||||||
|
def redeem_coupon(data: dict, session: dict = Depends(require_auth)):
|
||||||
|
"""
|
||||||
|
User: Redeem a coupon code.
|
||||||
|
|
||||||
|
Creates an access_grant and handles Wellpass pause/resume logic.
|
||||||
|
"""
|
||||||
|
code = data.get('code', '').strip().upper()
|
||||||
|
if not code:
|
||||||
|
raise HTTPException(400, "Coupon-Code fehlt")
|
||||||
|
|
||||||
|
profile_id = session['profile_id']
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Get coupon
|
||||||
|
cur.execute("""
|
||||||
|
SELECT * FROM coupons
|
||||||
|
WHERE code = %s AND active = true
|
||||||
|
""", (code,))
|
||||||
|
coupon = cur.fetchone()
|
||||||
|
|
||||||
|
if not coupon:
|
||||||
|
raise HTTPException(404, "Ungültiger Coupon-Code")
|
||||||
|
|
||||||
|
# Check validity period
|
||||||
|
now = datetime.now()
|
||||||
|
if coupon['valid_from'] and now < coupon['valid_from']:
|
||||||
|
raise HTTPException(400, "Coupon noch nicht gültig")
|
||||||
|
if coupon['valid_until'] and now > coupon['valid_until']:
|
||||||
|
raise HTTPException(400, "Coupon abgelaufen")
|
||||||
|
|
||||||
|
# Check max redemptions
|
||||||
|
if coupon['max_redemptions'] is not None:
|
||||||
|
if coupon['redemption_count'] >= coupon['max_redemptions']:
|
||||||
|
raise HTTPException(400, "Coupon bereits vollständig eingelöst")
|
||||||
|
|
||||||
|
# Check if user already redeemed this coupon
|
||||||
|
cur.execute("""
|
||||||
|
SELECT id FROM coupon_redemptions
|
||||||
|
WHERE coupon_id = %s AND profile_id = %s
|
||||||
|
""", (coupon['id'], profile_id))
|
||||||
|
if cur.fetchone():
|
||||||
|
raise HTTPException(400, "Du hast diesen Coupon bereits eingelöst")
|
||||||
|
|
||||||
|
# Create access grant
|
||||||
|
valid_from = now
|
||||||
|
valid_until = now + timedelta(days=coupon['duration_days']) if coupon['duration_days'] else None
|
||||||
|
|
||||||
|
# Wellpass logic: Pause existing personal grants
|
||||||
|
if coupon['type'] == 'wellpass':
|
||||||
|
cur.execute("""
|
||||||
|
SELECT id, valid_until
|
||||||
|
FROM access_grants
|
||||||
|
WHERE profile_id = %s
|
||||||
|
AND is_active = true
|
||||||
|
AND granted_by != 'wellpass'
|
||||||
|
AND valid_until > CURRENT_TIMESTAMP
|
||||||
|
""", (profile_id,))
|
||||||
|
active_grants = cur.fetchall()
|
||||||
|
|
||||||
|
for grant in active_grants:
|
||||||
|
# Calculate remaining days
|
||||||
|
remaining = (grant['valid_until'] - now).days
|
||||||
|
# Pause grant
|
||||||
|
cur.execute("""
|
||||||
|
UPDATE access_grants
|
||||||
|
SET is_active = false,
|
||||||
|
paused_at = CURRENT_TIMESTAMP,
|
||||||
|
remaining_days = %s
|
||||||
|
WHERE id = %s
|
||||||
|
""", (remaining, grant['id']))
|
||||||
|
|
||||||
|
# Insert access grant
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO access_grants (
|
||||||
|
profile_id, tier_id, granted_by, coupon_id,
|
||||||
|
valid_from, valid_until, is_active
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s, true)
|
||||||
|
RETURNING id
|
||||||
|
""", (
|
||||||
|
profile_id, coupon['tier_id'],
|
||||||
|
coupon['type'], coupon['id'],
|
||||||
|
valid_from, valid_until
|
||||||
|
))
|
||||||
|
grant_id = cur.fetchone()['id']
|
||||||
|
|
||||||
|
# Record redemption
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO coupon_redemptions (coupon_id, profile_id, access_grant_id)
|
||||||
|
VALUES (%s, %s, %s)
|
||||||
|
""", (coupon['id'], profile_id, grant_id))
|
||||||
|
|
||||||
|
# Increment coupon redemption count
|
||||||
|
cur.execute("""
|
||||||
|
UPDATE coupons
|
||||||
|
SET redemption_count = redemption_count + 1
|
||||||
|
WHERE id = %s
|
||||||
|
""", (coupon['id'],))
|
||||||
|
|
||||||
|
# Log activity
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO user_activity_log (profile_id, action, details)
|
||||||
|
VALUES (%s, 'coupon_redeemed', %s)
|
||||||
|
""", (
|
||||||
|
profile_id,
|
||||||
|
f'{{"coupon_code": "{code}", "tier": "{coupon["tier_id"]}", "duration_days": {coupon["duration_days"]}}}'
|
||||||
|
))
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"message": f"Coupon erfolgreich eingelöst: {coupon['tier_id']} für {coupon['duration_days']} Tage",
|
||||||
|
"grant_id": grant_id,
|
||||||
|
"valid_until": valid_until.isoformat() if valid_until else None
|
||||||
|
}
|
||||||
@@ -0,0 +1,304 @@
|
|||||||
|
"""
|
||||||
|
Data Export Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Handles CSV, JSON, and ZIP exports with photos.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import zipfile
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
from datetime import datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Header, Depends
|
||||||
|
from fastapi.responses import StreamingResponse, Response
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth
|
||||||
|
from routers.profiles import get_pid
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/export", tags=["export"])
|
||||||
|
|
||||||
|
PHOTOS_DIR = Path(os.getenv("PHOTOS_DIR", "./photos"))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/csv")
|
||||||
|
def export_csv(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Export all data as CSV."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
|
||||||
|
# Check export permission
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT export_enabled FROM profiles WHERE id=%s", (pid,))
|
||||||
|
prof = cur.fetchone()
|
||||||
|
if not prof or not prof['export_enabled']:
|
||||||
|
raise HTTPException(403, "Export ist für dieses Profil deaktiviert")
|
||||||
|
|
||||||
|
# Build CSV
|
||||||
|
output = io.StringIO()
|
||||||
|
writer = csv.writer(output)
|
||||||
|
|
||||||
|
# Header
|
||||||
|
writer.writerow(["Typ", "Datum", "Wert", "Details"])
|
||||||
|
|
||||||
|
# Weight
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT date, weight, note FROM weight_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||||
|
for r in cur.fetchall():
|
||||||
|
writer.writerow(["Gewicht", r['date'], f"{float(r['weight'])}kg", r['note'] or ""])
|
||||||
|
|
||||||
|
# Circumferences
|
||||||
|
cur.execute("SELECT date, c_waist, c_belly, c_hip FROM circumference_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||||
|
for r in cur.fetchall():
|
||||||
|
details = f"Taille:{float(r['c_waist'])}cm Bauch:{float(r['c_belly'])}cm Hüfte:{float(r['c_hip'])}cm"
|
||||||
|
writer.writerow(["Umfänge", r['date'], "", details])
|
||||||
|
|
||||||
|
# Caliper
|
||||||
|
cur.execute("SELECT date, body_fat_pct, lean_mass FROM caliper_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||||
|
for r in cur.fetchall():
|
||||||
|
writer.writerow(["Caliper", r['date'], f"{float(r['body_fat_pct'])}%", f"Magermasse:{float(r['lean_mass'])}kg"])
|
||||||
|
|
||||||
|
# Nutrition
|
||||||
|
cur.execute("SELECT date, kcal, protein_g FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||||
|
for r in cur.fetchall():
|
||||||
|
writer.writerow(["Ernährung", r['date'], f"{float(r['kcal'])}kcal", f"Protein:{float(r['protein_g'])}g"])
|
||||||
|
|
||||||
|
# Activity
|
||||||
|
cur.execute("SELECT date, activity_type, duration_min, kcal_active FROM activity_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||||
|
for r in cur.fetchall():
|
||||||
|
writer.writerow(["Training", r['date'], r['activity_type'], f"{float(r['duration_min'])}min {float(r['kcal_active'])}kcal"])
|
||||||
|
|
||||||
|
output.seek(0)
|
||||||
|
return StreamingResponse(
|
||||||
|
iter([output.getvalue()]),
|
||||||
|
media_type="text/csv",
|
||||||
|
headers={"Content-Disposition": f"attachment; filename=mitai-export-{pid}.csv"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/json")
|
||||||
|
def export_json(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Export all data as JSON."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
|
||||||
|
# Check export permission
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT export_enabled FROM profiles WHERE id=%s", (pid,))
|
||||||
|
prof = cur.fetchone()
|
||||||
|
if not prof or not prof['export_enabled']:
|
||||||
|
raise HTTPException(403, "Export ist für dieses Profil deaktiviert")
|
||||||
|
|
||||||
|
# Collect all data
|
||||||
|
data = {}
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||||
|
data['profile'] = r2d(cur.fetchone())
|
||||||
|
|
||||||
|
cur.execute("SELECT * FROM weight_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||||
|
data['weight'] = [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
cur.execute("SELECT * FROM circumference_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||||
|
data['circumferences'] = [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
cur.execute("SELECT * FROM caliper_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||||
|
data['caliper'] = [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
cur.execute("SELECT * FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||||
|
data['nutrition'] = [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
cur.execute("SELECT * FROM activity_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||||
|
data['activity'] = [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,))
|
||||||
|
data['insights'] = [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
def decimal_handler(obj):
|
||||||
|
if isinstance(obj, Decimal):
|
||||||
|
return float(obj)
|
||||||
|
return str(obj)
|
||||||
|
|
||||||
|
json_str = json.dumps(data, indent=2, default=decimal_handler)
|
||||||
|
return Response(
|
||||||
|
content=json_str,
|
||||||
|
media_type="application/json",
|
||||||
|
headers={"Content-Disposition": f"attachment; filename=mitai-export-{pid}.json"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/zip")
|
||||||
|
def export_zip(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Export all data as ZIP (CSV + JSON + photos) per specification."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
|
||||||
|
# Check export permission & get profile
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||||
|
prof = r2d(cur.fetchone())
|
||||||
|
if not prof or not prof.get('export_enabled'):
|
||||||
|
raise HTTPException(403, "Export ist für dieses Profil deaktiviert")
|
||||||
|
|
||||||
|
# Helper: CSV writer with UTF-8 BOM + semicolon
|
||||||
|
def write_csv(zf, filename, rows, columns):
|
||||||
|
if not rows:
|
||||||
|
return
|
||||||
|
output = io.StringIO()
|
||||||
|
writer = csv.writer(output, delimiter=';')
|
||||||
|
writer.writerow(columns)
|
||||||
|
for r in rows:
|
||||||
|
writer.writerow([
|
||||||
|
'' if r.get(col) is None else
|
||||||
|
(float(r[col]) if isinstance(r.get(col), Decimal) else r[col])
|
||||||
|
for col in columns
|
||||||
|
])
|
||||||
|
# UTF-8 with BOM for Excel
|
||||||
|
csv_bytes = '\ufeff'.encode('utf-8') + output.getvalue().encode('utf-8')
|
||||||
|
zf.writestr(f"data/{filename}", csv_bytes)
|
||||||
|
|
||||||
|
# Create ZIP
|
||||||
|
zip_buffer = io.BytesIO()
|
||||||
|
export_date = datetime.now().strftime('%Y-%m-%d')
|
||||||
|
profile_name = prof.get('name', 'export')
|
||||||
|
|
||||||
|
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zf:
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# 1. README.txt
|
||||||
|
readme = f"""Mitai Jinkendo – Datenexport
|
||||||
|
Version: 2
|
||||||
|
Exportiert am: {export_date}
|
||||||
|
Profil: {profile_name}
|
||||||
|
|
||||||
|
Inhalt:
|
||||||
|
- profile.json: Profildaten und Einstellungen
|
||||||
|
- data/*.csv: Messdaten (Semikolon-getrennt, UTF-8)
|
||||||
|
- insights/: KI-Auswertungen (JSON)
|
||||||
|
- photos/: Progress-Fotos (JPEG)
|
||||||
|
|
||||||
|
Import:
|
||||||
|
Dieser Export kann in Mitai Jinkendo unter
|
||||||
|
Einstellungen → Import → "Mitai Backup importieren"
|
||||||
|
wieder eingespielt werden.
|
||||||
|
|
||||||
|
Format-Version 2 (ab v9b):
|
||||||
|
Alle CSV-Dateien sind UTF-8 mit BOM kodiert.
|
||||||
|
Trennzeichen: Semikolon (;)
|
||||||
|
Datumsformat: YYYY-MM-DD
|
||||||
|
"""
|
||||||
|
zf.writestr("README.txt", readme.encode('utf-8'))
|
||||||
|
|
||||||
|
# 2. profile.json (ohne Passwort-Hash)
|
||||||
|
cur.execute("SELECT COUNT(*) as c FROM weight_log WHERE profile_id=%s", (pid,))
|
||||||
|
w_count = cur.fetchone()['c']
|
||||||
|
cur.execute("SELECT COUNT(*) as c FROM nutrition_log WHERE profile_id=%s", (pid,))
|
||||||
|
n_count = cur.fetchone()['c']
|
||||||
|
cur.execute("SELECT COUNT(*) as c FROM activity_log WHERE profile_id=%s", (pid,))
|
||||||
|
a_count = cur.fetchone()['c']
|
||||||
|
cur.execute("SELECT COUNT(*) as c FROM photos WHERE profile_id=%s", (pid,))
|
||||||
|
p_count = cur.fetchone()['c']
|
||||||
|
|
||||||
|
profile_data = {
|
||||||
|
"export_version": "2",
|
||||||
|
"export_date": export_date,
|
||||||
|
"app": "Mitai Jinkendo",
|
||||||
|
"profile": {
|
||||||
|
"name": prof.get('name'),
|
||||||
|
"email": prof.get('email'),
|
||||||
|
"sex": prof.get('sex'),
|
||||||
|
"height": float(prof['height']) if prof.get('height') else None,
|
||||||
|
"birth_year": prof['dob'].year if prof.get('dob') else None,
|
||||||
|
"goal_weight": float(prof['goal_weight']) if prof.get('goal_weight') else None,
|
||||||
|
"goal_bf_pct": float(prof['goal_bf_pct']) if prof.get('goal_bf_pct') else None,
|
||||||
|
"avatar_color": prof.get('avatar_color'),
|
||||||
|
"auth_type": prof.get('auth_type'),
|
||||||
|
"session_days": prof.get('session_days'),
|
||||||
|
"ai_enabled": prof.get('ai_enabled'),
|
||||||
|
"tier": prof.get('tier')
|
||||||
|
},
|
||||||
|
"stats": {
|
||||||
|
"weight_entries": w_count,
|
||||||
|
"nutrition_entries": n_count,
|
||||||
|
"activity_entries": a_count,
|
||||||
|
"photos": p_count
|
||||||
|
}
|
||||||
|
}
|
||||||
|
zf.writestr("profile.json", json.dumps(profile_data, indent=2, ensure_ascii=False).encode('utf-8'))
|
||||||
|
|
||||||
|
# 3-7. CSV exports (weight, circumferences, caliper, nutrition, activity)
|
||||||
|
cur.execute("SELECT id, date, weight, note, source, created FROM weight_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||||
|
write_csv(zf, "weight.csv", [r2d(r) for r in cur.fetchall()], ['id','date','weight','note','source','created'])
|
||||||
|
|
||||||
|
cur.execute("SELECT id, date, c_waist, c_hip, c_chest, c_neck, c_arm, c_thigh, c_calf, notes, created FROM circumference_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||||
|
rows = [r2d(r) for r in cur.fetchall()]
|
||||||
|
for r in rows:
|
||||||
|
r['waist'] = r.pop('c_waist', None); r['hip'] = r.pop('c_hip', None)
|
||||||
|
r['chest'] = r.pop('c_chest', None); r['neck'] = r.pop('c_neck', None)
|
||||||
|
r['upper_arm'] = r.pop('c_arm', None); r['thigh'] = r.pop('c_thigh', None)
|
||||||
|
r['calf'] = r.pop('c_calf', None); r['forearm'] = None; r['note'] = r.pop('notes', None)
|
||||||
|
write_csv(zf, "circumferences.csv", rows, ['id','date','waist','hip','chest','neck','upper_arm','thigh','calf','forearm','note','created'])
|
||||||
|
|
||||||
|
cur.execute("SELECT id, date, sf_chest, sf_abdomen, sf_thigh, sf_triceps, sf_subscap, sf_suprailiac, sf_axilla, sf_method, body_fat_pct, notes, created FROM caliper_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||||
|
rows = [r2d(r) for r in cur.fetchall()]
|
||||||
|
for r in rows:
|
||||||
|
r['chest'] = r.pop('sf_chest', None); r['abdomen'] = r.pop('sf_abdomen', None)
|
||||||
|
r['thigh'] = r.pop('sf_thigh', None); r['tricep'] = r.pop('sf_triceps', None)
|
||||||
|
r['subscapular'] = r.pop('sf_subscap', None); r['suprailiac'] = r.pop('sf_suprailiac', None)
|
||||||
|
r['midaxillary'] = r.pop('sf_axilla', None); r['method'] = r.pop('sf_method', None)
|
||||||
|
r['bf_percent'] = r.pop('body_fat_pct', None); r['note'] = r.pop('notes', None)
|
||||||
|
write_csv(zf, "caliper.csv", rows, ['id','date','chest','abdomen','thigh','tricep','subscapular','suprailiac','midaxillary','method','bf_percent','note','created'])
|
||||||
|
|
||||||
|
cur.execute("SELECT id, date, kcal, protein_g, fat_g, carbs_g, source, created FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||||
|
rows = [r2d(r) for r in cur.fetchall()]
|
||||||
|
for r in rows:
|
||||||
|
r['meal_name'] = ''; r['protein'] = r.pop('protein_g', None)
|
||||||
|
r['fat'] = r.pop('fat_g', None); r['carbs'] = r.pop('carbs_g', None)
|
||||||
|
r['fiber'] = None; r['note'] = ''
|
||||||
|
write_csv(zf, "nutrition.csv", rows, ['id','date','meal_name','kcal','protein','fat','carbs','fiber','note','source','created'])
|
||||||
|
|
||||||
|
cur.execute("SELECT id, date, activity_type, duration_min, kcal_active, hr_avg, hr_max, distance_km, notes, source, created FROM activity_log WHERE profile_id=%s ORDER BY date", (pid,))
|
||||||
|
rows = [r2d(r) for r in cur.fetchall()]
|
||||||
|
for r in rows:
|
||||||
|
r['name'] = r['activity_type']; r['type'] = r.pop('activity_type', None)
|
||||||
|
r['kcal'] = r.pop('kcal_active', None); r['heart_rate_avg'] = r.pop('hr_avg', None)
|
||||||
|
r['heart_rate_max'] = r.pop('hr_max', None); r['note'] = r.pop('notes', None)
|
||||||
|
write_csv(zf, "activity.csv", rows, ['id','date','name','type','duration_min','kcal','heart_rate_avg','heart_rate_max','distance_km','note','source','created'])
|
||||||
|
|
||||||
|
# 8. insights/ai_insights.json
|
||||||
|
cur.execute("SELECT id, scope, content, created FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,))
|
||||||
|
insights = []
|
||||||
|
for r in cur.fetchall():
|
||||||
|
rd = r2d(r)
|
||||||
|
insights.append({
|
||||||
|
"id": rd['id'],
|
||||||
|
"scope": rd['scope'],
|
||||||
|
"created": rd['created'].isoformat() if hasattr(rd['created'], 'isoformat') else str(rd['created']),
|
||||||
|
"result": rd['content']
|
||||||
|
})
|
||||||
|
if insights:
|
||||||
|
zf.writestr("insights/ai_insights.json", json.dumps(insights, indent=2, ensure_ascii=False).encode('utf-8'))
|
||||||
|
|
||||||
|
# 9. photos/
|
||||||
|
cur.execute("SELECT * FROM photos WHERE profile_id=%s ORDER BY date", (pid,))
|
||||||
|
photos = [r2d(r) for r in cur.fetchall()]
|
||||||
|
for i, photo in enumerate(photos):
|
||||||
|
photo_path = Path(PHOTOS_DIR) / photo['path']
|
||||||
|
if photo_path.exists():
|
||||||
|
filename = f"{photo.get('date') or export_date}_{i+1}{photo_path.suffix}"
|
||||||
|
zf.write(photo_path, f"photos/{filename}")
|
||||||
|
|
||||||
|
zip_buffer.seek(0)
|
||||||
|
filename = f"mitai-export-{profile_name.replace(' ','-')}-{export_date}.zip"
|
||||||
|
return StreamingResponse(
|
||||||
|
iter([zip_buffer.getvalue()]),
|
||||||
|
media_type="application/zip",
|
||||||
|
headers={"Content-Disposition": f"attachment; filename={filename}"}
|
||||||
|
)
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
"""
|
||||||
|
Feature Management Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Admin-only CRUD for features registry.
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter, HTTPException, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_admin
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/features", tags=["features"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def list_features(session: dict = Depends(require_admin)):
|
||||||
|
"""Admin: List all features."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("""
|
||||||
|
SELECT * FROM features
|
||||||
|
ORDER BY category, name
|
||||||
|
""")
|
||||||
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("")
|
||||||
|
def create_feature(data: dict, session: dict = Depends(require_admin)):
|
||||||
|
"""
|
||||||
|
Admin: Create new feature.
|
||||||
|
|
||||||
|
Required fields:
|
||||||
|
- id: Feature ID (e.g., 'new_data_source')
|
||||||
|
- name: Display name
|
||||||
|
- category: 'data', 'ai', 'export', 'integration'
|
||||||
|
- limit_type: 'count' or 'boolean'
|
||||||
|
- reset_period: 'never', 'daily', 'monthly'
|
||||||
|
- default_limit: INT or NULL (unlimited)
|
||||||
|
"""
|
||||||
|
feature_id = data.get('id', '').strip()
|
||||||
|
name = data.get('name', '').strip()
|
||||||
|
description = data.get('description', '')
|
||||||
|
category = data.get('category')
|
||||||
|
limit_type = data.get('limit_type', 'count')
|
||||||
|
reset_period = data.get('reset_period', 'never')
|
||||||
|
default_limit = data.get('default_limit')
|
||||||
|
|
||||||
|
if not feature_id or not name:
|
||||||
|
raise HTTPException(400, "ID und Name fehlen")
|
||||||
|
if category not in ['data', 'ai', 'export', 'integration']:
|
||||||
|
raise HTTPException(400, "Ungültige Kategorie")
|
||||||
|
if limit_type not in ['count', 'boolean']:
|
||||||
|
raise HTTPException(400, "limit_type muss 'count' oder 'boolean' sein")
|
||||||
|
if reset_period not in ['never', 'daily', 'monthly']:
|
||||||
|
raise HTTPException(400, "Ungültiger reset_period")
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Check if ID already exists
|
||||||
|
cur.execute("SELECT id FROM features WHERE id = %s", (feature_id,))
|
||||||
|
if cur.fetchone():
|
||||||
|
raise HTTPException(400, f"Feature '{feature_id}' existiert bereits")
|
||||||
|
|
||||||
|
# Create feature
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO features (
|
||||||
|
id, name, description, category, limit_type, reset_period, default_limit
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||||
|
""", (feature_id, name, description, category, limit_type, reset_period, default_limit))
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {"ok": True, "id": feature_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{feature_id}")
|
||||||
|
def update_feature(feature_id: str, data: dict, session: dict = Depends(require_admin)):
|
||||||
|
"""Admin: Update feature."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
updates = []
|
||||||
|
values = []
|
||||||
|
|
||||||
|
if 'name' in data:
|
||||||
|
updates.append('name = %s')
|
||||||
|
values.append(data['name'])
|
||||||
|
if 'description' in data:
|
||||||
|
updates.append('description = %s')
|
||||||
|
values.append(data['description'])
|
||||||
|
if 'default_limit' in data:
|
||||||
|
updates.append('default_limit = %s')
|
||||||
|
values.append(data['default_limit'])
|
||||||
|
if 'active' in data:
|
||||||
|
updates.append('active = %s')
|
||||||
|
values.append(data['active'])
|
||||||
|
|
||||||
|
if not updates:
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
updates.append('updated = CURRENT_TIMESTAMP')
|
||||||
|
values.append(feature_id)
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
f"UPDATE features SET {', '.join(updates)} WHERE id = %s",
|
||||||
|
values
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{feature_id}")
|
||||||
|
def delete_feature(feature_id: str, session: dict = Depends(require_admin)):
|
||||||
|
"""Admin: Delete feature (soft-delete: set active=false)."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("UPDATE features SET active = false WHERE id = %s", (feature_id,))
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True}
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
"""
|
||||||
|
Data Import Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Handles ZIP import with validation and rollback support.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
import zipfile
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, UploadFile, File, Header, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor
|
||||||
|
from auth import require_auth
|
||||||
|
from routers.profiles import get_pid
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/import", tags=["import"])
|
||||||
|
|
||||||
|
PHOTOS_DIR = Path(os.getenv("PHOTOS_DIR", "./photos"))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/zip")
|
||||||
|
async def import_zip(
|
||||||
|
file: UploadFile = File(...),
|
||||||
|
x_profile_id: Optional[str] = Header(default=None),
|
||||||
|
session: dict = Depends(require_auth)
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Import data from ZIP export file.
|
||||||
|
|
||||||
|
- Validates export format
|
||||||
|
- Imports missing entries only (ON CONFLICT DO NOTHING)
|
||||||
|
- Imports photos
|
||||||
|
- Returns import summary
|
||||||
|
- Full rollback on error
|
||||||
|
"""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
|
||||||
|
# Read uploaded file
|
||||||
|
content = await file.read()
|
||||||
|
zip_buffer = io.BytesIO(content)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with zipfile.ZipFile(zip_buffer, 'r') as zf:
|
||||||
|
# 1. Validate profile.json
|
||||||
|
if 'profile.json' not in zf.namelist():
|
||||||
|
raise HTTPException(400, "Ungültiger Export: profile.json fehlt")
|
||||||
|
|
||||||
|
profile_data = json.loads(zf.read('profile.json').decode('utf-8'))
|
||||||
|
export_version = profile_data.get('export_version', '1')
|
||||||
|
|
||||||
|
# Stats tracker
|
||||||
|
stats = {
|
||||||
|
'weight': 0,
|
||||||
|
'circumferences': 0,
|
||||||
|
'caliper': 0,
|
||||||
|
'nutrition': 0,
|
||||||
|
'activity': 0,
|
||||||
|
'photos': 0,
|
||||||
|
'insights': 0
|
||||||
|
}
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 2. Import weight.csv
|
||||||
|
if 'data/weight.csv' in zf.namelist():
|
||||||
|
csv_data = zf.read('data/weight.csv').decode('utf-8-sig')
|
||||||
|
reader = csv.DictReader(io.StringIO(csv_data), delimiter=';')
|
||||||
|
for row in reader:
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO weight_log (profile_id, date, weight, note, source, created)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s)
|
||||||
|
ON CONFLICT (profile_id, date) DO NOTHING
|
||||||
|
""", (
|
||||||
|
pid,
|
||||||
|
row['date'],
|
||||||
|
float(row['weight']) if row['weight'] else None,
|
||||||
|
row.get('note', ''),
|
||||||
|
row.get('source', 'import'),
|
||||||
|
row.get('created', datetime.now())
|
||||||
|
))
|
||||||
|
if cur.rowcount > 0:
|
||||||
|
stats['weight'] += 1
|
||||||
|
|
||||||
|
# 3. Import circumferences.csv
|
||||||
|
if 'data/circumferences.csv' in zf.namelist():
|
||||||
|
csv_data = zf.read('data/circumferences.csv').decode('utf-8-sig')
|
||||||
|
reader = csv.DictReader(io.StringIO(csv_data), delimiter=';')
|
||||||
|
for row in reader:
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO circumference_log (
|
||||||
|
profile_id, date, c_waist, c_hip, c_chest, c_neck,
|
||||||
|
c_arm, c_thigh, c_calf, notes, created
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
|
ON CONFLICT (profile_id, date) DO NOTHING
|
||||||
|
""", (
|
||||||
|
pid,
|
||||||
|
row['date'],
|
||||||
|
float(row['waist']) if row.get('waist') else None,
|
||||||
|
float(row['hip']) if row.get('hip') else None,
|
||||||
|
float(row['chest']) if row.get('chest') else None,
|
||||||
|
float(row['neck']) if row.get('neck') else None,
|
||||||
|
float(row['upper_arm']) if row.get('upper_arm') else None,
|
||||||
|
float(row['thigh']) if row.get('thigh') else None,
|
||||||
|
float(row['calf']) if row.get('calf') else None,
|
||||||
|
row.get('note', ''),
|
||||||
|
row.get('created', datetime.now())
|
||||||
|
))
|
||||||
|
if cur.rowcount > 0:
|
||||||
|
stats['circumferences'] += 1
|
||||||
|
|
||||||
|
# 4. Import caliper.csv
|
||||||
|
if 'data/caliper.csv' in zf.namelist():
|
||||||
|
csv_data = zf.read('data/caliper.csv').decode('utf-8-sig')
|
||||||
|
reader = csv.DictReader(io.StringIO(csv_data), delimiter=';')
|
||||||
|
for row in reader:
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO caliper_log (
|
||||||
|
profile_id, date, sf_chest, sf_abdomen, sf_thigh,
|
||||||
|
sf_triceps, sf_subscap, sf_suprailiac, sf_axilla,
|
||||||
|
sf_method, body_fat_pct, notes, created
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
|
ON CONFLICT (profile_id, date) DO NOTHING
|
||||||
|
""", (
|
||||||
|
pid,
|
||||||
|
row['date'],
|
||||||
|
float(row['chest']) if row.get('chest') else None,
|
||||||
|
float(row['abdomen']) if row.get('abdomen') else None,
|
||||||
|
float(row['thigh']) if row.get('thigh') else None,
|
||||||
|
float(row['tricep']) if row.get('tricep') else None,
|
||||||
|
float(row['subscapular']) if row.get('subscapular') else None,
|
||||||
|
float(row['suprailiac']) if row.get('suprailiac') else None,
|
||||||
|
float(row['midaxillary']) if row.get('midaxillary') else None,
|
||||||
|
row.get('method', 'jackson3'),
|
||||||
|
float(row['bf_percent']) if row.get('bf_percent') else None,
|
||||||
|
row.get('note', ''),
|
||||||
|
row.get('created', datetime.now())
|
||||||
|
))
|
||||||
|
if cur.rowcount > 0:
|
||||||
|
stats['caliper'] += 1
|
||||||
|
|
||||||
|
# 5. Import nutrition.csv
|
||||||
|
if 'data/nutrition.csv' in zf.namelist():
|
||||||
|
csv_data = zf.read('data/nutrition.csv').decode('utf-8-sig')
|
||||||
|
reader = csv.DictReader(io.StringIO(csv_data), delimiter=';')
|
||||||
|
for row in reader:
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO nutrition_log (
|
||||||
|
profile_id, date, kcal, protein_g, fat_g, carbs_g, source, created
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
|
ON CONFLICT (profile_id, date) DO NOTHING
|
||||||
|
""", (
|
||||||
|
pid,
|
||||||
|
row['date'],
|
||||||
|
float(row['kcal']) if row.get('kcal') else None,
|
||||||
|
float(row['protein']) if row.get('protein') else None,
|
||||||
|
float(row['fat']) if row.get('fat') else None,
|
||||||
|
float(row['carbs']) if row.get('carbs') else None,
|
||||||
|
row.get('source', 'import'),
|
||||||
|
row.get('created', datetime.now())
|
||||||
|
))
|
||||||
|
if cur.rowcount > 0:
|
||||||
|
stats['nutrition'] += 1
|
||||||
|
|
||||||
|
# 6. Import activity.csv
|
||||||
|
if 'data/activity.csv' in zf.namelist():
|
||||||
|
csv_data = zf.read('data/activity.csv').decode('utf-8-sig')
|
||||||
|
reader = csv.DictReader(io.StringIO(csv_data), delimiter=';')
|
||||||
|
for row in reader:
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO activity_log (
|
||||||
|
profile_id, date, activity_type, duration_min,
|
||||||
|
kcal_active, hr_avg, hr_max, distance_km, notes, source, created
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
|
""", (
|
||||||
|
pid,
|
||||||
|
row['date'],
|
||||||
|
row.get('type', 'Training'),
|
||||||
|
float(row['duration_min']) if row.get('duration_min') else None,
|
||||||
|
float(row['kcal']) if row.get('kcal') else None,
|
||||||
|
float(row['heart_rate_avg']) if row.get('heart_rate_avg') else None,
|
||||||
|
float(row['heart_rate_max']) if row.get('heart_rate_max') else None,
|
||||||
|
float(row['distance_km']) if row.get('distance_km') else None,
|
||||||
|
row.get('note', ''),
|
||||||
|
row.get('source', 'import'),
|
||||||
|
row.get('created', datetime.now())
|
||||||
|
))
|
||||||
|
if cur.rowcount > 0:
|
||||||
|
stats['activity'] += 1
|
||||||
|
|
||||||
|
# 7. Import ai_insights.json
|
||||||
|
if 'insights/ai_insights.json' in zf.namelist():
|
||||||
|
insights_data = json.loads(zf.read('insights/ai_insights.json').decode('utf-8'))
|
||||||
|
for insight in insights_data:
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO ai_insights (profile_id, scope, content, created)
|
||||||
|
VALUES (%s, %s, %s, %s)
|
||||||
|
""", (
|
||||||
|
pid,
|
||||||
|
insight['scope'],
|
||||||
|
insight['result'],
|
||||||
|
insight.get('created', datetime.now())
|
||||||
|
))
|
||||||
|
stats['insights'] += 1
|
||||||
|
|
||||||
|
# 8. Import photos
|
||||||
|
photo_files = [f for f in zf.namelist() if f.startswith('photos/') and not f.endswith('/')]
|
||||||
|
for photo_file in photo_files:
|
||||||
|
# Extract date from filename (format: YYYY-MM-DD_N.jpg)
|
||||||
|
filename = Path(photo_file).name
|
||||||
|
parts = filename.split('_')
|
||||||
|
photo_date = parts[0] if len(parts) > 0 else datetime.now().strftime('%Y-%m-%d')
|
||||||
|
|
||||||
|
# Generate new ID and path
|
||||||
|
photo_id = str(uuid.uuid4())
|
||||||
|
ext = Path(filename).suffix
|
||||||
|
new_filename = f"{photo_id}{ext}"
|
||||||
|
target_path = PHOTOS_DIR / new_filename
|
||||||
|
|
||||||
|
# Check if photo already exists for this date
|
||||||
|
cur.execute("""
|
||||||
|
SELECT id FROM photos
|
||||||
|
WHERE profile_id = %s AND date = %s
|
||||||
|
""", (pid, photo_date))
|
||||||
|
|
||||||
|
if cur.fetchone() is None:
|
||||||
|
# Write photo file
|
||||||
|
with open(target_path, 'wb') as f:
|
||||||
|
f.write(zf.read(photo_file))
|
||||||
|
|
||||||
|
# Insert DB record
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO photos (id, profile_id, date, path, created)
|
||||||
|
VALUES (%s, %s, %s, %s, %s)
|
||||||
|
""", (photo_id, pid, photo_date, new_filename, datetime.now()))
|
||||||
|
stats['photos'] += 1
|
||||||
|
|
||||||
|
# Commit transaction
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
# Rollback on any error
|
||||||
|
conn.rollback()
|
||||||
|
raise HTTPException(500, f"Import fehlgeschlagen: {str(e)}")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"message": "Import erfolgreich",
|
||||||
|
"stats": stats,
|
||||||
|
"total": sum(stats.values())
|
||||||
|
}
|
||||||
|
|
||||||
|
except zipfile.BadZipFile:
|
||||||
|
raise HTTPException(400, "Ungültige ZIP-Datei")
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(500, f"Import-Fehler: {str(e)}")
|
||||||
@@ -0,0 +1,460 @@
|
|||||||
|
"""
|
||||||
|
AI Insights Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Handles AI analysis execution, prompt management, and usage tracking.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
import httpx
|
||||||
|
from typing import Optional
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Header, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth, require_admin
|
||||||
|
from routers.profiles import get_pid
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api", tags=["insights"])
|
||||||
|
|
||||||
|
OPENROUTER_KEY = os.getenv("OPENROUTER_API_KEY", "")
|
||||||
|
OPENROUTER_MODEL = os.getenv("OPENROUTER_MODEL", "anthropic/claude-sonnet-4")
|
||||||
|
ANTHROPIC_KEY = os.getenv("ANTHROPIC_API_KEY", "")
|
||||||
|
|
||||||
|
|
||||||
|
# ── Helper Functions ──────────────────────────────────────────────────────────
|
||||||
|
def check_ai_limit(pid: str):
|
||||||
|
"""Check if profile has reached daily AI limit. Returns (allowed, limit, used)."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT ai_enabled, ai_limit_day FROM profiles WHERE id=%s", (pid,))
|
||||||
|
prof = cur.fetchone()
|
||||||
|
if not prof or not prof['ai_enabled']:
|
||||||
|
raise HTTPException(403, "KI ist für dieses Profil deaktiviert")
|
||||||
|
limit = prof['ai_limit_day']
|
||||||
|
if limit is None:
|
||||||
|
return (True, None, 0)
|
||||||
|
today = datetime.now().date().isoformat()
|
||||||
|
cur.execute("SELECT call_count FROM ai_usage WHERE profile_id=%s AND date=%s", (pid, today))
|
||||||
|
usage = cur.fetchone()
|
||||||
|
used = usage['call_count'] if usage else 0
|
||||||
|
if used >= limit:
|
||||||
|
raise HTTPException(429, f"Tägliches KI-Limit erreicht ({limit} Calls)")
|
||||||
|
return (True, limit, used)
|
||||||
|
|
||||||
|
|
||||||
|
def inc_ai_usage(pid: str):
|
||||||
|
"""Increment AI usage counter for today."""
|
||||||
|
today = datetime.now().date().isoformat()
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT id, call_count FROM ai_usage WHERE profile_id=%s AND date=%s", (pid, today))
|
||||||
|
row = cur.fetchone()
|
||||||
|
if row:
|
||||||
|
cur.execute("UPDATE ai_usage SET call_count=%s WHERE id=%s", (row['call_count']+1, row['id']))
|
||||||
|
else:
|
||||||
|
cur.execute("INSERT INTO ai_usage (id, profile_id, date, call_count) VALUES (%s,%s,%s,1)",
|
||||||
|
(str(uuid.uuid4()), pid, today))
|
||||||
|
|
||||||
|
|
||||||
|
def _get_profile_data(pid: str):
|
||||||
|
"""Fetch all relevant data for AI analysis."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||||
|
prof = r2d(cur.fetchone())
|
||||||
|
cur.execute("SELECT * FROM weight_log WHERE profile_id=%s ORDER BY date DESC LIMIT 90", (pid,))
|
||||||
|
weight = [r2d(r) for r in cur.fetchall()]
|
||||||
|
cur.execute("SELECT * FROM circumference_log WHERE profile_id=%s ORDER BY date DESC LIMIT 30", (pid,))
|
||||||
|
circ = [r2d(r) for r in cur.fetchall()]
|
||||||
|
cur.execute("SELECT * FROM caliper_log WHERE profile_id=%s ORDER BY date DESC LIMIT 30", (pid,))
|
||||||
|
caliper = [r2d(r) for r in cur.fetchall()]
|
||||||
|
cur.execute("SELECT * FROM nutrition_log WHERE profile_id=%s ORDER BY date DESC LIMIT 90", (pid,))
|
||||||
|
nutrition = [r2d(r) for r in cur.fetchall()]
|
||||||
|
cur.execute("SELECT * FROM activity_log WHERE profile_id=%s ORDER BY date DESC LIMIT 90", (pid,))
|
||||||
|
activity = [r2d(r) for r in cur.fetchall()]
|
||||||
|
return {
|
||||||
|
"profile": prof,
|
||||||
|
"weight": weight,
|
||||||
|
"circumference": circ,
|
||||||
|
"caliper": caliper,
|
||||||
|
"nutrition": nutrition,
|
||||||
|
"activity": activity
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _render_template(template: str, data: dict) -> str:
|
||||||
|
"""Simple template variable replacement."""
|
||||||
|
result = template
|
||||||
|
for k, v in data.items():
|
||||||
|
result = result.replace(f"{{{{{k}}}}}", str(v) if v is not None else "")
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _prepare_template_vars(data: dict) -> dict:
|
||||||
|
"""Prepare template variables from profile data."""
|
||||||
|
prof = data['profile']
|
||||||
|
weight = data['weight']
|
||||||
|
circ = data['circumference']
|
||||||
|
caliper = data['caliper']
|
||||||
|
nutrition = data['nutrition']
|
||||||
|
activity = data['activity']
|
||||||
|
|
||||||
|
vars = {
|
||||||
|
"name": prof.get('name', 'Nutzer'),
|
||||||
|
"geschlecht": "männlich" if prof.get('sex') == 'm' else "weiblich",
|
||||||
|
"height": prof.get('height', 178),
|
||||||
|
"goal_weight": float(prof.get('goal_weight')) if prof.get('goal_weight') else "nicht gesetzt",
|
||||||
|
"goal_bf_pct": float(prof.get('goal_bf_pct')) if prof.get('goal_bf_pct') else "nicht gesetzt",
|
||||||
|
"weight_aktuell": float(weight[0]['weight']) if weight else "keine Daten",
|
||||||
|
"kf_aktuell": float(caliper[0]['body_fat_pct']) if caliper and caliper[0].get('body_fat_pct') else "unbekannt",
|
||||||
|
}
|
||||||
|
|
||||||
|
# Calculate age from dob
|
||||||
|
if prof.get('dob'):
|
||||||
|
try:
|
||||||
|
from datetime import date
|
||||||
|
dob = datetime.strptime(prof['dob'], '%Y-%m-%d').date()
|
||||||
|
today = date.today()
|
||||||
|
age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
|
||||||
|
vars['age'] = age
|
||||||
|
except:
|
||||||
|
vars['age'] = "unbekannt"
|
||||||
|
else:
|
||||||
|
vars['age'] = "unbekannt"
|
||||||
|
|
||||||
|
# Weight trend summary
|
||||||
|
if len(weight) >= 2:
|
||||||
|
recent = weight[:30]
|
||||||
|
delta = float(recent[0]['weight']) - float(recent[-1]['weight'])
|
||||||
|
vars['weight_trend'] = f"{len(recent)} Einträge, Δ30d: {delta:+.1f}kg"
|
||||||
|
else:
|
||||||
|
vars['weight_trend'] = "zu wenig Daten"
|
||||||
|
|
||||||
|
# Caliper summary
|
||||||
|
if caliper:
|
||||||
|
c = caliper[0]
|
||||||
|
bf = float(c.get('body_fat_pct')) if c.get('body_fat_pct') else '?'
|
||||||
|
vars['caliper_summary'] = f"KF: {bf}%, Methode: {c.get('sf_method','?')}"
|
||||||
|
else:
|
||||||
|
vars['caliper_summary'] = "keine Daten"
|
||||||
|
|
||||||
|
# Circumference summary
|
||||||
|
if circ:
|
||||||
|
c = circ[0]
|
||||||
|
parts = []
|
||||||
|
for k in ['c_waist', 'c_belly', 'c_hip']:
|
||||||
|
if c.get(k): parts.append(f"{k.split('_')[1]}: {float(c[k])}cm")
|
||||||
|
vars['circ_summary'] = ", ".join(parts) if parts else "keine Daten"
|
||||||
|
else:
|
||||||
|
vars['circ_summary'] = "keine Daten"
|
||||||
|
|
||||||
|
# Nutrition summary
|
||||||
|
if nutrition:
|
||||||
|
n = len(nutrition)
|
||||||
|
avg_kcal = sum(float(d.get('kcal',0) or 0) for d in nutrition) / n
|
||||||
|
avg_prot = sum(float(d.get('protein_g',0) or 0) for d in nutrition) / n
|
||||||
|
vars['nutrition_summary'] = f"{n} Tage, Ø {avg_kcal:.0f}kcal, {avg_prot:.0f}g Protein"
|
||||||
|
vars['nutrition_detail'] = vars['nutrition_summary']
|
||||||
|
vars['nutrition_days'] = n
|
||||||
|
vars['kcal_avg'] = round(avg_kcal)
|
||||||
|
vars['protein_avg'] = round(avg_prot,1)
|
||||||
|
vars['fat_avg'] = round(sum(float(d.get('fat_g',0) or 0) for d in nutrition) / n,1)
|
||||||
|
vars['carb_avg'] = round(sum(float(d.get('carbs_g',0) or 0) for d in nutrition) / n,1)
|
||||||
|
else:
|
||||||
|
vars['nutrition_summary'] = "keine Daten"
|
||||||
|
vars['nutrition_detail'] = "keine Daten"
|
||||||
|
vars['nutrition_days'] = 0
|
||||||
|
vars['kcal_avg'] = 0
|
||||||
|
vars['protein_avg'] = 0
|
||||||
|
vars['fat_avg'] = 0
|
||||||
|
vars['carb_avg'] = 0
|
||||||
|
|
||||||
|
# Protein targets
|
||||||
|
w = weight[0]['weight'] if weight else prof.get('height',178) - 100
|
||||||
|
w = float(w) # Convert Decimal to float for math operations
|
||||||
|
vars['protein_ziel_low'] = round(w * 1.6)
|
||||||
|
vars['protein_ziel_high'] = round(w * 2.2)
|
||||||
|
|
||||||
|
# Activity summary
|
||||||
|
if activity:
|
||||||
|
n = len(activity)
|
||||||
|
total_kcal = sum(float(a.get('kcal_active',0) or 0) for a in activity)
|
||||||
|
vars['activity_summary'] = f"{n} Trainings, {total_kcal:.0f}kcal gesamt"
|
||||||
|
vars['activity_detail'] = vars['activity_summary']
|
||||||
|
vars['activity_kcal_summary'] = f"Ø {total_kcal/n:.0f}kcal/Training"
|
||||||
|
else:
|
||||||
|
vars['activity_summary'] = "keine Daten"
|
||||||
|
vars['activity_detail'] = "keine Daten"
|
||||||
|
vars['activity_kcal_summary'] = "keine Daten"
|
||||||
|
|
||||||
|
return vars
|
||||||
|
|
||||||
|
|
||||||
|
# ── Endpoints ─────────────────────────────────────────────────────────────────
|
||||||
|
@router.get("/insights")
|
||||||
|
def get_all_insights(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Get all AI insights for profile."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,))
|
||||||
|
rows = cur.fetchall()
|
||||||
|
return [r2d(r) for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/insights/latest")
|
||||||
|
def get_latest_insights(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Get latest AI insights across all scopes."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s ORDER BY created DESC LIMIT 10", (pid,))
|
||||||
|
rows = cur.fetchall()
|
||||||
|
return [r2d(r) for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/ai/insights/{scope}")
|
||||||
|
def get_ai_insight(scope: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Get latest insight for specific scope."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s AND scope=%s ORDER BY created DESC LIMIT 1", (pid,scope))
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row: return None
|
||||||
|
return r2d(row)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/insights/{insight_id}")
|
||||||
|
def delete_insight_by_id(insight_id: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Delete a specific insight by ID."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("DELETE FROM ai_insights WHERE id=%s AND profile_id=%s", (insight_id, pid))
|
||||||
|
return {"ok":True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/ai/insights/{scope}")
|
||||||
|
def delete_ai_insight(scope: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Delete all insights for specific scope."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("DELETE FROM ai_insights WHERE profile_id=%s AND scope=%s", (pid,scope))
|
||||||
|
return {"ok":True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/insights/run/{slug}")
|
||||||
|
async def analyze_with_prompt(slug: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Run AI analysis with specified prompt template."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
check_ai_limit(pid)
|
||||||
|
|
||||||
|
# Get prompt template
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT * FROM ai_prompts WHERE slug=%s AND active=true", (slug,))
|
||||||
|
prompt_row = cur.fetchone()
|
||||||
|
if not prompt_row:
|
||||||
|
raise HTTPException(404, f"Prompt '{slug}' nicht gefunden")
|
||||||
|
|
||||||
|
prompt_tmpl = prompt_row['template']
|
||||||
|
data = _get_profile_data(pid)
|
||||||
|
vars = _prepare_template_vars(data)
|
||||||
|
final_prompt = _render_template(prompt_tmpl, vars)
|
||||||
|
|
||||||
|
# Call AI
|
||||||
|
if ANTHROPIC_KEY:
|
||||||
|
# Use Anthropic SDK
|
||||||
|
import anthropic
|
||||||
|
client = anthropic.Anthropic(api_key=ANTHROPIC_KEY)
|
||||||
|
response = client.messages.create(
|
||||||
|
model="claude-sonnet-4-20250514",
|
||||||
|
max_tokens=2000,
|
||||||
|
messages=[{"role": "user", "content": final_prompt}]
|
||||||
|
)
|
||||||
|
content = response.content[0].text
|
||||||
|
elif OPENROUTER_KEY:
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
resp = await client.post("https://openrouter.ai/api/v1/chat/completions",
|
||||||
|
headers={"Authorization": f"Bearer {OPENROUTER_KEY}"},
|
||||||
|
json={
|
||||||
|
"model": OPENROUTER_MODEL,
|
||||||
|
"messages": [{"role": "user", "content": final_prompt}],
|
||||||
|
"max_tokens": 2000
|
||||||
|
},
|
||||||
|
timeout=60.0
|
||||||
|
)
|
||||||
|
if resp.status_code != 200:
|
||||||
|
raise HTTPException(500, f"KI-Fehler: {resp.text}")
|
||||||
|
content = resp.json()['choices'][0]['message']['content']
|
||||||
|
else:
|
||||||
|
raise HTTPException(500, "Keine KI-API konfiguriert")
|
||||||
|
|
||||||
|
# Save insight
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("DELETE FROM ai_insights WHERE profile_id=%s AND scope=%s", (pid, slug))
|
||||||
|
cur.execute("INSERT INTO ai_insights (id, profile_id, scope, content, created) VALUES (%s,%s,%s,%s,CURRENT_TIMESTAMP)",
|
||||||
|
(str(uuid.uuid4()), pid, slug, content))
|
||||||
|
|
||||||
|
inc_ai_usage(pid)
|
||||||
|
return {"scope": slug, "content": content}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/insights/pipeline")
|
||||||
|
async def analyze_pipeline(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Run 3-stage pipeline analysis."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
check_ai_limit(pid)
|
||||||
|
|
||||||
|
data = _get_profile_data(pid)
|
||||||
|
vars = _prepare_template_vars(data)
|
||||||
|
|
||||||
|
# Stage 1: Parallel JSON analyses
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT slug, template FROM ai_prompts WHERE slug LIKE 'pipeline_%' AND slug NOT IN ('pipeline_synthesis','pipeline_goals') AND active=true")
|
||||||
|
stage1_prompts = [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
stage1_results = {}
|
||||||
|
for p in stage1_prompts:
|
||||||
|
slug = p['slug']
|
||||||
|
final_prompt = _render_template(p['template'], vars)
|
||||||
|
|
||||||
|
if ANTHROPIC_KEY:
|
||||||
|
import anthropic
|
||||||
|
client = anthropic.Anthropic(api_key=ANTHROPIC_KEY)
|
||||||
|
response = client.messages.create(
|
||||||
|
model="claude-sonnet-4-20250514",
|
||||||
|
max_tokens=1000,
|
||||||
|
messages=[{"role": "user", "content": final_prompt}]
|
||||||
|
)
|
||||||
|
content = response.content[0].text.strip()
|
||||||
|
elif OPENROUTER_KEY:
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
resp = await client.post("https://openrouter.ai/api/v1/chat/completions",
|
||||||
|
headers={"Authorization": f"Bearer {OPENROUTER_KEY}"},
|
||||||
|
json={
|
||||||
|
"model": OPENROUTER_MODEL,
|
||||||
|
"messages": [{"role": "user", "content": final_prompt}],
|
||||||
|
"max_tokens": 1000
|
||||||
|
},
|
||||||
|
timeout=60.0
|
||||||
|
)
|
||||||
|
content = resp.json()['choices'][0]['message']['content'].strip()
|
||||||
|
else:
|
||||||
|
raise HTTPException(500, "Keine KI-API konfiguriert")
|
||||||
|
|
||||||
|
# Try to parse JSON, fallback to raw text
|
||||||
|
try:
|
||||||
|
stage1_results[slug] = json.loads(content)
|
||||||
|
except:
|
||||||
|
stage1_results[slug] = content
|
||||||
|
|
||||||
|
# Stage 2: Synthesis
|
||||||
|
vars['stage1_body'] = json.dumps(stage1_results.get('pipeline_body', {}), ensure_ascii=False)
|
||||||
|
vars['stage1_nutrition'] = json.dumps(stage1_results.get('pipeline_nutrition', {}), ensure_ascii=False)
|
||||||
|
vars['stage1_activity'] = json.dumps(stage1_results.get('pipeline_activity', {}), ensure_ascii=False)
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT template FROM ai_prompts WHERE slug='pipeline_synthesis' AND active=true")
|
||||||
|
synth_row = cur.fetchone()
|
||||||
|
if not synth_row:
|
||||||
|
raise HTTPException(500, "Pipeline synthesis prompt not found")
|
||||||
|
|
||||||
|
synth_prompt = _render_template(synth_row['template'], vars)
|
||||||
|
|
||||||
|
if ANTHROPIC_KEY:
|
||||||
|
import anthropic
|
||||||
|
client = anthropic.Anthropic(api_key=ANTHROPIC_KEY)
|
||||||
|
response = client.messages.create(
|
||||||
|
model="claude-sonnet-4-20250514",
|
||||||
|
max_tokens=2000,
|
||||||
|
messages=[{"role": "user", "content": synth_prompt}]
|
||||||
|
)
|
||||||
|
synthesis = response.content[0].text
|
||||||
|
elif OPENROUTER_KEY:
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
resp = await client.post("https://openrouter.ai/api/v1/chat/completions",
|
||||||
|
headers={"Authorization": f"Bearer {OPENROUTER_KEY}"},
|
||||||
|
json={
|
||||||
|
"model": OPENROUTER_MODEL,
|
||||||
|
"messages": [{"role": "user", "content": synth_prompt}],
|
||||||
|
"max_tokens": 2000
|
||||||
|
},
|
||||||
|
timeout=60.0
|
||||||
|
)
|
||||||
|
synthesis = resp.json()['choices'][0]['message']['content']
|
||||||
|
else:
|
||||||
|
raise HTTPException(500, "Keine KI-API konfiguriert")
|
||||||
|
|
||||||
|
# Stage 3: Goals (only if goals are set)
|
||||||
|
goals_text = None
|
||||||
|
prof = data['profile']
|
||||||
|
if prof.get('goal_weight') or prof.get('goal_bf_pct'):
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT template FROM ai_prompts WHERE slug='pipeline_goals' AND active=true")
|
||||||
|
goals_row = cur.fetchone()
|
||||||
|
if goals_row:
|
||||||
|
goals_prompt = _render_template(goals_row['template'], vars)
|
||||||
|
|
||||||
|
if ANTHROPIC_KEY:
|
||||||
|
import anthropic
|
||||||
|
client = anthropic.Anthropic(api_key=ANTHROPIC_KEY)
|
||||||
|
response = client.messages.create(
|
||||||
|
model="claude-sonnet-4-20250514",
|
||||||
|
max_tokens=800,
|
||||||
|
messages=[{"role": "user", "content": goals_prompt}]
|
||||||
|
)
|
||||||
|
goals_text = response.content[0].text
|
||||||
|
elif OPENROUTER_KEY:
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
resp = await client.post("https://openrouter.ai/api/v1/chat/completions",
|
||||||
|
headers={"Authorization": f"Bearer {OPENROUTER_KEY}"},
|
||||||
|
json={
|
||||||
|
"model": OPENROUTER_MODEL,
|
||||||
|
"messages": [{"role": "user", "content": goals_prompt}],
|
||||||
|
"max_tokens": 800
|
||||||
|
},
|
||||||
|
timeout=60.0
|
||||||
|
)
|
||||||
|
goals_text = resp.json()['choices'][0]['message']['content']
|
||||||
|
|
||||||
|
# Combine synthesis + goals
|
||||||
|
final_content = synthesis
|
||||||
|
if goals_text:
|
||||||
|
final_content += "\n\n" + goals_text
|
||||||
|
|
||||||
|
# Save as 'gesamt' scope
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("DELETE FROM ai_insights WHERE profile_id=%s AND scope='gesamt'", (pid,))
|
||||||
|
cur.execute("INSERT INTO ai_insights (id, profile_id, scope, content, created) VALUES (%s,%s,'gesamt',%s,CURRENT_TIMESTAMP)",
|
||||||
|
(str(uuid.uuid4()), pid, final_content))
|
||||||
|
|
||||||
|
inc_ai_usage(pid)
|
||||||
|
return {"scope": "gesamt", "content": final_content, "stage1": stage1_results}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/ai/usage")
|
||||||
|
def get_ai_usage(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Get AI usage stats for current profile."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT ai_limit_day FROM profiles WHERE id=%s", (pid,))
|
||||||
|
prof = cur.fetchone()
|
||||||
|
limit = prof['ai_limit_day'] if prof else None
|
||||||
|
|
||||||
|
today = datetime.now().date().isoformat()
|
||||||
|
cur.execute("SELECT call_count FROM ai_usage WHERE profile_id=%s AND date=%s", (pid, today))
|
||||||
|
usage = cur.fetchone()
|
||||||
|
used = usage['call_count'] if usage else 0
|
||||||
|
|
||||||
|
return {"limit": limit, "used": used, "remaining": (limit - used) if limit else None}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
"""
|
||||||
|
Nutrition Tracking Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Handles nutrition data, FDDB CSV import, correlations, and weekly aggregates.
|
||||||
|
"""
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
|
import uuid
|
||||||
|
from typing import Optional
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, UploadFile, File, Header, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth
|
||||||
|
from routers.profiles import get_pid
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/nutrition", tags=["nutrition"])
|
||||||
|
|
||||||
|
|
||||||
|
# ── Helper ────────────────────────────────────────────────────────────────────
|
||||||
|
def _pf(s):
|
||||||
|
"""Parse float from string (handles comma decimal separator)."""
|
||||||
|
try: return float(str(s).replace(',','.').strip())
|
||||||
|
except: return 0.0
|
||||||
|
|
||||||
|
|
||||||
|
# ── Endpoints ─────────────────────────────────────────────────────────────────
|
||||||
|
@router.post("/import-csv")
|
||||||
|
async def import_nutrition_csv(file: UploadFile=File(...), x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Import FDDB nutrition CSV."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
raw = await file.read()
|
||||||
|
try: text = raw.decode('utf-8')
|
||||||
|
except: text = raw.decode('latin-1')
|
||||||
|
if text.startswith('\ufeff'): text = text[1:]
|
||||||
|
if not text.strip(): raise HTTPException(400,"Leere Datei")
|
||||||
|
reader = csv.DictReader(io.StringIO(text), delimiter=';')
|
||||||
|
days: dict = {}
|
||||||
|
count = 0
|
||||||
|
for row in reader:
|
||||||
|
rd = row.get('datum_tag_monat_jahr_stunde_minute','').strip().strip('"')
|
||||||
|
if not rd: continue
|
||||||
|
try:
|
||||||
|
p = rd.split(' ')[0].split('.')
|
||||||
|
iso = f"{p[2]}-{p[1]}-{p[0]}"
|
||||||
|
except: continue
|
||||||
|
days.setdefault(iso,{'kcal':0,'fat_g':0,'carbs_g':0,'protein_g':0})
|
||||||
|
days[iso]['kcal'] += _pf(row.get('kj',0))/4.184
|
||||||
|
days[iso]['fat_g'] += _pf(row.get('fett_g',0))
|
||||||
|
days[iso]['carbs_g'] += _pf(row.get('kh_g',0))
|
||||||
|
days[iso]['protein_g'] += _pf(row.get('protein_g',0))
|
||||||
|
count+=1
|
||||||
|
inserted=0
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
for iso,vals in days.items():
|
||||||
|
kcal=round(vals['kcal'],1); fat=round(vals['fat_g'],1)
|
||||||
|
carbs=round(vals['carbs_g'],1); prot=round(vals['protein_g'],1)
|
||||||
|
cur.execute("SELECT id FROM nutrition_log WHERE profile_id=%s AND date=%s",(pid,iso))
|
||||||
|
if cur.fetchone():
|
||||||
|
cur.execute("UPDATE nutrition_log SET kcal=%s,protein_g=%s,fat_g=%s,carbs_g=%s WHERE profile_id=%s AND date=%s",
|
||||||
|
(kcal,prot,fat,carbs,pid,iso))
|
||||||
|
else:
|
||||||
|
cur.execute("INSERT INTO nutrition_log (id,profile_id,date,kcal,protein_g,fat_g,carbs_g,source,created) VALUES (%s,%s,%s,%s,%s,%s,%s,'csv',CURRENT_TIMESTAMP)",
|
||||||
|
(str(uuid.uuid4()),pid,iso,kcal,prot,fat,carbs))
|
||||||
|
inserted+=1
|
||||||
|
return {"rows_parsed":count,"days_imported":inserted,
|
||||||
|
"date_range":{"from":min(days) if days else None,"to":max(days) if days else None}}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def list_nutrition(limit: int=365, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Get nutrition entries for current profile."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"SELECT * FROM nutrition_log WHERE profile_id=%s ORDER BY date DESC LIMIT %s", (pid,limit))
|
||||||
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/correlations")
|
||||||
|
def nutrition_correlations(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Get nutrition data correlated with weight and body fat."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT * FROM nutrition_log WHERE profile_id=%s ORDER BY date",(pid,))
|
||||||
|
nutr={r['date']:r2d(r) for r in cur.fetchall()}
|
||||||
|
cur.execute("SELECT date,weight FROM weight_log WHERE profile_id=%s ORDER BY date",(pid,))
|
||||||
|
wlog={r['date']:r['weight'] for r in cur.fetchall()}
|
||||||
|
cur.execute("SELECT date,lean_mass,body_fat_pct FROM caliper_log WHERE profile_id=%s ORDER BY date",(pid,))
|
||||||
|
cals=sorted([r2d(r) for r in cur.fetchall()],key=lambda x:x['date'])
|
||||||
|
all_dates=sorted(set(list(nutr)+list(wlog)))
|
||||||
|
mi,last_cal,cal_by_date=0,{},{}
|
||||||
|
for d in all_dates:
|
||||||
|
while mi<len(cals) and cals[mi]['date']<=d: last_cal=cals[mi]; mi+=1
|
||||||
|
if last_cal: cal_by_date[d]=last_cal
|
||||||
|
result=[]
|
||||||
|
for d in all_dates:
|
||||||
|
if d not in nutr and d not in wlog: continue
|
||||||
|
row={'date':d}
|
||||||
|
if d in nutr: row.update({k:float(nutr[d][k]) if nutr[d][k] is not None else None for k in ['kcal','protein_g','fat_g','carbs_g']})
|
||||||
|
if d in wlog: row['weight']=float(wlog[d])
|
||||||
|
if d in cal_by_date:
|
||||||
|
lm = cal_by_date[d].get('lean_mass')
|
||||||
|
bf = cal_by_date[d].get('body_fat_pct')
|
||||||
|
row['lean_mass']=float(lm) if lm is not None else None
|
||||||
|
row['body_fat_pct']=float(bf) if bf is not None else None
|
||||||
|
result.append(row)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/weekly")
|
||||||
|
def nutrition_weekly(weeks: int=16, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Get nutrition data aggregated by week."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT * FROM nutrition_log WHERE profile_id=%s ORDER BY date DESC LIMIT %s",(pid,weeks*7))
|
||||||
|
rows=[r2d(r) for r in cur.fetchall()]
|
||||||
|
if not rows: return []
|
||||||
|
wm={}
|
||||||
|
for d in rows:
|
||||||
|
wk=datetime.strptime(d['date'],'%Y-%m-%d').strftime('%Y-W%V')
|
||||||
|
wm.setdefault(wk,[]).append(d)
|
||||||
|
result=[]
|
||||||
|
for wk in sorted(wm):
|
||||||
|
en=wm[wk]; n=len(en)
|
||||||
|
def avg(k): return round(sum(float(e.get(k) or 0) for e in en)/n,1)
|
||||||
|
result.append({'week':wk,'days':n,'kcal':avg('kcal'),'protein_g':avg('protein_g'),'fat_g':avg('fat_g'),'carbs_g':avg('carbs_g')})
|
||||||
|
return result
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
"""
|
||||||
|
Photo Management Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Handles progress photo uploads and retrieval.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, UploadFile, File, Header, HTTPException, Depends
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
import aiofiles
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth, require_auth_flexible
|
||||||
|
from routers.profiles import get_pid
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/photos", tags=["photos"])
|
||||||
|
|
||||||
|
PHOTOS_DIR = Path(os.getenv("PHOTOS_DIR", "./photos"))
|
||||||
|
PHOTOS_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("")
|
||||||
|
async def upload_photo(file: UploadFile=File(...), date: str="",
|
||||||
|
x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Upload progress photo."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
fid = str(uuid.uuid4())
|
||||||
|
ext = Path(file.filename).suffix or '.jpg'
|
||||||
|
path = PHOTOS_DIR / f"{fid}{ext}"
|
||||||
|
async with aiofiles.open(path,'wb') as f: await f.write(await file.read())
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("INSERT INTO photos (id,profile_id,date,path,created) VALUES (%s,%s,%s,%s,CURRENT_TIMESTAMP)",
|
||||||
|
(fid,pid,date,str(path)))
|
||||||
|
return {"id":fid,"date":date}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{fid}")
|
||||||
|
def get_photo(fid: str, session: dict=Depends(require_auth_flexible)):
|
||||||
|
"""Get photo by ID. Auth via header or query param (for <img> tags)."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT path FROM photos WHERE id=%s", (fid,))
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row: raise HTTPException(404, "Photo not found")
|
||||||
|
photo_path = Path(PHOTOS_DIR) / row['path']
|
||||||
|
if not photo_path.exists():
|
||||||
|
raise HTTPException(404, "Photo file not found")
|
||||||
|
return FileResponse(photo_path)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def list_photos(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Get all photos for current profile."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"SELECT * FROM photos WHERE profile_id=%s ORDER BY created DESC LIMIT 100", (pid,))
|
||||||
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
"""
|
||||||
|
Profile Management Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Handles profile CRUD operations for both admin and current user.
|
||||||
|
"""
|
||||||
|
import uuid
|
||||||
|
from typing import Optional
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Header, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth
|
||||||
|
from models import ProfileCreate, ProfileUpdate
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api", tags=["profiles"])
|
||||||
|
|
||||||
|
|
||||||
|
# ── Helper ────────────────────────────────────────────────────────────────────
|
||||||
|
def get_pid(x_profile_id: Optional[str] = Header(default=None)) -> str:
|
||||||
|
"""Get profile_id - from header for legacy endpoints."""
|
||||||
|
if x_profile_id:
|
||||||
|
return x_profile_id
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT id FROM profiles ORDER BY created LIMIT 1")
|
||||||
|
row = cur.fetchone()
|
||||||
|
if row: return row['id']
|
||||||
|
raise HTTPException(400, "Kein Profil gefunden")
|
||||||
|
|
||||||
|
|
||||||
|
# ── Admin Profile Management ──────────────────────────────────────────────────
|
||||||
|
@router.get("/profiles")
|
||||||
|
def list_profiles(session=Depends(require_auth)):
|
||||||
|
"""List all profiles (admin)."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT * FROM profiles ORDER BY created")
|
||||||
|
rows = cur.fetchall()
|
||||||
|
return [r2d(r) for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/profiles")
|
||||||
|
def create_profile(p: ProfileCreate, session=Depends(require_auth)):
|
||||||
|
"""Create new profile (admin)."""
|
||||||
|
pid = str(uuid.uuid4())
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("""INSERT INTO profiles (id,name,avatar_color,sex,dob,height,goal_weight,goal_bf_pct,created,updated)
|
||||||
|
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)""",
|
||||||
|
(pid,p.name,p.avatar_color,p.sex,p.dob,p.height,p.goal_weight,p.goal_bf_pct))
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||||
|
return r2d(cur.fetchone())
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/profiles/{pid}")
|
||||||
|
def get_profile(pid: str, session=Depends(require_auth)):
|
||||||
|
"""Get profile by ID."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row: raise HTTPException(404, "Profil nicht gefunden")
|
||||||
|
return r2d(row)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/profiles/{pid}")
|
||||||
|
def update_profile(pid: str, p: ProfileUpdate, session=Depends(require_auth)):
|
||||||
|
"""Update profile by ID (admin)."""
|
||||||
|
with get_db() as conn:
|
||||||
|
data = {k:v for k,v in p.model_dump().items() if v is not None}
|
||||||
|
data['updated'] = datetime.now().isoformat()
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(f"UPDATE profiles SET {', '.join(f'{k}=%s' for k in data)} WHERE id=%s",
|
||||||
|
list(data.values())+[pid])
|
||||||
|
return get_profile(pid, session)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/profiles/{pid}")
|
||||||
|
def delete_profile(pid: str, session=Depends(require_auth)):
|
||||||
|
"""Delete profile (admin)."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT COUNT(*) as count FROM profiles")
|
||||||
|
count = cur.fetchone()['count']
|
||||||
|
if count <= 1: raise HTTPException(400, "Letztes Profil kann nicht gelöscht werden")
|
||||||
|
for table in ['weight_log','circumference_log','caliper_log','nutrition_log','activity_log','ai_insights']:
|
||||||
|
cur.execute(f"DELETE FROM {table} WHERE profile_id=%s", (pid,))
|
||||||
|
cur.execute("DELETE FROM profiles WHERE id=%s", (pid,))
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
# ── Current User Profile ──────────────────────────────────────────────────────
|
||||||
|
@router.get("/profile")
|
||||||
|
def get_active_profile(x_profile_id: Optional[str] = Header(default=None), session: dict = Depends(require_auth)):
|
||||||
|
"""Legacy endpoint – returns active profile."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
return get_profile(pid, session)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/profile")
|
||||||
|
def update_active_profile(p: ProfileUpdate, x_profile_id: Optional[str] = Header(default=None), session: dict = Depends(require_auth)):
|
||||||
|
"""Update current user's profile."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
return update_profile(pid, p, session)
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
"""
|
||||||
|
AI Prompts Management Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Handles prompt template configuration (admin-editable).
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth, require_admin
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/prompts", tags=["prompts"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def list_prompts(session: dict=Depends(require_auth)):
|
||||||
|
"""
|
||||||
|
List AI prompts.
|
||||||
|
- Admins: see ALL prompts (including pipeline and inactive)
|
||||||
|
- Users: see only active single-analysis prompts
|
||||||
|
"""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
is_admin = session.get('role') == 'admin'
|
||||||
|
|
||||||
|
if is_admin:
|
||||||
|
# Admin sees everything
|
||||||
|
cur.execute("SELECT * FROM ai_prompts ORDER BY sort_order, slug")
|
||||||
|
else:
|
||||||
|
# Users see only active, non-pipeline prompts
|
||||||
|
cur.execute("SELECT * FROM ai_prompts WHERE active=true AND slug NOT LIKE 'pipeline_%' ORDER BY sort_order")
|
||||||
|
|
||||||
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{prompt_id}")
|
||||||
|
def update_prompt(prompt_id: str, data: dict, session: dict=Depends(require_admin)):
|
||||||
|
"""Update AI prompt template (admin only)."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
updates = []
|
||||||
|
values = []
|
||||||
|
if 'name' in data:
|
||||||
|
updates.append('name=%s')
|
||||||
|
values.append(data['name'])
|
||||||
|
if 'description' in data:
|
||||||
|
updates.append('description=%s')
|
||||||
|
values.append(data['description'])
|
||||||
|
if 'template' in data:
|
||||||
|
updates.append('template=%s')
|
||||||
|
values.append(data['template'])
|
||||||
|
if 'active' in data:
|
||||||
|
updates.append('active=%s')
|
||||||
|
# Convert to boolean (accepts true/false, 1/0)
|
||||||
|
values.append(bool(data['active']))
|
||||||
|
|
||||||
|
if updates:
|
||||||
|
cur.execute(f"UPDATE ai_prompts SET {', '.join(updates)}, updated=CURRENT_TIMESTAMP WHERE id=%s",
|
||||||
|
values + [prompt_id])
|
||||||
|
|
||||||
|
return {"ok": True}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
"""
|
||||||
|
Statistics Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Dashboard statistics showing entry counts across all categories.
|
||||||
|
"""
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Header, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor
|
||||||
|
from auth import require_auth
|
||||||
|
from routers.profiles import get_pid
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api", tags=["stats"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/stats")
|
||||||
|
def get_stats(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Get entry counts for all tracking categories."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT COUNT(*) as count FROM weight_log WHERE profile_id=%s",(pid,))
|
||||||
|
weight_count = cur.fetchone()['count']
|
||||||
|
cur.execute("SELECT COUNT(*) as count FROM circumference_log WHERE profile_id=%s",(pid,))
|
||||||
|
circ_count = cur.fetchone()['count']
|
||||||
|
cur.execute("SELECT COUNT(*) as count FROM caliper_log WHERE profile_id=%s",(pid,))
|
||||||
|
caliper_count = cur.fetchone()['count']
|
||||||
|
cur.execute("SELECT COUNT(*) as count FROM nutrition_log WHERE profile_id=%s",(pid,))
|
||||||
|
nutrition_count = cur.fetchone()['count']
|
||||||
|
cur.execute("SELECT COUNT(*) as count FROM activity_log WHERE profile_id=%s",(pid,))
|
||||||
|
activity_count = cur.fetchone()['count']
|
||||||
|
return {
|
||||||
|
"weight_count": weight_count,
|
||||||
|
"circ_count": circ_count,
|
||||||
|
"caliper_count": caliper_count,
|
||||||
|
"nutrition_count": nutrition_count,
|
||||||
|
"activity_count": activity_count
|
||||||
|
}
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
"""
|
||||||
|
User Subscription Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
User-facing subscription info (own tier, usage, limits).
|
||||||
|
"""
|
||||||
|
from datetime import datetime
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth, get_effective_tier, check_feature_access
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/subscription", tags=["subscription"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/me")
|
||||||
|
def get_my_subscription(session: dict = Depends(require_auth)):
|
||||||
|
"""
|
||||||
|
Get current user's subscription info.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- tier: Current effective tier (considers access_grants)
|
||||||
|
- profile_tier: Base tier from profile
|
||||||
|
- trial_ends_at: Trial expiration (if applicable)
|
||||||
|
- email_verified: Email verification status
|
||||||
|
- active_grants: List of active access grants (coupons, trials)
|
||||||
|
"""
|
||||||
|
profile_id = session['profile_id']
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Get profile info
|
||||||
|
cur.execute("""
|
||||||
|
SELECT tier, trial_ends_at, email_verified
|
||||||
|
FROM profiles
|
||||||
|
WHERE id = %s
|
||||||
|
""", (profile_id,))
|
||||||
|
profile = cur.fetchone()
|
||||||
|
|
||||||
|
if not profile:
|
||||||
|
return {"error": "Profile not found"}
|
||||||
|
|
||||||
|
# Get effective tier (considers access_grants)
|
||||||
|
effective_tier = get_effective_tier(profile_id)
|
||||||
|
|
||||||
|
# Get active access grants
|
||||||
|
cur.execute("""
|
||||||
|
SELECT
|
||||||
|
ag.id,
|
||||||
|
ag.tier_id,
|
||||||
|
ag.granted_by,
|
||||||
|
ag.valid_from,
|
||||||
|
ag.valid_until,
|
||||||
|
ag.is_active,
|
||||||
|
ag.paused_by,
|
||||||
|
ag.remaining_days,
|
||||||
|
t.name as tier_name
|
||||||
|
FROM access_grants ag
|
||||||
|
JOIN tiers t ON t.id = ag.tier_id
|
||||||
|
WHERE ag.profile_id = %s
|
||||||
|
AND ag.valid_until > CURRENT_TIMESTAMP
|
||||||
|
ORDER BY ag.valid_until DESC
|
||||||
|
""", (profile_id,))
|
||||||
|
grants = [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
# Get tier info
|
||||||
|
cur.execute("""
|
||||||
|
SELECT id, name, description, price_monthly_cents, price_yearly_cents
|
||||||
|
FROM tiers
|
||||||
|
WHERE id = %s
|
||||||
|
""", (effective_tier,))
|
||||||
|
tier_info = r2d(cur.fetchone())
|
||||||
|
|
||||||
|
return {
|
||||||
|
"tier": effective_tier,
|
||||||
|
"tier_info": tier_info,
|
||||||
|
"profile_tier": profile['tier'],
|
||||||
|
"trial_ends_at": profile['trial_ends_at'].isoformat() if profile['trial_ends_at'] else None,
|
||||||
|
"email_verified": profile['email_verified'],
|
||||||
|
"active_grants": grants
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/usage")
|
||||||
|
def get_my_usage(session: dict = Depends(require_auth)):
|
||||||
|
"""
|
||||||
|
Get current user's feature usage.
|
||||||
|
|
||||||
|
Returns list of features with current usage and limits.
|
||||||
|
"""
|
||||||
|
profile_id = session['profile_id']
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Get all active features
|
||||||
|
cur.execute("""
|
||||||
|
SELECT id, name, category, limit_type, reset_period
|
||||||
|
FROM features
|
||||||
|
WHERE active = true
|
||||||
|
ORDER BY category, name
|
||||||
|
""")
|
||||||
|
features = [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
# Get usage for each feature
|
||||||
|
usage_list = []
|
||||||
|
for feature in features:
|
||||||
|
access = check_feature_access(profile_id, feature['id'])
|
||||||
|
usage_list.append({
|
||||||
|
"feature_id": feature['id'],
|
||||||
|
"feature_name": feature['name'],
|
||||||
|
"category": feature['category'],
|
||||||
|
"limit_type": feature['limit_type'],
|
||||||
|
"reset_period": feature['reset_period'],
|
||||||
|
"allowed": access['allowed'],
|
||||||
|
"limit": access['limit'],
|
||||||
|
"used": access['used'],
|
||||||
|
"remaining": access['remaining'],
|
||||||
|
"reason": access['reason']
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
"tier": get_effective_tier(profile_id),
|
||||||
|
"features": usage_list
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/limits")
|
||||||
|
def get_my_limits(session: dict = Depends(require_auth)):
|
||||||
|
"""
|
||||||
|
Get all feature limits for current tier.
|
||||||
|
|
||||||
|
Simplified view - just shows what's allowed/not allowed.
|
||||||
|
"""
|
||||||
|
profile_id = session['profile_id']
|
||||||
|
tier_id = get_effective_tier(profile_id)
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Get all features with their limits for this tier
|
||||||
|
cur.execute("""
|
||||||
|
SELECT
|
||||||
|
f.id,
|
||||||
|
f.name,
|
||||||
|
f.category,
|
||||||
|
f.limit_type,
|
||||||
|
COALESCE(tl.limit_value, f.default_limit) as limit_value
|
||||||
|
FROM features f
|
||||||
|
LEFT JOIN tier_limits tl ON tl.feature_id = f.id AND tl.tier_id = %s
|
||||||
|
WHERE f.active = true
|
||||||
|
ORDER BY f.category, f.name
|
||||||
|
""", (tier_id,))
|
||||||
|
|
||||||
|
features = []
|
||||||
|
for row in cur.fetchall():
|
||||||
|
rd = r2d(row)
|
||||||
|
limit = rd['limit_value']
|
||||||
|
|
||||||
|
# Interpret limit
|
||||||
|
if limit is None:
|
||||||
|
status = "unlimited"
|
||||||
|
elif limit == 0:
|
||||||
|
status = "disabled"
|
||||||
|
elif rd['limit_type'] == 'boolean':
|
||||||
|
status = "enabled" if limit == 1 else "disabled"
|
||||||
|
else:
|
||||||
|
status = f"limit: {limit}"
|
||||||
|
|
||||||
|
features.append({
|
||||||
|
"feature_id": rd['id'],
|
||||||
|
"feature_name": rd['name'],
|
||||||
|
"category": rd['category'],
|
||||||
|
"limit": limit,
|
||||||
|
"status": status
|
||||||
|
})
|
||||||
|
|
||||||
|
# Get tier info
|
||||||
|
cur.execute("SELECT name, description FROM tiers WHERE id = %s", (tier_id,))
|
||||||
|
tier = cur.fetchone()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"tier_id": tier_id,
|
||||||
|
"tier_name": tier['name'] if tier else tier_id,
|
||||||
|
"tier_description": tier['description'] if tier else '',
|
||||||
|
"features": features
|
||||||
|
}
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
"""
|
||||||
|
Tier Limits Management Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Admin-only matrix editor for Tier x Feature limits.
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter, HTTPException, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_admin
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/tier-limits", tags=["tier-limits"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def get_tier_limits_matrix(session: dict = Depends(require_admin)):
|
||||||
|
"""
|
||||||
|
Admin: Get complete Tier x Feature matrix.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
{
|
||||||
|
"tiers": [{id, name}, ...],
|
||||||
|
"features": [{id, name, category}, ...],
|
||||||
|
"limits": {
|
||||||
|
"tier_id:feature_id": limit_value,
|
||||||
|
...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Get all tiers
|
||||||
|
cur.execute("SELECT id, name, sort_order FROM tiers WHERE active = true ORDER BY sort_order")
|
||||||
|
tiers = [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
# Get all features
|
||||||
|
cur.execute("""
|
||||||
|
SELECT id, name, category, limit_type, default_limit
|
||||||
|
FROM features
|
||||||
|
WHERE active = true
|
||||||
|
ORDER BY category, name
|
||||||
|
""")
|
||||||
|
features = [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
# Get all tier_limits
|
||||||
|
cur.execute("SELECT tier_id, feature_id, limit_value FROM tier_limits")
|
||||||
|
limits = {}
|
||||||
|
for row in cur.fetchall():
|
||||||
|
key = f"{row['tier_id']}:{row['feature_id']}"
|
||||||
|
limits[key] = row['limit_value']
|
||||||
|
|
||||||
|
return {
|
||||||
|
"tiers": tiers,
|
||||||
|
"features": features,
|
||||||
|
"limits": limits
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("")
|
||||||
|
def update_tier_limit(data: dict, session: dict = Depends(require_admin)):
|
||||||
|
"""
|
||||||
|
Admin: Update single tier limit.
|
||||||
|
|
||||||
|
Body:
|
||||||
|
{
|
||||||
|
"tier_id": "free",
|
||||||
|
"feature_id": "weight_entries",
|
||||||
|
"limit_value": 30 // NULL = unlimited, 0 = disabled
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
tier_id = data.get('tier_id')
|
||||||
|
feature_id = data.get('feature_id')
|
||||||
|
limit_value = data.get('limit_value') # Can be None (NULL)
|
||||||
|
|
||||||
|
if not tier_id or not feature_id:
|
||||||
|
raise HTTPException(400, "tier_id und feature_id fehlen")
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Upsert tier_limit
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO tier_limits (tier_id, feature_id, limit_value)
|
||||||
|
VALUES (%s, %s, %s)
|
||||||
|
ON CONFLICT (tier_id, feature_id)
|
||||||
|
DO UPDATE SET
|
||||||
|
limit_value = EXCLUDED.limit_value,
|
||||||
|
updated = CURRENT_TIMESTAMP
|
||||||
|
""", (tier_id, feature_id, limit_value))
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/batch")
|
||||||
|
def update_tier_limits_batch(data: dict, session: dict = Depends(require_admin)):
|
||||||
|
"""
|
||||||
|
Admin: Batch update multiple tier limits.
|
||||||
|
|
||||||
|
Body:
|
||||||
|
{
|
||||||
|
"updates": [
|
||||||
|
{"tier_id": "free", "feature_id": "weight_entries", "limit_value": 30},
|
||||||
|
{"tier_id": "free", "feature_id": "ai_calls", "limit_value": 0},
|
||||||
|
...
|
||||||
|
]
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
updates = data.get('updates', [])
|
||||||
|
|
||||||
|
if not updates:
|
||||||
|
raise HTTPException(400, "updates array fehlt")
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
for update in updates:
|
||||||
|
tier_id = update.get('tier_id')
|
||||||
|
feature_id = update.get('feature_id')
|
||||||
|
limit_value = update.get('limit_value')
|
||||||
|
|
||||||
|
if not tier_id or not feature_id:
|
||||||
|
continue # Skip invalid entries
|
||||||
|
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO tier_limits (tier_id, feature_id, limit_value)
|
||||||
|
VALUES (%s, %s, %s)
|
||||||
|
ON CONFLICT (tier_id, feature_id)
|
||||||
|
DO UPDATE SET
|
||||||
|
limit_value = EXCLUDED.limit_value,
|
||||||
|
updated = CURRENT_TIMESTAMP
|
||||||
|
""", (tier_id, feature_id, limit_value))
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {"ok": True, "updated": len(updates)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("")
|
||||||
|
def delete_tier_limit(tier_id: str, feature_id: str, session: dict = Depends(require_admin)):
|
||||||
|
"""
|
||||||
|
Admin: Delete tier limit (falls back to feature default).
|
||||||
|
|
||||||
|
Query params: ?tier_id=...&feature_id=...
|
||||||
|
"""
|
||||||
|
if not tier_id or not feature_id:
|
||||||
|
raise HTTPException(400, "tier_id und feature_id fehlen")
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("""
|
||||||
|
DELETE FROM tier_limits
|
||||||
|
WHERE tier_id = %s AND feature_id = %s
|
||||||
|
""", (tier_id, feature_id))
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {"ok": True}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
"""
|
||||||
|
Tier Management Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Admin-only CRUD for subscription tiers.
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter, HTTPException, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_admin
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/tiers", tags=["tiers"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def list_tiers(session: dict = Depends(require_admin)):
|
||||||
|
"""Admin: List all tiers."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("""
|
||||||
|
SELECT * FROM tiers
|
||||||
|
ORDER BY sort_order
|
||||||
|
""")
|
||||||
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("")
|
||||||
|
def create_tier(data: dict, session: dict = Depends(require_admin)):
|
||||||
|
"""
|
||||||
|
Admin: Create new tier.
|
||||||
|
|
||||||
|
Required fields:
|
||||||
|
- id: Tier ID (e.g., 'enterprise')
|
||||||
|
- name: Display name
|
||||||
|
- price_monthly_cents, price_yearly_cents: Prices (NULL for free tiers)
|
||||||
|
"""
|
||||||
|
tier_id = data.get('id', '').strip()
|
||||||
|
name = data.get('name', '').strip()
|
||||||
|
description = data.get('description', '')
|
||||||
|
price_monthly_cents = data.get('price_monthly_cents')
|
||||||
|
price_yearly_cents = data.get('price_yearly_cents')
|
||||||
|
sort_order = data.get('sort_order', 99)
|
||||||
|
|
||||||
|
if not tier_id or not name:
|
||||||
|
raise HTTPException(400, "ID und Name fehlen")
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Check if ID already exists
|
||||||
|
cur.execute("SELECT id FROM tiers WHERE id = %s", (tier_id,))
|
||||||
|
if cur.fetchone():
|
||||||
|
raise HTTPException(400, f"Tier '{tier_id}' existiert bereits")
|
||||||
|
|
||||||
|
# Create tier
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO tiers (
|
||||||
|
id, name, description, price_monthly_cents, price_yearly_cents, sort_order
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s)
|
||||||
|
""", (tier_id, name, description, price_monthly_cents, price_yearly_cents, sort_order))
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {"ok": True, "id": tier_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{tier_id}")
|
||||||
|
def update_tier(tier_id: str, data: dict, session: dict = Depends(require_admin)):
|
||||||
|
"""Admin: Update tier."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
updates = []
|
||||||
|
values = []
|
||||||
|
|
||||||
|
if 'name' in data:
|
||||||
|
updates.append('name = %s')
|
||||||
|
values.append(data['name'])
|
||||||
|
if 'description' in data:
|
||||||
|
updates.append('description = %s')
|
||||||
|
values.append(data['description'])
|
||||||
|
if 'price_monthly_cents' in data:
|
||||||
|
updates.append('price_monthly_cents = %s')
|
||||||
|
values.append(data['price_monthly_cents'])
|
||||||
|
if 'price_yearly_cents' in data:
|
||||||
|
updates.append('price_yearly_cents = %s')
|
||||||
|
values.append(data['price_yearly_cents'])
|
||||||
|
if 'active' in data:
|
||||||
|
updates.append('active = %s')
|
||||||
|
values.append(data['active'])
|
||||||
|
if 'sort_order' in data:
|
||||||
|
updates.append('sort_order = %s')
|
||||||
|
values.append(data['sort_order'])
|
||||||
|
|
||||||
|
if not updates:
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
updates.append('updated = CURRENT_TIMESTAMP')
|
||||||
|
values.append(tier_id)
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
f"UPDATE tiers SET {', '.join(updates)} WHERE id = %s",
|
||||||
|
values
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{tier_id}")
|
||||||
|
def delete_tier(tier_id: str, session: dict = Depends(require_admin)):
|
||||||
|
"""Admin: Delete tier (soft-delete: set active=false)."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("UPDATE tiers SET active = false WHERE id = %s", (tier_id,))
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""
|
||||||
|
User Restrictions Management Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Admin-only user-specific feature overrides.
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter, HTTPException, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_admin
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/user-restrictions", tags=["user-restrictions"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def list_user_restrictions(profile_id: str = None, session: dict = Depends(require_admin)):
|
||||||
|
"""
|
||||||
|
Admin: List user restrictions.
|
||||||
|
|
||||||
|
Optional query param: ?profile_id=... (filter by user)
|
||||||
|
"""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
if profile_id:
|
||||||
|
cur.execute("""
|
||||||
|
SELECT
|
||||||
|
ur.*,
|
||||||
|
f.name as feature_name,
|
||||||
|
f.category as feature_category,
|
||||||
|
p.name as profile_name
|
||||||
|
FROM user_feature_restrictions ur
|
||||||
|
JOIN features f ON f.id = ur.feature_id
|
||||||
|
JOIN profiles p ON p.id = ur.profile_id
|
||||||
|
WHERE ur.profile_id = %s
|
||||||
|
ORDER BY f.category, f.name
|
||||||
|
""", (profile_id,))
|
||||||
|
else:
|
||||||
|
cur.execute("""
|
||||||
|
SELECT
|
||||||
|
ur.*,
|
||||||
|
f.name as feature_name,
|
||||||
|
f.category as feature_category,
|
||||||
|
p.name as profile_name,
|
||||||
|
p.email as profile_email
|
||||||
|
FROM user_feature_restrictions ur
|
||||||
|
JOIN features f ON f.id = ur.feature_id
|
||||||
|
JOIN profiles p ON p.id = ur.profile_id
|
||||||
|
ORDER BY p.name, f.category, f.name
|
||||||
|
""")
|
||||||
|
|
||||||
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("")
|
||||||
|
def create_user_restriction(data: dict, session: dict = Depends(require_admin)):
|
||||||
|
"""
|
||||||
|
Admin: Create user-specific feature restriction.
|
||||||
|
|
||||||
|
Body:
|
||||||
|
{
|
||||||
|
"profile_id": "uuid",
|
||||||
|
"feature_id": "weight_entries",
|
||||||
|
"limit_value": 10, // NULL = unlimited, 0 = disabled
|
||||||
|
"reason": "Spam prevention"
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
profile_id = data.get('profile_id')
|
||||||
|
feature_id = data.get('feature_id')
|
||||||
|
limit_value = data.get('limit_value')
|
||||||
|
reason = data.get('reason', '')
|
||||||
|
|
||||||
|
if not profile_id or not feature_id:
|
||||||
|
raise HTTPException(400, "profile_id und feature_id fehlen")
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
# Check if restriction already exists
|
||||||
|
cur.execute("""
|
||||||
|
SELECT id FROM user_feature_restrictions
|
||||||
|
WHERE profile_id = %s AND feature_id = %s
|
||||||
|
""", (profile_id, feature_id))
|
||||||
|
|
||||||
|
if cur.fetchone():
|
||||||
|
raise HTTPException(400, "Einschränkung existiert bereits (nutze PUT zum Aktualisieren)")
|
||||||
|
|
||||||
|
# Create restriction
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO user_feature_restrictions (
|
||||||
|
profile_id, feature_id, limit_value, reason, created_by
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""", (profile_id, feature_id, limit_value, reason, session['profile_id']))
|
||||||
|
|
||||||
|
restriction_id = cur.fetchone()['id']
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {"ok": True, "id": restriction_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{restriction_id}")
|
||||||
|
def update_user_restriction(restriction_id: str, data: dict, session: dict = Depends(require_admin)):
|
||||||
|
"""Admin: Update user restriction."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
|
updates = []
|
||||||
|
values = []
|
||||||
|
|
||||||
|
if 'limit_value' in data:
|
||||||
|
updates.append('limit_value = %s')
|
||||||
|
values.append(data['limit_value'])
|
||||||
|
if 'reason' in data:
|
||||||
|
updates.append('reason = %s')
|
||||||
|
values.append(data['reason'])
|
||||||
|
|
||||||
|
if not updates:
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
updates.append('updated = CURRENT_TIMESTAMP')
|
||||||
|
values.append(restriction_id)
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
f"UPDATE user_feature_restrictions SET {', '.join(updates)} WHERE id = %s",
|
||||||
|
values
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{restriction_id}")
|
||||||
|
def delete_user_restriction(restriction_id: str, session: dict = Depends(require_admin)):
|
||||||
|
"""Admin: Delete user restriction (reverts to tier limit)."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("DELETE FROM user_feature_restrictions WHERE id = %s", (restriction_id,))
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
"""
|
||||||
|
Weight Tracking Endpoints for Mitai Jinkendo
|
||||||
|
|
||||||
|
Handles weight log CRUD operations and statistics.
|
||||||
|
"""
|
||||||
|
import uuid
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Header, Depends
|
||||||
|
|
||||||
|
from db import get_db, get_cursor, r2d
|
||||||
|
from auth import require_auth
|
||||||
|
from models import WeightEntry
|
||||||
|
from routers.profiles import get_pid
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/weight", tags=["weight"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def list_weight(limit: int=365, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Get weight entries for current profile."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"SELECT * FROM weight_log WHERE profile_id=%s ORDER BY date DESC LIMIT %s", (pid,limit))
|
||||||
|
return [r2d(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("")
|
||||||
|
def upsert_weight(e: WeightEntry, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Create or update weight entry (upsert by date)."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT id FROM weight_log WHERE profile_id=%s AND date=%s", (pid,e.date))
|
||||||
|
ex = cur.fetchone()
|
||||||
|
if ex:
|
||||||
|
cur.execute("UPDATE weight_log SET weight=%s,note=%s WHERE id=%s", (e.weight,e.note,ex['id']))
|
||||||
|
wid = ex['id']
|
||||||
|
else:
|
||||||
|
wid = str(uuid.uuid4())
|
||||||
|
cur.execute("INSERT INTO weight_log (id,profile_id,date,weight,note,created) VALUES (%s,%s,%s,%s,%s,CURRENT_TIMESTAMP)",
|
||||||
|
(wid,pid,e.date,e.weight,e.note))
|
||||||
|
return {"id":wid,"date":e.date,"weight":e.weight}
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{wid}")
|
||||||
|
def update_weight(wid: str, e: WeightEntry, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Update existing weight entry."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("UPDATE weight_log SET date=%s,weight=%s,note=%s WHERE id=%s AND profile_id=%s",
|
||||||
|
(e.date,e.weight,e.note,wid,pid))
|
||||||
|
return {"id":wid}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{wid}")
|
||||||
|
def delete_weight(wid: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Delete weight entry."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("DELETE FROM weight_log WHERE id=%s AND profile_id=%s", (wid,pid))
|
||||||
|
return {"ok":True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/stats")
|
||||||
|
def weight_stats(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||||
|
"""Get weight statistics (last 90 days)."""
|
||||||
|
pid = get_pid(x_profile_id)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT date,weight FROM weight_log WHERE profile_id=%s ORDER BY date DESC LIMIT 90", (pid,))
|
||||||
|
rows = cur.fetchall()
|
||||||
|
if not rows: return {"count":0,"latest":None,"prev":None,"min":None,"max":None,"avg_7d":None}
|
||||||
|
w=[float(r['weight']) for r in rows]
|
||||||
|
return {"count":len(rows),"latest":{"date":rows[0]['date'],"weight":float(rows[0]['weight'])},
|
||||||
|
"prev":{"date":rows[1]['date'],"weight":float(rows[1]['weight'])} if len(rows)>1 else None,
|
||||||
|
"min":min(w),"max":max(w),"avg_7d":round(sum(w[:7])/min(7,len(w)),2)}
|
||||||
Reference in new issue
Block a user