Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
272c123952 | ||
|
|
91c8a5332f | ||
|
|
a849d5db9e | ||
|
|
ae9743d6ed | ||
|
|
ae47652d0c | ||
|
|
c002cb1e54 | ||
|
|
9387670a7b | ||
|
|
a8df7f8359 | ||
|
|
2f302b26af | ||
|
|
26f8bcf86d | ||
|
|
95c57de8d0 | ||
|
|
d4a8401a6a | ||
|
|
aaf88a6f12 | ||
|
|
b789c1bd44 | ||
|
|
5062aa8068 | ||
|
|
8a042589e7 | ||
|
|
3898b5ad45 | ||
|
|
9d15336144 |
No files matched your search
@@ -96,19 +96,479 @@ mitai-jinkendo/
|
|||||||
- ✅ 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%)
|
- ✅ **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
|
||||||
@@ -443,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
|
||||||
+19
-1
@@ -18,6 +18,8 @@ from db import init_db
|
|||||||
from routers import auth, profiles, weight, circumference, caliper
|
from routers import auth, profiles, weight, circumference, caliper
|
||||||
from routers import activity, nutrition, photos, insights, prompts
|
from routers import activity, nutrition, photos, insights, prompts
|
||||||
from routers import admin, stats, exportdata, importdata
|
from routers import admin, stats, exportdata, importdata
|
||||||
|
from routers import subscription, coupons, features, tiers_mgmt, tier_limits
|
||||||
|
from routers import user_restrictions, access_grants
|
||||||
|
|
||||||
# ── App Configuration ─────────────────────────────────────────────────────────
|
# ── App Configuration ─────────────────────────────────────────────────────────
|
||||||
DATA_DIR = Path(os.getenv("DATA_DIR", "./data"))
|
DATA_DIR = Path(os.getenv("DATA_DIR", "./data"))
|
||||||
@@ -51,6 +53,13 @@ async def startup_event():
|
|||||||
print(f"⚠️ init_db() failed (non-fatal): {e}")
|
print(f"⚠️ init_db() failed (non-fatal): {e}")
|
||||||
# Don't crash on startup - can be created manually
|
# Don't crash on startup - can be created manually
|
||||||
|
|
||||||
|
# Apply v9c migration if needed
|
||||||
|
try:
|
||||||
|
from apply_v9c_migration import apply_migration
|
||||||
|
apply_migration()
|
||||||
|
except Exception as e:
|
||||||
|
print(f"⚠️ v9c migration failed (non-fatal): {e}")
|
||||||
|
|
||||||
# ── Register Routers ──────────────────────────────────────────────────────────
|
# ── Register Routers ──────────────────────────────────────────────────────────
|
||||||
app.include_router(auth.router) # /api/auth/*
|
app.include_router(auth.router) # /api/auth/*
|
||||||
app.include_router(profiles.router) # /api/profiles/*, /api/profile
|
app.include_router(profiles.router) # /api/profiles/*, /api/profile
|
||||||
@@ -67,8 +76,17 @@ app.include_router(stats.router) # /api/stats
|
|||||||
app.include_router(exportdata.router) # /api/export/*
|
app.include_router(exportdata.router) # /api/export/*
|
||||||
app.include_router(importdata.router) # /api/import/*
|
app.include_router(importdata.router) # /api/import/*
|
||||||
|
|
||||||
|
# v9c Subscription System
|
||||||
|
app.include_router(subscription.router) # /api/subscription/*
|
||||||
|
app.include_router(coupons.router) # /api/coupons/*
|
||||||
|
app.include_router(features.router) # /api/features (admin)
|
||||||
|
app.include_router(tiers_mgmt.router) # /api/tiers (admin)
|
||||||
|
app.include_router(tier_limits.router) # /api/tier-limits (admin)
|
||||||
|
app.include_router(user_restrictions.router) # /api/user-restrictions (admin)
|
||||||
|
app.include_router(access_grants.router) # /api/access-grants (admin)
|
||||||
|
|
||||||
# ── Health Check ──────────────────────────────────────────────────────────────
|
# ── Health Check ──────────────────────────────────────────────────────────────
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
def root():
|
def root():
|
||||||
"""API health check."""
|
"""API health check."""
|
||||||
return {"status": "ok", "service": "mitai-jinkendo", "version": "v9b"}
|
return {"status": "ok", "service": "mitai-jinkendo", "version": "v9c-dev"}
|
||||||
@@ -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
|
||||||
|
-- ============================================================================
|
||||||
@@ -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,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,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,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}
|
||||||
Reference in new issue
Block a user