Author SHA1 Message Date
LarsandClaude Opus 4.6 86f7a513fe feat: add self-registration frontend
Deploy Development / deploy (push) Failing after 25s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Components:
- Register.jsx: Registration form with validation
- Verify.jsx: Email verification page with auto-login
- API calls: register(), verifyEmail()

Features:
- Form validation (name min 2, email format, password min 8, password confirm)
- Success screen after registration (check email)
- Auto-login after verification → redirect to dashboard
- Error handling for invalid/expired tokens
- Link to registration from login page

Routes:
- /register → public (no login required)
- /verify?token=xxx → public
- Pattern matches existing /reset-password handling

UX:
- Clean success/error states
- Loading spinners
- Auto-redirect after verify (2s)
- "Jetzt registrieren" link on login

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 09:55:23 +01:00
LarsandClaude Opus 4.6 c1562a27f4 feat: add self-registration with email verification
Backend:
- New endpoint: POST /api/auth/register
- New endpoint: GET /api/auth/verify/{token}
- Migration: Add email_verified, verification_token, verification_expires
- Helper: send_email() for reusable SMTP
- Validation: email format, password length (min 8), name
- Auto-login after verification (returns session token)
- Rate limit: 3 registrations per hour per IP

Features:
- Verification token valid for 24h
- Existing users marked as verified (grandfather clause)
- SMTP configured via .env (SMTP_HOST, SMTP_USER, SMTP_PASS)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 09:53:11 +01:00
LarsandClaude Opus 4.6 888b5c3e40 fix: [BUG-003] correlations chart shows all weight data with extrapolation
Deploy Development / deploy (push) Successful in 35s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Changes:
- Show all data points (kcal OR weight, not only both)
- Extrapolate missing kcal values at end (use last known value)
- Dashed lines (strokeDasharray) for extrapolated values
- Solid lines for real measurements
- Weight always interpolates gaps (connectNulls=true)

Visual distinction:
- Solid = Real measurements + gap interpolation
- Dashed = Extrapolation at chart end

Closes: BUG-003

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 09:51:20 +01:00
LarsandClaude Opus 4.6 d1675dcc80 fix: [BUG-004] import history refreshes after CSV import
Solution: Force remount ImportHistory via key prop
- Added importHistoryKey state (timestamp)
- Update key after import → triggers useEffect reload
- ImportHistory now updates immediately after import

Closes: BUG-004

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 09:50:35 +01:00
LarsandClaude Opus 4.6 770a49b5f3 fix: update version string to v9c
Deploy Development / deploy (push) Successful in 35s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 08:59:24 +01:00
LarsandClaude Opus 4.6 0ab13c282e docs: update CLAUDE.md for v9c completion
Deploy Development / deploy (push) Successful in 35s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Changes:
- Version: v9c-dev → v9c (komplett)
- Added nutrition module enhancements (manual entry, edit/delete, filters, import history)
- Documented bug fixes (BUG-001, BUG-002)
- Moved open items to v9d
- Two-level tab layout documented

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 08:47:04 +01:00
LarsandClaude Opus 4.6 1f1100c289 refactor: restructure nutrition page with two-level tabs
Deploy Development / deploy (push) Successful in 35s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Layout changes:
- Input tabs at top: ✏️ Einzelerfassung (default) | 📥 Import
- Single entry form shown by default (was hidden in data tab)
- Import panel + history only visible in Import tab
- Analysis section below (unchanged): OverviewCards + Analysis tabs

Benefits:
- Cleaner separation of input methods vs analysis
- Manual entry more discoverable (was buried in data tab)
- Import history only shown when relevant
- Reduces clutter on initial view

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 08:43:55 +01:00
LarsandClaude Opus 4.6 02ca9772d6 feat: add manual nutrition entry form with auto-detect
Deploy Development / deploy (push) Successful in 34s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Features:
- Manual entry form above data list
- Date picker with auto-load existing entries
- Upsert logic: creates new or updates existing entry
- Smart button text: "Hinzufügen" vs "Aktualisieren"
- Prevents duplicate entries per day
- Feature enforcement for nutrition_entries

Backend:
- POST /nutrition - Create or update entry (upsert)
- GET /nutrition/by-date/{date} - Load entry by date
- Auto-detects existing entry and switches to UPDATE mode
- Increments usage counter only on INSERT

Frontend:
- EntryForm component with date picker + macros inputs
- Auto-loads data when date changes
- Shows info message when entry exists
- Success/error feedback
- Disabled state while loading/saving

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 08:37:01 +01:00
LarsandClaude Opus 4.6 873f08042e feat: add date filter to nutrition data tab
Deploy Development / deploy (push) Successful in 33s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 13s
Added dropdown filter with options:
- Letzte 7 Tage
- Letzte 30 Tage (default)
- Letzte 90 Tage
- Letztes Jahr
- Alle anzeigen

Shows filtered count vs total count in title.
Handles large datasets (7+ years) efficiently.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 08:33:03 +01:00
LarsandClaude Opus 4.6 0f072f4735 feat: add nutrition entry editing and import history
Deploy Development / deploy (push) Successful in 33s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Features:
- Import history panel showing all CSV imports with date, count, and range
- Edit/delete functionality for nutrition entries (inline editing)
- New backend endpoints: GET /import-history, PUT /{id}, DELETE /{id}

UI Changes:
- Import history displayed under import panel
- "Daten" tab now has edit/delete buttons per entry
- Inline form for editing macros (kcal, protein, fat, carbs)
- Confirmation dialog for deletion

Backend:
- nutrition.py: Added import_history, update_nutrition, delete_nutrition endpoints
- Groups imports by created date to show history

Frontend:
- NutritionPage: New DataTab and ImportHistory components
- api.js: Added nutritionImportHistory, updateNutrition, deleteNutrition

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 08:26:47 +01:00
LarsandClaude Opus 4.6 d833a60ad4 fix: [BUG-002] add missing Daten tab to show nutrition entries
Deploy Development / deploy (push) Successful in 34s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Problem: Imported nutrition data not visible in UI
Root Cause: NutritionPage only had analysis tabs, no raw data view
Solution: Added "Daten" tab with entries list showing date, kcal, macros
Tested: Entries now visible after CSV import

Closes: BUG-002

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 08:06:01 +01:00
LarsandClaude Opus 4.6 4d9c59ccf7 fix: [BUG-001] TypeError in nutrition_weekly endpoint
Deploy Development / deploy (push) Successful in 34s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Problem:
- /api/nutrition/weekly crashed with 500 Internal Server Error
- TypeError: strptime() argument 1 must be str, not datetime.date

Root Cause:
- d['date'] from PostgreSQL is already datetime.date object
- datetime.strptime() expects string input
- Line 156: wk=datetime.strptime(d['date'],'%Y-%m-%d').strftime('%Y-W%V')

Solution:
- Added type check before strptime()
- If date already has strftime method → use directly
- Else → parse as string first
- Works with both datetime.date objects and strings

Tested:
- /nutrition page loads without error
- Weekly aggregation works correctly
- Chart displays nutrition data

Closes: BUG-001

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 07:58:37 +01:00
LarsandClaude Opus 4.6 f2f089a223 docs: add pending features and known issues tracking
Deploy Development / deploy (push) Successful in 33s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
CLAUDE.md erweitert:
- Verweis auf PENDING_FEATURES.md (ausstehende Enforcement-Items)
- Verweis auf KNOWN_ISSUES.md (Bug-Tracking)

Lokal erstellt (in .claude/):

.claude/docs/PENDING_FEATURES.md:
- Dashboard-Assistent (keine Badges)
- Import-Endpoints ohne Enforcement (Activity CSV, Nutrition CSV)
- Weitere potenzielle Limitierungen (Export-Wiederholungen, etc.)
- Implementierungs-Richtlinien für späteres Nachziehen

.claude/docs/KNOWN_ISSUES.md:
- BUG-001: Nutrition Import-Seite zeigt keine bisherigen Importe
  (Daten vorhanden in Verlauf, aber Import-Panel zeigt keine Historie)
- Technische Schulden (alte AI-Limit-Checks, deprecated export_enabled)
- Bug-Meldung-Prozess dokumentiert

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 07:55:04 +01:00
LarsandClaude Opus 4.6 fed51453e4 docs: update CLAUDE.md with completed Phase 3+4 status
Deploy Development / deploy (push) Successful in 34s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 1s
Feature-Enforcement komplett:
- ✅ Phase 1-4 alle abgeschlossen
- 11 Features mit Monitoring, UI-Badges + Blocking
- Verweis auf neue FEATURE_ENFORCEMENT.md Dokumentation

Lokale Dokumentation erstellt:
- .claude/docs/architecture/FEATURE_ENFORCEMENT.md
- Vollständiger Guide für neue Feature-Integration
- Backend + Frontend Pattern mit Beispielen
- Checkliste + Debugging-Tipps

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 07:44:51 +01:00
LarsandClaude Opus 4.6 ed057fe545 feat: complete Phase 4 enforcement UI for all features (frontend)
Deploy Development / deploy (push) Successful in 35s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Alle verbleibenden Screens mit proaktiver Limit-Anzeige:

- ActivityPage: Manuelle Einträge mit Badge + deaktiviertem Button
- Analysis: AI-Analysen (Pipeline + Einzelanalysen) mit Hover-Tooltip
- NutritionPage: Hat bereits Error-Handling (bulk import)

Konsistentes Pattern:
- Usage-Badge im Titel
- Button deaktiviert + Hover-Tooltip bei Limit
- "🔒 Limit erreicht" Button-Text
- Error-Handling für API-Fehler
- Usage reload nach erfolgreichem Speichern

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 07:42:50 +01:00
LarsandClaude Opus 4.6 4b8e6755dc feat: complete Phase 4 enforcement for all features (backend)
Alle 11 Features blockieren jetzt bei Limit-Überschreitung:

Batch 1 (bereits erledigt):
- weight_entries, circumference_entries, caliper_entries

Batch 2:
- activity_entries
- nutrition_entries (CSV import)
- photos

Batch 3:
- ai_calls (einzelne Analysen)
- ai_pipeline (3-stufige Gesamtanalyse)
- data_export (CSV, JSON, ZIP)
- data_import (ZIP)

Entfernt: Alte check_ai_limit() Calls (ersetzt durch neue Feature-Limits)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 07:40:37 +01:00
LarsandClaude Opus 4.6 d13c2c7e25 fix: add dashboard weight enforcement and fix hover tooltips
Deploy Development / deploy (push) Successful in 35s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
- Dashboard QuickWeight: Feature limit enforcement hinzugefügt
- Hover-Tooltip Fix: Button in div wrapper (disabled buttons zeigen keine nativen tooltips)
- Error handling für Dashboard weight input
- Konsistentes UX über alle Eingabe-Screens

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 07:25:47 +01:00
LarsandClaude Opus 4.6 0f019f87a4 feat: add feature limit enforcement UI (Phase 4 Batch 1)
Deploy Development / deploy (push) Successful in 34s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Implementiert User-freundliches Limit-Feedback für Daten-Einträge:
- Button wird deaktiviert wenn Limit erreicht
- Hover-Tooltip erklärt warum ("Limit erreicht X/Y")
- Button-Text zeigt "🔒 Limit erreicht"
- Error-Handling für alle API-Fehler
- Usage-Badge wird nach Speichern aktualisiert

Betrifft: Weight, Circumference, Caliper Screens

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 07:14:34 +01:00
LarsandClaude Opus 4.6 cf522190c6 fix: correct indentation in auth.py _check_impl function
Deploy Development / deploy (push) Successful in 40s
Build Test / build-frontend (push) Successful in 12s
Build Test / lint-backend (push) Successful in 0s
Behebt IndentationError in Zeile 204 der _check_impl() Funktion.
Die Funktion wurde beim Connection-Pool-Fix erstellt, hatte aber
inkonsistente Einrückungen (8 statt 4 Spaces nach der ersten Zeile).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 07:06:53 +01:00
LarsandClaude Opus 4.6 329daaef1c fix: prevent connection pool exhaustion in features/usage
Deploy Development / deploy (push) Successful in 35s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
- Add optional conn parameter to get_effective_tier()
- Add optional conn parameter to check_feature_access()
- Pass existing connection in features.py loop
- Prevents opening 20+ connections simultaneously
- Fixes "connection pool exhausted" error

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 07:02:42 +01:00
LarsandClaude Opus 4.6 cbcb6a2a34 feat: Phase 4 Batch 1 - enable enforcement for data entries
Deploy Development / deploy (push) Successful in 36s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- Weight, Circumference, Caliper now BLOCK on limit exceeded
- Raise HTTPException(403) with user-friendly message
- Show used/limit and suggest contacting admin
- Phase 2 → Phase 4 transition

Phase 4: Enforcement (Batch 1/3)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 06:57:05 +01:00
LarsandClaude Opus 4.6 baad096ead refactor: consolidate badge styling to CSS classes
Deploy Development / deploy (push) Successful in 36s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- Move all positioning logic from inline styles to CSS
- New classes: .badge-container-right, .badge-button-layout
- All badge styling now in UsageBadge.css (single source)
- Easier to maintain and adjust globally
- Mobile responsive adjustments in one place

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 06:54:45 +01:00
LarsandClaude Opus 4.6 30df150b6f refactor: make UsageBadge more subtle and better positioned
Deploy Development / deploy (push) Successful in 36s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- Smaller font (0.65rem), more spacing (10px margin)
- Reduced opacity (0.6), hover effect (0.9)
- OK status now gray instead of green (less prominent)
- Position: right-aligned in headings (flex space-between)
- Buttons: badge on right side of main text, description below
- Much more discreet overall appearance

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 06:50:12 +01:00
LarsandClaude Opus 4.6 c59c71a1c7 feat: add UsageBadge to action buttons (Phase 3)
Deploy Development / deploy (push) Successful in 34s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
- Weight page: badge on "Eintrag hinzufügen" heading
- Settings: badges on export buttons (ZIP/JSON)
- Analysis: badges on pipeline and individual analysis titles
- Shows real-time usage status (e.g., "7/5" with red color)

Phase 3: Frontend Display complete

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 06:43:10 +01:00
LarsandClaude Opus 4.6 405abc1973 feat: add feature usage UI components (Phase 3)
Deploy Development / deploy (push) Successful in 35s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
- Add api.getFeatureUsage() endpoint call
- Create UsageBadge component (inline indicators)
- Create FeatureUsageOverview component (Settings table)
- Add "Kontingente" section to Settings page
- Color-coded status (green/yellow/red)
- Grouped by category
- Shows reset period and next reset date

Phase 3: Frontend Display

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 06:39:52 +01:00
LarsandClaude Opus 4.6 d10f605d66 feat: add GET /api/features/usage endpoint (Phase 3)
Deploy Development / deploy (push) Successful in 36s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
- Add user-facing usage overview endpoint
- Returns all features with usage, limits, reset info
- Fully dynamic - automatically includes new features
- Phase 3: Frontend Display preparation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 06:32:43 +01:00
LarsandClaude Opus 4.6 4e846605e9 docs: update CLAUDE.md - Phase 2 complete
Deploy Development / deploy (push) Successful in 34s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 12s
- Mark Feature-Enforcement Phase 2 as complete
- Add 4-phase model status overview
- Document feature_logger.py and JSON logging
- Update DB schema section with user_feature_usage

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 22:43:29 +01:00
LarsandClaude Opus 4.6 32d53b447d fix: pipeline typo and add features diagnostic script
Deploy Development / deploy (push) Successful in 34s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- Fix NameError in insights.py pipeline endpoint (access -> access_calls)
- Add check_features.py diagnostic script for debugging

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 22:32:09 +01:00
LarsandClaude Opus 4.6 1298bd235f feat: add structured JSON logging for all feature usage (Phase 2)
Deploy Development / deploy (push) Successful in 35s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
- Create feature_logger.py with JSON logging infrastructure
- Add log_feature_usage() calls to all 9 routers after check_feature_access()
- Logs written to /app/logs/feature-usage.log
- Tracks all usage (not just violations) for future analysis
- Phase 2: Non-blocking monitoring complete

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 22:18:12 +01:00
LarsandClaude Opus 4.6 ddcd2f4350 feat: v9c Phase 2 - Backend Non-Blocking Logging (12 Endpoints)
Deploy Development / deploy (push) Successful in 34s
Build Test / build-frontend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 1s
PHASE 2: Backend Non-Blocking Logging - KOMPLETT

Instrumentierte Endpoints (12):
- Data: weight, circumference, caliper, nutrition, activity, photos (6)
- AI: insights/run/{slug}, insights/pipeline (2)
- Export: csv, json, zip (3)
- Import: zip (1)

Pattern implementiert:
- check_feature_access() VOR Operation (non-blocking)
- [FEATURE-LIMIT] Logging wenn Limit überschritten
- increment_feature_usage() NACH Operation
- Alte Permission-Checks bleiben aktiv

Features geprüft:
- weight_entries, circumference_entries, caliper_entries
- nutrition_entries, activity_entries, photos
- ai_calls, ai_pipeline
- data_export, data_import

Monitoring: 1-2 Wochen Log-Only-Phase
Logs zeigen: Wie oft würde blockiert werden?
Nächste Phase: Frontend Display (Usage-Counter)

Phase 1 (Cleanup) + Phase 2 (Logging) vollständig!

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 21:59:33 +01:00
LarsandClaude Opus 4.6 73bea5ee86 feat: v9c Phase 1 - Feature consolidation & cleanup migration
Deploy Development / deploy (push) Successful in 33s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
PHASE 1: Cleanup & Analyse
- Feature-Konsolidierung: export_csv/json/zip → data_export (1 Feature)
- Umbenennung: csv_import → data_import
- Auto-Migration bei Container-Start (apply_v9c_migration.py)
- Diagnose-Script (check_features.sql)

Lessons Learned angewendet:
- Ein Feature für Export, nicht drei
- Migration ist idempotent (kann mehrfach laufen)
- Zeigt BEFORE/AFTER State im Log

Finaler Feature-Katalog (10 statt 13):
- Data: weight, circumference, caliper, nutrition, activity, photos
- AI: ai_calls, ai_pipeline
- Export/Import: data_export, data_import

Tier Limits:
- FREE: 30 data entries, 0 AI/export/import
- BASIC: unlimited data, 3 AI/month, 5 export/month, 3 import/month
- PREMIUM/SELFHOSTED: unlimited

Migration läuft automatisch auf dev UND prod beim Container-Start.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 18:57:39 +01:00
Lars 7040931816 claude.md überarbeitet
Deploy Development / deploy (push) Successful in 34s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
2026-03-20 18:22:45 +01:00
LarsandClaude Opus 4.6 ef8008a75d docs: update CLAUDE.md and add comprehensive membership system documentation
Deploy Development / deploy (push) Successful in 33s
Build Test / build-frontend (push) Successful in 12s
Build Test / lint-backend (push) Successful in 0s
Updates:
- CLAUDE.md: Reflect current v9c-dev status (enforcement disabled, history working)
- CLAUDE.md: Document simple AI limit system currently active
- CLAUDE.md: Update implementation status (admin UI complete, enforcement rolled back)

New Documentation:
- docs/MEMBERSHIP_SYSTEM.md: Complete v9c architecture documentation
  - Design decisions and rationale
  - Complete database schema (11 tables)
  - Backend API overview (7 routers, 30+ endpoints)
  - Frontend components (6 admin pages)
  - Feature enforcement rollback analysis
  - Lessons learned and next steps
  - Testing strategy
  - Deployment notes
  - Troubleshooting guide

The new doc provides complete reference for:
- Feature-Registry-Pattern implementation
- Tier system architecture
- Coupon system (3 types with stacking logic)
- User-Override system
- Access-Grant mechanics
- What went wrong with enforcement attempt
- Roadmap for v9d/v9e

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 15:44:29 +01:00
LarsandClaude Opus 4.6 e4f49c0351 fix: enable AI analysis history and correct pipeline scope
Deploy Development / deploy (push) Successful in 33s
Build Test / build-frontend (push) Successful in 12s
Build Test / lint-backend (push) Successful in 0s
Fixes two critical bugs in AI analysis storage:

1. History now works - analyses are saved, not overwritten
   - Removed DELETE statements before INSERT in insights.py
   - All analyses are now preserved per scope
   - Displayed in descending order by creation date

2. Pipeline saves under correct scope 'pipeline' instead of 'gesamt'
   - Changed scope from 'gesamt' to 'pipeline' in pipeline endpoint
   - Pipeline results now appear under correct category in history

3. Fixed pipeline appearing twice in UI
   - Filter now excludes both 'pipeline_*' and 'pipeline' from individual list
   - Pipeline only appears in dedicated section at top

Changes:
- backend/routers/insights.py: Removed DELETE, changed scope to 'pipeline'
- frontend/src/pages/Analysis.jsx: Fixed filter to exclude 'pipeline'

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 15:35:33 +01:00
LarsandClaude Opus 4.6 4fcde4abfb ROLLBACK: complete removal of broken feature enforcement system
Deploy Development / deploy (push) Successful in 32s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Reverts all feature enforcement changes (commits 3745ebd, cbad50a, cd4d912, 8415509)
to restore original working functionality.

Issues caused by feature enforcement implementation:
- Export buttons disappeared and never reappeared
- KI analysis counter not incrementing
- New analyses not saving
- Pipeline appearing twice
- Many core features broken

Restored files to working state before enforcement implementation (commit 0210844):
- Backend: auth.py, insights.py, exportdata.py, importdata.py, nutrition.py, activity.py
- Frontend: Analysis.jsx, SettingsPage.jsx, api.js
- Removed: FeatureGate.jsx, useFeatureAccess.js

The original simple AI limit system (ai_enabled, ai_limit_day) is now active again.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 15:19:56 +01:00
LarsandClaude Opus 4.6 8415509f4c fix: monthly reset now updates reset_at correctly
Deploy Development / deploy (push) Successful in 34s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Critical bug: usage limits were never resetting after first month because
reset_at timestamp was not updated during ON CONFLICT UPDATE.

This caused users to stay permanently blocked after reaching monthly limit once.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 13:14:35 +01:00
Lars cd4d9124b0 fix: auto-apply feature fixes migration on startup
Deploy Development / deploy (push) Successful in 33s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
2026-03-20 12:58:07 +01:00
LarsandClaude Opus 4.6 cbad50a987 fix: add missing feature check endpoint and features
Build Test / lint-backend (push) Waiting to run
Build Test / build-frontend (push) Waiting to run
Deploy Development / deploy (push) Has been cancelled
Critical fixes for feature enforcement:
- Add GET /api/features/{feature_id}/check-access endpoint (was missing!)
- Add migration for missing features: data_export, csv_import
- These features were used in frontend but didn't exist in DB

This fixes:
- "No analysis available" when setting KI limit
- Export features not working
- Frontend calling non-existent API endpoint

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 12:57:29 +01:00
LarsandClaude Opus 4.6 3745ebd6cd feat: implement v9c feature enforcement system
Deploy Development / deploy (push) Successful in 34s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Backend:
- Add feature access checks to insights, export, import endpoints
- Enforce ai_calls, ai_pipeline, data_export, csv_import limits
- Return HTTP 403 (disabled) or 429 (limit exceeded)

Frontend:
- Create useFeatureAccess hook for feature checking
- Create FeatureGate/FeatureBadge components
- Gate KI-Analysen in Analysis page
- Gate Export/Import in Settings page
- Show usage counters (e.g. "3/10")

Docs:
- Update CLAUDE.md with implementation status

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 12:43:41 +01:00
LarsandClaude Opus 4.6 0210844522 docs: CRITICAL - document missing feature enforcement
Deploy Development / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
⚠️ MAJOR GAP IDENTIFIED: Feature limits don't work!
- Admin UI exists to configure limits
- But actual enforcement (check_feature_access) is NOT called in endpoints
- Users can exceed limits, use disabled features

Backend TODO (CRITICAL):
- Add feature checks to insights.py (AI analysis)
- Add feature checks to exportdata.py, importdata.py
- Add feature checks to nutrition.py, activity.py (imports)
- Add feature checks to photos.py, data entry endpoints

Frontend TODO (UX):
- Implement useFeatureAccess() hook
- Create <FeatureGate> component
- Hide disabled features
- Show limit counters & upgrade prompts

Estimated work: 2-3 hours

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 12:25:31 +01:00
LarsandClaude Opus 4.6 5da18de708 docs: update CLAUDE.md - v9c Phase 3 status and lessons learned
Deploy Development / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 12s
- Mark Phase 3 as "MOSTLY DONE" (core features complete)
- Document all implemented admin/user pages
- Add AdminUserRestrictionsPage solution to "Bekannte Probleme"
- Detail effective value system, auto-remove redundant overrides
- List remaining v9c tasks: self-registration, trial UI, app settings

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 12:14:45 +01:00
LarsandClaude Opus 4.6 4e592dddc5 fix: AdminUserRestrictionsPage - show effective values, auto-remove redundant overrides
Deploy Development / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Major UX improvements:
- Display effective value in input (override if set, otherwise tier limit)
- Format NULL as "unlimited" (easy to type, no special char needed)
- Auto-remove override when value equals tier default
- "Zurück" button resets to tier default value
- Wider input field (120px) for "unlimited" text

This solves:
- User can now see and edit current effective values
- "unlimited" can be typed and saved
- Redundant overrides (value = tier default) are prevented
- No more confusion with empty fields vs actual values

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 12:08:29 +01:00
LarsandClaude Opus 4.6 adfa9ec139 fix: AdminUserRestrictionsPage - use same tier limits fallback as TierLimitsPage
Deploy Development / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Use `null` (unlimited) instead of `feature.default_limit` when no
tier_limits entry exists. This fixes Selfhosted tier showing 0
instead of ∞ for features like AI analysis.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 11:57:26 +01:00
LarsandClaude Opus 4.6 85f5938d7d fix: AdminUserRestrictionsPage - use exact TierLimitsPage input system
Deploy Development / deploy (push) Successful in 58s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
- formatValue: NULL → '' (empty field with placeholder ∞)
- handleChange: Accept ONLY '∞' or 'unlimited' (no other formats)
- Input styling: Green only for '∞', empty fields normal color
- Simplified legend: Only ∞ or unlimited accepted
- Boolean features: Toggle buttons with 1/0 values
- Add package-lock.json to .gitignore

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 11:34:48 +01:00
LarsandClaude Opus 4.6 917c8937cf feat: accept multiple formats for unlimited in user overrides
Deploy Development / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 12s
User can now input unlimited with:
- "unbegrenzt" (German)
- "unlimited" (English)
- "inf"
- "999999"
- "∞" (infinity symbol)

All map to NULL (unlimited) in database.

Updated legend to show:
- "unbegrenzt, inf, 999999" = Unbegrenzt
- Clear documentation for users

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 10:40:56 +01:00
LarsandClaude Opus 4.6 0c0b1ee811 fix: add missing Link import in SettingsPage
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 12s
Critical bug fix:
- Added missing "import { Link } from 'react-router-dom'"
- Caused Settings page to crash on render
- Route /settings now works again

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 10:36:00 +01:00
LarsandClaude Opus 4.6 a27f090616 feat: add SubscriptionPage - user-facing subscription info
Deploy Development / deploy (push) Successful in 53s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 20s
User can now view:
- Current tier (Free, Basic, Premium, Selfhosted) with icon
- Trial status and end date
- Access expiration date
- Feature limits with usage bars
- Progress indicators (green/orange/red based on usage)
- Reset period info (daily/monthly/never)

Coupon redemption:
- Input field for coupon code
- Auto-uppercase, monospace display
- Enter key support
- Success/error feedback
- Auto-refresh after redemption

Features:
- Clean card-based layout
- Visual tier badges with colors
- Progress bars for count limits
- Trial and access warnings
- Integrated in Settings page

Link added to SettingsPage:
- "👑 Abo-Status, Limits & Coupon einlösen"
- Easy access for all users

Phase 3 complete - all user-facing subscription features done!

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 10:31:04 +01:00
LarsandClaude Opus 4.6 3eae7eb43f refactor: remove legacy permission system, use only feature-overrides
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
AdminPanel.jsx:
- Removed ai_enabled, ai_limit_day, export_enabled UI
- Kept only role selection (Admin/User)
- Added link to Feature-Overrides page
- Simplified perms state to only role
- Changed display to show tier and email

AdminUserRestrictionsPage.jsx:
- Removed legacy system warning
- Clean interface, no confusion

Result:
- ONE consistent permission system (feature-overrides)
- Clear separation: role in AdminPanel, limits in Feature-Overrides
- No data migration needed (no old users exist)
- System ready for production

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 08:51:49 +01:00
LarsandClaude Opus 4.6 b1a1925360 fix: move buttons to header and add legacy system warning
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Button position fixed:
- Moved from fixed bottom bar to header (like TierLimitsPage)
- No longer covers bottom navigation menu
- Always visible when user selected
- "Abbrechen" only shown when changes exist

Legacy system warning added:
- Yellow warning box explaining old permission system
- Old system: ai_enabled, ai_limit_day, export_enabled in profiles table
- New system: feature_restrictions table with overrides
- Warning: both systems can conflict, new system has priority
- Recommendation: use only feature-overrides going forward

This addresses:
1. UI overlap issue (buttons covering navigation)
2. System architecture confusion (two permission systems)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 08:45:06 +01:00
LarsandClaude Opus 4.6 ac56974e83 fix: make buttons always visible in AdminUserRestrictionsPage
Deploy Development / deploy (push) Successful in 1m2s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Bottom bar changes:
- Always visible when user selected (not hidden)
- Buttons disabled when no changes (clearer state)
- Moved outside inner block to prevent hiding

Action column changes:
- "↺ Zurück" button always visible per feature
- Disabled when no override exists (grayed out)
- Consistent button presence improves UX

This fixes the issue where buttons were not shown
because they were conditionally rendered.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 08:26:18 +01:00
LarsandClaude Opus 4.6 5ef6a80a1f fix: add tier limits display and improve buttons in AdminUserRestrictionsPage
Deploy Development / deploy (push) Successful in 58s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Added tier limits column:
- Shows current tier-limit value for each feature
- Loads from tier-limits matrix based on user's tier
- Visual display for boolean (✓ AN / ✗ AUS) and count features
- Clear comparison: Tier-Limit vs Override-Wert

Added per-feature reset button:
- "↺ Zurück zu Standard" button per feature
- Only shown when override exists
- Removes override with single click

Improved bottom bar buttons:
- Renamed "Zurücksetzen" to "Abbrechen" (clearer)
- Always visible (not hidden when no changes)
- Disabled state when no changes
- Shows "Keine Änderungen" when nothing to save

Better UX:
- Tier-Limit column shows what user gets without override
- Override input highlighted when active (accent-light background)
- Clear action buttons per row
- Global save/cancel at bottom

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 08:13:11 +01:00
LarsandClaude Opus 4.6 365fe3d068 fix: complete rewrite of AdminUserRestrictionsPage
Deploy Development / deploy (push) Successful in 58s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Fixed all reported bugs:
1. Initial values now correct (empty = no override, not defaults)
2. Save/Reset buttons always visible (fixed bottom bar)
3. Toggle buttons work correctly (can be toggled multiple times)
4. Simplified table columns (removed confusing Tier-Limit/Aktiv/Aktion)

New logic:
- Empty input = no override (user uses tier standard)
- Value entered = override set
- Change tracking with 3 actions: set, remove, toggle
- Clear status display: "Override aktiv" vs "Tier-Standard"

Simplified table structure:
- Feature (name + type)
- Override-Wert (input/toggle)
- Status (has override yes/no)

Better UX:
- Placeholder text explains empty = tier standard
- Status badge shows if override is active
- Fixed bottom bar always present
- Buttons disabled only when no changes
- Legend explains all input options

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 08:08:02 +01:00
LarsandClaude Opus 4.6 72d8dd8df7 feat: add AdminUserRestrictionsPage for individual user overrides
Deploy Development / deploy (push) Successful in 59s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 12s
Per-user feature limit overrides:
- Select user from dropdown (shows tier)
- View all features with tier limits
- Set individual overrides that supersede tier limits
- Toggle buttons for boolean features
- Text inputs for count features
- Remove overrides to revert to tier limits

Features:
- User info card (avatar, name, email, tier)
- Feature table grouped by category
- Visual indicators for active overrides
- Change tracking with fixed bottom save bar
- Conditional rendering based on limit type
- Info box explaining override priority

UX improvements:
- Clear "Tier-Limit" vs "Override" columns
- Active/Inactive status per feature
- Batch save with change counter
- Confirmation before removing overrides
- Legend for input values

Use cases:
- Beta testers with extended limits
- Support requests for special access
- Temporary feature grants
- Custom enterprise configurations

Integrated in AdminPanel navigation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 07:59:49 +01:00
LarsandClaude Opus 4.6 18991025bf feat: add AdminCouponsPage for coupon management
Deploy Development / deploy (push) Successful in 57s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 13s
Full CRUD interface for coupons:
- Create, edit, delete coupons
- Three coupon types supported:
  - Single-Use: one-time redemption per user
  - Multi-Use Period: unlimited redemptions in timeframe (Wellpass)
  - Gift: bonus system coupons

Features:
- Auto-generate random coupon codes
- Configure tier, duration, validity period
- Set max redemptions (or unlimited)
- View redemption history per coupon (modal)
- Active/inactive state management
- Card-based layout with visual type indicators

Form improvements:
- Conditional fields based on coupon type
- Date pickers for period coupons
- Duration config for single-use/gift
- Help text for each field
- Labels above inputs (consistent with other pages)

Integrated in AdminPanel navigation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 07:53:47 +01:00
LarsandClaude Opus 4.6 bc4db19190 refactor: improve AdminFeaturesPage form layout and UX
Deploy Development / deploy (push) Successful in 1m0s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Layout improvements:
- Labels now above inputs (not beside)
- Inputs use full width for better readability
- Better spacing and visual hierarchy

Field changes:
- Removed "Einheit" field (unused, confusing)
- "Sortierung" renamed to "Anzeigereihenfolge" with help text
- Added help text under inputs for clarity

Conditional rendering:
- Boolean features: hide Reset-Periode and Standard-Limit
- Show info box explaining Boolean features
- Count features: show all relevant fields

Better UX:
- Clear explanations what each field does
- Visual feedback for different limit types
- Cleaner, more focused interface

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 07:47:00 +01:00
LarsandClaude Opus 4.6 69b6f38c89 refactor: change AdminFeaturesPage to configuration-only interface
Deploy Development / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 13s
Philosophy change:
- Features are registered via code/migrations, not UI
- AdminFeaturesPage now only configures existing features
- No create/delete functionality

Changes:
- Removed "Neues Feature" button and create form
- Removed delete functionality
- Feature ID now read-only in edit mode
- Added info box explaining feature registration
- Improved status display (Aktiv/Inaktiv)
- Added legend for limit types and reset periods
- Focus on configuration: limit type, reset period, defaults, active state

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 06:46:04 +01:00
LarsandClaude Opus 4.6 07a802dff6 feat: add admin pages for Features and Tiers management
Deploy Development / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
AdminFeaturesPage:
- Full CRUD for features registry
- Add/edit features with all properties
- Category, limit type, reset period configuration
- Default limits and sorting

AdminTiersPage:
- Full CRUD for subscription tiers
- Pricing configuration (monthly/yearly in cents)
- Active/inactive state management
- Card-based layout with edit/delete actions

Both pages:
- Form validation
- Success/error messaging
- Clean table/card layouts
- Integrated in AdminPanel navigation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 06:35:13 +01:00
LarsandClaude Opus 4.6 7d6d9dabf2 feat: add toggle buttons for boolean features in matrix editor
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- Boolean features now show as visual toggle buttons (AN/AUS)
- Desktop: compact toggle (✓ AN / ✗ AUS)
- Mobile: full-width toggle (✓ Aktiviert / ✗ Deaktiviert)
- Prevents invalid values for boolean features
- Green when enabled, gray when disabled

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 06:28:31 +01:00
LarsandClaude Opus 4.6 8bb5d85c16 fix: show all tiers in admin matrix editor including selfhosted
Deploy Development / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- Remove active=true filter - admins need to configure all tiers
- Add reset_period to features query for frontend display

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 06:19:32 +01:00
LarsandClaude Opus 4.6 759d5e5162 fix: improve AdminTierLimitsPage UX with responsive design
Deploy Development / deploy (push) Successful in 57s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- Fix input bug: cells now editable after deletion (temp value tracking)
- Add responsive design: mobile card view, desktop table view
- Mobile: accordion-style FeatureMobileCard with fixed bottom bar
- Desktop: enhanced table with better visual feedback
- Maintains PWA compatibility (no media query conflicts)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-20 06:17:52 +01:00
LarsandClaude Opus 4.6 9438b5d617 feat: add Tier Limits Matrix Editor (Admin UI)
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Phase 3 Frontend - First Component: Matrix Editor

New page: AdminTierLimitsPage
- Displays Tier x Feature matrix (editable table)
- Inline editing for all limit values
- Visual feedback for changes (highlighted cells)
- Batch save with validation
- Category grouping (data, ai, export, integration)
- Legend: ∞ = unlimited (NULL), ❌ = disabled (0), 1-999 = limit
- Responsive table with sticky column headers

Features:
- GET /api/tier-limits - Load matrix
- PUT /api/tier-limits/batch - Save all changes
- Change tracking (shows unsaved count)
- Reset button to discard changes
- Success/error messages

API helpers added (api.js):
- v9c subscription endpoints (user + admin)
- listFeatures, listTiers, getTierLimitsMatrix
- updateTierLimit, updateTierLimitsBatch
- listCoupons, redeemCoupon
- User restrictions, access grants

Navigation:
- Link in AdminPanel (Settings Page)
- Route: /admin/tier-limits

Ready for testing on Dev!

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 15:21:52 +01:00
LarsandClaude Opus 4.6 91c8a5332f docs: update v9c status and document known issue
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Phase 2 Backend complete:
- ✅ 11 new tables (Feature-Registry Pattern)
- ✅ Feature-access middleware
- ✅ 7 new routers, 30+ endpoints
- ✅ Tested on dev, all endpoints functional

Known issue documented:
- Admin user creation missing email field (workaround available)

Phase 3 (Frontend UI) remains TODO.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 14:57:57 +01:00
LarsandClaude Opus 4.6 a849d5db9e feat: add admin management routers for subscription system
Deploy Development / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Five new admin routers:

1. routers/features.py
   - GET/POST/PUT/DELETE /api/features
   - Feature registry CRUD
   - Allows adding new limitable features without schema changes

2. routers/tiers_mgmt.py
   - GET/POST/PUT/DELETE /api/tiers
   - Subscription tier management
   - Price configuration, sort order

3. routers/tier_limits.py
   - GET /api/tier-limits - Complete Tier x Feature matrix
   - PUT /api/tier-limits - Update single limit
   - PUT /api/tier-limits/batch - Batch update
   - DELETE /api/tier-limits - Remove limit (fallback to default)
   - Matrix editor backend

4. routers/user_restrictions.py
   - GET/POST/PUT/DELETE /api/user-restrictions
   - User-specific feature overrides
   - Highest priority in access hierarchy
   - Includes reason field for documentation

5. routers/access_grants.py
   - GET /api/access-grants - List grants with filters
   - POST /api/access-grants - Manual grant creation
   - PUT /api/access-grants/{id} - Extend/pause grants
   - DELETE /api/access-grants/{id} - Revoke access
   - Activity logging

All endpoints require admin authentication.
Completes backend API for v9c Phase 2.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 13:09:33 +01:00
LarsandClaude Opus 4.6 ae9743d6ed feat: add coupon management and redemption
Deploy Development / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 12s
New router: routers/coupons.py

Admin endpoints:
- GET /api/coupons - List all coupons with stats
- POST /api/coupons - Create new coupon
- PUT /api/coupons/{id} - Update coupon
- DELETE /api/coupons/{id} - Soft-delete (set active=false)
- GET /api/coupons/{id}/redemptions - Redemption history

User endpoints:
- POST /api/coupons/redeem - Redeem coupon code

Features:
- Three coupon types: single_use, period, wellpass
- Wellpass logic: Pauses existing personal grants, resumes after expiry
- Max redemptions limit (NULL = unlimited)
- Validity period checks
- Activity logging
- Duplicate redemption prevention

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 13:07:09 +01:00
LarsandClaude Opus 4.6 ae47652d0c feat: add user subscription info endpoints
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
New router: routers/subscription.py
Endpoints:
- GET /api/subscription/me - Own subscription info (tier, trial, grants)
- GET /api/subscription/usage - Feature usage with limits
- GET /api/subscription/limits - All feature limits for current tier

Features:
- Shows effective tier (considers access_grants)
- Lists active access grants (from coupons, trials)
- Per-feature usage tracking
- Email verification status

Uses new middleware: get_effective_tier(), check_feature_access()

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 13:05:55 +01:00
LarsandClaude Opus 4.6 c002cb1e54 feat: add feature-access middleware for v9c subscription system
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Has been cancelled
Implements flexible feature access control with 3-tier hierarchy:
1. User-specific restrictions (highest priority)
2. Tier limits
3. Feature defaults

New functions:
- get_effective_tier(profile_id) - Checks access_grants, falls back to profile.tier
- check_feature_access(profile_id, feature_id) - Complete access check
  Returns: {allowed, limit, used, remaining, reason}
- increment_feature_usage(profile_id, feature_id) - Usage tracking
- _calculate_next_reset(reset_period) - Helper for daily/monthly resets

Supports:
- Boolean features (enabled/disabled)
- Count-based features with limits
- Automatic reset (daily/monthly/never)
- Unlimited (NULL) and disabled (0) states

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 13:04:49 +01:00
LarsandClaude Opus 4.6 a8df7f8359 fix: correct UUID foreign key constraints in v9c migration
Deploy Development / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Changed all profile_id columns from TEXT to UUID to match profiles.id type.
Changed all auto-generated IDs from gen_random_uuid() to uuid_generate_v4()
to match existing schema.sql convention.

Fixed tables:
- tier_limits: id TEXT → UUID
- user_feature_restrictions: id, profile_id, created_by TEXT → UUID
- user_feature_usage: id, profile_id TEXT → UUID
- coupons: id, created_by TEXT → UUID
- coupon_redemptions: id, coupon_id, profile_id, access_grant_id TEXT → UUID
- access_grants: id, profile_id, coupon_id, paused_by TEXT → UUID
- user_activity_log: id, profile_id TEXT → UUID
- user_stats: profile_id TEXT → UUID
- profiles.invited_by: TEXT → UUID

This fixes: foreign key constraint "user_feature_restrictions_profile_id_fkey"
cannot be implemented - Key columns "profile_id" and "id" are of
incompatible types: text and uuid

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 12:50:12 +01:00
LarsandClaude Opus 4.6 2f302b26af feat: add v9c subscription system database schema
Deploy Development / deploy (push) Successful in 53s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Phase 1: Database Migration Complete

Created migration infrastructure:
- backend/migrations/v9c_subscription_system.sql (11 new tables)
- backend/apply_v9c_migration.py (auto-migration runner)
- Updated main.py startup event to apply migration

New tables (Feature-Registry Pattern):
1. app_settings - Global configuration
2. tiers - Subscription tiers (free/basic/premium/selfhosted)
3. features - Feature registry (11 limitable features)
4. tier_limits - Tier x Feature matrix (44 initial limits)
5. user_feature_restrictions - Individual user overrides
6. user_feature_usage - Usage tracking with reset periods
7. coupons - Coupon management (single-use, period, Wellpass)
8. coupon_redemptions - Redemption history
9. access_grants - Time-limited access with pause/resume logic
10. user_activity_log - Activity tracking (JSONB details)
11. user_stats - Aggregated statistics

Extended profiles table:
- tier, trial_ends_at, email_verified, email_verify_token
- invited_by, invitation_token

Initial data inserted:
- 4 tiers (free/basic/premium/selfhosted)
- 11 features (weight, circumference, caliper, nutrition, activity, photos, ai_calls, ai_pipeline, export_*)
- 44 tier_limits (complete Tier x Feature matrix)
- App settings (trial duration, self-registration config)

Migration auto-runs on container startup (similar to SQLite→PostgreSQL).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 12:42:43 +01:00
LarsandClaude Opus 4.6 26f8bcf86d docs: add Feature-Registry Pattern architecture for v9c
Deploy Development / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 12s
Replaced hardcoded tier limits with flexible Feature-Registry Pattern:
- features table: All limitable features (weight, AI, photos, export, etc.)
- tier_limits: Tier x Feature matrix (admin-configurable)
- user_feature_restrictions: Individual user overrides
- user_feature_usage: Usage tracking with configurable reset periods

Key capabilities:
- Add new limitable features without schema changes
- Admin UI for matrix-based limit configuration
- User-level overrides for specific restrictions
- Access hierarchy: User restriction > Tier limit > Feature default

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 12:40:25 +01:00
LarsandClaude Opus 4.6 95c57de8d0 docs: comprehensive v9c architecture plan - Subscription & Coupon System
Deploy Development / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Added detailed documentation for v9c features:
- Complete database schema (8 new tables)
- Backend architecture (6 new routers, middleware, cron jobs)
- Frontend extensions (pages, components, admin panels)
- Zugriffs-Hierarchie und Stacking-Logik
- Tier-System mit Admin-editierbaren Limits
- Coupon-System (Single-Use + Multi-Use Period)
- User Activity Tracking
- E-Mail Templates
- Migration roadmap (25 steps in 5 phases)

Spätere Features dokumentiert (v9d/v9e):
- Bonus-System & Gamification
- Stripe-Integration
- Partner-Verwaltung
- Admin-Benachrichtigungen

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 12:24:31 +01:00
LarsandClaude Opus 4.6 b4a1856f79 refactor: modular backend architecture with 14 router modules
Deploy Development / deploy (push) Successful in 58s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Phase 2 Complete - Backend Refactoring:
- Extracted all endpoints to dedicated router modules
- main.py: 1878 → 75 lines (-96% reduction)
- Created modular structure for maintainability

Router Structure (60 endpoints total):
├── auth.py          - 7 endpoints (login, logout, password reset)
├── profiles.py      - 7 endpoints (CRUD + current user)
├── weight.py        - 5 endpoints (tracking + stats)
├── circumference.py - 4 endpoints (body measurements)
├── caliper.py       - 4 endpoints (skinfold tracking)
├── activity.py      - 6 endpoints (workouts + Apple Health import)
├── nutrition.py     - 4 endpoints (diet + FDDB import)
├── photos.py        - 3 endpoints (progress photos)
├── insights.py      - 8 endpoints (AI analysis + pipeline)
├── prompts.py       - 2 endpoints (AI prompt management)
├── admin.py         - 7 endpoints (user management)
├── stats.py         - 1 endpoint (dashboard stats)
├── exportdata.py    - 3 endpoints (CSV/JSON/ZIP export)
└── importdata.py    - 1 endpoint (ZIP import)

Core modules maintained:
- db.py: PostgreSQL connection + helpers
- auth.py: Auth functions (hash, verify, sessions)
- models.py: 11 Pydantic models

Benefits:
- Self-contained modules with clear responsibilities
- Easier to navigate and modify specific features
- Improved code organization and readability
- 100% functional compatibility maintained
- All syntax checks passed

Updated CLAUDE.md with new architecture documentation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 11:15:35 +01:00
Lars 9e6a542289 fix: change password endpoint method from POST to PUT to match frontend
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
2026-03-19 10:13:07 +01:00
LarsandClaude Opus 4.6 c7d283c0c9 refactor: extract Pydantic models to models.py
Deploy Development / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Phase 1.3 - Data Models isolieren

NEUE DATEI:
- backend/models.py: Alle Pydantic Models (122 Zeilen)
  * ProfileCreate, ProfileUpdate
  * WeightEntry, CircumferenceEntry, CaliperEntry
  * ActivityEntry, NutritionDay
  * LoginRequest, PasswordResetRequest, PasswordResetConfirm
  * AdminProfileUpdate

ÄNDERUNGEN:
- backend/main.py:
  * Import models from models.py
  * Entfernt: ~60 Zeilen Model-Definitionen
  * Von 2025 → 1878 Zeilen (-147 Zeilen / -7%)

PROGRESS:
✅ db.py: Database + init_db
✅ auth.py: Auth functions + dependencies
✅ models.py: Pydantic schemas

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 09:53:51 +01:00
63 changed files with 19721 additions and 2631 deletions

No files matched your search

+2 -1
View File
@@ -60,4 +60,5 @@ tmp/
*.tmp
#.claude Konfiguration
.claude/
.claude/
.claude/settings.local.jsonfrontend/package-lock.json
+195 -596
View File
@@ -1,649 +1,248 @@
# Mitai Jinkendo – Entwickler-Kontext für Claude Code
## Projekt-Übersicht
**Mitai Jinkendo** (身体 Jinkendo) ist eine selbst-gehostete PWA für Körper-Tracking (Gewicht, Körperfett, Umfänge, Ernährung, Aktivität) mit KI-Auswertung. Teil der **Jinkendo**-App-Familie (人拳道 – Der menschliche Weg der Kampfkunst).
**Produktfamilie:** mitai · miken · ikigai · shinkan · kenkou (alle unter jinkendo.de)
**Mitai Jinkendo** (身体 Jinkendo) – selbst-gehostete PWA für Körper-Tracking mit KI-Auswertung.
Teil der **Jinkendo**-App-Familie (人拳道). Domains: jinkendo.de / .com / .life
## Tech-Stack
| Komponente | Technologie | Version |
|-----------|-------------|---------|
| Frontend | React 18 + Vite + PWA | Node 20 |
| Backend | FastAPI (Python) | Python 3.12 |
| Datenbank | PostgreSQL 16 (Alpine) | v9b |
| Container | Docker + Docker Compose | - |
| Webserver | nginx (Reverse Proxy) | Alpine |
| Auth | Token-basiert + bcrypt | - |
| KI | OpenRouter API (claude-sonnet-4) | - |
| Komponente | Technologie |
|-----------|-------------|
| Frontend | React 18 + Vite + PWA (Node 20) |
| Backend | FastAPI Python 3.12 |
| Datenbank | PostgreSQL 16 Alpine |
| Container | Docker + Docker Compose |
| Auth | Token-basiert + bcrypt |
| KI | OpenRouter API (claude-sonnet-4) |
## Ports
| Service | Prod | Dev |
|---------|------|-----|
| Frontend | 3002 | 3099 |
| Backend | 8002 | 8099 |
**Ports:** Prod 3002/8002 · Dev 3099/8099 – nie ändern!
## Verzeichnisstruktur
```
mitai-jinkendo/
├── backend/
│ ├── main.py # FastAPI App, alle Endpoints (~2000 Zeilen)
│ ├── requirements.txt
│ └── Dockerfile
├── frontend/
│ ├── src/
│ │ ├── App.jsx # Root, Auth-Gates, Navigation
│ │ ├── app.css # Globale Styles, CSS-Variablen
│ │ ├── context/
│ │ │ ├── AuthContext.jsx # Session, Login, Logout
│ │ │ └── ProfileContext.jsx # Aktives Profil
│ │ ├── pages/ # Alle Screens
│ │ └── utils/
│ │ ├── api.js # Alle API-Calls (injiziert Token automatisch)
│ │ ├── calc.js # Körperfett-Formeln
│ │ ├── interpret.js # Regelbasierte Auswertung
│ │ ├── Markdown.jsx # Eigener MD-Renderer
│ │ └── guideData.js # Messanleitungen
│ └── public/ # Icons (Jinkendo Ensō-Logo)
├── .gitea/workflows/
│ ├── deploy-prod.yml # Auto-Deploy bei Push auf main
│ ├── deploy-dev.yml # Auto-Deploy bei Push auf develop
│ └── test.yml # Build-Test bei jedem Push
├── docker-compose.yml # Produktion (Ports 3002/8002)
├── docker-compose.dev-env.yml # Development (Ports 3099/8099)
└── CLAUDE.md # Diese Datei
backend/
├── main.py # App-Setup + Router-Registration (~75 Zeilen)
├── db.py # PostgreSQL Connection Pool
├── auth.py # Hash, Verify, Sessions, Feature-Access-Control
├── models.py # Pydantic Models
├── feature_logger.py # Strukturiertes JSON-Logging (Phase 2)
└── routers/ # 14 Router-Module
auth · profiles · weight · circumference · caliper
activity · nutrition · photos · insights · prompts
admin · stats · exportdata · importdata
frontend/src/
├── App.jsx # Root, Auth-Gates, Navigation
├── app.css # CSS-Variablen + globale Styles
├── context/ # AuthContext · ProfileContext
├── pages/ # Alle Screens
└── utils/
api.js # ALLE API-Calls – Token automatisch injiziert
calc.js · interpret.js · Markdown.jsx · guideData.js
.claude/
├── settings.json
├── commands/ # /deploy /merge-to-prod /refactor /ui-responsive etc.
└── docs/
├── BACKLOG.md
├── functional/ # Fachliche Specs (TRAINING_TYPES, AI_PROMPTS, RESPONSIVE_UI)
└── technical/ # MEMBERSHIP_SYSTEM.md
```
## Aktuelle Version: v9b
## Aktuelle Version: v9c (komplett)
### Was implementiert ist:
- ✅ Multi-User mit E-Mail + Passwort Login (bcrypt)
- ✅ Auth-Middleware auf ALLE Endpoints (60+ Endpoints geschützt)
- ✅ Rate Limiting (Login: 5/min, Reset: 3/min)
- ✅ CORS konfigurierbar via ALLOWED_ORIGINS in .env
- ✅ Admin/User Rollen, KI-Limits, Export-Berechtigungen
- ✅ Gewicht, Umfänge, Caliper (4 Formeln), Ernährung, Aktivität
- ✅ FDDB CSV-Import (Ernährung), Apple Health CSV-Import (Aktivität)
- ✅ KI-Analyse: 6 Einzel-Prompts + 3-stufige Pipeline (parallel)
- ✅ Konfigurierbare Prompts mit Template-Variablen (Admin kann bearbeiten)
- ✅ Verlauf mit 5 Tabs + Zeitraumfilter + KI pro Sektion
- ✅ Dashboard mit Kennzahlen, Zielfortschritt, Combo-Chart
- ✅ Assistent-Modus (Schritt-für-Schritt Messung)
- ✅ PWA (iPhone Home Screen), Jinkendo Ensō-Logo
- ✅ E-Mail (SMTP) für Password-Recovery
- ✅ Admin-Panel: User verwalten, KI-Limits, E-Mail-Test, PIN/Email setzen
- ✅ Multi-Environment: Prod (mitai.jinkendo.de) + Dev (dev.mitai.jinkendo.de)
- ✅ Gitea CI/CD mit Auto-Deploy auf Raspberry Pi 5
- ✅ PostgreSQL 16 Migration (vollständig von SQLite migriert)
- ✅ Export: CSV, JSON, ZIP (mit Fotos)
- ✅ Automatische SQLite→PostgreSQL Migration bei Container-Start
### Implementiert ✅
- Login (E-Mail + bcrypt), Auth-Middleware alle Endpoints, Rate Limiting
- Gewicht · Umfänge · Caliper · Ernährung · Aktivität + CSV-Imports
- KI-Analyse: 6 Prompts + 3-stufige Pipeline
- Dashboard · Verlauf · Assistent-Modus · Fotos
- Admin-Panel · E-Mail (SMTP) · PWA
- PostgreSQL 16 · Modulare Router-Architektur
- Membership-System: Tiers · Coupons · Access-Grants · Admin-UI
- Export: CSV · JSON · ZIP
- **Feature-Enforcement (komplett):** Alle 11 Features mit Monitoring, UI-Badges + Blocking
- **Ernährungs-Modul (erweitert):**
- Manuelles Erfassungsformular mit Upsert-Logik (verhindert Duplikate)
- Import-Historie (CSV-Importe gruppiert nach Datum)
- Bearbeiten/Löschen von Einträgen (inline)
- Datumsfilter (7/30/90/365 Tage, Alle)
- Zwei-Ebenen-Layout: Eingabe (Einzelerfassung/Import) + Auswertung (Charts)
### Was in v9c kommt:
- 🔲 Selbst-Registrierung mit E-Mail-Bestätigung
- 🔲 Freemium Tier-System (free/basic/premium/selfhosted)
- 🔲 14-Tage Trial automatisch
- 🔲 Einladungslinks für Beta-Nutzer
- 🔲 Admin kann Tiers manuell setzen
### Feature-Enforcement Status (4-Phasen-Modell)
- ✅ **Phase 1:** Cleanup (Feature-Konsolidierung, Migration)
- ✅ **Phase 2:** Non-blocking Monitoring (JSON-Logs, alle 11 Features)
- ✅ **Phase 3:** Frontend Display (Usage-Badges, Quota-Übersicht, Hover-Tooltips)
- ✅ **Phase 4:** Enforcement (HTTP 403 bei Limit-Überschreitung, alle Features)
### Was in v9d kommt:
- 🔲 OAuth2-Grundgerüst für Fitness-Connectoren
- 🔲 Strava Connector
- 🔲 Withings Connector (Waage)
- 🔲 Garmin Connector
**Abgedeckte Features:** weight_entries, circumference_entries, caliper_entries, activity_entries, nutrition_entries, photos, ai_calls, ai_pipeline, data_export, data_import
### Bug-Fixes (v9c)
- ✅ **BUG-001:** TypeError in `/api/nutrition/weekly` (datetime.date vs string handling)
- ✅ **BUG-002:** Ernährungs-Daten Tab fehlte – importierte Einträge nicht sichtbar
### Offen v9d 🔲
- Selbst-Registrierung + E-Mail-Verifizierung
- Trial-System UI
- Schlaf-Modul
- Trainingstypen + Herzfrequenz
📚 Details: `.claude/docs/technical/MEMBERSHIP_SYSTEM.md` · `.claude/docs/architecture/FEATURE_ENFORCEMENT.md`
## Feature-Roadmap
> Vollständiges Backlog: `.claude/docs/BACKLOG.md`
> Beim Implementieren: verlinkte Dok-Datei zuerst lesen!
| Version | Feature | Dokumentation |
|---------|---------|---------------|
| v9c | Membership (aktiv) | `technical/MEMBERSHIP_SYSTEM.md` ✅ |
| v9d | Schlaf-Modul | `functional/SLEEP_MODULE.md` (ausstehend) |
| v9d | Trainingstypen + HF | `functional/TRAINING_TYPES.md` ✅ |
| v9e | Ziele + Vitalwerte | `functional/GOALS_VITALS.md` (ausstehend) |
| v9f | KI-Prompt Flexibilisierung | `functional/AI_PROMPTS.md` ✅ |
| v9g | Meditation + Selbstwahrnehmung | `functional/MEDITATION.md` (ausstehend) |
| v9h | Connectoren + Stripe | ausstehend |
| — | Responsive UI | `functional/RESPONSIVE_UI.md` ✅ |
## Deployment
### Infrastruktur
```
Internet → privat.stommer.com (Fritz!Box DynDNS)
→ Synology NAS (Reverse Proxy + Let's Encrypt)
→ Raspberry Pi 5 (192.168.2.49, Docker)
Internet → Fritz!Box (privat.stommer.com) → Synology NAS → Raspberry Pi 5 (192.168.2.49)
Git Workflow:
develop → Auto-Deploy → dev.mitai.jinkendo.de (bodytrack-dev/, Port 3099/8099)
main → Auto-Deploy → mitai.jinkendo.de (bodytrack/, Port 3002/8002)
Gitea: http://192.168.2.144:3000/Lars/mitai-jinkendo
Runner: Raspberry Pi (/home/lars/gitea-runner/)
Manuell:
cd /home/lars/docker/bodytrack[-dev]
docker compose -f docker-compose[.dev-env].yml build --no-cache && up -d
```
### Git Workflow
## Datenbank-Schema (PostgreSQL 16)
```
develop branch → Auto-Deploy → dev.mitai.jinkendo.de (Port 3099/8099)
main branch → Auto-Deploy → mitai.jinkendo.de (Port 3002/8002)
profiles – Nutzer (role, pin_hash/bcrypt, email, tier)
sessions – Auth-Tokens
weight_log – Gewicht (profile_id, date, weight)
circumference_log – 8 Umfangspunkte
caliper_log – Hautfalten, 4 Methoden
nutrition_log – Kalorien + Makros
activity_log – Training
photos – Progress-Fotos
ai_insights – KI-Auswertungen (scope = prompt-slug)
ai_prompts – Konfigurierbare Prompts (11 Standard)
ai_usage – KI-Calls pro Tag pro Profil
v9c neu (Membership):
subscriptions · coupons · coupon_redemptions · features
tier_limits · user_feature_restrictions · user_feature_usage
access_grants · user_activity_log
Feature-Logging (Phase 2):
/app/logs/feature-usage.log # JSON-Format, alle Feature-Zugriffe
Schema-Datei: backend/schema.sql
```
### Deployment-Befehle (manuell falls nötig)
```bash
# Prod
cd /home/lars/docker/bodytrack
docker compose -f docker-compose.yml build --no-cache
docker compose -f docker-compose.yml up -d
# Dev
cd /home/lars/docker/bodytrack-dev
docker compose -f docker-compose.dev-env.yml build --no-cache
docker compose -f docker-compose.dev-env.yml up -d
## API & Auth
```
Alle Endpoints: /api/...
Auth-Header: X-Auth-Token: <token>
Fehler: {"detail": "Fehlermeldung"}
Rate Limit: HTTP 429
## Datenbank-Schema (PostgreSQL 16, v9b)
### Wichtige Tabellen:
- `profiles` – Nutzer (role, pin_hash/bcrypt, email, auth_type, ai_enabled, tier)
- `sessions` – Auth-Tokens mit Ablaufdatum
- `weight_log` – Gewichtseinträge (profile_id, date, weight)
- `circumference_log` – 8 Umfangspunkte
- `caliper_log` – Hautfaltenmessung, 4 Methoden
- `nutrition_log` – Kalorien + Makros (aus FDDB-CSV)
- `activity_log` – Training (aus Apple Health oder manuell)
- `photos` – Progress Photos
- `ai_insights` – KI-Auswertungen (scope = prompt-slug)
- `ai_prompts` – Konfigurierbare Prompts mit Templates (11 Prompts)
- `ai_usage` – KI-Calls pro Tag pro Profil
**Schema-Datei:** `backend/schema.sql` (vollständiges PostgreSQL-Schema)
**Migration-Script:** `backend/migrate_to_postgres.py` (SQLite→PostgreSQL, automatisch)
## Auth-Flow (v9b)
Auth-Flow:
Login → E-Mail + Passwort → Token in localStorage
Token → X-Auth-Token Header → require_auth()
Profile-Id → immer aus Session, nie aus Header!
SHA256 → automatisch zu bcrypt migriert beim Login
```
Login-Screen → E-Mail + Passwort → Token im localStorage
Token → X-Auth-Token Header → Backend require_auth()
Profile-Id → aus Session (nicht aus Header!)
SHA256 Passwörter → automatisch zu bcrypt migriert beim Login
```
## API-Konventionen
- Alle Endpoints: `/api/...`
- Auth-Header: `X-Auth-Token: <token>`
- Responses: immer JSON
- Fehler: `{"detail": "Fehlermeldung"}`
- Rate Limit überschritten: HTTP 429
## Umgebungsvariablen (.env)
```
# Database (PostgreSQL)
DB_HOST=postgres
DB_PORT=5432
DB_NAME=mitai_prod
DB_USER=mitai_prod
DB_PASSWORD= # REQUIRED
# AI
OPENROUTER_API_KEY= # KI-Calls (optional, alternativ ANTHROPIC_API_KEY)
DB_HOST/PORT/NAME/USER/PASSWORD # PostgreSQL
OPENROUTER_API_KEY # KI
OPENROUTER_MODEL=anthropic/claude-sonnet-4
ANTHROPIC_API_KEY= # Direkte Anthropic API (optional)
# Email
SMTP_HOST= # E-Mail (für Recovery)
SMTP_PORT=587
SMTP_USER=
SMTP_PASS=
SMTP_FROM=
# App
SMTP_HOST/PORT/USER/PASS/FROM # E-Mail
APP_URL=https://mitai.jinkendo.de
ALLOWED_ORIGINS=https://mitai.jinkendo.de
DATA_DIR=/app/data
PHOTOS_DIR=/app/photos
ENVIRONMENT=production
```
## Wichtige Hinweise für Claude Code
1. **Ports immer 3002/8002 (Prod) oder 3099/8099 (Dev)** – nie ändern
2. **npm install** (nicht npm ci) – kein package-lock.json vorhanden
3. **PostgreSQL-Migrations** – Schema-Änderungen in `backend/schema.sql`, dann Container neu bauen
4. **Pipeline-Prompts** haben slug-Prefix `pipeline_` – nie als Einzelanalyse zeigen
5. **dayjs.week()** braucht Plugin – stattdessen native JS ISO-Wochenberechnung
6. **useNavigate()** nur in React-Komponenten, nicht in Helper-Functions
7. **api.js nutzen** für alle API-Calls – injiziert Token automatisch
8. **bcrypt** für alle neuen Passwort-Operationen verwenden
9. **session=Depends(require_auth)** als separater Parameter – nie in Header() einbetten
10. **RealDictCursor verwenden** – `get_cursor(conn)` statt `conn.cursor()` für dict-like row access
## Kritische Regeln für Claude Code
## Code-Style
- React: Functional Components, Hooks
- CSS: Inline-Styles + globale CSS-Variablen (var(--accent), var(--text1), etc.)
- API-Calls: immer über `api.js` (injiziert Token automatisch)
- Kein TypeScript (bewusst, für Einfachheit)
- Python: keine Type-Hints Pflicht, aber bei neuen Funktionen erwünscht
### Must-Do:
1. `api.js` für ALLE API-Calls nutzen – nie direktes `fetch()` ohne Token
2. `session: dict = Depends(require_auth)` als **separater** Parameter – nie in `Header()` einbetten
3. `bcrypt` für alle Passwort-Operationen
4. Neue DB-Spalten nur via Schema-Migration, nicht direkt
5. `npm install` (nicht npm ci) – kein package-lock.json
## Design-System
### Bekannte Fallstricke:
```python
# ❌ FALSCH – führt zu ungeschütztem Endpoint:
def endpoint(x: str = Header(default=None, session=Depends(require_auth))):
### Farben (CSS-Variablen)
```css
--accent: #1D9E75 /* Jinkendo Grün – Buttons, Links, Akzente */
--accent-dark: #085041 /* Dunkelgrün – Icon-Hintergrund, Header */
--accent-light: #E1F5EE /* Hellgrün – Hintergründe, Badges */
--bg: /* Seitenhintergrund (hell/dunkel auto) */
--surface: /* Card-Hintergrund */
--surface2: /* Sekundäre Fläche */
--border: /* Rahmen */
--text1: /* Primärer Text */
--text2: /* Sekundärer Text */
--text3: /* Muted Text, Labels */
--danger: #D85A30 /* Fehler, Warnungen */
# ✅ RICHTIG:
def endpoint(x: str = Header(default=None), session: dict = Depends(require_auth)):
```
### CSS-Klassen
```css
.card /* Weißer Container, border-radius 12px, box-shadow */
.btn /* Basis-Button */
.btn-primary /* Grüner Button (#1D9E75) */
.btn-secondary /* Grauer Button */
.btn-full /* 100% Breite */
.form-input /* Eingabefeld, volle Breite */
.form-label /* Feldbezeichnung, klein, uppercase */
.form-row /* Label + Input + Unit nebeneinander */
.form-unit /* Einheit rechts (kg, cm, etc.) */
.section-gap /* margin-bottom zwischen Sektionen */
.spinner /* Ladekreis, animiert */
```
### Abstände & Größen
```
Seiten-Padding: 16px seitlich
Card-Padding: 16-20px
Border-Radius: 12px (Cards), 8px (Buttons/Inputs), 50% (Avatare)
Icon-Größe: 16-20px inline, 24px standalone
Font-Größe: 12px (Labels), 14px (Body), 16-18px (Subtitel), 20-24px (Titel)
Font-Weight: 400 (normal), 600 (semi-bold), 700 (bold)
Bottom-Padding: 80px (für Mobile-Navigation)
```
### Komponenten-Muster
**Titelzeile einer Seite:**
```jsx
<div style={{display:'flex',alignItems:'center',
justifyContent:'space-between',marginBottom:20}}>
<div style={{fontSize:20,fontWeight:700,color:'var(--text1)'}}>
Seitentitel
</div>
<button className="btn btn-primary">Aktion</button>
</div>
```
**Ladezustand:**
```jsx
if (loading) return (
<div style={{display:'flex',justifyContent:'center',padding:40}}>
<div className="spinner"/>
</div>
)
```
**Fehlerzustand:**
```jsx
if (error) return (
<div style={{color:'var(--danger)',padding:16,textAlign:'center'}}>
{error}
</div>
)
```
**Leerer Zustand:**
```jsx
{items.length === 0 && (
<div style={{textAlign:'center',padding:40,color:'var(--text3)'}}>
<div style={{fontSize:32,marginBottom:8}}>📭</div>
<div>Noch keine Einträge</div>
</div>
)}
```
**Metric Card:**
```jsx
<div className="card" style={{padding:16,textAlign:'center'}}>
<div style={{fontSize:12,color:'var(--text3)',marginBottom:4}}>LABEL</div>
<div style={{fontSize:24,fontWeight:700,color:'var(--accent)'}}>
{value}
</div>
<div style={{fontSize:12,color:'var(--text3)'}}>Einheit</div>
</div>
```
### Jinkendo Logo-System
```
Grundelement: Ensō-Kreis (offen, Lücke 4-5 Uhr)
Farbe Ensō: #1D9E75
Hintergrund: #085041 (dunkelgrün)
Kern-Symbol: #5DCAA5 (mintgrün)
Wortmarke: Jin(light) + ken(bold #1D9E75) + do(light)
```
### Verfügbare Custom Commands
```
/deploy → Commit + Push vorbereiten
/merge-to-prod → develop → main mergen
/test → Manuelle Tests durchführen
/new-feature → Neues Feature-Template
/ui-component → Neue Komponente erstellen
/ui-page → Neue Seite erstellen
/fix-bug → Bug analysieren und beheben
/add-endpoint → Neuen API-Endpoint hinzufügen
/db-add-column → Neue DB-Spalte hinzufügen
```
## Jinkendo App-Familie & Markenarchitektur
### Philosophie
**Jinkendo** (人拳道) = Jin (人 Mensch) + Ken (拳 Faust) + Do (道 Weg)
"Der menschliche Weg der Kampfkunst" – ruhig aber kraftvoll, Selbstwahrnehmung, Meditation, Zielorientiert
### App-Familie (Subdomain-Architektur)
```
mitai.jinkendo.de → Körper-Tracker (身体 = eigener Körper) ← DIESE APP
miken.jinkendo.de → Meditation (眉間 = drittes Auge)
ikigai.jinkendo.de → Lebenssinn/Ziele (生き甲斐)
shinkan.jinkendo.de → Kampfsport (真観 = wahre Wahrnehmung)
kenkou.jinkendo.de → Gesundheit allgemein (健康) – für später aufsparen
```
### Registrierte Domains
- jinkendo.de, jinkendo.com, jinkendo.life – alle registriert bei Strato
## v9b Detailplan – Freemium Tier-System
### Tier-Modell
```
free → Selbst-Registrierung, 14-Tage Trial, eingeschränkt
basic → Kernfunktionen (Abo Stufe 1)
premium → Alles inkl. KI und Connectoren (Abo Stufe 2)
selfhosted → Lars' Heimversion, keine Einschränkungen
```
### Geplante DB-Erweiterungen (profiles Tabelle)
```sql
tier TEXT DEFAULT 'free'
trial_ends_at TEXT -- ISO datetime
sub_valid_until TEXT -- ISO datetime
email_verified INTEGER DEFAULT 0
email_verify_token TEXT
invited_by TEXT -- profile_id FK
invitation_token TEXT
```
### Tier-Limits (geplant)
| Feature | free | basic | premium | selfhosted |
|---------|------|-------|---------|------------|
| Gewicht-Einträge | 30 | unbegrenzt | unbegrenzt | unbegrenzt |
| KI-Analysen/Monat | 0 | 3 | unbegrenzt | unbegrenzt |
| Ernährung Import | ❌ | ✅ | ✅ | ✅ |
| Export | ❌ | ✅ | ✅ | ✅ |
| Fitness-Connectoren | ❌ | ❌ | ✅ | ✅ |
### Registrierungs-Flow (geplant)
```
1. Selbst-Registrierung: Name + E-Mail + Passwort
2. Auto-Trial: tier='free', trial_ends_at=now+14d
3. E-Mail-Bestätigung → email_verified=1
4. Trial läuft ab → Upgrade-Prompt
5. Einladungslinks: Admin generiert Token → direkt basic-Tier
6. Stripe Integration: später (v9b ohne Stripe, nur Tier-Logik)
```
## Infrastruktur Details
### Heimnetzwerk
```
Internet
→ Fritz!Box 7530 AX (DynDNS: privat.stommer.com)
→ Synology NAS (192.168.2.63, Reverse Proxy + Let's Encrypt)
→ Raspberry Pi 5 (192.168.2.49, Docker)
→ MiniPC (192.168.2.144, Gitea auf Port 3000)
```
### Synology Reverse Proxy Regeln
```
mitai.jinkendo.de → HTTP 192.168.2.49:3002 (Prod Frontend)
dev.mitai.jinkendo.de → HTTP 192.168.2.49:3099 (Dev Frontend)
```
### AdGuard DNS Rewrites (für internes Routing)
```
mitai.jinkendo.de → 192.168.2.63
dev.mitai.jinkendo.de → 192.168.2.63
```
### Fritz!Box DNS-Rebind Ausnahmen
```
jinkendo.de
mitai.jinkendo.de
```
### Pi Verzeichnisstruktur
```
/home/lars/docker/
├── bodytrack/ → Prod (main branch, docker-compose.yml)
└── bodytrack-dev/ → Dev (develop branch, docker-compose.dev-env.yml)
```
### Gitea Runner
```
Runner: raspberry-pi (auf Pi installiert)
Service: /etc/systemd/system/gitea-runner.service
Binary: /home/lars/gitea-runner/act_runner
```
### Container Namen
```
Prod: mitai-api, mitai-ui
Dev: dev-mitai-api, dev-mitai-ui
```
## Bekannte Probleme & Lösungen
### dayjs.week() – NIEMALS verwenden
```javascript
// ❌ Falsch:
const week = dayjs(date).week()
// ❌ FALSCH – dayjs.week() existiert nicht ohne Plugin:
dayjs(date).week()
// ✅ Richtig (ISO 8601):
const weekNum = (() => {
const dt = new Date(date)
dt.setHours(0,0,0,0)
dt.setDate(dt.getDate()+4-(dt.getDay()||7))
const y = new Date(dt.getFullYear(),0,1)
return Math.ceil(((dt-y)/86400000+1)/7)
})()
// ✅ RICHTIG – native ISO-Wochenberechnung:
const w = (d => Math.ceil(((new Date(d.setDate(d.getDate()+4-(d.getDay()||7)))-
new Date(d.getFullYear(),0,1))/86400000+1)/7))(new Date(date))
```
### session=Depends(require_auth) – Korrekte Platzierung
```python
# ❌ Falsch (führt zu NameError oder ungeschütztem Endpoint):
def endpoint(x_profile_id: Optional[str] = Header(default=None, session=Depends(require_auth))):
# ✅ Richtig (separater Parameter):
def endpoint(x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)):
# PostgreSQL Boolean (nicht SQLite 0/1):
WHERE active = true # ✅
WHERE active = 1 # ❌
```
### Recharts Bar fill=function – nicht unterstützt
```jsx
// ❌ Falsch:
<Bar fill={(entry) => entry.color}/>
## Design-System (Kurzreferenz)
```css
/* Farben */
--accent: #1D9E75 --accent-dark: #085041 --danger: #D85A30
--bg · --surface · --surface2 · --border · --text1 · --text2 · --text3
// ✅ Richtig:
<Bar fill="#1D9E75"/>
/* Klassen */
.card · .btn · .btn-primary · .btn-secondary · .btn-full
.form-input · .form-label · .form-row · .spinner
/* Abstände */
Seiten-Padding: 16px · Card-Padding: 16-20px · Border-Radius: 12px/8px
Bottom-Padding Mobile: 80px (Navigation)
```
### PostgreSQL Boolean-Syntax
```python
# ❌ Falsch (SQLite-Syntax):
cur.execute("SELECT * FROM ai_prompts WHERE active=1")
> Vollständige CSS-Variablen und Komponenten-Muster: `frontend/src/app.css`
> Responsive Layout-Spec: `.claude/docs/functional/RESPONSIVE_UI.md`
# ✅ Richtig (PostgreSQL):
cur.execute("SELECT * FROM ai_prompts WHERE active=true")
## Dokumentations-Referenzen
> **Für Claude Code:** Beim Arbeiten an einem Thema die entsprechende Datei lesen:
| Thema | Datei |
|-------|-------|
| Backend-Architektur, Router, DB-Zugriff | `.claude/docs/architecture/BACKEND.md` |
| Frontend-Architektur, api.js, Komponenten | `.claude/docs/architecture/FRONTEND.md` |
| **Feature-Enforcement (neue Features hinzufügen)** | `.claude/docs/architecture/FEATURE_ENFORCEMENT.md` |
| Coding Rules (Pflichtregeln) | `.claude/docs/rules/CODING_RULES.md` |
| Lessons Learned (Fehler vermeiden) | `.claude/docs/rules/LESSONS_LEARNED.md` |
| Feature Backlog (Übersicht) | `.claude/docs/BACKLOG.md` |
| **Pending Features (noch nicht enforced)** | `.claude/docs/PENDING_FEATURES.md` |
| **Known Issues (Bugs & Tech Debt)** | `.claude/docs/KNOWN_ISSUES.md` |
| Membership-System (v9c, technisch) | `.claude/docs/technical/MEMBERSHIP_SYSTEM.md` |
| Trainingstypen + HF (v9d, fachlich) | `.claude/docs/functional/TRAINING_TYPES.md` |
| KI-Prompt Flexibilisierung (v9f, fachlich) | `.claude/docs/functional/AI_PROMPTS.md` |
| Responsive UI (fachlich) | `.claude/docs/functional/RESPONSIVE_UI.md` |
## Jinkendo App-Familie
```
### RealDictCursor für dict-like row access
```python
# ❌ Falsch:
cur = conn.cursor()
cur.execute("SELECT COUNT(*) FROM weight_log")
count = cur.fetchone()[0] # Tuple index
# ✅ Richtig:
cur = get_cursor(conn) # Returns RealDictCursor
cur.execute("SELECT COUNT(*) as count FROM weight_log")
count = cur.fetchone()['count'] # Dict key
```
## v9b Migration – Lessons Learned
### PostgreSQL Migration (SQLite → PostgreSQL)
**Problem:** Docker Build hing 30+ Minuten bei `apt-get install postgresql-client`
**Lösung:** Alle apt-get dependencies entfernt, reine Python-Lösung mit psycopg2-binary
**Problem:** Leere date-Strings (`''`) führten zu PostgreSQL-Fehlern
**Lösung:** Migration-Script konvertiert leere Strings zu NULL für DATE-Spalten
**Problem:** Boolean-Felder (SQLite INTEGER 0/1 vs PostgreSQL BOOLEAN)
**Lösung:** Migration konvertiert automatisch, Backend nutzt `active=true` statt `active=1`
### API Endpoint Consistency (März 2026)
**Problem:** 11 kritische Endpoint-Mismatches zwischen Frontend und Backend gefunden
**Gelöst:**
- AI-Endpoints konsistent: `/api/insights/run/{slug}`, `/api/insights/pipeline`
- Password-Reset: `/api/auth/forgot-password`, `/api/auth/reset-password`
- Admin-Endpoints: `/permissions`, `/email`, `/pin` Sub-Routes
- Export: JSON + ZIP Endpoints hinzugefügt
- Prompt-Bearbeitung: PUT-Endpoint für Admins
**Tool:** Vollständiger Audit via Explore-Agent empfohlen bei größeren Änderungen
## Export/Import Spezifikation (v9c)
### ZIP-Export Struktur
```
mitai-export-{name}-{YYYY-MM-DD}.zip
├── README.txt ← Erklärung des Formats + Versionsnummer
├── profile.json ← Profildaten (ohne Passwort-Hash)
├── data/
│ ├── weight.csv ← Gewichtsverlauf
│ ├── circumferences.csv ← Umfänge (8 Messpunkte)
│ ├── caliper.csv ← Caliper-Messungen
│ ├── nutrition.csv ← Ernährungsdaten
│ └── activity.csv ← Aktivitäten
├── insights/
│ └── ai_insights.json ← KI-Auswertungen (alle gespeicherten)
└── photos/
├── {date}_{id}.jpg ← Progress-Fotos
└── ...
```
### CSV Format (alle Dateien)
```
- Trennzeichen: Semikolon (;) – Excel/LibreOffice kompatibel
- Encoding: UTF-8 mit BOM (für Windows Excel)
- Datumsformat: YYYY-MM-DD
- Dezimaltrennzeichen: Punkt (.)
- Erste Zeile: Header
- Nullwerte: leer (nicht "null" oder "NULL")
```
### weight.csv Spalten
```
id;date;weight;note;source;created
```
### circumferences.csv Spalten
```
id;date;waist;hip;chest;neck;upper_arm;thigh;calf;forearm;note;created
```
### caliper.csv Spalten
```
id;date;chest;abdomen;thigh;tricep;subscapular;suprailiac;midaxillary;method;bf_percent;note;created
```
### nutrition.csv Spalten
```
id;date;meal_name;kcal;protein;fat;carbs;fiber;note;source;created
```
### activity.csv Spalten
```
id;date;name;type;duration_min;kcal;heart_rate_avg;heart_rate_max;distance_km;note;source;created
```
### profile.json Struktur
```json
{
"export_version": "2",
"export_date": "2026-03-18",
"app": "Mitai Jinkendo",
"profile": {
"name": "Lars",
"email": "lars@stommer.com",
"sex": "m",
"height": 178,
"birth_year": 1980,
"goal_weight": 82,
"goal_bf_pct": 14,
"avatar_color": "#1D9E75",
"auth_type": "password",
"session_days": 30,
"ai_enabled": true,
"tier": "selfhosted"
},
"stats": {
"weight_entries": 150,
"nutrition_entries": 300,
"activity_entries": 45,
"photos": 12
}
}
```
### ai_insights.json Struktur
```json
[
{
"id": "uuid",
"scope": "gesamt",
"created": "2026-03-18T10:00:00",
"result": "KI-Analyse Text..."
}
]
```
### README.txt Inhalt
```
Mitai Jinkendo – Datenexport
Version: 2
Exportiert am: YYYY-MM-DD
Profil: {name}
Inhalt:
- profile.json: Profildaten und Einstellungen
- data/*.csv: Messdaten (Semikolon-getrennt, UTF-8)
- insights/: KI-Auswertungen (JSON)
- photos/: Progress-Fotos (JPEG)
Import:
Dieser Export kann in Mitai Jinkendo unter
Einstellungen → Import → "Mitai Backup importieren"
wieder eingespielt werden.
Format-Version 2 (ab v9b):
Alle CSV-Dateien sind UTF-8 mit BOM kodiert.
Trennzeichen: Semikolon (;)
Datumsformat: YYYY-MM-DD
```
### Import-Funktion (zu implementieren)
**Endpoint:** `POST /api/import/zip`
**Verhalten:**
- Akzeptiert ZIP-Datei (multipart/form-data)
- Erkennt export_version aus profile.json
- Importiert nur fehlende Einträge (kein Duplikat)
- Fotos werden nicht überschrieben falls bereits vorhanden
- Gibt Zusammenfassung zurück: wie viele Einträge je Kategorie importiert
- Bei Fehler: vollständiger Rollback (alle oder nichts)
**Duplikat-Erkennung:**
```python
# INSERT ... ON CONFLICT (profile_id, date) DO NOTHING
# weight: UNIQUE (profile_id, date)
# nutrition: UNIQUE (profile_id, date, meal_name)
# activity: UNIQUE (profile_id, date, name)
# caliper: UNIQUE (profile_id, date)
# circumferences: UNIQUE (profile_id, date)
```
**Frontend:** Neuer Button in SettingsPage:
```
[ZIP exportieren] [JSON exportieren] [Backup importieren]
mitai.jinkendo.de → Körper-Tracker (diese App)
miken.jinkendo.de → Meditation (眉間)
ikigai.jinkendo.de → Lebenssinn (生き甲斐)
shinkan.jinkendo.de → Kampfsport (真観)
```
+253
View File
@@ -0,0 +1,253 @@
#!/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()
# Even if main migration is done, check cleanup
apply_cleanup_migration()
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!")
# Apply fix migration if exists
fix_migration_path = os.path.join(
os.path.dirname(__file__),
"migrations",
"v9c_fix_features.sql"
)
if os.path.exists(fix_migration_path):
print("[v9c Migration] Applying feature fixes...")
with open(fix_migration_path, 'r', encoding='utf-8') as f:
fix_sql = f.read()
conn = get_db_connection()
cur = conn.cursor()
cur.execute(fix_sql)
conn.commit()
cur.close()
conn.close()
print("[v9c Migration] ✅ Feature fixes applied!")
# 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()
# After successful migration, apply cleanup
apply_cleanup_migration()
except Exception as e:
print(f"[v9c Migration] ❌ Error: {e}")
raise
def cleanup_features_needed(conn):
"""Check if feature cleanup migration is needed."""
cur = conn.cursor()
# Check if old export features still exist
cur.execute("""
SELECT COUNT(*) as count FROM features
WHERE id IN ('export_csv', 'export_json', 'export_zip')
""")
old_exports = cur.fetchone()['count']
# Check if csv_import needs to be renamed
cur.execute("""
SELECT COUNT(*) as count FROM features
WHERE id = 'csv_import'
""")
old_import = cur.fetchone()['count']
cur.close()
# Cleanup needed if old features exist
return old_exports > 0 or old_import > 0
def apply_cleanup_migration():
"""Apply v9c feature cleanup migration."""
print("[v9c Cleanup] Checking if cleanup migration is needed...")
try:
conn = get_db_connection()
if not cleanup_features_needed(conn):
print("[v9c Cleanup] Already applied, skipping.")
conn.close()
return
print("[v9c Cleanup] Applying feature consolidation...")
# Show BEFORE state
cur = conn.cursor()
cur.execute("SELECT id, name FROM features ORDER BY category, id")
features_before = [f"{r['id']} ({r['name']})" for r in cur.fetchall()]
print(f"[v9c Cleanup] Features BEFORE: {len(features_before)} features")
for f in features_before:
print(f" - {f}")
cur.close()
# Read cleanup migration SQL
cleanup_path = os.path.join(
os.path.dirname(__file__),
"migrations",
"v9c_cleanup_features.sql"
)
if not os.path.exists(cleanup_path):
print(f"[v9c Cleanup] ⚠️ Cleanup migration file not found: {cleanup_path}")
conn.close()
return
with open(cleanup_path, 'r', encoding='utf-8') as f:
cleanup_sql = f.read()
# Execute cleanup migration
cur = conn.cursor()
cur.execute(cleanup_sql)
conn.commit()
cur.close()
# Show AFTER state
cur = conn.cursor()
cur.execute("SELECT id, name, category FROM features ORDER BY category, id")
features_after = cur.fetchall()
print(f"[v9c Cleanup] Features AFTER: {len(features_after)} features")
# Group by category
categories = {}
for f in features_after:
cat = f['category'] or 'other'
if cat not in categories:
categories[cat] = []
categories[cat].append(f"{f['id']} ({f['name']})")
for cat, feats in sorted(categories.items()):
print(f" {cat.upper()}:")
for f in feats:
print(f" - {f}")
# Verify tier_limits updated
cur.execute("""
SELECT tier_id, feature_id, limit_value
FROM tier_limits
WHERE feature_id IN ('data_export', 'data_import')
ORDER BY tier_id, feature_id
""")
limits = cur.fetchall()
print(f"[v9c Cleanup] Tier limits for data_export/data_import:")
for lim in limits:
limit_str = 'unlimited' if lim['limit_value'] is None else lim['limit_value']
print(f" {lim['tier_id']}.{lim['feature_id']} = {limit_str}")
cur.close()
conn.close()
print("[v9c Cleanup] ✅ Feature cleanup completed successfully!")
except Exception as e:
print(f"[v9c Cleanup] ❌ Error: {e}")
raise
if __name__ == "__main__":
apply_migration()
+258
View File
@@ -7,6 +7,7 @@ for FastAPI endpoints.
import hashlib
import secrets
from typing import Optional
from datetime import datetime, timedelta
from fastapi import Header, Query, HTTPException
import bcrypt
@@ -114,3 +115,260 @@ def require_admin(x_auth_token: Optional[str] = Header(default=None)):
if session['role'] != 'admin':
raise HTTPException(403, "Nur für Admins")
return session
# ============================================================================
# Feature Access Control (v9c)
# ============================================================================
def get_effective_tier(profile_id: str, conn=None) -> str:
"""
Get the effective tier for a profile.
Checks for active access_grants first (from coupons, trials, etc.),
then falls back to profile.tier.
Args:
profile_id: User profile ID
conn: Optional existing DB connection (to avoid pool exhaustion)
Returns:
tier_id (str): 'free', 'basic', 'premium', or 'selfhosted'
"""
# Use existing connection if provided, otherwise open new one
if 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'
else:
# Open new connection if none provided
with get_db() as conn:
return get_effective_tier(profile_id, conn)
def check_feature_access(profile_id: str, feature_id: str, conn=None) -> 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)
Args:
profile_id: User profile ID
feature_id: Feature ID to check
conn: Optional existing DB connection (to avoid pool exhaustion)
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'
}
"""
# Use existing connection if provided
if conn:
return _check_impl(profile_id, feature_id, conn)
else:
with get_db() as conn:
return _check_impl(profile_id, feature_id, conn)
def _check_impl(profile_id: str, feature_id: str, conn) -> dict:
"""Internal implementation of check_feature_access."""
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, conn)
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
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
"""Quick diagnostic script to check features table."""
from db import get_db, get_cursor
with get_db() as conn:
cur = get_cursor(conn)
print("\n=== FEATURES TABLE ===")
cur.execute("SELECT id, name, active, limit_type, reset_period FROM features ORDER BY id")
features = cur.fetchall()
if not features:
print("❌ NO FEATURES FOUND! Migration failed!")
else:
for r in features:
print(f" {r['id']:30} {r['name']:40} active={r['active']} type={r['limit_type']:8} reset={r['reset_period']}")
print(f"\nTotal features: {len(features)}")
print("\n=== USER_FEATURE_USAGE (recent) ===")
cur.execute("""
SELECT profile_id, feature_id, usage_count, reset_at
FROM user_feature_usage
ORDER BY updated DESC
LIMIT 10
""")
usages = cur.fetchall()
if not usages:
print(" (no usage records yet)")
else:
for r in usages:
print(f" {r['profile_id'][:8]}... -> {r['feature_id']:30} used={r['usage_count']} reset_at={r['reset_at']}")
print(f"\nTotal usage records: {len(usages)}")
+1 -1
View File
@@ -93,7 +93,7 @@ def get_profile_count():
if __name__ == "__main__":
print("═══════════════════════════════════════════════════════════")
print("MITAI JINKENDO - Database Initialization (v9b)")
print("MITAI JINKENDO - Database Initialization (v9c)")
print("═══════════════════════════════════════════════════════════")
# Wait for PostgreSQL
+76
View File
@@ -0,0 +1,76 @@
"""
Feature Usage Logger for Mitai Jinkendo
Logs all feature access checks to a separate JSON log file for analysis.
Phase 2: Non-blocking monitoring of feature usage.
"""
import logging
import json
from datetime import datetime
from pathlib import Path
# ── Setup Feature Usage Logger ───────────────────────────────────────────────
feature_usage_logger = logging.getLogger('feature_usage')
feature_usage_logger.setLevel(logging.INFO)
feature_usage_logger.propagate = False # Don't propagate to root logger
# Ensure logs directory exists
LOG_DIR = Path('/app/logs')
LOG_DIR.mkdir(parents=True, exist_ok=True)
# FileHandler for JSON logs
log_file = LOG_DIR / 'feature-usage.log'
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(logging.Formatter('%(message)s')) # JSON only
feature_usage_logger.addHandler(file_handler)
# Also log to console in dev (optional)
# console_handler = logging.StreamHandler()
# console_handler.setFormatter(logging.Formatter('[FEATURE-USAGE] %(message)s'))
# feature_usage_logger.addHandler(console_handler)
# ── Logging Function ──────────────────────────────────────────────────────────
def log_feature_usage(user_id: str, feature_id: str, access: dict, action: str):
"""
Log feature usage in structured JSON format.
Args:
user_id: Profile UUID
feature_id: Feature identifier (e.g., 'weight_entries', 'ai_calls')
access: Result from check_feature_access() containing:
- allowed: bool
- limit: int | None
- used: int
- remaining: int | None
- reason: str
action: Type of action (e.g., 'create', 'export', 'analyze')
Example log entry:
{
"timestamp": "2026-03-20T15:30:45.123456",
"user_id": "abc-123",
"feature": "weight_entries",
"action": "create",
"used": 5,
"limit": 100,
"remaining": 95,
"allowed": true,
"reason": "within_limit"
}
"""
entry = {
"timestamp": datetime.now().isoformat(),
"user_id": user_id,
"feature": feature_id,
"action": action,
"used": access.get('used', 0),
"limit": access.get('limit'), # None for unlimited
"remaining": access.get('remaining'), # None for unlimited
"allowed": access.get('allowed', True),
"reason": access.get('reason', 'unknown')
}
feature_usage_logger.info(json.dumps(entry))
+59 -1907
View File
File diff suppressed because it is too large. Load diff
+1878
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,25 @@
-- ================================================================
-- Migration 003: Add Email Verification Fields
-- Version: v9c
-- Date: 2026-03-21
-- ================================================================
-- Add email verification columns to profiles table
ALTER TABLE profiles
ADD COLUMN IF NOT EXISTS email_verified BOOLEAN DEFAULT FALSE,
ADD COLUMN IF NOT EXISTS verification_token TEXT,
ADD COLUMN IF NOT EXISTS verification_expires TIMESTAMP WITH TIME ZONE;
-- Create index for verification token lookups
CREATE INDEX IF NOT EXISTS idx_profiles_verification_token
ON profiles(verification_token)
WHERE verification_token IS NOT NULL;
-- Mark existing users with email as verified (grandfather clause)
UPDATE profiles
SET email_verified = TRUE
WHERE email IS NOT NULL AND email_verified IS NULL;
COMMENT ON COLUMN profiles.email_verified IS 'Whether email address has been verified';
COMMENT ON COLUMN profiles.verification_token IS 'One-time token for email verification';
COMMENT ON COLUMN profiles.verification_expires IS 'Verification token expiry (24h from creation)';
+50
View File
@@ -0,0 +1,50 @@
-- ============================================================================
-- Feature Check Script - Diagnose vor/nach Migration
-- ============================================================================
-- Usage: psql -U mitai_dev -d mitai_dev -f check_features.sql
-- ============================================================================
\echo '=== CURRENT FEATURES ==='
SELECT id, name, category, limit_type, reset_period, default_limit, active
FROM features
ORDER BY category, id;
\echo ''
\echo '=== TIER LIMITS MATRIX ==='
SELECT
f.id as feature,
f.category,
MAX(CASE WHEN tl.tier_id = 'free' THEN COALESCE(tl.limit_value::text, '∞') END) as free,
MAX(CASE WHEN tl.tier_id = 'basic' THEN COALESCE(tl.limit_value::text, '∞') END) as basic,
MAX(CASE WHEN tl.tier_id = 'premium' THEN COALESCE(tl.limit_value::text, '∞') END) as premium,
MAX(CASE WHEN tl.tier_id = 'selfhosted' THEN COALESCE(tl.limit_value::text, '∞') END) as selfhosted
FROM features f
LEFT JOIN tier_limits tl ON f.id = tl.feature_id
GROUP BY f.id, f.category
ORDER BY f.category, f.id;
\echo ''
\echo '=== FEATURE COUNT BY CATEGORY ==='
SELECT category, COUNT(*) as count
FROM features
WHERE active = true
GROUP BY category
ORDER BY category;
\echo ''
\echo '=== ORPHANED TIER LIMITS (feature not exists) ==='
SELECT tl.tier_id, tl.feature_id, tl.limit_value
FROM tier_limits tl
LEFT JOIN features f ON tl.feature_id = f.id
WHERE f.id IS NULL;
\echo ''
\echo '=== USER FEATURE USAGE (current usage tracking) ==='
SELECT
p.name as user,
ufu.feature_id,
ufu.usage_count,
ufu.reset_at
FROM user_feature_usage ufu
JOIN profiles p ON ufu.profile_id = p.id
ORDER BY p.name, ufu.feature_id;
+141
View File
@@ -0,0 +1,141 @@
-- ============================================================================
-- v9c Cleanup: Feature-Konsolidierung
-- ============================================================================
-- Created: 2026-03-20
-- Purpose: Konsolidiere Export-Features (export_csv/json/zip → data_export)
-- und Import-Features (csv_import → data_import)
--
-- Idempotent: Kann mehrfach ausgeführt werden
--
-- Lessons Learned:
-- "Ein Feature für Export, nicht drei (csv/json/zip)"
-- ============================================================================
-- ============================================================================
-- 1. Rename csv_import to data_import
-- ============================================================================
UPDATE features
SET
id = 'data_import',
name = 'Daten importieren',
description = 'CSV-Import (FDDB, Apple Health) + ZIP-Backup-Import'
WHERE id = 'csv_import';
-- Update tier_limits references
UPDATE tier_limits
SET feature_id = 'data_import'
WHERE feature_id = 'csv_import';
-- Update user_feature_restrictions references
UPDATE user_feature_restrictions
SET feature_id = 'data_import'
WHERE feature_id = 'csv_import';
-- Update user_feature_usage references
UPDATE user_feature_usage
SET feature_id = 'data_import'
WHERE feature_id = 'csv_import';
-- ============================================================================
-- 2. Remove old export_csv/json/zip features
-- ============================================================================
-- Remove tier_limits for old features
DELETE FROM tier_limits
WHERE feature_id IN ('export_csv', 'export_json', 'export_zip');
-- Remove user restrictions for old features
DELETE FROM user_feature_restrictions
WHERE feature_id IN ('export_csv', 'export_json', 'export_zip');
-- Remove usage tracking for old features
DELETE FROM user_feature_usage
WHERE feature_id IN ('export_csv', 'export_json', 'export_zip');
-- Remove old feature definitions
DELETE FROM features
WHERE id IN ('export_csv', 'export_json', 'export_zip');
-- ============================================================================
-- 3. Ensure data_export exists and is properly configured
-- ============================================================================
INSERT INTO features (id, name, description, category, limit_type, reset_period, default_limit, active)
VALUES ('data_export', 'Daten exportieren', 'CSV/JSON/ZIP Export', 'export', 'count', 'monthly', 0, true)
ON CONFLICT (id) DO UPDATE SET
name = EXCLUDED.name,
description = EXCLUDED.description,
category = EXCLUDED.category,
limit_type = EXCLUDED.limit_type,
reset_period = EXCLUDED.reset_period;
-- ============================================================================
-- 4. Ensure data_import exists and is properly configured
-- ============================================================================
INSERT INTO features (id, name, description, category, limit_type, reset_period, default_limit, active)
VALUES ('data_import', 'Daten importieren', 'CSV-Import (FDDB, Apple Health) + ZIP-Backup-Import', 'import', 'count', 'monthly', 0, true)
ON CONFLICT (id) DO UPDATE SET
name = EXCLUDED.name,
description = EXCLUDED.description,
category = EXCLUDED.category,
limit_type = EXCLUDED.limit_type,
reset_period = EXCLUDED.reset_period;
-- ============================================================================
-- 5. Update tier_limits for data_export (consolidate from old features)
-- ============================================================================
-- FREE tier: no export
INSERT INTO tier_limits (tier_id, feature_id, limit_value)
VALUES ('free', 'data_export', 0)
ON CONFLICT (tier_id, feature_id) DO UPDATE SET limit_value = EXCLUDED.limit_value;
-- BASIC tier: 5 exports/month
INSERT INTO tier_limits (tier_id, feature_id, limit_value)
VALUES ('basic', 'data_export', 5)
ON CONFLICT (tier_id, feature_id) DO UPDATE SET limit_value = EXCLUDED.limit_value;
-- PREMIUM tier: unlimited
INSERT INTO tier_limits (tier_id, feature_id, limit_value)
VALUES ('premium', 'data_export', NULL)
ON CONFLICT (tier_id, feature_id) DO UPDATE SET limit_value = EXCLUDED.limit_value;
-- SELFHOSTED tier: unlimited
INSERT INTO tier_limits (tier_id, feature_id, limit_value)
VALUES ('selfhosted', 'data_export', NULL)
ON CONFLICT (tier_id, feature_id) DO UPDATE SET limit_value = EXCLUDED.limit_value;
-- ============================================================================
-- 6. Update tier_limits for data_import
-- ============================================================================
-- FREE tier: no import
INSERT INTO tier_limits (tier_id, feature_id, limit_value)
VALUES ('free', 'data_import', 0)
ON CONFLICT (tier_id, feature_id) DO UPDATE SET limit_value = EXCLUDED.limit_value;
-- BASIC tier: 3 imports/month
INSERT INTO tier_limits (tier_id, feature_id, limit_value)
VALUES ('basic', 'data_import', 3)
ON CONFLICT (tier_id, feature_id) DO UPDATE SET limit_value = EXCLUDED.limit_value;
-- PREMIUM tier: unlimited
INSERT INTO tier_limits (tier_id, feature_id, limit_value)
VALUES ('premium', 'data_import', NULL)
ON CONFLICT (tier_id, feature_id) DO UPDATE SET limit_value = EXCLUDED.limit_value;
-- SELFHOSTED tier: unlimited
INSERT INTO tier_limits (tier_id, feature_id, limit_value)
VALUES ('selfhosted', 'data_import', NULL)
ON CONFLICT (tier_id, feature_id) DO UPDATE SET limit_value = EXCLUDED.limit_value;
-- ============================================================================
-- Cleanup complete
-- ============================================================================
-- Final feature list:
-- Data: weight_entries, circumference_entries, caliper_entries,
-- nutrition_entries, activity_entries, photos
-- AI: ai_calls, ai_pipeline
-- Export/Import: data_export, data_import
--
-- Total: 10 features (down from 13)
-- ============================================================================
+33
View File
@@ -0,0 +1,33 @@
-- Fix missing features for v9c feature enforcement
-- 2026-03-20
-- Add missing features
INSERT INTO features (id, name, description, category, limit_type, reset_period, default_limit, active) VALUES
('data_export', 'Daten exportieren', 'CSV/JSON/ZIP Export', 'export', 'count', 'monthly', 0, true),
('csv_import', 'CSV importieren', 'FDDB/Apple Health CSV Import + ZIP Backup Import', 'import', 'count', 'monthly', 0, true)
ON CONFLICT (id) DO NOTHING;
-- Add tier limits for new features
-- FREE tier
INSERT INTO tier_limits (tier_id, feature_id, limit_value) VALUES
('free', 'data_export', 0), -- Kein Export
('free', 'csv_import', 0) -- Kein Import
ON CONFLICT (tier_id, feature_id) DO NOTHING;
-- BASIC tier
INSERT INTO tier_limits (tier_id, feature_id, limit_value) VALUES
('basic', 'data_export', 5), -- 5 Exporte/Monat
('basic', 'csv_import', 3) -- 3 Imports/Monat
ON CONFLICT (tier_id, feature_id) DO NOTHING;
-- PREMIUM tier
INSERT INTO tier_limits (tier_id, feature_id, limit_value) VALUES
('premium', 'data_export', NULL), -- Unbegrenzt
('premium', 'csv_import', NULL) -- Unbegrenzt
ON CONFLICT (tier_id, feature_id) DO NOTHING;
-- SELFHOSTED tier
INSERT INTO tier_limits (tier_id, feature_id, limit_value) VALUES
('selfhosted', 'data_export', NULL), -- Unbegrenzt
('selfhosted', 'csv_import', NULL) -- Unbegrenzt
ON CONFLICT (tier_id, feature_id) DO NOTHING;
@@ -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
-- ============================================================================
+125
View File
@@ -0,0 +1,125 @@
"""
Pydantic Models for Mitai Jinkendo API
Data validation schemas for request/response bodies.
"""
from typing import Optional
from pydantic import BaseModel
# ── Profile Models ────────────────────────────────────────────────────────────
class ProfileCreate(BaseModel):
name: str
avatar_color: Optional[str] = '#1D9E75'
sex: Optional[str] = 'm'
dob: Optional[str] = None
height: Optional[float] = 178
goal_weight: Optional[float] = None
goal_bf_pct: Optional[float] = None
class ProfileUpdate(BaseModel):
name: Optional[str] = None
avatar_color: Optional[str] = None
sex: Optional[str] = None
dob: Optional[str] = None
height: Optional[float] = None
goal_weight: Optional[float] = None
goal_bf_pct: Optional[float] = None
# ── Tracking Models ───────────────────────────────────────────────────────────
class WeightEntry(BaseModel):
date: str
weight: float
note: Optional[str] = None
class CircumferenceEntry(BaseModel):
date: str
c_neck: Optional[float] = None
c_chest: Optional[float] = None
c_waist: Optional[float] = None
c_belly: Optional[float] = None
c_hip: Optional[float] = None
c_thigh: Optional[float] = None
c_calf: Optional[float] = None
c_arm: Optional[float] = None
notes: Optional[str] = None
photo_id: Optional[str] = None
class CaliperEntry(BaseModel):
date: str
sf_method: Optional[str] = 'jackson3'
sf_chest: Optional[float] = None
sf_axilla: Optional[float] = None
sf_triceps: Optional[float] = None
sf_subscap: Optional[float] = None
sf_suprailiac: Optional[float] = None
sf_abdomen: Optional[float] = None
sf_thigh: Optional[float] = None
sf_calf_med: Optional[float] = None
sf_lowerback: Optional[float] = None
sf_biceps: Optional[float] = None
body_fat_pct: Optional[float] = None
lean_mass: Optional[float] = None
fat_mass: Optional[float] = None
notes: Optional[str] = None
class ActivityEntry(BaseModel):
date: str
start_time: Optional[str] = None
end_time: Optional[str] = None
activity_type: str
duration_min: Optional[float] = None
kcal_active: Optional[float] = None
kcal_resting: Optional[float] = None
hr_avg: Optional[float] = None
hr_max: Optional[float] = None
distance_km: Optional[float] = None
rpe: Optional[int] = None
source: Optional[str] = 'manual'
notes: Optional[str] = None
class NutritionDay(BaseModel):
date: str
kcal: Optional[float] = None
protein_g: Optional[float] = None
fat_g: Optional[float] = None
carbs_g: Optional[float] = None
# ── Auth Models ───────────────────────────────────────────────────────────────
class LoginRequest(BaseModel):
email: str
password: str
class PasswordResetRequest(BaseModel):
email: str
class PasswordResetConfirm(BaseModel):
token: str
new_password: str
class RegisterRequest(BaseModel):
name: str
email: str
password: str
# ── Admin Models ──────────────────────────────────────────────────────────────
class AdminProfileUpdate(BaseModel):
role: Optional[str] = None
ai_enabled: Optional[int] = None
ai_limit_day: Optional[int] = None
export_enabled: Optional[int] = None
View File
Whitespace-only changes.
+192
View File
@@ -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}
+160
View File
@@ -0,0 +1,160 @@
"""
Activity Tracking Endpoints for Mitai Jinkendo
Handles workout/activity logging, statistics, and Apple Health CSV import.
"""
import csv
import io
import uuid
import logging
from typing import Optional
from fastapi import APIRouter, HTTPException, UploadFile, File, Header, Depends
from db import get_db, get_cursor, r2d
from auth import require_auth, check_feature_access, increment_feature_usage
from models import ActivityEntry
from routers.profiles import get_pid
from feature_logger import log_feature_usage
router = APIRouter(prefix="/api/activity", tags=["activity"])
logger = logging.getLogger(__name__)
@router.get("")
def list_activity(limit: int=200, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get activity entries for current profile."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT * FROM activity_log WHERE profile_id=%s ORDER BY date DESC, start_time DESC LIMIT %s", (pid,limit))
return [r2d(r) for r in cur.fetchall()]
@router.post("")
def create_activity(e: ActivityEntry, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Create new activity entry."""
pid = get_pid(x_profile_id)
# Phase 4: Check feature access and ENFORCE
access = check_feature_access(pid, 'activity_entries')
log_feature_usage(pid, 'activity_entries', access, 'create')
if not access['allowed']:
logger.warning(
f"[FEATURE-LIMIT] User {pid} blocked: "
f"activity_entries {access['reason']} (used: {access['used']}, limit: {access['limit']})"
)
raise HTTPException(
status_code=403,
detail=f"Limit erreicht: Du hast das Kontingent für Aktivitätseinträge überschritten ({access['used']}/{access['limit']}). "
f"Bitte kontaktiere den Admin oder warte bis zum nächsten Reset."
)
eid = str(uuid.uuid4())
d = e.model_dump()
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""INSERT INTO activity_log
(id,profile_id,date,start_time,end_time,activity_type,duration_min,kcal_active,kcal_resting,
hr_avg,hr_max,distance_km,rpe,source,notes,created)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,CURRENT_TIMESTAMP)""",
(eid,pid,d['date'],d['start_time'],d['end_time'],d['activity_type'],d['duration_min'],
d['kcal_active'],d['kcal_resting'],d['hr_avg'],d['hr_max'],d['distance_km'],
d['rpe'],d['source'],d['notes']))
# Phase 2: Increment usage counter (always for new entries)
increment_feature_usage(pid, 'activity_entries')
return {"id":eid,"date":e.date}
@router.put("/{eid}")
def update_activity(eid: str, e: ActivityEntry, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Update existing activity entry."""
pid = get_pid(x_profile_id)
with get_db() as conn:
d = e.model_dump()
cur = get_cursor(conn)
cur.execute(f"UPDATE activity_log SET {', '.join(f'{k}=%s' for k in d)} WHERE id=%s AND profile_id=%s",
list(d.values())+[eid,pid])
return {"id":eid}
@router.delete("/{eid}")
def delete_activity(eid: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Delete activity entry."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("DELETE FROM activity_log WHERE id=%s AND profile_id=%s", (eid,pid))
return {"ok":True}
@router.get("/stats")
def activity_stats(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get activity statistics (last 30 entries)."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT * FROM activity_log WHERE profile_id=%s ORDER BY date DESC LIMIT 30", (pid,))
rows = [r2d(r) for r in cur.fetchall()]
if not rows: return {"count":0,"total_kcal":0,"total_min":0,"by_type":{}}
total_kcal=sum(float(r.get('kcal_active') or 0) for r in rows)
total_min=sum(float(r.get('duration_min') or 0) for r in rows)
by_type={}
for r in rows:
t=r['activity_type']; by_type.setdefault(t,{'count':0,'kcal':0,'min':0})
by_type[t]['count']+=1
by_type[t]['kcal']+=float(r.get('kcal_active') or 0)
by_type[t]['min']+=float(r.get('duration_min') or 0)
return {"count":len(rows),"total_kcal":round(total_kcal),"total_min":round(total_min),"by_type":by_type}
@router.post("/import-csv")
async def import_activity_csv(file: UploadFile=File(...), x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Import Apple Health workout CSV."""
pid = get_pid(x_profile_id)
raw = await file.read()
try: text = raw.decode('utf-8')
except: text = raw.decode('latin-1')
if text.startswith('\ufeff'): text = text[1:]
if not text.strip(): raise HTTPException(400,"Leere Datei")
reader = csv.DictReader(io.StringIO(text))
inserted = skipped = 0
with get_db() as conn:
cur = get_cursor(conn)
for row in reader:
wtype = row.get('Workout Type','').strip()
start = row.get('Start','').strip()
if not wtype or not start: continue
try: date = start[:10]
except: continue
dur = row.get('Duration','').strip()
duration_min = None
if dur:
try:
p = dur.split(':')
duration_min = round(int(p[0])*60+int(p[1])+int(p[2])/60,1)
except: pass
def kj(v):
try: return round(float(v)/4.184) if v else None
except: return None
def tf(v):
try: return round(float(v),1) if v else None
except: return None
try:
cur.execute("""INSERT INTO activity_log
(id,profile_id,date,start_time,end_time,activity_type,duration_min,kcal_active,kcal_resting,
hr_avg,hr_max,distance_km,source,created)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,'apple_health',CURRENT_TIMESTAMP)""",
(str(uuid.uuid4()),pid,date,start,row.get('End',''),wtype,duration_min,
kj(row.get('Aktive Energie (kJ)','')),kj(row.get('Ruheeinträge (kJ)','')),
tf(row.get('Durchschn. Herzfrequenz (count/min)','')),
tf(row.get('Max. Herzfrequenz (count/min)','')),
tf(row.get('Distanz (km)',''))))
inserted+=1
except: skipped+=1
return {"inserted":inserted,"skipped":skipped,"message":f"{inserted} Trainings importiert"}
+157
View File
@@ -0,0 +1,157 @@
"""
Admin Management Endpoints for Mitai Jinkendo
Handles user management, permissions, and email testing (admin-only).
"""
import os
import smtplib
from email.mime.text import MIMEText
from datetime import datetime
from fastapi import APIRouter, HTTPException, Depends
from db import get_db, get_cursor, r2d
from auth import require_admin, hash_pin
from models import AdminProfileUpdate
router = APIRouter(prefix="/api/admin", tags=["admin"])
@router.get("/profiles")
def admin_list_profiles(session: dict=Depends(require_admin)):
"""Admin: List all profiles with stats."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles ORDER BY created")
profs = [r2d(r) for r in cur.fetchall()]
for p in profs:
pid = p['id']
cur.execute("SELECT COUNT(*) as count FROM weight_log WHERE profile_id=%s", (pid,))
p['weight_count'] = cur.fetchone()['count']
cur.execute("SELECT COUNT(*) as count FROM ai_insights WHERE profile_id=%s", (pid,))
p['ai_insights_count'] = cur.fetchone()['count']
today = datetime.now().date().isoformat()
cur.execute("SELECT call_count FROM ai_usage WHERE profile_id=%s AND date=%s", (pid, today))
usage = cur.fetchone()
p['ai_usage_today'] = usage['call_count'] if usage else 0
return profs
@router.put("/profiles/{pid}")
def admin_update_profile(pid: str, data: AdminProfileUpdate, session: dict=Depends(require_admin)):
"""Admin: Update profile settings."""
with get_db() as conn:
updates = {k:v for k,v in data.model_dump().items() if v is not None}
if not updates:
return {"ok": True}
cur = get_cursor(conn)
cur.execute(f"UPDATE profiles SET {', '.join(f'{k}=%s' for k in updates)} WHERE id=%s",
list(updates.values()) + [pid])
return {"ok": True}
@router.put("/profiles/{pid}/permissions")
def admin_set_permissions(pid: str, data: dict, session: dict=Depends(require_admin)):
"""Admin: Set profile permissions."""
with get_db() as conn:
cur = get_cursor(conn)
updates = []
values = []
if 'ai_enabled' in data:
updates.append('ai_enabled=%s')
values.append(data['ai_enabled'])
if 'ai_limit_day' in data:
updates.append('ai_limit_day=%s')
values.append(data['ai_limit_day'])
if 'export_enabled' in data:
updates.append('export_enabled=%s')
values.append(data['export_enabled'])
if 'role' in data:
updates.append('role=%s')
values.append(data['role'])
if updates:
cur.execute(f"UPDATE profiles SET {', '.join(updates)} WHERE id=%s", values + [pid])
return {"ok": True}
@router.put("/profiles/{pid}/email")
def admin_set_email(pid: str, data: dict, session: dict=Depends(require_admin)):
"""Admin: Set profile email."""
email = data.get('email', '').strip().lower()
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("UPDATE profiles SET email=%s WHERE id=%s", (email if email else None, pid))
return {"ok": True}
@router.put("/profiles/{pid}/pin")
def admin_set_pin(pid: str, data: dict, session: dict=Depends(require_admin)):
"""Admin: Set profile PIN/password."""
new_pin = data.get('pin', '')
if len(new_pin) < 4:
raise HTTPException(400, "PIN/Passwort muss mind. 4 Zeichen haben")
new_hash = hash_pin(new_pin)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, pid))
return {"ok": True}
@router.get("/email/status")
def admin_email_status(session: dict=Depends(require_admin)):
"""Admin: Check email configuration status."""
smtp_host = os.getenv("SMTP_HOST")
smtp_user = os.getenv("SMTP_USER")
smtp_pass = os.getenv("SMTP_PASS")
app_url = os.getenv("APP_URL", "http://localhost:3002")
configured = bool(smtp_host and smtp_user and smtp_pass)
return {
"configured": configured,
"smtp_host": smtp_host or "",
"smtp_user": smtp_user or "",
"app_url": app_url
}
@router.post("/email/test")
def admin_test_email(data: dict, session: dict=Depends(require_admin)):
"""Admin: Send test email."""
email = data.get('to', '')
if not email:
raise HTTPException(400, "E-Mail-Adresse fehlt")
try:
smtp_host = os.getenv("SMTP_HOST")
smtp_port = int(os.getenv("SMTP_PORT", 587))
smtp_user = os.getenv("SMTP_USER")
smtp_pass = os.getenv("SMTP_PASS")
smtp_from = os.getenv("SMTP_FROM")
if not smtp_host or not smtp_user or not smtp_pass:
raise HTTPException(500, "SMTP nicht konfiguriert")
msg = MIMEText("Dies ist eine Test-E-Mail von Mitai Jinkendo.")
msg['Subject'] = "Test-E-Mail"
msg['From'] = smtp_from
msg['To'] = email
with smtplib.SMTP(smtp_host, smtp_port) as server:
server.starttls()
server.login(smtp_user, smtp_pass)
server.send_message(msg)
return {"ok": True, "message": f"Test-E-Mail an {email} gesendet"}
except Exception as e:
raise HTTPException(500, f"Fehler beim Senden: {str(e)}")
+324
View File
@@ -0,0 +1,324 @@
"""
Authentication Endpoints for Mitai Jinkendo
Handles login, logout, password reset, and profile authentication.
"""
import os
import secrets
import smtplib
from typing import Optional
from datetime import datetime, timedelta
from email.mime.text import MIMEText
from fastapi import APIRouter, HTTPException, Header, Depends
from starlette.requests import Request
from slowapi import Limiter
from slowapi.util import get_remote_address
from db import get_db, get_cursor
from auth import hash_pin, verify_pin, make_token, require_auth
from models import LoginRequest, PasswordResetRequest, PasswordResetConfirm, RegisterRequest
router = APIRouter(prefix="/api/auth", tags=["auth"])
limiter = Limiter(key_func=get_remote_address)
@router.post("/login")
@limiter.limit("5/minute")
async def login(req: LoginRequest, request: Request):
"""Login with email + password."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE email=%s", (req.email.lower().strip(),))
prof = cur.fetchone()
if not prof:
raise HTTPException(401, "Ungültige Zugangsdaten")
# Verify password
if not verify_pin(req.password, prof['pin_hash']):
raise HTTPException(401, "Ungültige Zugangsdaten")
# Auto-upgrade from SHA256 to bcrypt
if prof['pin_hash'] and not prof['pin_hash'].startswith('$2'):
new_hash = hash_pin(req.password)
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, prof['id']))
# Create session
token = make_token()
session_days = prof.get('session_days', 30)
expires = datetime.now() + timedelta(days=session_days)
cur.execute("INSERT INTO sessions (token, profile_id, expires_at, created) VALUES (%s,%s,%s,CURRENT_TIMESTAMP)",
(token, prof['id'], expires.isoformat()))
return {
"token": token,
"profile_id": prof['id'],
"name": prof['name'],
"role": prof['role'],
"expires_at": expires.isoformat()
}
@router.post("/logout")
def logout(x_auth_token: Optional[str]=Header(default=None)):
"""Logout (delete session)."""
if x_auth_token:
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("DELETE FROM sessions WHERE token=%s", (x_auth_token,))
return {"ok": True}
@router.get("/me")
def get_me(session: dict=Depends(require_auth)):
"""Get current user info."""
pid = session['profile_id']
# Import here to avoid circular dependency
from routers.profiles import get_profile
return get_profile(pid, session)
@router.get("/status")
def auth_status():
"""Health check endpoint."""
return {"status": "ok", "service": "mitai-jinkendo", "version": "v9b"}
@router.put("/pin")
def change_pin(req: dict, session: dict=Depends(require_auth)):
"""Change PIN/password for current user."""
pid = session['profile_id']
new_pin = req.get('pin', '')
if len(new_pin) < 4:
raise HTTPException(400, "PIN/Passwort muss mind. 4 Zeichen haben")
new_hash = hash_pin(new_pin)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, pid))
return {"ok": True}
@router.post("/forgot-password")
@limiter.limit("3/minute")
async def password_reset_request(req: PasswordResetRequest, request: Request):
"""Request password reset email."""
email = req.email.lower().strip()
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT id, name FROM profiles WHERE email=%s", (email,))
prof = cur.fetchone()
if not prof:
# Don't reveal if email exists
return {"ok": True, "message": "Falls die E-Mail existiert, wurde ein Reset-Link gesendet."}
# Generate reset token
token = secrets.token_urlsafe(32)
expires = datetime.now() + timedelta(hours=1)
# Store in sessions table (reuse mechanism)
cur.execute("INSERT INTO sessions (token, profile_id, expires_at, created) VALUES (%s,%s,%s,CURRENT_TIMESTAMP)",
(f"reset_{token}", prof['id'], expires.isoformat()))
# Send email
try:
smtp_host = os.getenv("SMTP_HOST")
smtp_port = int(os.getenv("SMTP_PORT", 587))
smtp_user = os.getenv("SMTP_USER")
smtp_pass = os.getenv("SMTP_PASS")
smtp_from = os.getenv("SMTP_FROM")
app_url = os.getenv("APP_URL", "https://mitai.jinkendo.de")
if smtp_host and smtp_user and smtp_pass:
msg = MIMEText(f"""Hallo {prof['name']},
Du hast einen Passwort-Reset angefordert.
Reset-Link: {app_url}/reset-password?token={token}
Der Link ist 1 Stunde gültig.
Falls du diese Anfrage nicht gestellt hast, ignoriere diese E-Mail.
Dein Mitai Jinkendo Team
""")
msg['Subject'] = "Passwort zurücksetzen – Mitai Jinkendo"
msg['From'] = smtp_from
msg['To'] = email
with smtplib.SMTP(smtp_host, smtp_port) as server:
server.starttls()
server.login(smtp_user, smtp_pass)
server.send_message(msg)
except Exception as e:
print(f"Email error: {e}")
return {"ok": True, "message": "Falls die E-Mail existiert, wurde ein Reset-Link gesendet."}
@router.post("/reset-password")
def password_reset_confirm(req: PasswordResetConfirm):
"""Confirm password reset with token."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT profile_id FROM sessions WHERE token=%s AND expires_at > CURRENT_TIMESTAMP",
(f"reset_{req.token}",))
sess = cur.fetchone()
if not sess:
raise HTTPException(400, "Ungültiger oder abgelaufener Reset-Link")
pid = sess['profile_id']
new_hash = hash_pin(req.new_password)
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, pid))
cur.execute("DELETE FROM sessions WHERE token=%s", (f"reset_{req.token}",))
return {"ok": True, "message": "Passwort erfolgreich zurückgesetzt"}
# ── Helper: Send Email ────────────────────────────────────────────────────────
def send_email(to_email: str, subject: str, body: str):
"""Send email via SMTP (reusable helper)."""
try:
smtp_host = os.getenv("SMTP_HOST")
smtp_port = int(os.getenv("SMTP_PORT", 587))
smtp_user = os.getenv("SMTP_USER")
smtp_pass = os.getenv("SMTP_PASS")
smtp_from = os.getenv("SMTP_FROM", "noreply@jinkendo.de")
if not smtp_host or not smtp_user or not smtp_pass:
print("SMTP not configured, skipping email")
return False
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = smtp_from
msg['To'] = to_email
with smtplib.SMTP(smtp_host, smtp_port) as server:
server.starttls()
server.login(smtp_user, smtp_pass)
server.send_message(msg)
return True
except Exception as e:
print(f"Email error: {e}")
return False
# ── Registration Endpoints ────────────────────────────────────────────────────
@router.post("/register")
@limiter.limit("3/hour")
async def register(req: RegisterRequest, request: Request):
"""Self-registration with email verification."""
email = req.email.lower().strip()
name = req.name.strip()
password = req.password
# Validation
if not email or '@' not in email:
raise HTTPException(400, "Ungültige E-Mail-Adresse")
if len(password) < 8:
raise HTTPException(400, "Passwort muss mindestens 8 Zeichen lang sein")
if not name or len(name) < 2:
raise HTTPException(400, "Name muss mindestens 2 Zeichen lang sein")
with get_db() as conn:
cur = get_cursor(conn)
# Check if email already exists
cur.execute("SELECT id FROM profiles WHERE email=%s", (email,))
if cur.fetchone():
raise HTTPException(400, "E-Mail-Adresse bereits registriert")
# Generate verification token
verification_token = secrets.token_urlsafe(32)
verification_expires = datetime.now() + timedelta(hours=24)
# Create profile (inactive until verified)
profile_id = str(secrets.token_hex(16))
pin_hash = hash_pin(password)
cur.execute("""
INSERT INTO profiles (
id, name, email, pin_hash, auth_type, role, tier,
email_verified, verification_token, verification_expires,
created
) VALUES (%s, %s, %s, %s, 'email', 'user', 'free', FALSE, %s, %s, CURRENT_TIMESTAMP)
""", (profile_id, name, email, pin_hash, verification_token, verification_expires))
# Send verification email
app_url = os.getenv("APP_URL", "https://mitai.jinkendo.de")
verify_url = f"{app_url}/verify?token={verification_token}"
email_body = f"""Hallo {name},
willkommen bei Mitai Jinkendo!
Bitte bestätige deine E-Mail-Adresse um die Registrierung abzuschließen:
{verify_url}
Der Link ist 24 Stunden gültig.
Dein Mitai Jinkendo Team
"""
send_email(email, "Willkommen bei Mitai Jinkendo – E-Mail bestätigen", email_body)
return {
"ok": True,
"message": "Registrierung erfolgreich! Bitte prüfe dein E-Mail-Postfach und bestätige deine E-Mail-Adresse."
}
@router.get("/verify/{token}")
async def verify_email(token: str):
"""Verify email address and activate account."""
with get_db() as conn:
cur = get_cursor(conn)
# Find profile with this verification token
cur.execute("""
SELECT id, name, email, email_verified, verification_expires
FROM profiles
WHERE verification_token=%s
""", (token,))
prof = cur.fetchone()
if not prof:
raise HTTPException(400, "Ungültiger Verifikations-Link")
if prof['email_verified']:
raise HTTPException(400, "E-Mail-Adresse bereits bestätigt")
# Check if token expired
if prof['verification_expires'] and datetime.now() > prof['verification_expires']:
raise HTTPException(400, "Verifikations-Link abgelaufen. Bitte registriere dich erneut.")
# Mark as verified and clear token
cur.execute("""
UPDATE profiles
SET email_verified=TRUE, verification_token=NULL, verification_expires=NULL
WHERE id=%s
""", (prof['id'],))
# Create session (auto-login after verification)
session_token = make_token()
expires = datetime.now() + timedelta(days=30)
cur.execute("""
INSERT INTO sessions (token, profile_id, expires_at, created)
VALUES (%s, %s, %s, CURRENT_TIMESTAMP)
""", (session_token, prof['id'], expires))
return {
"ok": True,
"message": "E-Mail-Adresse erfolgreich bestätigt!",
"token": session_token,
"profile": {
"id": prof['id'],
"name": prof['name'],
"email": prof['email']
}
}
+102
View File
@@ -0,0 +1,102 @@
"""
Caliper/Skinfold Tracking Endpoints for Mitai Jinkendo
Handles body fat measurements via skinfold caliper (4 methods supported).
"""
import uuid
import logging
from typing import Optional
from fastapi import APIRouter, Header, Depends, HTTPException
from db import get_db, get_cursor, r2d
from auth import require_auth, check_feature_access, increment_feature_usage
from models import CaliperEntry
from routers.profiles import get_pid
from feature_logger import log_feature_usage
router = APIRouter(prefix="/api/caliper", tags=["caliper"])
logger = logging.getLogger(__name__)
@router.get("")
def list_caliper(limit: int=100, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get caliper entries for current profile."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT * FROM caliper_log WHERE profile_id=%s ORDER BY date DESC LIMIT %s", (pid,limit))
return [r2d(r) for r in cur.fetchall()]
@router.post("")
def upsert_caliper(e: CaliperEntry, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Create or update caliper entry (upsert by date)."""
pid = get_pid(x_profile_id)
# Phase 4: Check feature access and ENFORCE
access = check_feature_access(pid, 'caliper_entries')
log_feature_usage(pid, 'caliper_entries', access, 'create')
if not access['allowed']:
logger.warning(
f"[FEATURE-LIMIT] User {pid} blocked: "
f"caliper_entries {access['reason']} (used: {access['used']}, limit: {access['limit']})"
)
raise HTTPException(
status_code=403,
detail=f"Limit erreicht: Du hast das Kontingent für Caliper-Einträge überschritten ({access['used']}/{access['limit']}). "
f"Bitte kontaktiere den Admin oder warte bis zum nächsten Reset."
)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT id FROM caliper_log WHERE profile_id=%s AND date=%s", (pid,e.date))
ex = cur.fetchone()
d = e.model_dump()
is_new_entry = not ex
if ex:
# UPDATE existing entry
eid = ex['id']
sets = ', '.join(f"{k}=%s" for k in d if k!='date')
cur.execute(f"UPDATE caliper_log SET {sets} WHERE id=%s",
[v for k,v in d.items() if k!='date']+[eid])
else:
# INSERT new entry
eid = str(uuid.uuid4())
cur.execute("""INSERT INTO caliper_log
(id,profile_id,date,sf_method,sf_chest,sf_axilla,sf_triceps,sf_subscap,sf_suprailiac,
sf_abdomen,sf_thigh,sf_calf_med,sf_lowerback,sf_biceps,body_fat_pct,lean_mass,fat_mass,notes,created)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,CURRENT_TIMESTAMP)""",
(eid,pid,d['date'],d['sf_method'],d['sf_chest'],d['sf_axilla'],d['sf_triceps'],
d['sf_subscap'],d['sf_suprailiac'],d['sf_abdomen'],d['sf_thigh'],d['sf_calf_med'],
d['sf_lowerback'],d['sf_biceps'],d['body_fat_pct'],d['lean_mass'],d['fat_mass'],d['notes']))
# Phase 2: Increment usage counter (only for new entries)
increment_feature_usage(pid, 'caliper_entries')
return {"id":eid,"date":e.date}
@router.put("/{eid}")
def update_caliper(eid: str, e: CaliperEntry, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Update existing caliper entry."""
pid = get_pid(x_profile_id)
with get_db() as conn:
d = e.model_dump()
cur = get_cursor(conn)
cur.execute(f"UPDATE caliper_log SET {', '.join(f'{k}=%s' for k in d)} WHERE id=%s AND profile_id=%s",
list(d.values())+[eid,pid])
return {"id":eid}
@router.delete("/{eid}")
def delete_caliper(eid: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Delete caliper entry."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("DELETE FROM caliper_log WHERE id=%s AND profile_id=%s", (eid,pid))
return {"ok":True}
+100
View File
@@ -0,0 +1,100 @@
"""
Circumference Tracking Endpoints for Mitai Jinkendo
Handles body circumference measurements (8 measurement points).
"""
import uuid
import logging
from typing import Optional
from fastapi import APIRouter, Header, Depends, HTTPException
from db import get_db, get_cursor, r2d
from auth import require_auth, check_feature_access, increment_feature_usage
from models import CircumferenceEntry
from routers.profiles import get_pid
from feature_logger import log_feature_usage
router = APIRouter(prefix="/api/circumferences", tags=["circumference"])
logger = logging.getLogger(__name__)
@router.get("")
def list_circs(limit: int=100, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get circumference entries for current profile."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT * FROM circumference_log WHERE profile_id=%s ORDER BY date DESC LIMIT %s", (pid,limit))
return [r2d(r) for r in cur.fetchall()]
@router.post("")
def upsert_circ(e: CircumferenceEntry, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Create or update circumference entry (upsert by date)."""
pid = get_pid(x_profile_id)
# Phase 4: Check feature access and ENFORCE
access = check_feature_access(pid, 'circumference_entries')
log_feature_usage(pid, 'circumference_entries', access, 'create')
if not access['allowed']:
logger.warning(
f"[FEATURE-LIMIT] User {pid} blocked: "
f"circumference_entries {access['reason']} (used: {access['used']}, limit: {access['limit']})"
)
raise HTTPException(
status_code=403,
detail=f"Limit erreicht: Du hast das Kontingent für Umfangs-Einträge überschritten ({access['used']}/{access['limit']}). "
f"Bitte kontaktiere den Admin oder warte bis zum nächsten Reset."
)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT id FROM circumference_log WHERE profile_id=%s AND date=%s", (pid,e.date))
ex = cur.fetchone()
d = e.model_dump()
is_new_entry = not ex
if ex:
# UPDATE existing entry
eid = ex['id']
sets = ', '.join(f"{k}=%s" for k in d if k!='date')
cur.execute(f"UPDATE circumference_log SET {sets} WHERE id=%s",
[v for k,v in d.items() if k!='date']+[eid])
else:
# INSERT new entry
eid = str(uuid.uuid4())
cur.execute("""INSERT INTO circumference_log
(id,profile_id,date,c_neck,c_chest,c_waist,c_belly,c_hip,c_thigh,c_calf,c_arm,notes,photo_id,created)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,CURRENT_TIMESTAMP)""",
(eid,pid,d['date'],d['c_neck'],d['c_chest'],d['c_waist'],d['c_belly'],
d['c_hip'],d['c_thigh'],d['c_calf'],d['c_arm'],d['notes'],d['photo_id']))
# Phase 2: Increment usage counter (only for new entries)
increment_feature_usage(pid, 'circumference_entries')
return {"id":eid,"date":e.date}
@router.put("/{eid}")
def update_circ(eid: str, e: CircumferenceEntry, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Update existing circumference entry."""
pid = get_pid(x_profile_id)
with get_db() as conn:
d = e.model_dump()
cur = get_cursor(conn)
cur.execute(f"UPDATE circumference_log SET {', '.join(f'{k}=%s' for k in d)} WHERE id=%s AND profile_id=%s",
list(d.values())+[eid,pid])
return {"id":eid}
@router.delete("/{eid}")
def delete_circ(eid: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Delete circumference entry."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("DELETE FROM circumference_log WHERE id=%s AND profile_id=%s", (eid,pid))
return {"ok":True}
+282
View File
@@ -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
}
+346
View File
@@ -0,0 +1,346 @@
"""
Data Export Endpoints for Mitai Jinkendo
Handles CSV, JSON, and ZIP exports with photos.
"""
import os
import csv
import io
import json
import logging
import zipfile
from pathlib import Path
from typing import Optional
from datetime import datetime
from decimal import Decimal
from fastapi import APIRouter, HTTPException, Header, Depends
from fastapi.responses import StreamingResponse, Response
from db import get_db, get_cursor, r2d
from auth import require_auth, check_feature_access, increment_feature_usage
from routers.profiles import get_pid
from feature_logger import log_feature_usage
router = APIRouter(prefix="/api/export", tags=["export"])
logger = logging.getLogger(__name__)
PHOTOS_DIR = Path(os.getenv("PHOTOS_DIR", "./photos"))
@router.get("/csv")
def export_csv(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Export all data as CSV."""
pid = get_pid(x_profile_id)
# Phase 4: Check feature access and ENFORCE
access = check_feature_access(pid, 'data_export')
log_feature_usage(pid, 'data_export', access, 'export_csv')
if not access['allowed']:
logger.warning(
f"[FEATURE-LIMIT] User {pid} blocked: "
f"data_export {access['reason']} (used: {access['used']}, limit: {access['limit']})"
)
raise HTTPException(
status_code=403,
detail=f"Limit erreicht: Du hast das Kontingent für Daten-Exporte überschritten ({access['used']}/{access['limit']}). "
f"Bitte kontaktiere den Admin oder warte bis zum nächsten Reset."
)
# Build CSV
output = io.StringIO()
writer = csv.writer(output)
# Header
writer.writerow(["Typ", "Datum", "Wert", "Details"])
# Weight
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT date, weight, note FROM weight_log WHERE profile_id=%s ORDER BY date", (pid,))
for r in cur.fetchall():
writer.writerow(["Gewicht", r['date'], f"{float(r['weight'])}kg", r['note'] or ""])
# Circumferences
cur.execute("SELECT date, c_waist, c_belly, c_hip FROM circumference_log WHERE profile_id=%s ORDER BY date", (pid,))
for r in cur.fetchall():
details = f"Taille:{float(r['c_waist'])}cm Bauch:{float(r['c_belly'])}cm Hüfte:{float(r['c_hip'])}cm"
writer.writerow(["Umfänge", r['date'], "", details])
# Caliper
cur.execute("SELECT date, body_fat_pct, lean_mass FROM caliper_log WHERE profile_id=%s ORDER BY date", (pid,))
for r in cur.fetchall():
writer.writerow(["Caliper", r['date'], f"{float(r['body_fat_pct'])}%", f"Magermasse:{float(r['lean_mass'])}kg"])
# Nutrition
cur.execute("SELECT date, kcal, protein_g FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,))
for r in cur.fetchall():
writer.writerow(["Ernährung", r['date'], f"{float(r['kcal'])}kcal", f"Protein:{float(r['protein_g'])}g"])
# Activity
cur.execute("SELECT date, activity_type, duration_min, kcal_active FROM activity_log WHERE profile_id=%s ORDER BY date", (pid,))
for r in cur.fetchall():
writer.writerow(["Training", r['date'], r['activity_type'], f"{float(r['duration_min'])}min {float(r['kcal_active'])}kcal"])
output.seek(0)
# Phase 2: Increment usage counter
increment_feature_usage(pid, 'data_export')
return StreamingResponse(
iter([output.getvalue()]),
media_type="text/csv",
headers={"Content-Disposition": f"attachment; filename=mitai-export-{pid}.csv"}
)
@router.get("/json")
def export_json(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Export all data as JSON."""
pid = get_pid(x_profile_id)
# Phase 4: Check feature access and ENFORCE
access = check_feature_access(pid, 'data_export')
log_feature_usage(pid, 'data_export', access, 'export_json')
if not access['allowed']:
logger.warning(
f"[FEATURE-LIMIT] User {pid} blocked: "
f"data_export {access['reason']} (used: {access['used']}, limit: {access['limit']})"
)
raise HTTPException(
status_code=403,
detail=f"Limit erreicht: Du hast das Kontingent für Daten-Exporte überschritten ({access['used']}/{access['limit']}). "
f"Bitte kontaktiere den Admin oder warte bis zum nächsten Reset."
)
# Collect all data
data = {}
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
data['profile'] = r2d(cur.fetchone())
cur.execute("SELECT * FROM weight_log WHERE profile_id=%s ORDER BY date", (pid,))
data['weight'] = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM circumference_log WHERE profile_id=%s ORDER BY date", (pid,))
data['circumferences'] = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM caliper_log WHERE profile_id=%s ORDER BY date", (pid,))
data['caliper'] = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,))
data['nutrition'] = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM activity_log WHERE profile_id=%s ORDER BY date", (pid,))
data['activity'] = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,))
data['insights'] = [r2d(r) for r in cur.fetchall()]
def decimal_handler(obj):
if isinstance(obj, Decimal):
return float(obj)
return str(obj)
json_str = json.dumps(data, indent=2, default=decimal_handler)
# Phase 2: Increment usage counter
increment_feature_usage(pid, 'data_export')
return Response(
content=json_str,
media_type="application/json",
headers={"Content-Disposition": f"attachment; filename=mitai-export-{pid}.json"}
)
@router.get("/zip")
def export_zip(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Export all data as ZIP (CSV + JSON + photos) per specification."""
pid = get_pid(x_profile_id)
# Phase 4: Check feature access and ENFORCE
access = check_feature_access(pid, 'data_export')
log_feature_usage(pid, 'data_export', access, 'export_zip')
if not access['allowed']:
logger.warning(
f"[FEATURE-LIMIT] User {pid} blocked: "
f"data_export {access['reason']} (used: {access['used']}, limit: {access['limit']})"
)
raise HTTPException(
status_code=403,
detail=f"Limit erreicht: Du hast das Kontingent für Daten-Exporte überschritten ({access['used']}/{access['limit']}). "
f"Bitte kontaktiere den Admin oder warte bis zum nächsten Reset."
)
# Get profile
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
prof = r2d(cur.fetchone())
# Helper: CSV writer with UTF-8 BOM + semicolon
def write_csv(zf, filename, rows, columns):
if not rows:
return
output = io.StringIO()
writer = csv.writer(output, delimiter=';')
writer.writerow(columns)
for r in rows:
writer.writerow([
'' if r.get(col) is None else
(float(r[col]) if isinstance(r.get(col), Decimal) else r[col])
for col in columns
])
# UTF-8 with BOM for Excel
csv_bytes = '\ufeff'.encode('utf-8') + output.getvalue().encode('utf-8')
zf.writestr(f"data/{filename}", csv_bytes)
# Create ZIP
zip_buffer = io.BytesIO()
export_date = datetime.now().strftime('%Y-%m-%d')
profile_name = prof.get('name', 'export')
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zf:
with get_db() as conn:
cur = get_cursor(conn)
# 1. README.txt
readme = f"""Mitai Jinkendo – Datenexport
Version: 2
Exportiert am: {export_date}
Profil: {profile_name}
Inhalt:
- profile.json: Profildaten und Einstellungen
- data/*.csv: Messdaten (Semikolon-getrennt, UTF-8)
- insights/: KI-Auswertungen (JSON)
- photos/: Progress-Fotos (JPEG)
Import:
Dieser Export kann in Mitai Jinkendo unter
Einstellungen → Import → "Mitai Backup importieren"
wieder eingespielt werden.
Format-Version 2 (ab v9b):
Alle CSV-Dateien sind UTF-8 mit BOM kodiert.
Trennzeichen: Semikolon (;)
Datumsformat: YYYY-MM-DD
"""
zf.writestr("README.txt", readme.encode('utf-8'))
# 2. profile.json (ohne Passwort-Hash)
cur.execute("SELECT COUNT(*) as c FROM weight_log WHERE profile_id=%s", (pid,))
w_count = cur.fetchone()['c']
cur.execute("SELECT COUNT(*) as c FROM nutrition_log WHERE profile_id=%s", (pid,))
n_count = cur.fetchone()['c']
cur.execute("SELECT COUNT(*) as c FROM activity_log WHERE profile_id=%s", (pid,))
a_count = cur.fetchone()['c']
cur.execute("SELECT COUNT(*) as c FROM photos WHERE profile_id=%s", (pid,))
p_count = cur.fetchone()['c']
profile_data = {
"export_version": "2",
"export_date": export_date,
"app": "Mitai Jinkendo",
"profile": {
"name": prof.get('name'),
"email": prof.get('email'),
"sex": prof.get('sex'),
"height": float(prof['height']) if prof.get('height') else None,
"birth_year": prof['dob'].year if prof.get('dob') else None,
"goal_weight": float(prof['goal_weight']) if prof.get('goal_weight') else None,
"goal_bf_pct": float(prof['goal_bf_pct']) if prof.get('goal_bf_pct') else None,
"avatar_color": prof.get('avatar_color'),
"auth_type": prof.get('auth_type'),
"session_days": prof.get('session_days'),
"ai_enabled": prof.get('ai_enabled'),
"tier": prof.get('tier')
},
"stats": {
"weight_entries": w_count,
"nutrition_entries": n_count,
"activity_entries": a_count,
"photos": p_count
}
}
zf.writestr("profile.json", json.dumps(profile_data, indent=2, ensure_ascii=False).encode('utf-8'))
# 3-7. CSV exports (weight, circumferences, caliper, nutrition, activity)
cur.execute("SELECT id, date, weight, note, source, created FROM weight_log WHERE profile_id=%s ORDER BY date", (pid,))
write_csv(zf, "weight.csv", [r2d(r) for r in cur.fetchall()], ['id','date','weight','note','source','created'])
cur.execute("SELECT id, date, c_waist, c_hip, c_chest, c_neck, c_arm, c_thigh, c_calf, notes, created FROM circumference_log WHERE profile_id=%s ORDER BY date", (pid,))
rows = [r2d(r) for r in cur.fetchall()]
for r in rows:
r['waist'] = r.pop('c_waist', None); r['hip'] = r.pop('c_hip', None)
r['chest'] = r.pop('c_chest', None); r['neck'] = r.pop('c_neck', None)
r['upper_arm'] = r.pop('c_arm', None); r['thigh'] = r.pop('c_thigh', None)
r['calf'] = r.pop('c_calf', None); r['forearm'] = None; r['note'] = r.pop('notes', None)
write_csv(zf, "circumferences.csv", rows, ['id','date','waist','hip','chest','neck','upper_arm','thigh','calf','forearm','note','created'])
cur.execute("SELECT id, date, sf_chest, sf_abdomen, sf_thigh, sf_triceps, sf_subscap, sf_suprailiac, sf_axilla, sf_method, body_fat_pct, notes, created FROM caliper_log WHERE profile_id=%s ORDER BY date", (pid,))
rows = [r2d(r) for r in cur.fetchall()]
for r in rows:
r['chest'] = r.pop('sf_chest', None); r['abdomen'] = r.pop('sf_abdomen', None)
r['thigh'] = r.pop('sf_thigh', None); r['tricep'] = r.pop('sf_triceps', None)
r['subscapular'] = r.pop('sf_subscap', None); r['suprailiac'] = r.pop('sf_suprailiac', None)
r['midaxillary'] = r.pop('sf_axilla', None); r['method'] = r.pop('sf_method', None)
r['bf_percent'] = r.pop('body_fat_pct', None); r['note'] = r.pop('notes', None)
write_csv(zf, "caliper.csv", rows, ['id','date','chest','abdomen','thigh','tricep','subscapular','suprailiac','midaxillary','method','bf_percent','note','created'])
cur.execute("SELECT id, date, kcal, protein_g, fat_g, carbs_g, source, created FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,))
rows = [r2d(r) for r in cur.fetchall()]
for r in rows:
r['meal_name'] = ''; r['protein'] = r.pop('protein_g', None)
r['fat'] = r.pop('fat_g', None); r['carbs'] = r.pop('carbs_g', None)
r['fiber'] = None; r['note'] = ''
write_csv(zf, "nutrition.csv", rows, ['id','date','meal_name','kcal','protein','fat','carbs','fiber','note','source','created'])
cur.execute("SELECT id, date, activity_type, duration_min, kcal_active, hr_avg, hr_max, distance_km, notes, source, created FROM activity_log WHERE profile_id=%s ORDER BY date", (pid,))
rows = [r2d(r) for r in cur.fetchall()]
for r in rows:
r['name'] = r['activity_type']; r['type'] = r.pop('activity_type', None)
r['kcal'] = r.pop('kcal_active', None); r['heart_rate_avg'] = r.pop('hr_avg', None)
r['heart_rate_max'] = r.pop('hr_max', None); r['note'] = r.pop('notes', None)
write_csv(zf, "activity.csv", rows, ['id','date','name','type','duration_min','kcal','heart_rate_avg','heart_rate_max','distance_km','note','source','created'])
# 8. insights/ai_insights.json
cur.execute("SELECT id, scope, content, created FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,))
insights = []
for r in cur.fetchall():
rd = r2d(r)
insights.append({
"id": rd['id'],
"scope": rd['scope'],
"created": rd['created'].isoformat() if hasattr(rd['created'], 'isoformat') else str(rd['created']),
"result": rd['content']
})
if insights:
zf.writestr("insights/ai_insights.json", json.dumps(insights, indent=2, ensure_ascii=False).encode('utf-8'))
# 9. photos/
cur.execute("SELECT * FROM photos WHERE profile_id=%s ORDER BY date", (pid,))
photos = [r2d(r) for r in cur.fetchall()]
for i, photo in enumerate(photos):
photo_path = Path(PHOTOS_DIR) / photo['path']
if photo_path.exists():
filename = f"{photo.get('date') or export_date}_{i+1}{photo_path.suffix}"
zf.write(photo_path, f"photos/{filename}")
zip_buffer.seek(0)
filename = f"mitai-export-{profile_name.replace(' ','-')}-{export_date}.zip"
# Phase 2: Increment usage counter
increment_feature_usage(pid, 'data_export')
return StreamingResponse(
iter([zip_buffer.getvalue()]),
media_type="application/zip",
headers={"Content-Disposition": f"attachment; filename={filename}"}
)
+223
View File
@@ -0,0 +1,223 @@
"""
Feature Management Endpoints for Mitai Jinkendo
Admin-only CRUD for features registry.
User endpoint for feature usage overview (Phase 3).
"""
from typing import Optional
from datetime import datetime
from fastapi import APIRouter, HTTPException, Header, Depends
from db import get_db, get_cursor, r2d
from auth import require_admin, require_auth, check_feature_access
from routers.profiles import get_pid
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}
@router.get("/{feature_id}/check-access")
def check_access(feature_id: str, session: dict = Depends(require_auth)):
"""
User: Check if current user can access a feature.
Returns:
- allowed: bool - whether user can use the feature
- limit: int|null - total limit (null = unlimited)
- used: int - current usage
- remaining: int|null - remaining uses (null = unlimited)
- reason: str - why access is granted/denied
"""
profile_id = session['profile_id']
result = check_feature_access(profile_id, feature_id)
return result
@router.get("/usage")
def get_feature_usage(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""
User: Get usage overview for all active features (Phase 3: Frontend Display).
Returns list of all features with current usage, limits, and reset info.
Automatically includes new features from database - no code changes needed.
Response:
[
{
"feature_id": "weight_entries",
"name": "Gewichtseinträge",
"description": "Anzahl der Gewichtseinträge",
"category": "data",
"limit_type": "count",
"reset_period": "never",
"used": 5,
"limit": 10,
"remaining": 5,
"allowed": true,
"reset_at": null
},
...
]
"""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
# Get all active features (dynamic - picks up new features automatically)
cur.execute("""
SELECT id, name, description, category, limit_type, reset_period
FROM features
WHERE active = true
ORDER BY category, name
""")
features = [r2d(r) for r in cur.fetchall()]
result = []
for feature in features:
# Use existing check_feature_access to get usage and limits
# This respects user overrides, tier limits, and feature defaults
# Pass connection to avoid pool exhaustion
access = check_feature_access(pid, feature['id'], conn)
# Get reset date from user_feature_usage
cur.execute("""
SELECT reset_at
FROM user_feature_usage
WHERE profile_id = %s AND feature_id = %s
""", (pid, feature['id']))
usage_row = cur.fetchone()
# Format reset_at as ISO string
reset_at = None
if usage_row and usage_row['reset_at']:
if isinstance(usage_row['reset_at'], datetime):
reset_at = usage_row['reset_at'].isoformat()
else:
reset_at = str(usage_row['reset_at'])
result.append({
'feature_id': feature['id'],
'name': feature['name'],
'description': feature.get('description'),
'category': feature.get('category'),
'limit_type': feature['limit_type'],
'reset_period': feature['reset_period'],
'used': access['used'],
'limit': access['limit'],
'remaining': access['remaining'],
'allowed': access['allowed'],
'reset_at': reset_at
})
return result
+288
View File
@@ -0,0 +1,288 @@
"""
Data Import Endpoints for Mitai Jinkendo
Handles ZIP import with validation and rollback support.
"""
import os
import csv
import io
import json
import uuid
import logging
import zipfile
from pathlib import Path
from typing import Optional
from datetime import datetime
from fastapi import APIRouter, HTTPException, UploadFile, File, Header, Depends
from db import get_db, get_cursor
from auth import require_auth, check_feature_access, increment_feature_usage
from routers.profiles import get_pid
from feature_logger import log_feature_usage
router = APIRouter(prefix="/api/import", tags=["import"])
logger = logging.getLogger(__name__)
PHOTOS_DIR = Path(os.getenv("PHOTOS_DIR", "./photos"))
@router.post("/zip")
async def import_zip(
file: UploadFile = File(...),
x_profile_id: Optional[str] = Header(default=None),
session: dict = Depends(require_auth)
):
"""
Import data from ZIP export file.
- Validates export format
- Imports missing entries only (ON CONFLICT DO NOTHING)
- Imports photos
- Returns import summary
- Full rollback on error
"""
pid = get_pid(x_profile_id)
# Phase 4: Check feature access and ENFORCE
access = check_feature_access(pid, 'data_import')
log_feature_usage(pid, 'data_import', access, 'import_zip')
if not access['allowed']:
logger.warning(
f"[FEATURE-LIMIT] User {pid} blocked: "
f"data_import {access['reason']} (used: {access['used']}, limit: {access['limit']})"
)
raise HTTPException(
status_code=403,
detail=f"Limit erreicht: Du hast das Kontingent für Daten-Importe überschritten ({access['used']}/{access['limit']}). "
f"Bitte kontaktiere den Admin oder warte bis zum nächsten Reset."
)
# Read uploaded file
content = await file.read()
zip_buffer = io.BytesIO(content)
try:
with zipfile.ZipFile(zip_buffer, 'r') as zf:
# 1. Validate profile.json
if 'profile.json' not in zf.namelist():
raise HTTPException(400, "Ungültiger Export: profile.json fehlt")
profile_data = json.loads(zf.read('profile.json').decode('utf-8'))
export_version = profile_data.get('export_version', '1')
# Stats tracker
stats = {
'weight': 0,
'circumferences': 0,
'caliper': 0,
'nutrition': 0,
'activity': 0,
'photos': 0,
'insights': 0
}
with get_db() as conn:
cur = get_cursor(conn)
try:
# 2. Import weight.csv
if 'data/weight.csv' in zf.namelist():
csv_data = zf.read('data/weight.csv').decode('utf-8-sig')
reader = csv.DictReader(io.StringIO(csv_data), delimiter=';')
for row in reader:
cur.execute("""
INSERT INTO weight_log (profile_id, date, weight, note, source, created)
VALUES (%s, %s, %s, %s, %s, %s)
ON CONFLICT (profile_id, date) DO NOTHING
""", (
pid,
row['date'],
float(row['weight']) if row['weight'] else None,
row.get('note', ''),
row.get('source', 'import'),
row.get('created', datetime.now())
))
if cur.rowcount > 0:
stats['weight'] += 1
# 3. Import circumferences.csv
if 'data/circumferences.csv' in zf.namelist():
csv_data = zf.read('data/circumferences.csv').decode('utf-8-sig')
reader = csv.DictReader(io.StringIO(csv_data), delimiter=';')
for row in reader:
cur.execute("""
INSERT INTO circumference_log (
profile_id, date, c_waist, c_hip, c_chest, c_neck,
c_arm, c_thigh, c_calf, notes, created
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (profile_id, date) DO NOTHING
""", (
pid,
row['date'],
float(row['waist']) if row.get('waist') else None,
float(row['hip']) if row.get('hip') else None,
float(row['chest']) if row.get('chest') else None,
float(row['neck']) if row.get('neck') else None,
float(row['upper_arm']) if row.get('upper_arm') else None,
float(row['thigh']) if row.get('thigh') else None,
float(row['calf']) if row.get('calf') else None,
row.get('note', ''),
row.get('created', datetime.now())
))
if cur.rowcount > 0:
stats['circumferences'] += 1
# 4. Import caliper.csv
if 'data/caliper.csv' in zf.namelist():
csv_data = zf.read('data/caliper.csv').decode('utf-8-sig')
reader = csv.DictReader(io.StringIO(csv_data), delimiter=';')
for row in reader:
cur.execute("""
INSERT INTO caliper_log (
profile_id, date, sf_chest, sf_abdomen, sf_thigh,
sf_triceps, sf_subscap, sf_suprailiac, sf_axilla,
sf_method, body_fat_pct, notes, created
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (profile_id, date) DO NOTHING
""", (
pid,
row['date'],
float(row['chest']) if row.get('chest') else None,
float(row['abdomen']) if row.get('abdomen') else None,
float(row['thigh']) if row.get('thigh') else None,
float(row['tricep']) if row.get('tricep') else None,
float(row['subscapular']) if row.get('subscapular') else None,
float(row['suprailiac']) if row.get('suprailiac') else None,
float(row['midaxillary']) if row.get('midaxillary') else None,
row.get('method', 'jackson3'),
float(row['bf_percent']) if row.get('bf_percent') else None,
row.get('note', ''),
row.get('created', datetime.now())
))
if cur.rowcount > 0:
stats['caliper'] += 1
# 5. Import nutrition.csv
if 'data/nutrition.csv' in zf.namelist():
csv_data = zf.read('data/nutrition.csv').decode('utf-8-sig')
reader = csv.DictReader(io.StringIO(csv_data), delimiter=';')
for row in reader:
cur.execute("""
INSERT INTO nutrition_log (
profile_id, date, kcal, protein_g, fat_g, carbs_g, source, created
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (profile_id, date) DO NOTHING
""", (
pid,
row['date'],
float(row['kcal']) if row.get('kcal') else None,
float(row['protein']) if row.get('protein') else None,
float(row['fat']) if row.get('fat') else None,
float(row['carbs']) if row.get('carbs') else None,
row.get('source', 'import'),
row.get('created', datetime.now())
))
if cur.rowcount > 0:
stats['nutrition'] += 1
# 6. Import activity.csv
if 'data/activity.csv' in zf.namelist():
csv_data = zf.read('data/activity.csv').decode('utf-8-sig')
reader = csv.DictReader(io.StringIO(csv_data), delimiter=';')
for row in reader:
cur.execute("""
INSERT INTO activity_log (
profile_id, date, activity_type, duration_min,
kcal_active, hr_avg, hr_max, distance_km, notes, source, created
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
""", (
pid,
row['date'],
row.get('type', 'Training'),
float(row['duration_min']) if row.get('duration_min') else None,
float(row['kcal']) if row.get('kcal') else None,
float(row['heart_rate_avg']) if row.get('heart_rate_avg') else None,
float(row['heart_rate_max']) if row.get('heart_rate_max') else None,
float(row['distance_km']) if row.get('distance_km') else None,
row.get('note', ''),
row.get('source', 'import'),
row.get('created', datetime.now())
))
if cur.rowcount > 0:
stats['activity'] += 1
# 7. Import ai_insights.json
if 'insights/ai_insights.json' in zf.namelist():
insights_data = json.loads(zf.read('insights/ai_insights.json').decode('utf-8'))
for insight in insights_data:
cur.execute("""
INSERT INTO ai_insights (profile_id, scope, content, created)
VALUES (%s, %s, %s, %s)
""", (
pid,
insight['scope'],
insight['result'],
insight.get('created', datetime.now())
))
stats['insights'] += 1
# 8. Import photos
photo_files = [f for f in zf.namelist() if f.startswith('photos/') and not f.endswith('/')]
for photo_file in photo_files:
# Extract date from filename (format: YYYY-MM-DD_N.jpg)
filename = Path(photo_file).name
parts = filename.split('_')
photo_date = parts[0] if len(parts) > 0 else datetime.now().strftime('%Y-%m-%d')
# Generate new ID and path
photo_id = str(uuid.uuid4())
ext = Path(filename).suffix
new_filename = f"{photo_id}{ext}"
target_path = PHOTOS_DIR / new_filename
# Check if photo already exists for this date
cur.execute("""
SELECT id FROM photos
WHERE profile_id = %s AND date = %s
""", (pid, photo_date))
if cur.fetchone() is None:
# Write photo file
with open(target_path, 'wb') as f:
f.write(zf.read(photo_file))
# Insert DB record
cur.execute("""
INSERT INTO photos (id, profile_id, date, path, created)
VALUES (%s, %s, %s, %s, %s)
""", (photo_id, pid, photo_date, new_filename, datetime.now()))
stats['photos'] += 1
# Commit transaction
conn.commit()
except Exception as e:
# Rollback on any error
conn.rollback()
raise HTTPException(500, f"Import fehlgeschlagen: {str(e)}")
# Phase 2: Increment usage counter
increment_feature_usage(pid, 'data_import')
return {
"ok": True,
"message": "Import erfolgreich",
"stats": stats,
"total": sum(stats.values())
}
except zipfile.BadZipFile:
raise HTTPException(400, "Ungültige ZIP-Datei")
except Exception as e:
raise HTTPException(500, f"Import-Fehler: {str(e)}")
+514
View File
@@ -0,0 +1,514 @@
"""
AI Insights Endpoints for Mitai Jinkendo
Handles AI analysis execution, prompt management, and usage tracking.
"""
import os
import json
import uuid
import logging
import httpx
from typing import Optional
from datetime import datetime
from fastapi import APIRouter, HTTPException, Header, Depends
from db import get_db, get_cursor, r2d
from auth import require_auth, require_admin, check_feature_access, increment_feature_usage
from routers.profiles import get_pid
from feature_logger import log_feature_usage
router = APIRouter(prefix="/api", tags=["insights"])
logger = logging.getLogger(__name__)
OPENROUTER_KEY = os.getenv("OPENROUTER_API_KEY", "")
OPENROUTER_MODEL = os.getenv("OPENROUTER_MODEL", "anthropic/claude-sonnet-4")
ANTHROPIC_KEY = os.getenv("ANTHROPIC_API_KEY", "")
# ── Helper Functions ──────────────────────────────────────────────────────────
def check_ai_limit(pid: str):
"""Check if profile has reached daily AI limit. Returns (allowed, limit, used)."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT ai_enabled, ai_limit_day FROM profiles WHERE id=%s", (pid,))
prof = cur.fetchone()
if not prof or not prof['ai_enabled']:
raise HTTPException(403, "KI ist für dieses Profil deaktiviert")
limit = prof['ai_limit_day']
if limit is None:
return (True, None, 0)
today = datetime.now().date().isoformat()
cur.execute("SELECT call_count FROM ai_usage WHERE profile_id=%s AND date=%s", (pid, today))
usage = cur.fetchone()
used = usage['call_count'] if usage else 0
if used >= limit:
raise HTTPException(429, f"Tägliches KI-Limit erreicht ({limit} Calls)")
return (True, limit, used)
def inc_ai_usage(pid: str):
"""Increment AI usage counter for today."""
today = datetime.now().date().isoformat()
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT id, call_count FROM ai_usage WHERE profile_id=%s AND date=%s", (pid, today))
row = cur.fetchone()
if row:
cur.execute("UPDATE ai_usage SET call_count=%s WHERE id=%s", (row['call_count']+1, row['id']))
else:
cur.execute("INSERT INTO ai_usage (id, profile_id, date, call_count) VALUES (%s,%s,%s,1)",
(str(uuid.uuid4()), pid, today))
def _get_profile_data(pid: str):
"""Fetch all relevant data for AI analysis."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
prof = r2d(cur.fetchone())
cur.execute("SELECT * FROM weight_log WHERE profile_id=%s ORDER BY date DESC LIMIT 90", (pid,))
weight = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM circumference_log WHERE profile_id=%s ORDER BY date DESC LIMIT 30", (pid,))
circ = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM caliper_log WHERE profile_id=%s ORDER BY date DESC LIMIT 30", (pid,))
caliper = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM nutrition_log WHERE profile_id=%s ORDER BY date DESC LIMIT 90", (pid,))
nutrition = [r2d(r) for r in cur.fetchall()]
cur.execute("SELECT * FROM activity_log WHERE profile_id=%s ORDER BY date DESC LIMIT 90", (pid,))
activity = [r2d(r) for r in cur.fetchall()]
return {
"profile": prof,
"weight": weight,
"circumference": circ,
"caliper": caliper,
"nutrition": nutrition,
"activity": activity
}
def _render_template(template: str, data: dict) -> str:
"""Simple template variable replacement."""
result = template
for k, v in data.items():
result = result.replace(f"{{{{{k}}}}}", str(v) if v is not None else "")
return result
def _prepare_template_vars(data: dict) -> dict:
"""Prepare template variables from profile data."""
prof = data['profile']
weight = data['weight']
circ = data['circumference']
caliper = data['caliper']
nutrition = data['nutrition']
activity = data['activity']
vars = {
"name": prof.get('name', 'Nutzer'),
"geschlecht": "männlich" if prof.get('sex') == 'm' else "weiblich",
"height": prof.get('height', 178),
"goal_weight": float(prof.get('goal_weight')) if prof.get('goal_weight') else "nicht gesetzt",
"goal_bf_pct": float(prof.get('goal_bf_pct')) if prof.get('goal_bf_pct') else "nicht gesetzt",
"weight_aktuell": float(weight[0]['weight']) if weight else "keine Daten",
"kf_aktuell": float(caliper[0]['body_fat_pct']) if caliper and caliper[0].get('body_fat_pct') else "unbekannt",
}
# Calculate age from dob
if prof.get('dob'):
try:
from datetime import date
dob = datetime.strptime(prof['dob'], '%Y-%m-%d').date()
today = date.today()
age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
vars['age'] = age
except:
vars['age'] = "unbekannt"
else:
vars['age'] = "unbekannt"
# Weight trend summary
if len(weight) >= 2:
recent = weight[:30]
delta = float(recent[0]['weight']) - float(recent[-1]['weight'])
vars['weight_trend'] = f"{len(recent)} Einträge, Δ30d: {delta:+.1f}kg"
else:
vars['weight_trend'] = "zu wenig Daten"
# Caliper summary
if caliper:
c = caliper[0]
bf = float(c.get('body_fat_pct')) if c.get('body_fat_pct') else '?'
vars['caliper_summary'] = f"KF: {bf}%, Methode: {c.get('sf_method','?')}"
else:
vars['caliper_summary'] = "keine Daten"
# Circumference summary
if circ:
c = circ[0]
parts = []
for k in ['c_waist', 'c_belly', 'c_hip']:
if c.get(k): parts.append(f"{k.split('_')[1]}: {float(c[k])}cm")
vars['circ_summary'] = ", ".join(parts) if parts else "keine Daten"
else:
vars['circ_summary'] = "keine Daten"
# Nutrition summary
if nutrition:
n = len(nutrition)
avg_kcal = sum(float(d.get('kcal',0) or 0) for d in nutrition) / n
avg_prot = sum(float(d.get('protein_g',0) or 0) for d in nutrition) / n
vars['nutrition_summary'] = f"{n} Tage, Ø {avg_kcal:.0f}kcal, {avg_prot:.0f}g Protein"
vars['nutrition_detail'] = vars['nutrition_summary']
vars['nutrition_days'] = n
vars['kcal_avg'] = round(avg_kcal)
vars['protein_avg'] = round(avg_prot,1)
vars['fat_avg'] = round(sum(float(d.get('fat_g',0) or 0) for d in nutrition) / n,1)
vars['carb_avg'] = round(sum(float(d.get('carbs_g',0) or 0) for d in nutrition) / n,1)
else:
vars['nutrition_summary'] = "keine Daten"
vars['nutrition_detail'] = "keine Daten"
vars['nutrition_days'] = 0
vars['kcal_avg'] = 0
vars['protein_avg'] = 0
vars['fat_avg'] = 0
vars['carb_avg'] = 0
# Protein targets
w = weight[0]['weight'] if weight else prof.get('height',178) - 100
w = float(w) # Convert Decimal to float for math operations
vars['protein_ziel_low'] = round(w * 1.6)
vars['protein_ziel_high'] = round(w * 2.2)
# Activity summary
if activity:
n = len(activity)
total_kcal = sum(float(a.get('kcal_active',0) or 0) for a in activity)
vars['activity_summary'] = f"{n} Trainings, {total_kcal:.0f}kcal gesamt"
vars['activity_detail'] = vars['activity_summary']
vars['activity_kcal_summary'] = f"Ø {total_kcal/n:.0f}kcal/Training"
else:
vars['activity_summary'] = "keine Daten"
vars['activity_detail'] = "keine Daten"
vars['activity_kcal_summary'] = "keine Daten"
return vars
# ── Endpoints ─────────────────────────────────────────────────────────────────
@router.get("/insights")
def get_all_insights(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get all AI insights for profile."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,))
rows = cur.fetchall()
return [r2d(r) for r in rows]
@router.get("/insights/latest")
def get_latest_insights(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get latest AI insights across all scopes."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s ORDER BY created DESC LIMIT 10", (pid,))
rows = cur.fetchall()
return [r2d(r) for r in rows]
@router.get("/ai/insights/{scope}")
def get_ai_insight(scope: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get latest insight for specific scope."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s AND scope=%s ORDER BY created DESC LIMIT 1", (pid,scope))
row = cur.fetchone()
if not row: return None
return r2d(row)
@router.delete("/insights/{insight_id}")
def delete_insight_by_id(insight_id: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Delete a specific insight by ID."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("DELETE FROM ai_insights WHERE id=%s AND profile_id=%s", (insight_id, pid))
return {"ok":True}
@router.delete("/ai/insights/{scope}")
def delete_ai_insight(scope: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Delete all insights for specific scope."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("DELETE FROM ai_insights WHERE profile_id=%s AND scope=%s", (pid,scope))
return {"ok":True}
@router.post("/insights/run/{slug}")
async def analyze_with_prompt(slug: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Run AI analysis with specified prompt template."""
pid = get_pid(x_profile_id)
# Phase 4: Check feature access and ENFORCE
access = check_feature_access(pid, 'ai_calls')
log_feature_usage(pid, 'ai_calls', access, 'analyze')
if not access['allowed']:
logger.warning(
f"[FEATURE-LIMIT] User {pid} blocked: "
f"ai_calls {access['reason']} (used: {access['used']}, limit: {access['limit']})"
)
raise HTTPException(
status_code=403,
detail=f"Limit erreicht: Du hast das Kontingent für KI-Analysen überschritten ({access['used']}/{access['limit']}). "
f"Bitte kontaktiere den Admin oder warte bis zum nächsten Reset."
)
# Get prompt template
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM ai_prompts WHERE slug=%s AND active=true", (slug,))
prompt_row = cur.fetchone()
if not prompt_row:
raise HTTPException(404, f"Prompt '{slug}' nicht gefunden")
prompt_tmpl = prompt_row['template']
data = _get_profile_data(pid)
vars = _prepare_template_vars(data)
final_prompt = _render_template(prompt_tmpl, vars)
# Call AI
if ANTHROPIC_KEY:
# Use Anthropic SDK
import anthropic
client = anthropic.Anthropic(api_key=ANTHROPIC_KEY)
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=2000,
messages=[{"role": "user", "content": final_prompt}]
)
content = response.content[0].text
elif OPENROUTER_KEY:
async with httpx.AsyncClient() as client:
resp = await client.post("https://openrouter.ai/api/v1/chat/completions",
headers={"Authorization": f"Bearer {OPENROUTER_KEY}"},
json={
"model": OPENROUTER_MODEL,
"messages": [{"role": "user", "content": final_prompt}],
"max_tokens": 2000
},
timeout=60.0
)
if resp.status_code != 200:
raise HTTPException(500, f"KI-Fehler: {resp.text}")
content = resp.json()['choices'][0]['message']['content']
else:
raise HTTPException(500, "Keine KI-API konfiguriert")
# Save insight (with history - no DELETE)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("INSERT INTO ai_insights (id, profile_id, scope, content, created) VALUES (%s,%s,%s,%s,CURRENT_TIMESTAMP)",
(str(uuid.uuid4()), pid, slug, content))
# Phase 2: Increment new feature usage counter
increment_feature_usage(pid, 'ai_calls')
# Old usage tracking (keep for now)
inc_ai_usage(pid)
return {"scope": slug, "content": content}
@router.post("/insights/pipeline")
async def analyze_pipeline(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Run 3-stage pipeline analysis."""
pid = get_pid(x_profile_id)
# Phase 4: Check pipeline feature access (boolean - enabled/disabled)
access_pipeline = check_feature_access(pid, 'ai_pipeline')
log_feature_usage(pid, 'ai_pipeline', access_pipeline, 'pipeline')
if not access_pipeline['allowed']:
logger.warning(
f"[FEATURE-LIMIT] User {pid} blocked: "
f"ai_pipeline {access_pipeline['reason']}"
)
raise HTTPException(
status_code=403,
detail=f"Pipeline-Analyse ist nicht verfügbar. Bitte kontaktiere den Admin."
)
# Also check ai_calls (pipeline uses API calls too)
access_calls = check_feature_access(pid, 'ai_calls')
log_feature_usage(pid, 'ai_calls', access_calls, 'pipeline_calls')
if not access_calls['allowed']:
logger.warning(
f"[FEATURE-LIMIT] User {pid} blocked: "
f"ai_calls {access_calls['reason']} (used: {access_calls['used']}, limit: {access_calls['limit']})"
)
raise HTTPException(
status_code=403,
detail=f"Limit erreicht: Du hast das Kontingent für KI-Analysen überschritten ({access_calls['used']}/{access_calls['limit']}). "
f"Bitte kontaktiere den Admin oder warte bis zum nächsten Reset."
)
data = _get_profile_data(pid)
vars = _prepare_template_vars(data)
# Stage 1: Parallel JSON analyses
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT slug, template FROM ai_prompts WHERE slug LIKE 'pipeline_%' AND slug NOT IN ('pipeline_synthesis','pipeline_goals') AND active=true")
stage1_prompts = [r2d(r) for r in cur.fetchall()]
stage1_results = {}
for p in stage1_prompts:
slug = p['slug']
final_prompt = _render_template(p['template'], vars)
if ANTHROPIC_KEY:
import anthropic
client = anthropic.Anthropic(api_key=ANTHROPIC_KEY)
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1000,
messages=[{"role": "user", "content": final_prompt}]
)
content = response.content[0].text.strip()
elif OPENROUTER_KEY:
async with httpx.AsyncClient() as client:
resp = await client.post("https://openrouter.ai/api/v1/chat/completions",
headers={"Authorization": f"Bearer {OPENROUTER_KEY}"},
json={
"model": OPENROUTER_MODEL,
"messages": [{"role": "user", "content": final_prompt}],
"max_tokens": 1000
},
timeout=60.0
)
content = resp.json()['choices'][0]['message']['content'].strip()
else:
raise HTTPException(500, "Keine KI-API konfiguriert")
# Try to parse JSON, fallback to raw text
try:
stage1_results[slug] = json.loads(content)
except:
stage1_results[slug] = content
# Stage 2: Synthesis
vars['stage1_body'] = json.dumps(stage1_results.get('pipeline_body', {}), ensure_ascii=False)
vars['stage1_nutrition'] = json.dumps(stage1_results.get('pipeline_nutrition', {}), ensure_ascii=False)
vars['stage1_activity'] = json.dumps(stage1_results.get('pipeline_activity', {}), ensure_ascii=False)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT template FROM ai_prompts WHERE slug='pipeline_synthesis' AND active=true")
synth_row = cur.fetchone()
if not synth_row:
raise HTTPException(500, "Pipeline synthesis prompt not found")
synth_prompt = _render_template(synth_row['template'], vars)
if ANTHROPIC_KEY:
import anthropic
client = anthropic.Anthropic(api_key=ANTHROPIC_KEY)
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=2000,
messages=[{"role": "user", "content": synth_prompt}]
)
synthesis = response.content[0].text
elif OPENROUTER_KEY:
async with httpx.AsyncClient() as client:
resp = await client.post("https://openrouter.ai/api/v1/chat/completions",
headers={"Authorization": f"Bearer {OPENROUTER_KEY}"},
json={
"model": OPENROUTER_MODEL,
"messages": [{"role": "user", "content": synth_prompt}],
"max_tokens": 2000
},
timeout=60.0
)
synthesis = resp.json()['choices'][0]['message']['content']
else:
raise HTTPException(500, "Keine KI-API konfiguriert")
# Stage 3: Goals (only if goals are set)
goals_text = None
prof = data['profile']
if prof.get('goal_weight') or prof.get('goal_bf_pct'):
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT template FROM ai_prompts WHERE slug='pipeline_goals' AND active=true")
goals_row = cur.fetchone()
if goals_row:
goals_prompt = _render_template(goals_row['template'], vars)
if ANTHROPIC_KEY:
import anthropic
client = anthropic.Anthropic(api_key=ANTHROPIC_KEY)
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=800,
messages=[{"role": "user", "content": goals_prompt}]
)
goals_text = response.content[0].text
elif OPENROUTER_KEY:
async with httpx.AsyncClient() as client:
resp = await client.post("https://openrouter.ai/api/v1/chat/completions",
headers={"Authorization": f"Bearer {OPENROUTER_KEY}"},
json={
"model": OPENROUTER_MODEL,
"messages": [{"role": "user", "content": goals_prompt}],
"max_tokens": 800
},
timeout=60.0
)
goals_text = resp.json()['choices'][0]['message']['content']
# Combine synthesis + goals
final_content = synthesis
if goals_text:
final_content += "\n\n" + goals_text
# Save as 'pipeline' scope (with history - no DELETE)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("INSERT INTO ai_insights (id, profile_id, scope, content, created) VALUES (%s,%s,'pipeline',%s,CURRENT_TIMESTAMP)",
(str(uuid.uuid4()), pid, final_content))
# Phase 2: Increment ai_calls usage (pipeline uses multiple API calls)
# Note: We increment once per pipeline run, not per individual call
increment_feature_usage(pid, 'ai_calls')
# Old usage tracking (keep for now)
inc_ai_usage(pid)
return {"scope": "pipeline", "content": final_content, "stage1": stage1_results}
@router.get("/ai/usage")
def get_ai_usage(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get AI usage stats for current profile."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT ai_limit_day FROM profiles WHERE id=%s", (pid,))
prof = cur.fetchone()
limit = prof['ai_limit_day'] if prof else None
today = datetime.now().date().isoformat()
cur.execute("SELECT call_count FROM ai_usage WHERE profile_id=%s AND date=%s", (pid, today))
usage = cur.fetchone()
used = usage['call_count'] if usage else 0
return {"limit": limit, "used": used, "remaining": (limit - used) if limit else None}
+289
View File
@@ -0,0 +1,289 @@
"""
Nutrition Tracking Endpoints for Mitai Jinkendo
Handles nutrition data, FDDB CSV import, correlations, and weekly aggregates.
"""
import csv
import io
import uuid
import logging
from typing import Optional
from datetime import datetime
from fastapi import APIRouter, HTTPException, UploadFile, File, Header, Depends
from db import get_db, get_cursor, r2d
from auth import require_auth, check_feature_access, increment_feature_usage
from routers.profiles import get_pid
from feature_logger import log_feature_usage
router = APIRouter(prefix="/api/nutrition", tags=["nutrition"])
logger = logging.getLogger(__name__)
# ── Helper ────────────────────────────────────────────────────────────────────
def _pf(s):
"""Parse float from string (handles comma decimal separator)."""
try: return float(str(s).replace(',','.').strip())
except: return 0.0
# ── Endpoints ─────────────────────────────────────────────────────────────────
@router.post("/import-csv")
async def import_nutrition_csv(file: UploadFile=File(...), x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Import FDDB nutrition CSV."""
pid = get_pid(x_profile_id)
# Phase 4: Check feature access and ENFORCE
# Note: CSV import can create many entries - we check once before import
access = check_feature_access(pid, 'nutrition_entries')
log_feature_usage(pid, 'nutrition_entries', access, 'import_csv')
if not access['allowed']:
logger.warning(
f"[FEATURE-LIMIT] User {pid} blocked: "
f"nutrition_entries {access['reason']} (used: {access['used']}, limit: {access['limit']})"
)
raise HTTPException(
status_code=403,
detail=f"Limit erreicht: Du hast das Kontingent für Ernährungseinträge überschritten ({access['used']}/{access['limit']}). "
f"Bitte kontaktiere den Admin oder warte bis zum nächsten Reset."
)
raw = await file.read()
try: text = raw.decode('utf-8')
except: text = raw.decode('latin-1')
if text.startswith('\ufeff'): text = text[1:]
if not text.strip(): raise HTTPException(400,"Leere Datei")
reader = csv.DictReader(io.StringIO(text), delimiter=';')
days: dict = {}
count = 0
for row in reader:
rd = row.get('datum_tag_monat_jahr_stunde_minute','').strip().strip('"')
if not rd: continue
try:
p = rd.split(' ')[0].split('.')
iso = f"{p[2]}-{p[1]}-{p[0]}"
except: continue
days.setdefault(iso,{'kcal':0,'fat_g':0,'carbs_g':0,'protein_g':0})
days[iso]['kcal'] += _pf(row.get('kj',0))/4.184
days[iso]['fat_g'] += _pf(row.get('fett_g',0))
days[iso]['carbs_g'] += _pf(row.get('kh_g',0))
days[iso]['protein_g'] += _pf(row.get('protein_g',0))
count+=1
inserted=0
new_entries=0
with get_db() as conn:
cur = get_cursor(conn)
for iso,vals in days.items():
kcal=round(vals['kcal'],1); fat=round(vals['fat_g'],1)
carbs=round(vals['carbs_g'],1); prot=round(vals['protein_g'],1)
cur.execute("SELECT id FROM nutrition_log WHERE profile_id=%s AND date=%s",(pid,iso))
is_new = not cur.fetchone()
if not is_new:
# UPDATE existing
cur.execute("UPDATE nutrition_log SET kcal=%s,protein_g=%s,fat_g=%s,carbs_g=%s WHERE profile_id=%s AND date=%s",
(kcal,prot,fat,carbs,pid,iso))
else:
# INSERT new
cur.execute("INSERT INTO nutrition_log (id,profile_id,date,kcal,protein_g,fat_g,carbs_g,source,created) VALUES (%s,%s,%s,%s,%s,%s,%s,'csv',CURRENT_TIMESTAMP)",
(str(uuid.uuid4()),pid,iso,kcal,prot,fat,carbs))
new_entries += 1
inserted+=1
# Phase 2: Increment usage counter for each new entry created
for _ in range(new_entries):
increment_feature_usage(pid, 'nutrition_entries')
return {"rows_parsed":count,"days_imported":inserted,"new_entries":new_entries,
"date_range":{"from":min(days) if days else None,"to":max(days) if days else None}}
@router.post("")
def create_nutrition(date: str, kcal: float, protein_g: float, fat_g: float, carbs_g: float,
x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Create or update nutrition entry for a specific date."""
pid = get_pid(x_profile_id)
# Validate date format
try:
datetime.strptime(date, '%Y-%m-%d')
except ValueError:
raise HTTPException(400, "Ungültiges Datumsformat. Erwartet: YYYY-MM-DD")
with get_db() as conn:
cur = get_cursor(conn)
# Check if entry exists
cur.execute("SELECT id FROM nutrition_log WHERE profile_id=%s AND date=%s", (pid, date))
existing = cur.fetchone()
if existing:
# UPDATE existing entry
cur.execute("""
UPDATE nutrition_log
SET kcal=%s, protein_g=%s, fat_g=%s, carbs_g=%s, source='manual'
WHERE id=%s AND profile_id=%s
""", (round(kcal,1), round(protein_g,1), round(fat_g,1), round(carbs_g,1), existing['id'], pid))
return {"success": True, "mode": "updated", "id": existing['id']}
else:
# Phase 4: Check feature access before INSERT
access = check_feature_access(pid, 'nutrition_entries')
log_feature_usage(pid, 'nutrition_entries', access, 'create')
if not access['allowed']:
logger.warning(
f"[FEATURE-LIMIT] User {pid} blocked: "
f"nutrition_entries {access['reason']} (used: {access['used']}, limit: {access['limit']})"
)
raise HTTPException(
status_code=403,
detail=f"Limit erreicht: Du hast das Kontingent für Ernährungseinträge überschritten ({access['used']}/{access['limit']}). "
f"Bitte kontaktiere den Admin oder warte bis zum nächsten Reset."
)
# INSERT new entry
new_id = str(uuid.uuid4())
cur.execute("""
INSERT INTO nutrition_log (id, profile_id, date, kcal, protein_g, fat_g, carbs_g, source, created)
VALUES (%s, %s, %s, %s, %s, %s, %s, 'manual', CURRENT_TIMESTAMP)
""", (new_id, pid, date, round(kcal,1), round(protein_g,1), round(fat_g,1), round(carbs_g,1)))
# Phase 2: Increment usage counter
increment_feature_usage(pid, 'nutrition_entries')
return {"success": True, "mode": "created", "id": new_id}
@router.get("")
def list_nutrition(limit: int=365, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get nutrition entries for current profile."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT * FROM nutrition_log WHERE profile_id=%s ORDER BY date DESC LIMIT %s", (pid,limit))
return [r2d(r) for r in cur.fetchall()]
@router.get("/by-date/{date}")
def get_nutrition_by_date(date: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get nutrition entry for a specific date."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM nutrition_log WHERE profile_id=%s AND date=%s", (pid, date))
row = cur.fetchone()
return r2d(row) if row else None
@router.get("/correlations")
def nutrition_correlations(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get nutrition data correlated with weight and body fat."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM nutrition_log WHERE profile_id=%s ORDER BY date",(pid,))
nutr={r['date']:r2d(r) for r in cur.fetchall()}
cur.execute("SELECT date,weight FROM weight_log WHERE profile_id=%s ORDER BY date",(pid,))
wlog={r['date']:r['weight'] for r in cur.fetchall()}
cur.execute("SELECT date,lean_mass,body_fat_pct FROM caliper_log WHERE profile_id=%s ORDER BY date",(pid,))
cals=sorted([r2d(r) for r in cur.fetchall()],key=lambda x:x['date'])
all_dates=sorted(set(list(nutr)+list(wlog)))
mi,last_cal,cal_by_date=0,{},{}
for d in all_dates:
while mi<len(cals) and cals[mi]['date']<=d: last_cal=cals[mi]; mi+=1
if last_cal: cal_by_date[d]=last_cal
result=[]
for d in all_dates:
if d not in nutr and d not in wlog: continue
row={'date':d}
if d in nutr: row.update({k:float(nutr[d][k]) if nutr[d][k] is not None else None for k in ['kcal','protein_g','fat_g','carbs_g']})
if d in wlog: row['weight']=float(wlog[d])
if d in cal_by_date:
lm = cal_by_date[d].get('lean_mass')
bf = cal_by_date[d].get('body_fat_pct')
row['lean_mass']=float(lm) if lm is not None else None
row['body_fat_pct']=float(bf) if bf is not None else None
result.append(row)
return result
@router.get("/weekly")
def nutrition_weekly(weeks: int=16, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get nutrition data aggregated by week."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM nutrition_log WHERE profile_id=%s ORDER BY date DESC LIMIT %s",(pid,weeks*7))
rows=[r2d(r) for r in cur.fetchall()]
if not rows: return []
wm={}
for d in rows:
# Handle both datetime.date objects (from DB) and strings
date_obj = d['date'] if hasattr(d['date'], 'strftime') else datetime.strptime(d['date'],'%Y-%m-%d')
wk = date_obj.strftime('%Y-W%V')
wm.setdefault(wk,[]).append(d)
result=[]
for wk in sorted(wm):
en=wm[wk]; n=len(en)
def avg(k): return round(sum(float(e.get(k) or 0) for e in en)/n,1)
result.append({'week':wk,'days':n,'kcal':avg('kcal'),'protein_g':avg('protein_g'),'fat_g':avg('fat_g'),'carbs_g':avg('carbs_g')})
return result
@router.get("/import-history")
def import_history(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get import history by grouping entries by created timestamp."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT
DATE(created) as import_date,
COUNT(*) as count,
MIN(date) as date_from,
MAX(date) as date_to,
MAX(created) as last_created
FROM nutrition_log
WHERE profile_id=%s AND source='csv'
GROUP BY DATE(created)
ORDER BY DATE(created) DESC
""", (pid,))
return [r2d(r) for r in cur.fetchall()]
@router.put("/{entry_id}")
def update_nutrition(entry_id: str, kcal: float, protein_g: float, fat_g: float, carbs_g: float,
x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Update nutrition entry macros."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
# Verify ownership
cur.execute("SELECT id FROM nutrition_log WHERE id=%s AND profile_id=%s", (entry_id, pid))
if not cur.fetchone():
raise HTTPException(404, "Eintrag nicht gefunden")
cur.execute("""
UPDATE nutrition_log
SET kcal=%s, protein_g=%s, fat_g=%s, carbs_g=%s
WHERE id=%s AND profile_id=%s
""", (round(kcal,1), round(protein_g,1), round(fat_g,1), round(carbs_g,1), entry_id, pid))
return {"success": True}
@router.delete("/{entry_id}")
def delete_nutrition(entry_id: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Delete nutrition entry."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
# Verify ownership
cur.execute("SELECT id FROM nutrition_log WHERE id=%s AND profile_id=%s", (entry_id, pid))
if not cur.fetchone():
raise HTTPException(404, "Eintrag nicht gefunden")
cur.execute("DELETE FROM nutrition_log WHERE id=%s AND profile_id=%s", (entry_id, pid))
return {"success": True}
+86
View File
@@ -0,0 +1,86 @@
"""
Photo Management Endpoints for Mitai Jinkendo
Handles progress photo uploads and retrieval.
"""
import os
import uuid
import logging
from pathlib import Path
from typing import Optional
from fastapi import APIRouter, UploadFile, File, Header, HTTPException, Depends
from fastapi.responses import FileResponse
import aiofiles
from db import get_db, get_cursor, r2d
from auth import require_auth, require_auth_flexible, check_feature_access, increment_feature_usage
from routers.profiles import get_pid
from feature_logger import log_feature_usage
router = APIRouter(prefix="/api/photos", tags=["photos"])
logger = logging.getLogger(__name__)
PHOTOS_DIR = Path(os.getenv("PHOTOS_DIR", "./photos"))
PHOTOS_DIR.mkdir(parents=True, exist_ok=True)
@router.post("")
async def upload_photo(file: UploadFile=File(...), date: str="",
x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Upload progress photo."""
pid = get_pid(x_profile_id)
# Phase 4: Check feature access and ENFORCE
access = check_feature_access(pid, 'photos')
log_feature_usage(pid, 'photos', access, 'upload')
if not access['allowed']:
logger.warning(
f"[FEATURE-LIMIT] User {pid} blocked: "
f"photos {access['reason']} (used: {access['used']}, limit: {access['limit']})"
)
raise HTTPException(
status_code=403,
detail=f"Limit erreicht: Du hast das Kontingent für Fotos überschritten ({access['used']}/{access['limit']}). "
f"Bitte kontaktiere den Admin oder warte bis zum nächsten Reset."
)
fid = str(uuid.uuid4())
ext = Path(file.filename).suffix or '.jpg'
path = PHOTOS_DIR / f"{fid}{ext}"
async with aiofiles.open(path,'wb') as f: await f.write(await file.read())
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("INSERT INTO photos (id,profile_id,date,path,created) VALUES (%s,%s,%s,%s,CURRENT_TIMESTAMP)",
(fid,pid,date,str(path)))
# Phase 2: Increment usage counter
increment_feature_usage(pid, 'photos')
return {"id":fid,"date":date}
@router.get("/{fid}")
def get_photo(fid: str, session: dict=Depends(require_auth_flexible)):
"""Get photo by ID. Auth via header or query param (for <img> tags)."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT path FROM photos WHERE id=%s", (fid,))
row = cur.fetchone()
if not row: raise HTTPException(404, "Photo not found")
photo_path = Path(PHOTOS_DIR) / row['path']
if not photo_path.exists():
raise HTTPException(404, "Photo file not found")
return FileResponse(photo_path)
@router.get("")
def list_photos(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get all photos for current profile."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT * FROM photos WHERE profile_id=%s ORDER BY created DESC LIMIT 100", (pid,))
return [r2d(r) for r in cur.fetchall()]
+107
View File
@@ -0,0 +1,107 @@
"""
Profile Management Endpoints for Mitai Jinkendo
Handles profile CRUD operations for both admin and current user.
"""
import uuid
from typing import Optional
from datetime import datetime
from fastapi import APIRouter, HTTPException, Header, Depends
from db import get_db, get_cursor, r2d
from auth import require_auth
from models import ProfileCreate, ProfileUpdate
router = APIRouter(prefix="/api", tags=["profiles"])
# ── Helper ────────────────────────────────────────────────────────────────────
def get_pid(x_profile_id: Optional[str] = Header(default=None)) -> str:
"""Get profile_id - from header for legacy endpoints."""
if x_profile_id:
return x_profile_id
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT id FROM profiles ORDER BY created LIMIT 1")
row = cur.fetchone()
if row: return row['id']
raise HTTPException(400, "Kein Profil gefunden")
# ── Admin Profile Management ──────────────────────────────────────────────────
@router.get("/profiles")
def list_profiles(session=Depends(require_auth)):
"""List all profiles (admin)."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles ORDER BY created")
rows = cur.fetchall()
return [r2d(r) for r in rows]
@router.post("/profiles")
def create_profile(p: ProfileCreate, session=Depends(require_auth)):
"""Create new profile (admin)."""
pid = str(uuid.uuid4())
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""INSERT INTO profiles (id,name,avatar_color,sex,dob,height,goal_weight,goal_bf_pct,created,updated)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)""",
(pid,p.name,p.avatar_color,p.sex,p.dob,p.height,p.goal_weight,p.goal_bf_pct))
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
return r2d(cur.fetchone())
@router.get("/profiles/{pid}")
def get_profile(pid: str, session=Depends(require_auth)):
"""Get profile by ID."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
row = cur.fetchone()
if not row: raise HTTPException(404, "Profil nicht gefunden")
return r2d(row)
@router.put("/profiles/{pid}")
def update_profile(pid: str, p: ProfileUpdate, session=Depends(require_auth)):
"""Update profile by ID (admin)."""
with get_db() as conn:
data = {k:v for k,v in p.model_dump().items() if v is not None}
data['updated'] = datetime.now().isoformat()
cur = get_cursor(conn)
cur.execute(f"UPDATE profiles SET {', '.join(f'{k}=%s' for k in data)} WHERE id=%s",
list(data.values())+[pid])
return get_profile(pid, session)
@router.delete("/profiles/{pid}")
def delete_profile(pid: str, session=Depends(require_auth)):
"""Delete profile (admin)."""
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT COUNT(*) as count FROM profiles")
count = cur.fetchone()['count']
if count <= 1: raise HTTPException(400, "Letztes Profil kann nicht gelöscht werden")
for table in ['weight_log','circumference_log','caliper_log','nutrition_log','activity_log','ai_insights']:
cur.execute(f"DELETE FROM {table} WHERE profile_id=%s", (pid,))
cur.execute("DELETE FROM profiles WHERE id=%s", (pid,))
return {"ok": True}
# ── Current User Profile ──────────────────────────────────────────────────────
@router.get("/profile")
def get_active_profile(x_profile_id: Optional[str] = Header(default=None), session: dict = Depends(require_auth)):
"""Legacy endpoint – returns active profile."""
pid = get_pid(x_profile_id)
return get_profile(pid, session)
@router.put("/profile")
def update_active_profile(p: ProfileUpdate, x_profile_id: Optional[str] = Header(default=None), session: dict = Depends(require_auth)):
"""Update current user's profile."""
pid = get_pid(x_profile_id)
return update_profile(pid, p, session)
+60
View File
@@ -0,0 +1,60 @@
"""
AI Prompts Management Endpoints for Mitai Jinkendo
Handles prompt template configuration (admin-editable).
"""
from fastapi import APIRouter, Depends
from db import get_db, get_cursor, r2d
from auth import require_auth, require_admin
router = APIRouter(prefix="/api/prompts", tags=["prompts"])
@router.get("")
def list_prompts(session: dict=Depends(require_auth)):
"""
List AI prompts.
- Admins: see ALL prompts (including pipeline and inactive)
- Users: see only active single-analysis prompts
"""
with get_db() as conn:
cur = get_cursor(conn)
is_admin = session.get('role') == 'admin'
if is_admin:
# Admin sees everything
cur.execute("SELECT * FROM ai_prompts ORDER BY sort_order, slug")
else:
# Users see only active, non-pipeline prompts
cur.execute("SELECT * FROM ai_prompts WHERE active=true AND slug NOT LIKE 'pipeline_%' ORDER BY sort_order")
return [r2d(r) for r in cur.fetchall()]
@router.put("/{prompt_id}")
def update_prompt(prompt_id: str, data: dict, session: dict=Depends(require_admin)):
"""Update AI prompt template (admin only)."""
with get_db() as conn:
cur = get_cursor(conn)
updates = []
values = []
if 'name' in data:
updates.append('name=%s')
values.append(data['name'])
if 'description' in data:
updates.append('description=%s')
values.append(data['description'])
if 'template' in data:
updates.append('template=%s')
values.append(data['template'])
if 'active' in data:
updates.append('active=%s')
# Convert to boolean (accepts true/false, 1/0)
values.append(bool(data['active']))
if updates:
cur.execute(f"UPDATE ai_prompts SET {', '.join(updates)}, updated=CURRENT_TIMESTAMP WHERE id=%s",
values + [prompt_id])
return {"ok": True}
+39
View File
@@ -0,0 +1,39 @@
"""
Statistics Endpoints for Mitai Jinkendo
Dashboard statistics showing entry counts across all categories.
"""
from typing import Optional
from fastapi import APIRouter, Header, Depends
from db import get_db, get_cursor
from auth import require_auth
from routers.profiles import get_pid
router = APIRouter(prefix="/api", tags=["stats"])
@router.get("/stats")
def get_stats(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get entry counts for all tracking categories."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT COUNT(*) as count FROM weight_log WHERE profile_id=%s",(pid,))
weight_count = cur.fetchone()['count']
cur.execute("SELECT COUNT(*) as count FROM circumference_log WHERE profile_id=%s",(pid,))
circ_count = cur.fetchone()['count']
cur.execute("SELECT COUNT(*) as count FROM caliper_log WHERE profile_id=%s",(pid,))
caliper_count = cur.fetchone()['count']
cur.execute("SELECT COUNT(*) as count FROM nutrition_log WHERE profile_id=%s",(pid,))
nutrition_count = cur.fetchone()['count']
cur.execute("SELECT COUNT(*) as count FROM activity_log WHERE profile_id=%s",(pid,))
activity_count = cur.fetchone()['count']
return {
"weight_count": weight_count,
"circ_count": circ_count,
"caliper_count": caliper_count,
"nutrition_count": nutrition_count,
"activity_count": activity_count
}
+187
View File
@@ -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
}
+158
View File
@@ -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 (including inactive - admin needs to configure all)
cur.execute("SELECT id, name, sort_order FROM tiers 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, reset_period
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}
+117
View File
@@ -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}
+140
View File
@@ -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}
+111
View File
@@ -0,0 +1,111 @@
"""
Weight Tracking Endpoints for Mitai Jinkendo
Handles weight log CRUD operations and statistics.
"""
import uuid
import logging
from typing import Optional
from fastapi import APIRouter, Header, Depends, HTTPException
from db import get_db, get_cursor, r2d
from auth import require_auth, check_feature_access, increment_feature_usage
from models import WeightEntry
from routers.profiles import get_pid
from feature_logger import log_feature_usage
router = APIRouter(prefix="/api/weight", tags=["weight"])
logger = logging.getLogger(__name__)
@router.get("")
def list_weight(limit: int=365, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get weight entries for current profile."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT * FROM weight_log WHERE profile_id=%s ORDER BY date DESC LIMIT %s", (pid,limit))
return [r2d(r) for r in cur.fetchall()]
@router.post("")
def upsert_weight(e: WeightEntry, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Create or update weight entry (upsert by date)."""
pid = get_pid(x_profile_id)
# Phase 4: Check feature access and ENFORCE
access = check_feature_access(pid, 'weight_entries')
# Structured logging (always)
log_feature_usage(pid, 'weight_entries', access, 'create')
# BLOCK if limit exceeded
if not access['allowed']:
logger.warning(
f"[FEATURE-LIMIT] User {pid} blocked: "
f"weight_entries {access['reason']} (used: {access['used']}, limit: {access['limit']})"
)
raise HTTPException(
status_code=403,
detail=f"Limit erreicht: Du hast das Kontingent für Gewichtseinträge überschritten ({access['used']}/{access['limit']}). "
f"Bitte kontaktiere den Admin oder warte bis zum nächsten Reset."
)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT id FROM weight_log WHERE profile_id=%s AND date=%s", (pid,e.date))
ex = cur.fetchone()
is_new_entry = not ex
if ex:
# UPDATE existing entry
cur.execute("UPDATE weight_log SET weight=%s,note=%s WHERE id=%s", (e.weight,e.note,ex['id']))
wid = ex['id']
else:
# INSERT new entry
wid = str(uuid.uuid4())
cur.execute("INSERT INTO weight_log (id,profile_id,date,weight,note,created) VALUES (%s,%s,%s,%s,%s,CURRENT_TIMESTAMP)",
(wid,pid,e.date,e.weight,e.note))
# Phase 2: Increment usage counter (only for new entries)
increment_feature_usage(pid, 'weight_entries')
return {"id":wid,"date":e.date,"weight":e.weight}
@router.put("/{wid}")
def update_weight(wid: str, e: WeightEntry, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Update existing weight entry."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("UPDATE weight_log SET date=%s,weight=%s,note=%s WHERE id=%s AND profile_id=%s",
(e.date,e.weight,e.note,wid,pid))
return {"id":wid}
@router.delete("/{wid}")
def delete_weight(wid: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Delete weight entry."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("DELETE FROM weight_log WHERE id=%s AND profile_id=%s", (wid,pid))
return {"ok":True}
@router.get("/stats")
def weight_stats(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
"""Get weight statistics (last 90 days)."""
pid = get_pid(x_profile_id)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("SELECT date,weight FROM weight_log WHERE profile_id=%s ORDER BY date DESC LIMIT 90", (pid,))
rows = cur.fetchall()
if not rows: return {"count":0,"latest":None,"prev":None,"min":None,"max":None,"avg_7d":None}
w=[float(r['weight']) for r in rows]
return {"count":len(rows),"latest":{"date":rows[0]['date'],"weight":float(rows[0]['weight'])},
"prev":{"date":rows[1]['date'],"weight":float(rows[1]['weight'])} if len(rows)>1 else None,
"min":min(w),"max":max(w),"avg_7d":round(sum(w[:7])/min(7,len(w)),2)}
File diff suppressed because it is too large. Load diff
+6766
View File
File diff suppressed because it is too large. Load diff
+33 -2
View File
@@ -8,6 +8,8 @@ import { Avatar } from './pages/ProfileSelect'
import SetupScreen from './pages/SetupScreen'
import { ResetPassword } from './pages/PasswordRecovery'
import LoginScreen from './pages/LoginScreen'
import Register from './pages/Register'
import Verify from './pages/Verify'
import Dashboard from './pages/Dashboard'
import CaptureHub from './pages/CaptureHub'
import WeightScreen from './pages/WeightScreen'
@@ -20,6 +22,12 @@ import ActivityPage from './pages/ActivityPage'
import Analysis from './pages/Analysis'
import SettingsPage from './pages/SettingsPage'
import GuidePage from './pages/GuidePage'
import AdminTierLimitsPage from './pages/AdminTierLimitsPage'
import AdminFeaturesPage from './pages/AdminFeaturesPage'
import AdminTiersPage from './pages/AdminTiersPage'
import AdminCouponsPage from './pages/AdminCouponsPage'
import AdminUserRestrictionsPage from './pages/AdminUserRestrictionsPage'
import SubscriptionPage from './pages/SubscriptionPage'
import './app.css'
function Nav() {
@@ -53,9 +61,26 @@ function AppShell() {
}
}, [session?.profile_id])
// Handle password reset link
// Handle public pages (register, verify, reset-password)
const urlParams = new URLSearchParams(window.location.search)
const resetToken = urlParams.get('reset-password') || (window.location.pathname === '/reset-password' ? urlParams.get('token') : null)
const currentPath = window.location.pathname
// Register page
if (currentPath === '/register') return (
<div style={{minHeight:'100vh',background:'var(--bg)',padding:24}}>
<Register/>
</div>
)
// Verify email page
if (currentPath === '/verify') return (
<div style={{minHeight:'100vh',background:'var(--bg)',padding:24}}>
<Verify/>
</div>
)
// Password reset page
const resetToken = urlParams.get('reset-password') || (currentPath === '/reset-password' ? urlParams.get('token') : null)
if (resetToken) return (
<div style={{minHeight:'100vh',display:'flex',alignItems:'center',justifyContent:'center',
background:'var(--bg)',padding:24}}>
@@ -115,6 +140,12 @@ function AppShell() {
<Route path="/analysis" element={<Analysis/>}/>
<Route path="/settings" element={<SettingsPage/>}/>
<Route path="/guide" element={<GuidePage/>}/>
<Route path="/admin/tier-limits" element={<AdminTierLimitsPage/>}/>
<Route path="/admin/features" element={<AdminFeaturesPage/>}/>
<Route path="/admin/tiers" element={<AdminTiersPage/>}/>
<Route path="/admin/coupons" element={<AdminCouponsPage/>}/>
<Route path="/admin/user-restrictions" element={<AdminUserRestrictionsPage/>}/>
<Route path="/subscription" element={<SubscriptionPage/>}/>
</Routes>
</main>
<Nav/>
@@ -0,0 +1,163 @@
/**
* FeatureUsageOverview Styles
* Phase 3: Frontend Display
*/
.feature-usage-overview {
display: flex;
flex-direction: column;
gap: 16px;
}
.feature-usage-loading,
.feature-usage-error,
.feature-usage-empty {
padding: 20px;
text-align: center;
color: var(--text2);
font-size: 14px;
}
.feature-usage-loading {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
}
.feature-usage-error {
background: rgba(216, 90, 48, 0.1);
color: var(--danger);
border-radius: 8px;
}
/* Category grouping */
.feature-category {
display: flex;
flex-direction: column;
gap: 8px;
}
.feature-category-label {
font-size: 11px;
font-weight: 600;
color: var(--text3);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.feature-list {
display: flex;
flex-direction: column;
gap: 8px;
}
/* Feature item */
.feature-item {
padding: 12px;
background: var(--surface2);
border-radius: 8px;
border: 1px solid var(--border);
transition: all 0.2s;
}
.feature-item--exceeded {
border-color: var(--danger);
background: rgba(216, 90, 48, 0.05);
}
.feature-item--warning {
border-color: #d97706;
background: rgba(217, 119, 6, 0.05);
}
.feature-item--ok {
border-color: var(--border);
}
.feature-main {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.feature-name {
font-size: 14px;
font-weight: 500;
color: var(--text1);
}
.feature-usage {
font-size: 14px;
white-space: nowrap;
}
.usage-unlimited {
color: var(--accent);
font-weight: 500;
}
.usage-boolean {
font-weight: 500;
padding: 2px 8px;
border-radius: 4px;
font-size: 12px;
}
.usage-boolean.enabled {
color: var(--accent);
background: rgba(29, 158, 117, 0.1);
}
.usage-boolean.disabled {
color: var(--text3);
background: rgba(136, 135, 128, 0.1);
}
.usage-count {
color: var(--text1);
font-variant-numeric: tabular-nums;
}
.usage-count strong {
font-weight: 600;
}
.feature-item--exceeded .usage-count {
color: var(--danger);
}
.feature-item--warning .usage-count {
color: #d97706;
}
/* Meta info */
.feature-meta {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 8px;
font-size: 11px;
color: var(--text3);
}
.meta-reset,
.meta-next-reset {
padding: 2px 6px;
background: var(--surface);
border-radius: 4px;
}
/* Responsive */
@media (max-width: 640px) {
.feature-main {
flex-direction: column;
align-items: flex-start;
gap: 6px;
}
.feature-usage {
width: 100%;
}
}
@@ -0,0 +1,142 @@
/**
* FeatureUsageOverview - Full feature usage table for Settings page
*
* Shows all features with usage, limits, reset period, and next reset date
* Phase 3: Frontend Display
*/
import { useState, useEffect } from 'react'
import { api } from '../utils/api'
import './FeatureUsageOverview.css'
const RESET_PERIOD_LABELS = {
'never': 'Niemals',
'daily': 'Täglich',
'monthly': 'Monatlich'
}
const CATEGORY_LABELS = {
'data': 'Daten',
'ai': 'KI',
'export': 'Export',
'import': 'Import',
'integration': 'Integration'
}
export default function FeatureUsageOverview() {
const [features, setFeatures] = useState([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
useEffect(() => {
loadFeatures()
}, [])
const loadFeatures = async () => {
try {
setLoading(true)
const data = await api.getFeatureUsage()
setFeatures(data)
setError(null)
} catch (err) {
console.error('Failed to load feature usage:', err)
setError('Fehler beim Laden der Kontingente')
} finally {
setLoading(false)
}
}
const formatResetDate = (resetAt) => {
if (!resetAt) return '—'
try {
const date = new Date(resetAt)
return date.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' })
} catch {
return '—'
}
}
const getStatusClass = (feature) => {
if (!feature.allowed || feature.remaining < 0) return 'exceeded'
if (feature.limit && feature.remaining <= Math.ceil(feature.limit * 0.2)) return 'warning'
return 'ok'
}
// Group by category
const byCategory = features.reduce((acc, f) => {
const cat = f.category || 'other'
if (!acc[cat]) acc[cat] = []
acc[cat].push(f)
return acc
}, {})
if (loading) {
return (
<div className="feature-usage-loading">
<div className="spinner" />
Lade Kontingente...
</div>
)
}
if (error) {
return (
<div className="feature-usage-error">
⚠️ {error}
</div>
)
}
if (features.length === 0) {
return (
<div className="feature-usage-empty">
Keine Features gefunden
</div>
)
}
return (
<div className="feature-usage-overview">
{Object.entries(byCategory).map(([category, items]) => (
<div key={category} className="feature-category">
<div className="feature-category-label">
{CATEGORY_LABELS[category] || category}
</div>
<div className="feature-list">
{items.map(feature => (
<div key={feature.feature_id} className={`feature-item feature-item--${getStatusClass(feature)}`}>
<div className="feature-main">
<div className="feature-name">{feature.name}</div>
<div className="feature-usage">
{feature.limit === null ? (
<span className="usage-unlimited">Unbegrenzt</span>
) : feature.limit_type === 'boolean' ? (
<span className={`usage-boolean ${feature.allowed ? 'enabled' : 'disabled'}`}>
{feature.allowed ? '✓ Aktiviert' : '✗ Deaktiviert'}
</span>
) : (
<span className="usage-count">
<strong>{feature.used}</strong> / {feature.limit}
</span>
)}
</div>
</div>
{feature.limit_type === 'count' && feature.limit !== null && (
<div className="feature-meta">
<span className="meta-reset">
Reset: {RESET_PERIOD_LABELS[feature.reset_period] || feature.reset_period}
</span>
{feature.reset_at && (
<span className="meta-next-reset">
Nächster Reset: {formatResetDate(feature.reset_at)}
</span>
)}
</div>
)}
</div>
))}
</div>
</div>
))}
</div>
)
}
+103
View File
@@ -0,0 +1,103 @@
/**
* UsageBadge Styles - Dezente Version
*
* Sehr kleine, subtile Badge für Usage-Anzeige
* Phase 3: Frontend Display
*/
.usage-badge {
display: inline-block;
font-size: 0.65rem;
font-weight: 500;
padding: 2px 5px;
border-radius: 3px;
margin-left: 10px;
opacity: 0.6;
font-variant-numeric: tabular-nums;
white-space: nowrap;
transition: opacity 0.2s;
}
.usage-badge:hover {
opacity: 0.9;
}
.usage-badge--ok {
color: var(--text3, #888);
background: rgba(136, 135, 128, 0.08);
}
.usage-badge--warning {
color: #d97706;
background: rgba(217, 119, 6, 0.08);
}
.usage-badge--exceeded {
color: var(--danger, #D85A30);
background: rgba(216, 90, 48, 0.1);
font-weight: 600;
opacity: 0.75;
}
.usage-badge--exceeded:hover {
opacity: 1;
}
/* Responsive: Even smaller on mobile */
@media (max-width: 640px) {
.usage-badge {
font-size: 0.6rem;
padding: 1px 4px;
margin-left: 8px;
}
}
/* ============================================================================
Badge Container Styles - Positioning
============================================================================
Zentrale Konfiguration für Badge-Platzierung in verschiedenen Kontexten.
Alle Anpassungen an Layout/Spacing hier vornehmen!
*/
/* Badge rechts außen (für Headings/Titles) */
.badge-container-right {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
/* Badge rechts im Button (mit Beschreibung darunter) */
.badge-button-layout {
display: flex;
flex-direction: column;
align-items: stretch;
gap: 2px;
}
.badge-button-header {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
}
.badge-button-description {
font-size: 11px;
opacity: 0.8;
display: block;
margin-top: 2px;
text-align: left;
}
/* Mobile Anpassungen */
@media (max-width: 640px) {
.badge-container-right {
gap: 8px;
}
.badge-button-description {
font-size: 10px;
}
}
+31
View File
@@ -0,0 +1,31 @@
/**
* UsageBadge - Small inline usage indicator
*
* Shows usage quota in format: (used/limit)
* Color-coded: green (ok), yellow (warning), red (exceeded)
*
* Phase 3: Frontend Display
*/
import './UsageBadge.css'
export default function UsageBadge({ used, limit, remaining, allowed }) {
// Don't show badge if unlimited
if (limit === null || limit === undefined) {
return null
}
// Determine status for color coding
let status = 'ok'
if (!allowed || remaining < 0) {
status = 'exceeded'
} else if (limit > 0 && remaining <= Math.ceil(limit * 0.2)) {
// Warning at 20% or less remaining
status = 'warning'
}
return (
<span className={`usage-badge usage-badge--${status}`}>
({used}/{limit})
</span>
)
}
+63 -15
View File
@@ -2,6 +2,7 @@ import { useState, useEffect, useRef } from 'react'
import { Upload, Pencil, Trash2, Check, X, CheckCircle } from 'lucide-react'
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from 'recharts'
import { api } from '../utils/api'
import UsageBadge from '../components/UsageBadge'
import dayjs from 'dayjs'
import 'dayjs/locale/de'
dayjs.locale('de')
@@ -79,7 +80,7 @@ function ImportPanel({ onImported }) {
}
// ── Manual Entry ──────────────────────────────────────────────────────────────
function EntryForm({ form, setForm, onSave, onCancel, saveLabel='Speichern' }) {
function EntryForm({ form, setForm, onSave, onCancel, saveLabel='Speichern', saving=false, error=null, usage=null }) {
const set = (k,v) => setForm(f=>({...f,[k]:v}))
return (
<div>
@@ -130,8 +131,25 @@ function EntryForm({ form, setForm, onSave, onCancel, saveLabel='Speichern' }) {
value={form.notes||''} onChange={e=>set('notes',e.target.value)}/>
<span className="form-unit"/>
</div>
{error && (
<div style={{padding:'10px',background:'var(--danger-bg)',border:'1px solid var(--danger)',borderRadius:8,fontSize:13,color:'var(--danger)',marginBottom:8}}>
{error}
</div>
)}
<div style={{display:'flex',gap:6,marginTop:8}}>
<button className="btn btn-primary" style={{flex:1}} onClick={onSave}>{saveLabel}</button>
<div
title={usage && !usage.allowed ? `Limit erreicht (${usage.used}/${usage.limit}). Kontaktiere den Admin oder warte bis zum nächsten Reset.` : ''}
style={{flex:1,display:'inline-block'}}
>
<button
className="btn btn-primary"
style={{width:'100%', cursor: (usage && !usage.allowed) ? 'not-allowed' : 'pointer'}}
onClick={onSave}
disabled={saving || (usage && !usage.allowed)}
>
{(usage && !usage.allowed) ? '🔒 Limit erreicht' : saveLabel}
</button>
</div>
{onCancel && <button className="btn btn-secondary" style={{flex:1}} onClick={onCancel}><X size={13}/> Abbrechen</button>}
</div>
</div>
@@ -145,25 +163,51 @@ export default function ActivityPage() {
const [tab, setTab] = useState('list')
const [form, setForm] = useState(empty())
const [editing, setEditing] = useState(null)
const [saving, setSaving] = useState(false)
const [saved, setSaved] = useState(false)
const [error, setError] = useState(null)
const [activityUsage, setActivityUsage] = useState(null) // Phase 4: Usage badge
const load = async () => {
const [e, s] = await Promise.all([api.listActivity(), api.activityStats()])
setEntries(e); setStats(s)
}
useEffect(()=>{ load() },[])
const loadUsage = () => {
api.getFeatureUsage().then(features => {
const activityFeature = features.find(f => f.feature_id === 'activity_entries')
setActivityUsage(activityFeature)
}).catch(err => console.error('Failed to load usage:', err))
}
useEffect(()=>{
load()
loadUsage()
},[])
const handleSave = async () => {
const payload = {...form}
if(payload.duration_min) payload.duration_min = parseFloat(payload.duration_min)
if(payload.kcal_active) payload.kcal_active = parseFloat(payload.kcal_active)
if(payload.hr_avg) payload.hr_avg = parseFloat(payload.hr_avg)
if(payload.hr_max) payload.hr_max = parseFloat(payload.hr_max)
if(payload.rpe) payload.rpe = parseInt(payload.rpe)
payload.source = 'manual'
await api.createActivity(payload)
setSaved(true); await load()
setTimeout(()=>{ setSaved(false); setForm(empty()) }, 1500)
setSaving(true)
setError(null)
try {
const payload = {...form}
if(payload.duration_min) payload.duration_min = parseFloat(payload.duration_min)
if(payload.kcal_active) payload.kcal_active = parseFloat(payload.kcal_active)
if(payload.hr_avg) payload.hr_avg = parseFloat(payload.hr_avg)
if(payload.hr_max) payload.hr_max = parseFloat(payload.hr_max)
if(payload.rpe) payload.rpe = parseInt(payload.rpe)
payload.source = 'manual'
await api.createActivity(payload)
setSaved(true)
await load()
await loadUsage() // Reload usage after save
setTimeout(()=>{ setSaved(false); setForm(empty()) }, 1500)
} catch (err) {
console.error('Save failed:', err)
setError(err.message || 'Fehler beim Speichern')
setTimeout(()=>setError(null), 5000)
} finally {
setSaving(false)
}
}
const handleUpdate = async () => {
@@ -225,9 +269,13 @@ export default function ActivityPage() {
{tab==='add' && (
<div className="card section-gap">
<div className="card-title">Training eintragen</div>
<div className="card-title badge-container-right">
<span>Training eintragen</span>
{activityUsage && <UsageBadge {...activityUsage} />}
</div>
<EntryForm form={form} setForm={setForm}
onSave={handleSave} saveLabel={saved?'✓ Gespeichert!':'Speichern'}/>
onSave={handleSave} saveLabel={saved?'✓ Gespeichert!':'Speichern'}
saving={saving} error={error} usage={activityUsage}/>
</div>
)}
+523
View File
@@ -0,0 +1,523 @@
import { useState, useEffect } from 'react'
import { Save, Plus, Edit2, Trash2, X, Eye, Gift, Ticket } from 'lucide-react'
import { api } from '../utils/api'
export default function AdminCouponsPage() {
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [success, setSuccess] = useState('')
const [coupons, setCoupons] = useState([])
const [editingId, setEditingId] = useState(null)
const [showAddForm, setShowAddForm] = useState(false)
const [viewingRedemptions, setViewingRedemptions] = useState(null)
const [redemptions, setRedemptions] = useState([])
const [formData, setFormData] = useState({
code: '',
type: 'single_use',
valid_from: '',
valid_until: '',
grants_tier: 'premium',
duration_days: 30,
max_redemptions: 1,
notes: '',
active: true
})
useEffect(() => {
loadCoupons()
}, [])
async function loadCoupons() {
try {
setLoading(true)
const data = await api.listCoupons()
setCoupons(data)
setError('')
} catch (e) {
setError(e.message)
} finally {
setLoading(false)
}
}
async function loadRedemptions(couponId) {
try {
const data = await api.getCouponRedemptions(couponId)
setRedemptions(data)
setViewingRedemptions(couponId)
} catch (e) {
setError(e.message)
}
}
function resetForm() {
setFormData({
code: '',
type: 'single_use',
valid_from: '',
valid_until: '',
grants_tier: 'premium',
duration_days: 30,
max_redemptions: 1,
notes: '',
active: true
})
setEditingId(null)
setShowAddForm(false)
}
function startEdit(coupon) {
setFormData({
code: coupon.code,
type: coupon.type,
valid_from: coupon.valid_from ? coupon.valid_from.split('T')[0] : '',
valid_until: coupon.valid_until ? coupon.valid_until.split('T')[0] : '',
grants_tier: coupon.grants_tier,
duration_days: coupon.duration_days || 30,
max_redemptions: coupon.max_redemptions || 1,
notes: coupon.notes || '',
active: coupon.active
})
setEditingId(coupon.id)
setShowAddForm(false)
}
function startAdd() {
// Generate random code
const randomCode = `${formData.type === 'gift' ? 'GIFT' : 'PROMO'}-${Math.random().toString(36).substr(2, 8).toUpperCase()}`
setFormData({ ...formData, code: randomCode })
setShowAddForm(true)
setEditingId(null)
}
async function handleSave() {
try {
setError('')
setSuccess('')
if (!formData.code.trim()) {
setError('Code erforderlich')
return
}
const payload = {
code: formData.code.trim().toUpperCase(),
type: formData.type,
valid_from: formData.valid_from || null,
valid_until: formData.valid_until || null,
grants_tier: formData.grants_tier,
duration_days: parseInt(formData.duration_days) || null,
max_redemptions: formData.type === 'single_use' ? 1 : (parseInt(formData.max_redemptions) || null),
notes: formData.notes.trim(),
active: formData.active
}
if (editingId) {
await api.updateCoupon(editingId, payload)
setSuccess('Coupon aktualisiert')
} else {
await api.createCoupon(payload)
setSuccess('Coupon erstellt')
}
await loadCoupons()
resetForm()
} catch (e) {
setError(e.message)
}
}
async function handleDelete(couponId) {
if (!confirm('Coupon wirklich löschen?')) return
try {
setError('')
await api.deleteCoupon(couponId)
setSuccess('Coupon gelöscht')
await loadCoupons()
} catch (e) {
setError(e.message)
}
}
function formatDate(dateStr) {
if (!dateStr) return '-'
return new Date(dateStr).toLocaleDateString('de-DE')
}
if (loading) return (
<div style={{ display: 'flex', justifyContent: 'center', padding: 40 }}>
<div className="spinner" />
</div>
)
const couponTypes = [
{ value: 'single_use', label: 'Single-Use (einmalig)', icon: '🎟️' },
{ value: 'multi_use_period', label: 'Multi-Use Period (Zeitraum)', icon: '🔄' },
{ value: 'gift', label: 'Geschenk-Coupon', icon: '🎁' }
]
const tierOptions = [
{ value: 'free', label: 'Free' },
{ value: 'basic', label: 'Basic' },
{ value: 'premium', label: 'Premium' }
]
return (
<div style={{ paddingBottom: 80 }}>
{/* Header */}
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
marginBottom: 20
}}>
<div>
<div style={{ fontSize: 20, fontWeight: 700, color: 'var(--text1)' }}>
Coupon-Verwaltung
</div>
<div style={{ fontSize: 13, color: 'var(--text3)', marginTop: 4 }}>
Trial-Codes, Wellpass-Integration, Geschenk-Coupons
</div>
</div>
{!showAddForm && !editingId && (
<button className="btn btn-primary" onClick={startAdd}>
<Plus size={16} /> Neuer Coupon
</button>
)}
</div>
{/* Messages */}
{error && (
<div style={{
padding: 12, background: 'var(--danger)', color: 'white',
borderRadius: 8, marginBottom: 16, fontSize: 14
}}>
{error}
</div>
)}
{success && (
<div style={{
padding: 12, background: 'var(--accent)', color: 'white',
borderRadius: 8, marginBottom: 16, fontSize: 14
}}>
{success}
</div>
)}
{/* Add/Edit Form */}
{(showAddForm || editingId) && (
<div className="card" style={{ padding: 20, marginBottom: 20 }}>
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
marginBottom: 16
}}>
<div style={{ fontSize: 16, fontWeight: 600 }}>
{editingId ? 'Coupon bearbeiten' : 'Neuer Coupon'}
</div>
<button
className="btn btn-secondary"
onClick={resetForm}
style={{ padding: '6px 12px' }}
>
<X size={16} />
</button>
</div>
<div style={{ display: 'grid', gap: 16 }}>
{/* Code */}
<div>
<label className="form-label" style={{ display: 'block', marginBottom: 6 }}>
Coupon-Code *
</label>
<input
className="form-input"
style={{ width: '100%', fontFamily: 'monospace', textTransform: 'uppercase' }}
value={formData.code}
onChange={(e) => setFormData({ ...formData, code: e.target.value })}
placeholder="Z.B. PROMO-2026"
/>
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 4 }}>
Wird automatisch in Großbuchstaben konvertiert
</div>
</div>
{/* Type */}
<div>
<label className="form-label" style={{ display: 'block', marginBottom: 6 }}>
Coupon-Typ
</label>
<select
className="form-input"
style={{ width: '100%' }}
value={formData.type}
onChange={(e) => setFormData({ ...formData, type: e.target.value })}
>
{couponTypes.map(t => (
<option key={t.value} value={t.value}>
{t.icon} {t.label}
</option>
))}
</select>
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 4 }}>
{formData.type === 'single_use' && 'Kann nur einmal pro User eingelöst werden'}
{formData.type === 'multi_use_period' && 'Unbegrenzte Einlösungen im Gültigkeitszeitraum (z.B. Wellpass)'}
{formData.type === 'gift' && 'Geschenk-Coupon für Bonus-System'}
</div>
</div>
{/* Tier */}
<div>
<label className="form-label" style={{ display: 'block', marginBottom: 6 }}>
Gewährt Tier
</label>
<select
className="form-input"
style={{ width: '100%' }}
value={formData.grants_tier}
onChange={(e) => setFormData({ ...formData, grants_tier: e.target.value })}
>
{tierOptions.map(t => (
<option key={t.value} value={t.value}>{t.label}</option>
))}
</select>
</div>
{/* Duration (only for single_use and gift) */}
{(formData.type === 'single_use' || formData.type === 'gift') && (
<div>
<label className="form-label" style={{ display: 'block', marginBottom: 6 }}>
Gültigkeitsdauer (Tage)
</label>
<input
className="form-input"
style={{ width: '100%' }}
type="number"
value={formData.duration_days}
onChange={(e) => setFormData({ ...formData, duration_days: e.target.value })}
/>
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 4 }}>
Wie lange ist der gewährte Zugriff gültig?
</div>
</div>
)}
{/* Valid From/Until (for multi_use_period) */}
{formData.type === 'multi_use_period' && (
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
<div>
<label className="form-label" style={{ display: 'block', marginBottom: 6 }}>
Gültig ab
</label>
<input
className="form-input"
style={{ width: '100%' }}
type="date"
value={formData.valid_from}
onChange={(e) => setFormData({ ...formData, valid_from: e.target.value })}
/>
</div>
<div>
<label className="form-label" style={{ display: 'block', marginBottom: 6 }}>
Gültig bis
</label>
<input
className="form-input"
style={{ width: '100%' }}
type="date"
value={formData.valid_until}
onChange={(e) => setFormData({ ...formData, valid_until: e.target.value })}
/>
</div>
</div>
)}
{/* Max Redemptions (not for single_use) */}
{formData.type !== 'single_use' && (
<div>
<label className="form-label" style={{ display: 'block', marginBottom: 6 }}>
Maximale Einlösungen (optional)
</label>
<input
className="form-input"
style={{ width: '100%' }}
type="number"
value={formData.max_redemptions}
onChange={(e) => setFormData({ ...formData, max_redemptions: e.target.value })}
placeholder="Leer = unbegrenzt"
/>
</div>
)}
{/* Notes */}
<div>
<label className="form-label" style={{ display: 'block', marginBottom: 6 }}>
Notizen (optional)
</label>
<input
className="form-input"
style={{ width: '100%' }}
value={formData.notes}
onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
placeholder="Z.B. 'Für Marketing-Kampagne März 2026'"
/>
</div>
{/* Active */}
<div>
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
<input
type="checkbox"
checked={formData.active}
onChange={(e) => setFormData({ ...formData, active: e.target.checked })}
/>
Coupon aktiviert (kann eingelöst werden)
</label>
</div>
{/* Actions */}
<div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
<button className="btn btn-primary" onClick={handleSave}>
<Save size={14} /> {editingId ? 'Aktualisieren' : 'Erstellen'}
</button>
<button className="btn btn-secondary" onClick={resetForm}>
Abbrechen
</button>
</div>
</div>
</div>
)}
{/* Redemptions Modal */}
{viewingRedemptions && (
<div style={{
position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
background: 'rgba(0,0,0,0.5)', zIndex: 1000,
display: 'flex', alignItems: 'center', justifyContent: 'center',
padding: 20
}} onClick={() => setViewingRedemptions(null)}>
<div className="card" style={{ padding: 20, maxWidth: 600, width: '100%', maxHeight: '80vh', overflow: 'auto' }}
onClick={(e) => e.stopPropagation()}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
<div style={{ fontSize: 16, fontWeight: 600 }}>Einlösungen</div>
<button className="btn btn-secondary" onClick={() => setViewingRedemptions(null)} style={{ padding: '6px 12px' }}>
<X size={16} />
</button>
</div>
{redemptions.length === 0 ? (
<div style={{ textAlign: 'center', padding: 40, color: 'var(--text3)' }}>
Noch keine Einlösungen
</div>
) : (
<div style={{ display: 'grid', gap: 8 }}>
{redemptions.map(r => (
<div key={r.id} className="card" style={{ padding: 12, background: 'var(--surface)' }}>
<div style={{ fontWeight: 500 }}>{r.profile_name || `User #${r.profile_id}`}</div>
<div style={{ fontSize: 12, color: 'var(--text3)', marginTop: 2 }}>
Eingelöst am {formatDate(r.redeemed_at)}
</div>
</div>
))}
</div>
)}
</div>
</div>
)}
{/* Coupons List */}
<div style={{ display: 'grid', gap: 12 }}>
{coupons.length === 0 && (
<div className="card" style={{ padding: 40, textAlign: 'center', color: 'var(--text3)' }}>
Keine Coupons vorhanden
</div>
)}
{coupons.map(coupon => (
<div
key={coupon.id}
className="card"
style={{
padding: 16,
opacity: coupon.active ? 1 : 0.6,
border: coupon.active ? '1px solid var(--border)' : '1px dashed var(--border)'
}}
>
<div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
<div style={{ flex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
<div style={{
fontSize: 16, fontWeight: 700, color: 'var(--text1)',
fontFamily: 'monospace', background: 'var(--surface2)',
padding: '4px 8px', borderRadius: 4
}}>
{coupon.code}
</div>
<span style={{
padding: '2px 8px', borderRadius: 4, fontSize: 11,
background: 'var(--accent-light)', color: 'var(--accent-dark)', fontWeight: 600
}}>
{couponTypes.find(t => t.value === coupon.type)?.icon} {couponTypes.find(t => t.value === coupon.type)?.label}
</span>
{!coupon.active && (
<span style={{
padding: '2px 8px', borderRadius: 4, fontSize: 10,
background: 'var(--danger)', color: 'white', fontWeight: 600
}}>
INAKTIV
</span>
)}
</div>
<div style={{ fontSize: 13, color: 'var(--text2)', marginBottom: 8 }}>
Gewährt: <strong>{coupon.grants_tier}</strong>
{coupon.duration_days && ` für ${coupon.duration_days} Tage`}
</div>
{coupon.notes && (
<div style={{ fontSize: 12, color: 'var(--text3)', marginBottom: 8 }}>
📝 {coupon.notes}
</div>
)}
<div style={{ display: 'flex', gap: 16, fontSize: 12, color: 'var(--text3)' }}>
{coupon.valid_from && (
<div><strong>Gültig ab:</strong> {formatDate(coupon.valid_from)}</div>
)}
{coupon.valid_until && (
<div><strong>Gültig bis:</strong> {formatDate(coupon.valid_until)}</div>
)}
<div>
<strong>Einlösungen:</strong> {coupon.current_redemptions || 0}
{coupon.max_redemptions ? ` / ${coupon.max_redemptions}` : ' / ∞'}
</div>
</div>
</div>
<div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
<button
className="btn btn-secondary"
onClick={() => loadRedemptions(coupon.id)}
style={{ padding: '6px 12px', fontSize: 12 }}
title="Einlösungen anzeigen"
>
<Eye size={14} />
</button>
<button
className="btn btn-secondary"
onClick={() => startEdit(coupon)}
style={{ padding: '6px 12px', fontSize: 12 }}
>
<Edit2 size={14} />
</button>
<button
className="btn btn-secondary"
onClick={() => handleDelete(coupon.id)}
style={{ padding: '6px 12px', fontSize: 12, color: 'var(--danger)' }}
>
<Trash2 size={14} />
</button>
</div>
</div>
</div>
))}
</div>
</div>
)
}
+480
View File
@@ -0,0 +1,480 @@
import { useState, useEffect } from 'react'
import { Save, Edit2, X, Info } from 'lucide-react'
import { api } from '../utils/api'
export default function AdminFeaturesPage() {
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [success, setSuccess] = useState('')
const [features, setFeatures] = useState([])
const [editingId, setEditingId] = useState(null)
const [formData, setFormData] = useState({
name: '',
category: 'data',
description: '',
limit_type: 'count',
default_limit: '',
reset_period: 'never',
visible_in_admin: true,
sort_order: 50,
active: true
})
useEffect(() => {
loadFeatures()
}, [])
async function loadFeatures() {
try {
setLoading(true)
const data = await api.listFeatures()
setFeatures(data)
setError('')
} catch (e) {
setError(e.message)
} finally {
setLoading(false)
}
}
function resetForm() {
setFormData({
name: '',
category: 'data',
description: '',
limit_type: 'count',
default_limit: '',
reset_period: 'never',
visible_in_admin: true,
sort_order: 50,
active: true
})
setEditingId(null)
}
function startEdit(feature) {
setFormData({
name: feature.name,
category: feature.category,
description: feature.description || '',
limit_type: feature.limit_type,
default_limit: feature.default_limit === null ? '' : feature.default_limit,
reset_period: feature.reset_period,
visible_in_admin: feature.visible_in_admin,
sort_order: feature.sort_order || 50,
active: feature.active
})
setEditingId(feature.id)
}
async function handleSave() {
try {
setError('')
setSuccess('')
if (!formData.name.trim()) {
setError('Name erforderlich')
return
}
const payload = {
name: formData.name.trim(),
category: formData.category,
description: formData.description.trim(),
limit_type: formData.limit_type,
default_limit: formData.default_limit === '' ? null : parseInt(formData.default_limit),
reset_period: formData.reset_period,
visible_in_admin: formData.visible_in_admin,
sort_order: formData.sort_order,
active: formData.active
}
await api.updateFeature(editingId, payload)
setSuccess('Feature aktualisiert')
await loadFeatures()
resetForm()
} catch (e) {
setError(e.message)
}
}
if (loading) return (
<div style={{ display: 'flex', justifyContent: 'center', padding: 40 }}>
<div className="spinner" />
</div>
)
const categoryOptions = [
{ value: 'data', label: 'Daten' },
{ value: 'ai', label: 'KI' },
{ value: 'export', label: 'Export' },
{ value: 'integration', label: 'Integrationen' }
]
const resetPeriodOptions = [
{ value: 'never', label: 'Nie (akkumuliert)' },
{ value: 'daily', label: 'Täglich' },
{ value: 'monthly', label: 'Monatlich' }
]
const limitTypeOptions = [
{ value: 'count', label: 'Anzahl (Count)' },
{ value: 'boolean', label: 'Ja/Nein (Boolean)' }
]
return (
<div style={{ paddingBottom: 80 }}>
{/* Header */}
<div style={{ marginBottom: 20 }}>
<div style={{ fontSize: 20, fontWeight: 700, color: 'var(--text1)' }}>
Feature-Konfiguration
</div>
<div style={{ fontSize: 13, color: 'var(--text3)', marginTop: 4 }}>
Limitierungs-Einstellungen für registrierte Features
</div>
</div>
{/* Info Box */}
<div style={{
padding: 12, background: 'var(--accent-light)', borderRadius: 8,
marginBottom: 16, fontSize: 12, color: 'var(--accent-dark)',
display: 'flex', gap: 8, alignItems: 'flex-start'
}}>
<Info size={16} style={{ marginTop: 2, flexShrink: 0 }} />
<div>
<strong>Hinweis:</strong> Features werden automatisch via Code registriert.
Hier können nur Basis-Einstellungen (Limit-Typ, Reset-Periode, Standards) angepasst werden.
Neue Features hinzuzufügen erfordert Code-Änderungen im Backend.
</div>
</div>
{/* Messages */}
{error && (
<div style={{
padding: 12, background: 'var(--danger)', color: 'white',
borderRadius: 8, marginBottom: 16, fontSize: 14
}}>
{error}
</div>
)}
{success && (
<div style={{
padding: 12, background: 'var(--accent)', color: 'white',
borderRadius: 8, marginBottom: 16, fontSize: 14
}}>
{success}
</div>
)}
{/* Edit Form */}
{editingId && (
<div className="card" style={{ padding: 20, marginBottom: 20 }}>
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
marginBottom: 16
}}>
<div style={{ fontSize: 16, fontWeight: 600 }}>
Feature konfigurieren
</div>
<button
className="btn btn-secondary"
onClick={resetForm}
style={{ padding: '6px 12px' }}
>
<X size={16} />
</button>
</div>
<div style={{ display: 'grid', gap: 16 }}>
{/* Feature ID (read-only) */}
<div>
<label className="form-label" style={{ display: 'block', marginBottom: 6 }}>
Feature ID
</label>
<input
className="form-input"
value={editingId}
disabled
style={{
width: '100%',
background: 'var(--surface2)',
color: 'var(--text3)',
cursor: 'not-allowed',
fontFamily: 'monospace'
}}
/>
</div>
{/* Name */}
<div>
<label className="form-label" style={{ display: 'block', marginBottom: 6 }}>
Name *
</label>
<input
className="form-input"
style={{ width: '100%' }}
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder="z.B. Gewichtseinträge"
/>
</div>
{/* Description */}
<div>
<label className="form-label" style={{ display: 'block', marginBottom: 6 }}>
Beschreibung (optional)
</label>
<input
className="form-input"
style={{ width: '100%' }}
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="Kurze Erklärung was dieses Feature limitiert"
/>
</div>
{/* Category + Limit Type */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
<div>
<label className="form-label" style={{ display: 'block', marginBottom: 6 }}>
Kategorie
</label>
<select
className="form-input"
style={{ width: '100%' }}
value={formData.category}
onChange={(e) => setFormData({ ...formData, category: e.target.value })}
>
{categoryOptions.map(o => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
</select>
</div>
<div>
<label className="form-label" style={{ display: 'block', marginBottom: 6 }}>
Limit-Typ
</label>
<select
className="form-input"
style={{ width: '100%' }}
value={formData.limit_type}
onChange={(e) => setFormData({ ...formData, limit_type: e.target.value })}
>
{limitTypeOptions.map(o => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
</select>
</div>
</div>
{/* Count-specific fields (only for limit_type='count') */}
{formData.limit_type === 'count' && (
<>
{/* Reset Period */}
<div>
<label className="form-label" style={{ display: 'block', marginBottom: 6 }}>
Reset-Periode
</label>
<select
className="form-input"
style={{ width: '100%' }}
value={formData.reset_period}
onChange={(e) => setFormData({ ...formData, reset_period: e.target.value })}
>
{resetPeriodOptions.map(o => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
</select>
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 4 }}>
Wann wird der Nutzungszähler zurückgesetzt?
</div>
</div>
{/* Default Limit */}
<div>
<label className="form-label" style={{ display: 'block', marginBottom: 6 }}>
Standard-Limit
</label>
<input
className="form-input"
style={{ width: '100%' }}
type="number"
value={formData.default_limit}
onChange={(e) => setFormData({ ...formData, default_limit: e.target.value })}
placeholder="Leer = unbegrenzt"
/>
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 4 }}>
Fallback-Wert wenn kein Tier-spezifisches Limit gesetzt ist
</div>
</div>
</>
)}
{/* Boolean info */}
{formData.limit_type === 'boolean' && (
<div style={{
padding: 12, background: 'var(--accent-light)', borderRadius: 8,
fontSize: 12, color: 'var(--accent-dark)'
}}>
<strong>Boolean-Feature:</strong> Ist entweder verfügbar (AN) oder nicht verfügbar (AUS).
Keine Zähler oder Reset-Perioden notwendig.
</div>
)}
{/* Sort Order */}
<div>
<label className="form-label" style={{ display: 'block', marginBottom: 6 }}>
Anzeigereihenfolge
</label>
<input
className="form-input"
style={{ width: '100%' }}
type="number"
value={formData.sort_order}
onChange={(e) => setFormData({ ...formData, sort_order: parseInt(e.target.value) || 50 })}
/>
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 4 }}>
Niedrigere Werte erscheinen weiter oben in Listen (Standard: 50)
</div>
</div>
{/* Checkboxes */}
<div style={{ display: 'flex', gap: 16, paddingTop: 8 }}>
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
<input
type="checkbox"
checked={formData.visible_in_admin}
onChange={(e) => setFormData({ ...formData, visible_in_admin: e.target.checked })}
/>
Im Admin sichtbar
</label>
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
<input
type="checkbox"
checked={formData.active}
onChange={(e) => setFormData({ ...formData, active: e.target.checked })}
/>
Feature aktiviert
</label>
</div>
{/* Actions */}
<div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
<button className="btn btn-primary" onClick={handleSave}>
<Save size={14} /> Speichern
</button>
<button className="btn btn-secondary" onClick={resetForm}>
Abbrechen
</button>
</div>
</div>
</div>
)}
{/* Features List */}
<div className="card" style={{ padding: 0, overflow: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
<thead>
<tr style={{ background: 'var(--surface2)' }}>
<th style={{ textAlign: 'left', padding: '12px 16px', fontWeight: 600 }}>Feature</th>
<th style={{ textAlign: 'left', padding: '12px 16px', fontWeight: 600 }}>Kategorie</th>
<th style={{ textAlign: 'center', padding: '12px 16px', fontWeight: 600 }}>Limit-Typ</th>
<th style={{ textAlign: 'center', padding: '12px 16px', fontWeight: 600 }}>Reset</th>
<th style={{ textAlign: 'center', padding: '12px 16px', fontWeight: 600 }}>Standard</th>
<th style={{ textAlign: 'center', padding: '12px 16px', fontWeight: 600 }}>Status</th>
<th style={{ textAlign: 'right', padding: '12px 16px', fontWeight: 600 }}>Aktion</th>
</tr>
</thead>
<tbody>
{features.length === 0 && (
<tr>
<td colSpan={7} style={{ textAlign: 'center', padding: 40, color: 'var(--text3)' }}>
Keine Features registriert
</td>
</tr>
)}
{features.map((feature, idx) => (
<tr
key={feature.id}
style={{
borderBottom: idx === features.length - 1 ? 'none' : '1px solid var(--border)',
background: feature.active ? 'transparent' : 'var(--surface)',
opacity: feature.active ? 1 : 0.6
}}
>
<td style={{ padding: '12px 16px' }}>
<div style={{ fontWeight: 500 }}>{feature.name}</div>
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 2, fontFamily: 'monospace' }}>
{feature.id}
</div>
{feature.description && (
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 2 }}>
{feature.description}
</div>
)}
</td>
<td style={{ padding: '12px 16px' }}>
<span style={{
padding: '2px 8px', borderRadius: 4, fontSize: 11,
background: 'var(--accent-light)', color: 'var(--accent-dark)', fontWeight: 600
}}>
{feature.category}
</span>
</td>
<td style={{ padding: '12px 16px', textAlign: 'center' }}>
<span style={{
padding: '2px 8px', borderRadius: 4, fontSize: 11,
background: feature.limit_type === 'boolean' ? 'var(--surface2)' : 'var(--surface2)',
fontWeight: 500
}}>
{feature.limit_type === 'boolean' ? '✓/✗' : '123'}
</span>
</td>
<td style={{ padding: '12px 16px', textAlign: 'center', fontSize: 11, color: 'var(--text3)' }}>
{feature.reset_period === 'never' ? '∞' : feature.reset_period === 'daily' ? '1d' : '1m'}
</td>
<td style={{ padding: '12px 16px', textAlign: 'center', fontWeight: 500 }}>
{feature.default_limit === null ? '∞' : feature.default_limit}
</td>
<td style={{ padding: '12px 16px', textAlign: 'center' }}>
{feature.active ? (
<span style={{ color: 'var(--accent)', fontWeight: 600 }}>✓ Aktiv</span>
) : (
<span style={{ color: 'var(--text3)' }}>✗ Inaktiv</span>
)}
</td>
<td style={{ padding: '12px 16px', textAlign: 'right' }}>
<button
className="btn btn-secondary"
onClick={() => startEdit(feature)}
style={{ padding: '6px 12px', fontSize: 12 }}
>
<Edit2 size={14} /> Konfigurieren
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* Legend */}
<div style={{
marginTop: 16, padding: 12, background: 'var(--surface2)',
borderRadius: 8, fontSize: 12, color: 'var(--text3)'
}}>
<strong>Limit-Typ:</strong>
<div style={{ marginTop: 4 }}>
<strong>Boolean (✓/✗):</strong> Feature ist entweder verfügbar oder nicht (z.B. "KI aktiviert")
</div>
<div style={{ marginTop: 2 }}>
<strong>Count (123):</strong> Feature hat ein Nutzungs-Limit (z.B. "max. 50 Einträge")
</div>
<div style={{ marginTop: 8 }}>
<strong>Reset-Periode:</strong> ∞ = nie, 1d = täglich, 1m = monatlich
</div>
</div>
</div>
)
}
+54 -27
View File
@@ -1,5 +1,6 @@
import { useState, useEffect } from 'react'
import { Plus, Trash2, Pencil, Check, X, Shield, Key } from 'lucide-react'
import { Plus, Trash2, Pencil, Check, X, Shield, Key, Settings } from 'lucide-react'
import { Link } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import { api } from '../utils/api'
@@ -142,10 +143,7 @@ function EmailEditor({ profileId, currentEmail, onSaved }) {
function ProfileCard({ profile, currentId, onRefresh }) {
const [expanded, setExpanded] = useState(false)
const [perms, setPerms] = useState({
ai_enabled: profile.ai_enabled ?? 1,
ai_limit_day: profile.ai_limit_day || '',
export_enabled: profile.export_enabled ?? 1,
role: profile.role || 'user',
role: profile.role || 'user',
})
const [saving, setSaving] = useState(false)
const [newPin, setNewPin] = useState('')
@@ -156,10 +154,7 @@ function ProfileCard({ profile, currentId, onRefresh }) {
setSaving(true)
try {
await api.adminSetPermissions(profile.id, {
ai_enabled: perms.ai_enabled,
ai_limit_day: perms.ai_limit_day ? parseInt(perms.ai_limit_day) : null,
export_enabled: perms.export_enabled,
role: perms.role,
role: perms.role,
})
await onRefresh()
} finally { setSaving(false) }
@@ -195,9 +190,8 @@ function ProfileCard({ profile, currentId, onRefresh }) {
{isSelf && <span style={{fontSize:10,color:'var(--text3)'}}>Du</span>}
</div>
<div style={{fontSize:11,color:'var(--text3)'}}>
KI: {profile.ai_enabled?`✓${profile.ai_limit_day?` (max ${profile.ai_limit_day}/Tag)`:''}` : '✗'} ·
Export: {profile.export_enabled?'✓':'✗'} ·
Calls heute: {profile.ai_calls_today||0}
Tier: {profile.tier || 'free'} ·
Email: {profile.email || 'nicht gesetzt'}
</div>
</div>
<div style={{display:'flex',gap:6}}>
@@ -232,23 +226,19 @@ function ProfileCard({ profile, currentId, onRefresh }) {
</button>
))}
</div>
<button className="btn btn-primary btn-full" style={{marginTop:8}} onClick={savePerms} disabled={saving}>
{saving?'Speichern…':'Rolle speichern'}
</button>
</div>
<Toggle value={!!perms.ai_enabled} onChange={v=>setPerms(p=>({...p,ai_enabled:v?1:0}))} label="KI-Analysen erlaubt"/>
{!!perms.ai_enabled && (
<div className="form-row" style={{paddingTop:6}}>
<label className="form-label" style={{fontSize:12}}>Max. KI-Calls/Tag</label>
<input type="number" className="form-input" style={{width:70}} min={1} max={100}
placeholder="∞" value={perms.ai_limit_day}
onChange={e=>setPerms(p=>({...p,ai_limit_day:e.target.value}))}/>
<span className="form-unit" style={{fontSize:11}}>/Tag</span>
</div>
)}
<Toggle value={!!perms.export_enabled} onChange={v=>setPerms(p=>({...p,export_enabled:v?1:0}))} label="Daten-Export erlaubt"/>
<button className="btn btn-primary btn-full" style={{marginTop:10}} onClick={savePerms} disabled={saving}>
{saving?'Speichern…':'Berechtigungen speichern'}
</button>
{/* Feature-Overrides */}
<div style={{marginBottom:12,padding:10,background:'var(--accent-light)',borderRadius:6,fontSize:12}}>
<strong>Feature-Limits:</strong> Nutze die neue{' '}
<Link to="/admin/user-restrictions" style={{color:'var(--accent-dark)',fontWeight:600}}>
User Feature-Overrides
</Link>{' '}
Seite um individuelle Limits zu setzen.
</div>
{/* Email */}
<div style={{marginTop:12,paddingTop:12,borderTop:'1px solid var(--border)'}}>
@@ -397,6 +387,43 @@ export default function AdminPanel() {
{/* Email Settings */}
<EmailSettings/>
{/* v9c Subscription Management */}
<div className="card section-gap" style={{marginTop:16}}>
<div style={{fontWeight:700,fontSize:14,marginBottom:12,display:'flex',alignItems:'center',gap:6}}>
<Settings size={16} color="var(--accent)"/> Subscription-System (v9c)
</div>
<div style={{fontSize:12,color:'var(--text3)',marginBottom:12,lineHeight:1.5}}>
Verwalte Tiers, Features und Limits für das neue Freemium-System.
</div>
<div style={{display:'grid',gap:8}}>
<Link to="/admin/tiers">
<button className="btn btn-secondary btn-full">
🎯 Tiers verwalten
</button>
</Link>
<Link to="/admin/features">
<button className="btn btn-secondary btn-full">
🔧 Feature-Registry verwalten
</button>
</Link>
<Link to="/admin/tier-limits">
<button className="btn btn-secondary btn-full">
📊 Tier Limits Matrix bearbeiten
</button>
</Link>
<Link to="/admin/coupons">
<button className="btn btn-secondary btn-full">
🎟️ Coupons verwalten
</button>
</Link>
<Link to="/admin/user-restrictions">
<button className="btn btn-secondary btn-full">
👤 User Feature-Overrides
</button>
</Link>
</div>
</div>
</div>
)
}
+499
View File
@@ -0,0 +1,499 @@
import { useState, useEffect } from 'react'
import { Save, RotateCcw, ChevronDown, ChevronUp } from 'lucide-react'
import { api } from '../utils/api'
export default function AdminTierLimitsPage() {
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [success, setSuccess] = useState('')
const [matrix, setMatrix] = useState({ tiers: [], features: [], limits: {} })
const [changes, setChanges] = useState({})
const [saving, setSaving] = useState(false)
const [isMobile, setIsMobile] = useState(window.innerWidth < 768)
useEffect(() => {
loadMatrix()
const handleResize = () => setIsMobile(window.innerWidth < 768)
window.addEventListener('resize', handleResize)
return () => window.removeEventListener('resize', handleResize)
}, [])
async function loadMatrix() {
try {
setLoading(true)
const data = await api.getTierLimitsMatrix()
setMatrix(data)
setChanges({})
setError('')
} catch (e) {
setError(e.message)
} finally {
setLoading(false)
}
}
function handleChange(tierId, featureId, value) {
const key = `${tierId}:${featureId}`
const newChanges = { ...changes }
// Allow temporary empty input for better UX
if (value === '') {
newChanges[key] = { tierId, featureId, value: '', tempValue: '' }
setChanges(newChanges)
return
}
// Parse value
let parsedValue = null
if (value === 'unlimited' || value === '∞') {
parsedValue = null // unlimited
} else if (value === '0' || value === 'disabled') {
parsedValue = 0 // disabled
} else {
const num = parseInt(value)
if (!isNaN(num) && num >= 0) {
parsedValue = num
} else {
return // invalid input, ignore
}
}
newChanges[key] = { tierId, featureId, value: parsedValue, tempValue: value }
setChanges(newChanges)
}
async function saveChanges() {
// Filter out empty temporary values
const validChanges = Object.values(changes).filter(c => c.value !== '')
if (validChanges.length === 0) {
setSuccess('Keine Änderungen')
return
}
try {
setSaving(true)
setError('')
setSuccess('')
const updates = validChanges.map(c => ({
tier_id: c.tierId,
feature_id: c.featureId,
limit_value: c.value
}))
await api.updateTierLimitsBatch(updates)
setSuccess(`${updates.length} Limits gespeichert`)
await loadMatrix()
} catch (e) {
setError(e.message)
} finally {
setSaving(false)
}
}
function getCurrentValue(tierId, featureId) {
const key = `${tierId}:${featureId}`
if (key in changes) {
// Return temp value for display
return changes[key].tempValue !== undefined ? changes[key].tempValue : changes[key].value
}
return matrix.limits[key] ?? null
}
function formatValue(val) {
if (val === '' || val === null || val === undefined) return ''
if (val === '∞' || val === 'unlimited') return '∞'
if (val === 0 || val === '0') return '0'
return val.toString()
}
function groupFeaturesByCategory() {
const groups = {}
matrix.features.forEach(f => {
if (!groups[f.category]) groups[f.category] = []
groups[f.category].push(f)
})
return groups
}
if (loading) return (
<div style={{ display: 'flex', justifyContent: 'center', padding: 40 }}>
<div className="spinner" />
</div>
)
const hasChanges = Object.keys(changes).filter(k => changes[k].value !== '').length > 0
const categoryGroups = groupFeaturesByCategory()
const categoryIcons = { data: '📊', ai: '🤖', export: '📤', integration: '🔗' }
const categoryNames = { data: 'DATEN', ai: 'KI', export: 'EXPORT', integration: 'INTEGRATIONEN' }
// Mobile: Card-based view
if (isMobile) {
return (
<div style={{ paddingBottom: 100 }}>
{/* Header */}
<div style={{ marginBottom: 20 }}>
<div style={{ fontSize: 20, fontWeight: 700, color: 'var(--text1)' }}>
Tier Limits
</div>
<div style={{ fontSize: 13, color: 'var(--text3)', marginTop: 4 }}>
Limits pro Tier konfigurieren
</div>
</div>
{/* Messages */}
{error && (
<div style={{
padding: 12, background: 'var(--danger)', color: 'white',
borderRadius: 8, marginBottom: 16, fontSize: 13
}}>
{error}
</div>
)}
{success && (
<div style={{
padding: 12, background: 'var(--accent)', color: 'white',
borderRadius: 8, marginBottom: 16, fontSize: 13
}}>
{success}
</div>
)}
{/* Mobile: Feature Cards */}
{Object.entries(categoryGroups).map(([category, features]) => (
<div key={category} style={{ marginBottom: 20 }}>
{/* Category Header */}
<div style={{
padding: '6px 12px', background: 'var(--accent-light)', borderRadius: 8,
fontWeight: 600, fontSize: 11, textTransform: 'uppercase',
color: 'var(--accent-dark)', marginBottom: 8
}}>
{categoryIcons[category]} {categoryNames[category] || category}
</div>
{/* Features */}
{features.map(feature => (
<FeatureMobileCard
key={feature.id}
feature={feature}
tiers={matrix.tiers}
getCurrentValue={getCurrentValue}
handleChange={handleChange}
changes={changes}
/>
))}
</div>
))}
{/* Fixed Bottom Bar */}
<div style={{
position: 'fixed', bottom: 0, left: 0, right: 0,
background: 'var(--bg)', borderTop: '1px solid var(--border)',
padding: 16, display: 'flex', gap: 8, zIndex: 100,
boxShadow: '0 -2px 10px rgba(0,0,0,0.1)'
}}>
{hasChanges && (
<button
className="btn btn-secondary"
onClick={() => { setChanges({}); setSuccess(''); setError('') }}
disabled={saving}
style={{ flex: 1 }}
>
<RotateCcw size={14}/> Zurück
</button>
)}
<button
className="btn btn-primary"
onClick={saveChanges}
disabled={saving || !hasChanges}
style={{ flex: hasChanges ? 2 : 1 }}
>
{saving ? '...' : hasChanges ? <><Save size={14}/> {Object.keys(changes).filter(k=>changes[k].value!=='').length} Speichern</> : 'Keine Änderungen'}
</button>
</div>
</div>
)
}
// Desktop: Table view
return (
<div style={{ paddingBottom: 80 }}>
{/* Header */}
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
marginBottom: 20
}}>
<div>
<div style={{ fontSize: 20, fontWeight: 700, color: 'var(--text1)' }}>
Tier Limits Matrix
</div>
<div style={{ fontSize: 13, color: 'var(--text3)', marginTop: 4 }}>
Feature-Limits pro Tier (leer = unbegrenzt, 0 = deaktiviert)
</div>
</div>
<div style={{ display: 'flex', gap: 8 }}>
{hasChanges && (
<button
className="btn btn-secondary"
onClick={() => { setChanges({}); setSuccess(''); setError('') }}
disabled={saving}
>
<RotateCcw size={14}/> Zurücksetzen
</button>
)}
<button
className="btn btn-primary"
onClick={saveChanges}
disabled={saving || !hasChanges}
>
{saving ? 'Speichern...' : hasChanges ? `${Object.keys(changes).filter(k=>changes[k].value!=='').length} Änderungen speichern` : <><Save size={14}/> Speichern</>}
</button>
</div>
</div>
{/* Messages */}
{error && (
<div style={{
padding: 12, background: 'var(--danger)', color: 'white',
borderRadius: 8, marginBottom: 16, fontSize: 14
}}>
{error}
</div>
)}
{success && (
<div style={{
padding: 12, background: 'var(--accent)', color: 'white',
borderRadius: 8, marginBottom: 16, fontSize: 14
}}>
{success}
</div>
)}
{/* Matrix Table */}
<div className="card" style={{ padding: 0, overflow: 'auto' }}>
<table style={{
width: '100%', borderCollapse: 'collapse', fontSize: 13,
minWidth: 800
}}>
<thead>
<tr style={{ background: 'var(--surface2)' }}>
<th style={{
textAlign: 'left', padding: '12px 16px', fontWeight: 600,
position: 'sticky', left: 0, background: 'var(--surface2)', zIndex: 10,
borderRight: '1px solid var(--border)'
}}>
Feature
</th>
{matrix.tiers.map(tier => (
<th key={tier.id} style={{
textAlign: 'center', padding: '12px 16px', fontWeight: 600,
minWidth: 100
}}>
<div>{tier.name}</div>
<div style={{ fontSize: 10, fontWeight: 400, color: 'var(--text3)', marginTop: 2 }}>
{tier.id}
</div>
</th>
))}
</tr>
</thead>
<tbody>
{Object.entries(categoryGroups).map(([category, features]) => (
<>
{/* Category Header */}
<tr key={`cat-${category}`} style={{ background: 'var(--accent-light)' }}>
<td colSpan={matrix.tiers.length + 1} style={{
padding: '8px 16px', fontWeight: 600, fontSize: 11,
textTransform: 'uppercase', letterSpacing: '0.5px',
color: 'var(--accent-dark)'
}}>
{categoryIcons[category]} {categoryNames[category] || category}
</td>
</tr>
{/* Feature Rows */}
{features.map((feature, idx) => (
<tr key={feature.id} style={{
borderBottom: idx === features.length - 1 ? '2px solid var(--border)' : '1px solid var(--border)'
}}>
<td style={{
padding: '8px 16px', fontWeight: 500,
position: 'sticky', left: 0, background: 'var(--bg)', zIndex: 5,
borderRight: '1px solid var(--border)'
}}>
<div>{feature.name}</div>
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 2 }}>
{feature.limit_type === 'boolean' ? '(ja/nein)' : `(count, reset: ${feature.reset_period})`}
</div>
</td>
{matrix.tiers.map(tier => {
const currentValue = getCurrentValue(tier.id, feature.id)
const isChanged = `${tier.id}:${feature.id}` in changes && changes[`${tier.id}:${feature.id}`].value !== ''
// Boolean features: Toggle button
if (feature.limit_type === 'boolean') {
const isEnabled = currentValue !== 0 && currentValue !== '0'
return (
<td key={`${tier.id}-${feature.id}`} style={{
textAlign: 'center', padding: 8,
background: isChanged ? 'var(--accent-light)' : 'transparent'
}}>
<button
onClick={() => handleChange(tier.id, feature.id, isEnabled ? '0' : '1')}
style={{
padding: '6px 16px',
border: `2px solid ${isEnabled ? 'var(--accent)' : 'var(--border)'}`,
borderRadius: 20,
background: isEnabled ? 'var(--accent)' : 'var(--surface)',
color: isEnabled ? 'white' : 'var(--text3)',
fontSize: 12,
fontWeight: 600,
cursor: 'pointer',
transition: 'all 0.2s',
minWidth: 70
}}
>
{isEnabled ? '✓ AN' : '✗ AUS'}
</button>
</td>
)
}
// Count features: Text input
return (
<td key={`${tier.id}-${feature.id}`} style={{
textAlign: 'center', padding: 8,
background: isChanged ? 'var(--accent-light)' : 'transparent'
}}>
<input
type="text"
value={formatValue(currentValue)}
onChange={(e) => handleChange(tier.id, feature.id, e.target.value)}
placeholder="∞"
style={{
width: '80px',
padding: '6px 8px',
border: `1.5px solid ${isChanged ? 'var(--accent)' : 'var(--border)'}`,
borderRadius: 6,
textAlign: 'center',
fontSize: 13,
fontWeight: isChanged ? 600 : 400,
background: 'var(--bg)',
color: currentValue === 0 || currentValue === '0' ? 'var(--danger)' :
currentValue === null || currentValue === '' || currentValue === '∞' ? 'var(--accent)' : 'var(--text1)'
}}
/>
</td>
)
})}
</tr>
))}
</>
))}
</tbody>
</table>
</div>
{/* Legend */}
<div style={{
marginTop: 16, padding: 12, background: 'var(--surface2)',
borderRadius: 8, fontSize: 12, color: 'var(--text3)'
}}>
<strong>Eingabe:</strong>
<div style={{ marginTop: 8, display: 'flex', gap: 24, flexWrap: 'wrap' }}>
<span><strong style={{ color: 'var(--accent)' }}>leer oder ∞</strong> = Unbegrenzt</span>
<span><strong style={{ color: 'var(--danger)' }}>0</strong> = Deaktiviert</span>
<span><strong>1-999999</strong> = Limit-Wert</span>
</div>
</div>
</div>
)
}
// Mobile Card Component
function FeatureMobileCard({ feature, tiers, getCurrentValue, handleChange, changes }) {
const [expanded, setExpanded] = useState(false)
return (
<div className="card" style={{ marginBottom: 8, padding: 12 }}>
{/* Feature Header */}
<div
onClick={() => setExpanded(!expanded)}
style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
cursor: 'pointer', padding: '4px 0'
}}
>
<div>
<div style={{ fontWeight: 600, fontSize: 13 }}>{feature.name}</div>
<div style={{ fontSize: 11, color: 'var(--text3)' }}>
{feature.limit_type === 'boolean' ? '(ja/nein)' : `(${feature.reset_period})`}
</div>
</div>
{expanded ? <ChevronUp size={16}/> : <ChevronDown size={16}/>}
</div>
{/* Tier Inputs (Expanded) */}
{expanded && (
<div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--border)' }}>
{tiers.map(tier => {
const currentValue = getCurrentValue(tier.id, feature.id)
const isChanged = `${tier.id}:${feature.id}` in changes && changes[`${tier.id}:${feature.id}`].value !== ''
// Boolean features: Toggle button
if (feature.limit_type === 'boolean') {
const isEnabled = currentValue !== 0 && currentValue !== '0'
return (
<div key={tier.id} className="form-row" style={{ marginBottom: 8, alignItems: 'center' }}>
<label className="form-label" style={{ fontSize: 12 }}>{tier.name}</label>
<button
onClick={() => handleChange(tier.id, feature.id, isEnabled ? '0' : '1')}
style={{
flex: 1,
padding: '8px 16px',
border: `2px solid ${isEnabled ? 'var(--accent)' : 'var(--border)'}`,
borderRadius: 20,
background: isEnabled ? 'var(--accent)' : 'var(--surface)',
color: isEnabled ? 'white' : 'var(--text3)',
fontSize: 13,
fontWeight: 600,
cursor: 'pointer',
transition: 'all 0.2s'
}}
>
{isEnabled ? '✓ Aktiviert' : '✗ Deaktiviert'}
</button>
</div>
)
}
// Count features: Text input
return (
<div key={tier.id} className="form-row" style={{ marginBottom: 8 }}>
<label className="form-label" style={{ fontSize: 12 }}>{tier.name}</label>
<input
type="text"
className="form-input"
value={currentValue === null || currentValue === undefined ? '' : currentValue.toString()}
onChange={(e) => handleChange(tier.id, feature.id, e.target.value)}
placeholder="∞"
style={{
border: `1.5px solid ${isChanged ? 'var(--accent)' : 'var(--border)'}`,
background: isChanged ? 'var(--accent-light)' : 'var(--bg)',
color: currentValue === 0 ? 'var(--danger)' :
currentValue === null || currentValue === '' ? 'var(--accent)' : 'var(--text1)',
fontWeight: isChanged ? 600 : 400
}}
/>
<span className="form-unit" style={{ fontSize: 11 }}>
{currentValue === null || currentValue === '' ? '∞' : currentValue === 0 ? '❌' : '✓'}
</span>
</div>
)
})}
</div>
)}
</div>
)
}
+392
View File
@@ -0,0 +1,392 @@
import { useState, useEffect } from 'react'
import { Save, Plus, Edit2, Trash2, X } from 'lucide-react'
import { api } from '../utils/api'
export default function AdminTiersPage() {
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [success, setSuccess] = useState('')
const [tiers, setTiers] = useState([])
const [editingId, setEditingId] = useState(null)
const [showAddForm, setShowAddForm] = useState(false)
const [formData, setFormData] = useState({
id: '',
name: '',
description: '',
price_monthly_cents: '',
price_yearly_cents: '',
sort_order: 50,
active: true
})
useEffect(() => {
loadTiers()
}, [])
async function loadTiers() {
try {
setLoading(true)
const data = await api.listTiers()
setTiers(data)
setError('')
} catch (e) {
setError(e.message)
} finally {
setLoading(false)
}
}
function resetForm() {
setFormData({
id: '',
name: '',
description: '',
price_monthly_cents: '',
price_yearly_cents: '',
sort_order: 50,
active: true
})
setEditingId(null)
setShowAddForm(false)
}
function startEdit(tier) {
setFormData({
id: tier.id,
name: tier.name,
description: tier.description || '',
price_monthly_cents: tier.price_monthly_cents === null ? '' : tier.price_monthly_cents,
price_yearly_cents: tier.price_yearly_cents === null ? '' : tier.price_yearly_cents,
sort_order: tier.sort_order || 50,
active: tier.active
})
setEditingId(tier.id)
setShowAddForm(false)
}
async function handleSave() {
try {
setError('')
setSuccess('')
// Validation
if (!formData.name.trim()) {
setError('Name erforderlich')
return
}
const payload = {
name: formData.name.trim(),
description: formData.description.trim(),
price_monthly_cents: formData.price_monthly_cents === '' ? null : parseInt(formData.price_monthly_cents),
price_yearly_cents: formData.price_yearly_cents === '' ? null : parseInt(formData.price_yearly_cents),
sort_order: formData.sort_order,
active: formData.active
}
if (editingId) {
// Update existing
await api.updateTier(editingId, payload)
setSuccess('Tier aktualisiert')
} else {
// Create new
if (!formData.id.trim()) {
setError('ID erforderlich')
return
}
payload.id = formData.id.trim()
await api.createTier(payload)
setSuccess('Tier erstellt')
}
await loadTiers()
resetForm()
} catch (e) {
setError(e.message)
}
}
async function handleDelete(tierId) {
if (!confirm('Tier wirklich deaktivieren?')) return
try {
setError('')
await api.deleteTier(tierId)
setSuccess('Tier deaktiviert')
await loadTiers()
} catch (e) {
setError(e.message)
}
}
function formatPrice(cents) {
if (cents === null || cents === undefined) return 'Kostenlos'
return `${(cents / 100).toFixed(2)} €`
}
if (loading) return (
<div style={{ display: 'flex', justifyContent: 'center', padding: 40 }}>
<div className="spinner" />
</div>
)
return (
<div style={{ paddingBottom: 80 }}>
{/* Header */}
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
marginBottom: 20
}}>
<div>
<div style={{ fontSize: 20, fontWeight: 700, color: 'var(--text1)' }}>
Tier-Verwaltung
</div>
<div style={{ fontSize: 13, color: 'var(--text3)', marginTop: 4 }}>
Subscription-Tiers konfigurieren
</div>
</div>
{!showAddForm && !editingId && (
<button
className="btn btn-primary"
onClick={() => setShowAddForm(true)}
>
<Plus size={16} /> Neuer Tier
</button>
)}
</div>
{/* Messages */}
{error && (
<div style={{
padding: 12, background: 'var(--danger)', color: 'white',
borderRadius: 8, marginBottom: 16, fontSize: 14
}}>
{error}
</div>
)}
{success && (
<div style={{
padding: 12, background: 'var(--accent)', color: 'white',
borderRadius: 8, marginBottom: 16, fontSize: 14
}}>
{success}
</div>
)}
{/* Add/Edit Form */}
{(showAddForm || editingId) && (
<div className="card" style={{ padding: 20, marginBottom: 20 }}>
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
marginBottom: 16
}}>
<div style={{ fontSize: 16, fontWeight: 600 }}>
{editingId ? 'Tier bearbeiten' : 'Neuen Tier erstellen'}
</div>
<button
className="btn btn-secondary"
onClick={resetForm}
style={{ padding: '6px 12px' }}
>
<X size={16} />
</button>
</div>
<div style={{ display: 'grid', gap: 12 }}>
{/* ID (nur bei Neuanlage) */}
{!editingId && (
<div className="form-row">
<label className="form-label">ID (Slug) *</label>
<input
className="form-input"
value={formData.id}
onChange={(e) => setFormData({ ...formData, id: e.target.value })}
placeholder="z.B. enterprise"
/>
<span className="form-unit" style={{ fontSize: 11, color: 'var(--text3)' }}>
Kleinbuchstaben, keine Leerzeichen
</span>
</div>
)}
{/* Name */}
<div className="form-row">
<label className="form-label">Name *</label>
<input
className="form-input"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder="z.B. Enterprise"
/>
</div>
{/* Description */}
<div className="form-row">
<label className="form-label">Beschreibung</label>
<input
className="form-input"
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="z.B. Für Teams und Unternehmen"
/>
</div>
{/* Pricing */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
<div className="form-row">
<label className="form-label">Monatspreis (Cent)</label>
<input
className="form-input"
type="number"
value={formData.price_monthly_cents}
onChange={(e) => setFormData({ ...formData, price_monthly_cents: e.target.value })}
placeholder="Leer = kostenlos"
/>
<span className="form-unit" style={{ fontSize: 11 }}>
{formData.price_monthly_cents ? formatPrice(parseInt(formData.price_monthly_cents)) : '-'}
</span>
</div>
<div className="form-row">
<label className="form-label">Jahrespreis (Cent)</label>
<input
className="form-input"
type="number"
value={formData.price_yearly_cents}
onChange={(e) => setFormData({ ...formData, price_yearly_cents: e.target.value })}
placeholder="Leer = kostenlos"
/>
<span className="form-unit" style={{ fontSize: 11 }}>
{formData.price_yearly_cents ? formatPrice(parseInt(formData.price_yearly_cents)) : '-'}
</span>
</div>
</div>
{/* Sort Order + Active */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 12, alignItems: 'end' }}>
<div className="form-row">
<label className="form-label">Sortierung</label>
<input
className="form-input"
type="number"
value={formData.sort_order}
onChange={(e) => setFormData({ ...formData, sort_order: parseInt(e.target.value) || 50 })}
/>
</div>
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, paddingBottom: 8 }}>
<input
type="checkbox"
checked={formData.active}
onChange={(e) => setFormData({ ...formData, active: e.target.checked })}
/>
Aktiv
</label>
</div>
{/* Actions */}
<div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
<button className="btn btn-primary" onClick={handleSave}>
<Save size={14} /> {editingId ? 'Aktualisieren' : 'Erstellen'}
</button>
<button className="btn btn-secondary" onClick={resetForm}>
Abbrechen
</button>
</div>
</div>
</div>
)}
{/* Tiers List */}
<div style={{ display: 'grid', gap: 12 }}>
{tiers.length === 0 && (
<div className="card" style={{ padding: 40, textAlign: 'center', color: 'var(--text3)' }}>
Keine Tiers vorhanden
</div>
)}
{tiers.map(tier => (
<div
key={tier.id}
className="card"
style={{
padding: 16,
opacity: tier.active ? 1 : 0.6,
border: tier.active ? '1px solid var(--border)' : '1px dashed var(--border)'
}}
>
<div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
<div style={{ flex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
<div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text1)' }}>
{tier.name}
</div>
<span style={{
padding: '2px 8px', borderRadius: 4, fontSize: 10,
background: 'var(--surface2)', color: 'var(--text3)', fontFamily: 'monospace'
}}>
{tier.id}
</span>
{!tier.active && (
<span style={{
padding: '2px 8px', borderRadius: 4, fontSize: 10,
background: 'var(--danger)', color: 'white', fontWeight: 600
}}>
INAKTIV
</span>
)}
</div>
{tier.description && (
<div style={{ fontSize: 13, color: 'var(--text2)', marginBottom: 8 }}>
{tier.description}
</div>
)}
<div style={{ display: 'flex', gap: 16, fontSize: 12, color: 'var(--text3)' }}>
<div>
<strong>Monatlich:</strong> {formatPrice(tier.price_monthly_cents)}
</div>
<div>
<strong>Jährlich:</strong> {formatPrice(tier.price_yearly_cents)}
</div>
<div>
<strong>Sortierung:</strong> {tier.sort_order}
</div>
</div>
</div>
<div style={{ display: 'flex', gap: 4 }}>
<button
className="btn btn-secondary"
onClick={() => startEdit(tier)}
style={{ padding: '6px 12px', fontSize: 12 }}
>
<Edit2 size={14} />
</button>
<button
className="btn btn-secondary"
onClick={() => handleDelete(tier.id)}
style={{ padding: '6px 12px', fontSize: 12, color: 'var(--danger)' }}
disabled={!tier.active}
>
<Trash2 size={14} />
</button>
</div>
</div>
</div>
))}
</div>
{/* Info */}
<div style={{
marginTop: 16, padding: 12, background: 'var(--surface2)',
borderRadius: 8, fontSize: 12, color: 'var(--text3)'
}}>
<strong>Hinweis:</strong> Limits für jeden Tier können in der{' '}
<a href="/admin/tier-limits" style={{ color: 'var(--accent)', textDecoration: 'none' }}>
Tier Limits Matrix
</a>{' '}
konfiguriert werden.
</div>
</div>
)
}
@@ -0,0 +1,538 @@
import { useState, useEffect } from 'react'
import { Save, AlertCircle, X, RotateCcw } from 'lucide-react'
import { api } from '../utils/api'
export default function AdminUserRestrictionsPage() {
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [success, setSuccess] = useState('')
const [users, setUsers] = useState([])
const [features, setFeatures] = useState([])
const [selectedUserId, setSelectedUserId] = useState('')
const [selectedUser, setSelectedUser] = useState(null)
const [restrictions, setRestrictions] = useState([])
const [tierLimits, setTierLimits] = useState({})
const [changes, setChanges] = useState({})
const [saving, setSaving] = useState(false)
useEffect(() => {
loadInitialData()
}, [])
useEffect(() => {
if (selectedUserId) {
loadUserData(selectedUserId)
} else {
setSelectedUser(null)
setRestrictions([])
setChanges({})
}
}, [selectedUserId])
async function loadInitialData() {
try {
setLoading(true)
const [usersData, featuresData] = await Promise.all([
api.adminListProfiles(),
api.listFeatures()
])
setUsers(usersData)
setFeatures(featuresData.filter(f => f.active))
setError('')
} catch (e) {
setError(e.message)
} finally {
setLoading(false)
}
}
async function loadUserData(userId) {
try {
const [user, restrictionsData, limitsMatrix] = await Promise.all([
api.adminListProfiles().then(users => users.find(u => u.id === userId)),
api.listUserRestrictions(userId),
api.getTierLimitsMatrix()
])
setSelectedUser(user)
setRestrictions(restrictionsData)
// Build tier limits lookup for this user's tier
const userTier = user.tier || 'free'
const limits = {}
features.forEach(feature => {
const key = `${userTier}:${feature.id}`
// Use same fallback logic as TierLimitsPage: undefined → null (unlimited)
limits[feature.id] = limitsMatrix.limits[key] ?? null
})
setTierLimits(limits)
setChanges({})
setError('')
setSuccess('')
} catch (e) {
setError(e.message)
}
}
function handleChange(featureId, value) {
const newChanges = { ...changes }
const tierLimit = tierLimits[featureId]
// Parse value (EXACTLY like TierLimitsPage)
let parsedValue = null
if (value === 'unlimited' || value === '∞') {
parsedValue = null // unlimited
} else if (value === '0' || value === 'disabled') {
parsedValue = 0 // disabled
} else if (value === '') {
parsedValue = null // empty → unlimited
} else {
const num = parseInt(value)
if (!isNaN(num) && num >= 0) {
parsedValue = num
} else {
return // invalid input, ignore
}
}
// Check if value equals tier limit → remove override
if (parsedValue === tierLimit) {
newChanges[featureId] = { action: 'remove', tempValue: value }
} else {
// Different from tier default → set override
newChanges[featureId] = { action: 'set', value: parsedValue, tempValue: value }
}
setChanges(newChanges)
}
function handleToggle(featureId) {
// Get current state
const restriction = restrictions.find(r => r.feature_id === featureId)
let currentValue = restriction?.limit_value ?? null
// Check if there's a pending change
if (featureId in changes && changes[featureId].action === 'set') {
currentValue = changes[featureId].value
}
// Toggle between 1 (enabled) and 0 (disabled)
const isCurrentlyEnabled = currentValue !== 0 && currentValue !== '0'
const newValue = isCurrentlyEnabled ? 0 : 1
const newChanges = { ...changes }
newChanges[featureId] = { action: 'set', value: newValue, tempValue: newValue.toString() }
setChanges(newChanges)
}
async function handleSave() {
if (!selectedUserId) return
try {
setSaving(true)
setError('')
setSuccess('')
let changeCount = 0
for (const [featureId, change] of Object.entries(changes)) {
const existingRestriction = restrictions.find(r => r.feature_id === featureId)
if (change.action === 'remove') {
// Remove restriction if exists
if (existingRestriction) {
await api.deleteUserRestriction(existingRestriction.id)
changeCount++
}
} else if (change.action === 'set') {
// Create or update
if (existingRestriction) {
await api.updateUserRestriction(existingRestriction.id, {
limit_value: change.value,
enabled: true
})
} else {
await api.createUserRestriction({
profile_id: selectedUserId,
feature_id: featureId,
limit_value: change.value,
enabled: true,
reason: 'Admin override'
})
}
changeCount++
}
}
setSuccess(`${changeCount} Änderung(en) gespeichert`)
await loadUserData(selectedUserId)
} catch (e) {
setError(e.message)
} finally {
setSaving(false)
}
}
function getDisplayValue(featureId) {
// Check pending changes first
if (featureId in changes) {
const change = changes[featureId]
if (change.action === 'remove') {
// Returning to tier default
return formatValue(tierLimits[featureId])
}
if (change.action === 'set') {
// Use tempValue for display if available, otherwise format the value
return change.tempValue !== undefined ? change.tempValue : formatValue(change.value)
}
}
// Show override if exists, otherwise tier limit (= effective value)
const restriction = restrictions.find(r => r.feature_id === featureId)
if (restriction) {
return formatValue(restriction.limit_value)
}
// No override: show tier limit as default
return formatValue(tierLimits[featureId])
}
function formatValue(val) {
if (val === null || val === undefined) return 'unlimited'
if (val === '' ) return ''
if (val === '∞' || val === 'unlimited') return 'unlimited'
if (val === 0 || val === '0') return '0'
return val.toString()
}
function getToggleState(featureId) {
// Check pending changes first
if (featureId in changes && changes[featureId].action === 'set') {
const val = changes[featureId].value
return val !== 0 && val !== '0'
}
// Check existing restriction
const restriction = restrictions.find(r => r.feature_id === featureId)
if (!restriction) {
// No override: use tier default
const tierLimit = tierLimits[featureId]
return tierLimit !== 0 && tierLimit !== '0'
}
// For boolean features: limit_value determines state
return restriction.limit_value !== 0 && restriction.limit_value !== '0'
}
function hasOverride(featureId) {
return restrictions.some(r => r.feature_id === featureId)
}
function isChanged(featureId) {
return featureId in changes
}
if (loading) return (
<div style={{ display: 'flex', justifyContent: 'center', padding: 40 }}>
<div className="spinner" />
</div>
)
const hasChanges = Object.keys(changes).length > 0
const categoryGroups = {}
features.forEach(f => {
if (!categoryGroups[f.category]) categoryGroups[f.category] = []
categoryGroups[f.category].push(f)
})
const categoryIcons = { data: '📊', ai: '🤖', export: '📤', integration: '🔗' }
const categoryNames = { data: 'DATEN', ai: 'KI', export: 'EXPORT', integration: 'INTEGRATIONEN' }
return (
<div style={{ paddingBottom: 80 }}>
{/* Header */}
<div style={{ marginBottom: 20 }}>
<div style={{ fontSize: 20, fontWeight: 700, color: 'var(--text1)' }}>
User Feature-Overrides
</div>
<div style={{ fontSize: 13, color: 'var(--text3)', marginTop: 4 }}>
Individuelle Feature-Limits für einzelne User setzen
</div>
</div>
{/* Info Box */}
<div style={{
padding: 12, background: 'var(--accent-light)', borderRadius: 8,
marginBottom: 16, fontSize: 12, color: 'var(--accent-dark)',
display: 'flex', gap: 8, alignItems: 'flex-start'
}}>
<AlertCircle size={16} style={{ marginTop: 2, flexShrink: 0 }} />
<div>
<strong>Hinweis:</strong> Felder zeigen effektive Werte (Override falls gesetzt, sonst Tier-Standard).
Wert ändern → Override wird gesetzt. Wert = Tier-Standard → Override wird entfernt.
</div>
</div>
{/* Messages */}
{error && (
<div style={{
padding: 12, background: 'var(--danger)', color: 'white',
borderRadius: 8, marginBottom: 16, fontSize: 14
}}>
{error}
</div>
)}
{success && (
<div style={{
padding: 12, background: 'var(--accent)', color: 'white',
borderRadius: 8, marginBottom: 16, fontSize: 14
}}>
{success}
</div>
)}
{/* User Selection */}
<div className="card" style={{ padding: 16, marginBottom: 16 }}>
<label className="form-label" style={{ display: 'block', marginBottom: 8 }}>
User auswählen
</label>
<select
className="form-input"
style={{ width: '100%' }}
value={selectedUserId}
onChange={(e) => setSelectedUserId(e.target.value)}
>
<option value="">-- User auswählen --</option>
{users.map(u => (
<option key={u.id} value={u.id}>
{u.name} ({u.email || u.id}) - Tier: {u.tier || 'free'}
</option>
))}
</select>
</div>
{/* User Info + Features */}
{selectedUser && (
<>
{/* Action Buttons */}
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
marginBottom: 16
}}>
<div style={{ fontSize: 16, fontWeight: 600 }}>
Feature-Overrides für {selectedUser.name}
</div>
<div style={{ display: 'flex', gap: 8 }}>
{hasChanges && (
<button
className="btn btn-secondary"
onClick={() => setChanges({})}
disabled={saving}
>
<X size={14} /> Abbrechen
</button>
)}
<button
className="btn btn-primary"
onClick={handleSave}
disabled={!hasChanges || saving}
>
{saving ? 'Speichern...' : hasChanges ? `${Object.keys(changes).length} Änderung(en) speichern` : 'Keine Änderungen'}
</button>
</div>
</div>
{/* User Info Card */}
<div className="card" style={{ padding: 16, marginBottom: 16 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<div style={{
width: 40, height: 40, borderRadius: '50%',
background: selectedUser.avatar_color || 'var(--accent)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
color: 'white', fontWeight: 700, fontSize: 18
}}>
{selectedUser.name?.charAt(0).toUpperCase()}
</div>
<div style={{ flex: 1 }}>
<div style={{ fontWeight: 600, fontSize: 14 }}>{selectedUser.name}</div>
<div style={{ fontSize: 12, color: 'var(--text3)' }}>
{selectedUser.email || `ID: ${selectedUser.id}`}
</div>
</div>
<div style={{
padding: '4px 12px', borderRadius: 6,
background: 'var(--accent-light)', color: 'var(--accent-dark)',
fontSize: 12, fontWeight: 600
}}>
Tier: {selectedUser.tier || 'free'}
</div>
</div>
</div>
{/* Features Table */}
<div className="card" style={{ padding: 0, overflow: 'auto', marginBottom: 16 }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
<thead>
<tr style={{ background: 'var(--surface2)' }}>
<th style={{ textAlign: 'left', padding: '12px 16px', fontWeight: 600 }}>
Feature
</th>
<th style={{ textAlign: 'center', padding: '12px 16px', fontWeight: 600 }}>
Tier-Limit
</th>
<th style={{ textAlign: 'center', padding: '12px 16px', fontWeight: 600 }}>
Override-Wert
</th>
<th style={{ textAlign: 'right', padding: '12px 16px', fontWeight: 600 }}>
Aktion
</th>
</tr>
</thead>
<tbody>
{Object.entries(categoryGroups).map(([category, categoryFeatures]) => (
<>
{/* Category Header */}
<tr key={`cat-${category}`} style={{ background: 'var(--accent-light)' }}>
<td colSpan={4} style={{
padding: '8px 16px', fontWeight: 600, fontSize: 11,
textTransform: 'uppercase', letterSpacing: '0.5px',
color: 'var(--accent-dark)'
}}>
{categoryIcons[category]} {categoryNames[category] || category}
</td>
</tr>
{/* Feature Rows */}
{categoryFeatures.map(feature => {
const displayValue = getDisplayValue(feature.id)
const toggleState = getToggleState(feature.id)
const override = hasOverride(feature.id)
const changed = isChanged(feature.id)
return (
<tr key={feature.id} style={{
borderBottom: '1px solid var(--border)',
background: changed ? 'var(--accent-light)' : 'transparent'
}}>
{/* Feature Name */}
<td style={{ padding: '12px 16px' }}>
<div style={{ fontWeight: 500 }}>{feature.name}</div>
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 2 }}>
{feature.limit_type === 'boolean' ? '(ja/nein)' : `(${feature.reset_period})`}
</div>
</td>
{/* Tier-Limit */}
<td style={{ padding: '12px 16px', textAlign: 'center' }}>
{feature.limit_type === 'boolean' ? (
<span style={{
padding: '6px 12px', borderRadius: 20,
background: tierLimits[feature.id] !== 0 ? 'var(--accent-light)' : 'var(--surface2)',
color: tierLimits[feature.id] !== 0 ? 'var(--accent-dark)' : 'var(--text3)',
fontSize: 12, fontWeight: 600
}}>
{tierLimits[feature.id] !== 0 ? '✓ AN' : '✗ AUS'}
</span>
) : (
<span style={{ fontWeight: 500, color: 'var(--text2)' }}>
{tierLimits[feature.id] === null ? '∞' : tierLimits[feature.id]}
</span>
)}
</td>
{/* Override Input */}
<td style={{ padding: '12px 16px', textAlign: 'center' }}>
{feature.limit_type === 'boolean' ? (
<button
onClick={() => handleToggle(feature.id)}
style={{
padding: '6px 16px',
border: `2px solid ${toggleState ? 'var(--accent)' : 'var(--border)'}`,
borderRadius: 20,
background: toggleState ? 'var(--accent)' : 'var(--surface)',
color: toggleState ? 'white' : 'var(--text3)',
fontSize: 12,
fontWeight: 600,
cursor: 'pointer',
transition: 'all 0.2s',
minWidth: 80
}}
>
{toggleState ? '✓ AN' : '✗ AUS'}
</button>
) : (
<input
type="text"
value={displayValue}
onChange={(e) => handleChange(feature.id, e.target.value)}
placeholder=""
style={{
width: '120px',
padding: '6px 8px',
border: `1.5px solid ${changed ? 'var(--accent)' : override ? 'var(--accent)' : 'var(--border)'}`,
borderRadius: 6,
textAlign: 'center',
fontSize: 13,
fontWeight: override || changed ? 600 : 400,
background: override || changed ? 'var(--accent-light)' : 'var(--bg)',
color: displayValue === '0' ? 'var(--danger)' :
displayValue === 'unlimited' ? 'var(--accent)' : 'var(--text1)'
}}
/>
)}
</td>
{/* Action */}
<td style={{ padding: '12px 16px', textAlign: 'right' }}>
<button
className="btn btn-secondary"
onClick={() => {
// Reset to tier default
const tierValue = tierLimits[feature.id]
handleChange(feature.id, formatValue(tierValue))
}}
disabled={!override}
style={{
padding: '4px 8px',
fontSize: 11,
opacity: override ? 1 : 0.4,
cursor: override ? 'pointer' : 'not-allowed'
}}
>
↺ Zurück
</button>
</td>
</tr>
)
})}
</>
))}
</tbody>
</table>
</div>
{/* Legend */}
<div style={{
marginTop: 16, padding: 12, background: 'var(--surface2)',
borderRadius: 8, fontSize: 12, color: 'var(--text3)'
}}>
<strong>Eingabe:</strong>
<div style={{ marginTop: 8, display: 'flex', gap: 16, flexWrap: 'wrap' }}>
<span><strong>unlimited</strong> = Unbegrenzt</span>
<span><strong style={{ color: 'var(--danger)' }}>0</strong> = Feature deaktiviert</span>
<span><strong>1+</strong> = Limit-Wert</span>
</div>
<div style={{ marginTop: 8, fontSize: 11, opacity: 0.8 }}>
• Feld zeigt effektiven Wert (Override falls gesetzt, sonst Tier-Standard)<br />
• Wert ändern → Override wird gesetzt<br />
• Wert = Tier-Standard → Override wird entfernt
</div>
</div>
</>
)}
</div>
)
}
+52 -16
View File
@@ -3,6 +3,7 @@ import { Brain, Pencil, Trash2, ChevronDown, ChevronUp, Check, X } from 'lucide-
import { api } from '../utils/api'
import { useAuth } from '../context/AuthContext'
import Markdown from '../utils/Markdown'
import UsageBadge from '../components/UsageBadge'
import dayjs from 'dayjs'
import 'dayjs/locale/de'
dayjs.locale('de')
@@ -114,6 +115,7 @@ export default function Analysis() {
const [tab, setTab] = useState('run')
const [newResult, setNewResult] = useState(null)
const [pipelineLoading, setPipelineLoading] = useState(false)
const [aiUsage, setAiUsage] = useState(null) // Phase 3: Usage badge
const loadAll = async () => {
const [p, i] = await Promise.all([
@@ -123,7 +125,15 @@ export default function Analysis() {
setPrompts(Array.isArray(p)?p:[])
setAllInsights(Array.isArray(i)?i:[])
}
useEffect(()=>{ loadAll() },[])
useEffect(()=>{
loadAll()
// Load feature usage for badges
api.getFeatureUsage().then(features => {
const aiFeature = features.find(f => f.feature_id === 'ai_calls')
setAiUsage(aiFeature)
}).catch(err => console.error('Failed to load usage:', err))
},[])
const runPipeline = async () => {
setPipelineLoading(true); setError(null); setNewResult(null)
@@ -177,7 +187,7 @@ export default function Analysis() {
grouped[key].push(ins)
})
const activePrompts = prompts.filter(p=>p.active && !p.slug.startsWith('pipeline_'))
const activePrompts = prompts.filter(p=>p.active && !p.slug.startsWith('pipeline_') && p.slug !== 'pipeline')
// Pipeline is available if the "pipeline" prompt is active
const pipelinePrompt = prompts.find(p=>p.slug==='pipeline')
@@ -230,7 +240,10 @@ export default function Analysis() {
<div className="card" style={{marginBottom:16,borderColor:'var(--accent)',borderWidth:2}}>
<div style={{display:'flex',alignItems:'flex-start',gap:12}}>
<div style={{flex:1}}>
<div style={{fontWeight:700,fontSize:15,color:'var(--accent)'}}>🔬 Mehrstufige Gesamtanalyse</div>
<div className="badge-container-right" style={{fontWeight:700,fontSize:15,color:'var(--accent)'}}>
<span>🔬 Mehrstufige Gesamtanalyse</span>
{aiUsage && <UsageBadge {...aiUsage} />}
</div>
<div style={{fontSize:12,color:'var(--text2)',marginTop:3,lineHeight:1.5}}>
3 spezialisierte KI-Calls parallel (Körper + Ernährung + Aktivität),
dann Synthese + Zielabgleich. Detaillierteste Auswertung.
@@ -241,12 +254,22 @@ export default function Analysis() {
</div>
)}
</div>
<button className="btn btn-primary" style={{flexShrink:0,minWidth:100}}
onClick={runPipeline} disabled={!!loading||pipelineLoading}>
{pipelineLoading
? <><div className="spinner" style={{width:13,height:13}}/> Läuft…</>
: <><Brain size={13}/> Starten</>}
</button>
<div
title={aiUsage && !aiUsage.allowed ? `Limit erreicht (${aiUsage.used}/${aiUsage.limit}). Kontaktiere den Admin oder warte bis zum nächsten Reset.` : ''}
style={{display:'inline-block'}}
>
<button
className="btn btn-primary"
style={{flexShrink:0,minWidth:100, cursor: (aiUsage && !aiUsage.allowed) ? 'not-allowed' : 'pointer'}}
onClick={runPipeline}
disabled={!!loading||pipelineLoading||(aiUsage && !aiUsage.allowed)}
>
{pipelineLoading
? <><div className="spinner" style={{width:13,height:13}}/> Läuft…</>
: (aiUsage && !aiUsage.allowed) ? '🔒 Limit'
: <><Brain size={13}/> Starten</>}
</button>
</div>
{!canUseAI && <div style={{fontSize:11,color:'#D85A30',marginTop:4}}>🔒 KI nicht freigeschaltet</div>}
</div>
{pipelineLoading && (
@@ -282,7 +305,10 @@ export default function Analysis() {
<div key={p.id} className="card section-gap">
<div style={{display:'flex',alignItems:'flex-start',gap:12}}>
<div style={{flex:1}}>
<div style={{fontWeight:600,fontSize:15}}>{SLUG_LABELS[p.slug]||p.name}</div>
<div className="badge-container-right" style={{fontWeight:600,fontSize:15}}>
<span>{SLUG_LABELS[p.slug]||p.name}</span>
{aiUsage && <UsageBadge {...aiUsage} />}
</div>
{p.description && <div style={{fontSize:12,color:'var(--text3)',marginTop:2}}>{p.description}</div>}
{existing && (
<div style={{fontSize:11,color:'var(--text3)',marginTop:3}}>
@@ -290,12 +316,22 @@ export default function Analysis() {
</div>
)}
</div>
<button className="btn btn-primary" style={{flexShrink:0,minWidth:90}}
onClick={()=>runPrompt(p.slug)} disabled={!!loading||!canUseAI}>
{loading===p.slug
? <><div className="spinner" style={{width:13,height:13}}/> Läuft…</>
: <><Brain size={13}/> {existing?'Neu erstellen':'Starten'}</>}
</button>
<div
title={aiUsage && !aiUsage.allowed ? `Limit erreicht (${aiUsage.used}/${aiUsage.limit}). Kontaktiere den Admin oder warte bis zum nächsten Reset.` : ''}
style={{display:'inline-block'}}
>
<button
className="btn btn-primary"
style={{flexShrink:0,minWidth:90, cursor: (aiUsage && !aiUsage.allowed) ? 'not-allowed' : 'pointer'}}
onClick={()=>runPrompt(p.slug)}
disabled={!!loading||!canUseAI||(aiUsage && !aiUsage.allowed)}
>
{loading===p.slug
? <><div className="spinner" style={{width:13,height:13}}/> Läuft…</>
: (aiUsage && !aiUsage.allowed) ? '🔒 Limit'
: <><Brain size={13}/> {existing?'Neu erstellen':'Starten'}</>}
</button>
</div>
</div>
{/* Show existing result collapsed */}
{existing && newResult?.id !== existing.id && (
+58 -10
View File
@@ -4,6 +4,7 @@ import { useNavigate } from 'react-router-dom'
import { api } from '../utils/api'
import { calcBodyFat, getBfCategory, METHOD_POINTS } from '../utils/calc'
import { CALIPER_POINTS, CALIPER_METHODS } from '../utils/guideData'
import UsageBadge from '../components/UsageBadge'
import dayjs from 'dayjs'
function emptyForm() {
@@ -15,7 +16,7 @@ function emptyForm() {
}
}
function CaliperForm({ form, setForm, profile, onSave, onCancel, saveLabel='Speichern' }) {
function CaliperForm({ form, setForm, profile, onSave, onCancel, saveLabel='Speichern', saving=false, error=null, usage=null }) {
const sex = profile?.sex||'m'
const age = profile?.dob ? Math.floor((Date.now()-new Date(profile.dob))/(365.25*24*3600*1000)) : 30
const weight = form.weight || 80
@@ -65,8 +66,25 @@ function CaliperForm({ form, setForm, profile, onSave, onCancel, saveLabel='Spei
<input type="text" className="form-input" placeholder="optional" value={form.notes||''} onChange={e=>set('notes',e.target.value)}/>
<span className="form-unit"/>
</div>
{error && (
<div style={{padding:'10px',background:'var(--danger-bg)',border:'1px solid var(--danger)',borderRadius:8,fontSize:13,color:'var(--danger)',marginBottom:8}}>
{error}
</div>
)}
<div style={{display:'flex',gap:6,marginTop:8}}>
<button className="btn btn-primary" style={{flex:1}} onClick={()=>onSave(bfPct, sex)}>{saveLabel}</button>
<div
title={usage && !usage.allowed ? `Limit erreicht (${usage.used}/${usage.limit}). Kontaktiere den Admin oder warte bis zum nächsten Reset.` : ''}
style={{flex:1,display:'inline-block'}}
>
<button
className="btn btn-primary"
style={{width:'100%', cursor: (usage && !usage.allowed) ? 'not-allowed' : 'pointer'}}
onClick={()=>onSave(bfPct, sex)}
disabled={saving || (usage && !usage.allowed)}
>
{(usage && !usage.allowed) ? '🔒 Limit erreicht' : saveLabel}
</button>
</div>
{onCancel && <button className="btn btn-secondary" style={{flex:1}} onClick={onCancel}><X size={13}/> Abbrechen</button>}
</div>
</div>
@@ -78,12 +96,26 @@ export default function CaliperScreen() {
const [profile, setProfile] = useState(null)
const [form, setForm] = useState(emptyForm())
const [editing, setEditing] = useState(null)
const [saving, setSaving] = useState(false)
const [saved, setSaved] = useState(false)
const [error, setError] = useState(null)
const [caliperUsage, setCaliperUsage] = useState(null) // Phase 4: Usage badge
const nav = useNavigate()
const load = () => Promise.all([api.listCaliper(), api.getProfile()])
.then(([e,p])=>{ setEntries(e); setProfile(p) })
useEffect(()=>{ load() },[])
const loadUsage = () => {
api.getFeatureUsage().then(features => {
const caliperFeature = features.find(f => f.feature_id === 'caliper_entries')
setCaliperUsage(caliperFeature)
}).catch(err => console.error('Failed to load usage:', err))
}
useEffect(()=>{
load()
loadUsage()
},[])
const buildPayload = (f, bfPct, sex) => {
const weight = profile?.weight || null
@@ -97,11 +129,23 @@ export default function CaliperScreen() {
}
const handleSave = async (bfPct, sex) => {
const payload = buildPayload(form, bfPct, sex)
await api.upsertCaliper(payload)
setSaved(true); await load()
setTimeout(()=>setSaved(false),2000)
setForm(emptyForm())
setSaving(true)
setError(null)
try {
const payload = buildPayload(form, bfPct, sex)
await api.upsertCaliper(payload)
setSaved(true)
await load()
await loadUsage() // Reload usage after save
setTimeout(()=>setSaved(false),2000)
setForm(emptyForm())
} catch (err) {
console.error('Save failed:', err)
setError(err.message || 'Fehler beim Speichern')
setTimeout(()=>setError(null), 5000)
} finally {
setSaving(false)
}
}
const handleUpdate = async (bfPct, sex) => {
@@ -125,9 +169,13 @@ export default function CaliperScreen() {
</div>
<div className="card section-gap">
<div className="card-title">Neue Messung</div>
<div className="card-title badge-container-right">
<span>Neue Messung</span>
{caliperUsage && <UsageBadge {...caliperUsage} />}
</div>
<CaliperForm form={form} setForm={setForm} profile={profile}
onSave={handleSave} saveLabel={saved?'✓ Gespeichert!':'Speichern'}/>
onSave={handleSave} saveLabel={saved?'✓ Gespeichert!':'Speichern'}
saving={saving} error={error} usage={caliperUsage}/>
</div>
<div className="section-gap">
+51 -7
View File
@@ -3,6 +3,7 @@ import { Pencil, Trash2, Check, X, Camera, BookOpen } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { api } from '../utils/api'
import { CIRCUMFERENCE_POINTS } from '../utils/guideData'
import UsageBadge from '../components/UsageBadge'
import dayjs from 'dayjs'
const FIELDS = ['c_neck','c_chest','c_waist','c_belly','c_hip','c_thigh','c_calf','c_arm']
@@ -16,18 +17,32 @@ export default function CircumScreen() {
const [editing, setEditing] = useState(null)
const [saving, setSaving] = useState(false)
const [saved, setSaved] = useState(false)
const [error, setError] = useState(null)
const [photoFile, setPhotoFile] = useState(null)
const [photoPreview, setPhotoPreview] = useState(null)
const [circumUsage, setCircumUsage] = useState(null) // Phase 4: Usage badge
const fileRef = useRef()
const nav = useNavigate()
const load = () => api.listCirc().then(setEntries)
useEffect(()=>{ load() },[])
const loadUsage = () => {
api.getFeatureUsage().then(features => {
const circumFeature = features.find(f => f.feature_id === 'circumference_entries')
setCircumUsage(circumFeature)
}).catch(err => console.error('Failed to load usage:', err))
}
useEffect(()=>{
load()
loadUsage()
},[])
const set = (k,v) => setForm(f=>({...f,[k]:v}))
const handleSave = async () => {
setSaving(true)
setError(null)
try {
const payload = {}
payload.date = form.date
@@ -38,10 +53,18 @@ export default function CircumScreen() {
payload.photo_id = pr.id
}
await api.upsertCirc(payload)
setSaved(true); await load()
setSaved(true)
await load()
await loadUsage() // Reload usage after save
setTimeout(()=>setSaved(false),2000)
setForm(empty()); setPhotoFile(null); setPhotoPreview(null)
} finally { setSaving(false) }
} catch (err) {
console.error('Save failed:', err)
setError(err.message || 'Fehler beim Speichern')
setTimeout(()=>setError(null), 5000)
} finally {
setSaving(false)
}
}
const startEdit = (e) => setEditing({...e})
@@ -72,7 +95,10 @@ export default function CircumScreen() {
{/* Eingabe */}
<div className="card section-gap">
<div className="card-title">Neue Messung</div>
<div className="card-title badge-container-right">
<span>Neue Messung</span>
{circumUsage && <UsageBadge {...circumUsage} />}
</div>
<div className="form-row">
<label className="form-label">Datum</label>
<input type="date" className="form-input" style={{width:140}} value={form.date} onChange={e=>set('date',e.target.value)}/>
@@ -99,9 +125,27 @@ export default function CircumScreen() {
<button className="btn btn-secondary btn-full" onClick={()=>fileRef.current.click()}>
<Camera size={14}/> {photoPreview?'Foto ändern':'Foto hinzufügen'}
</button>
<button className="btn btn-primary btn-full" style={{marginTop:8}} onClick={handleSave} disabled={saving}>
{saved ? <><Check size={14}/> Gespeichert!</> : saving ? '…' : 'Speichern'}
</button>
{error && (
<div style={{padding:'10px',background:'var(--danger-bg)',border:'1px solid var(--danger)',borderRadius:8,fontSize:13,color:'var(--danger)',marginTop:8}}>
{error}
</div>
)}
<div
title={circumUsage && !circumUsage.allowed ? `Limit erreicht (${circumUsage.used}/${circumUsage.limit}). Kontaktiere den Admin oder warte bis zum nächsten Reset.` : ''}
style={{display:'inline-block',width:'100%',marginTop:8}}
>
<button
className="btn btn-primary btn-full"
style={{cursor: (circumUsage && !circumUsage.allowed) ? 'not-allowed' : 'pointer'}}
onClick={handleSave}
disabled={saving || (circumUsage && !circumUsage.allowed)}
>
{saved ? <><Check size={14}/> Gespeichert!</>
: saving ? '…'
: (circumUsage && !circumUsage.allowed) ? '🔒 Limit erreicht'
: 'Speichern'}
</button>
</div>
</div>
{/* Liste */}
+55 -12
View File
@@ -27,32 +27,75 @@ function QuickWeight({ onSaved }) {
const [input, setInput] = useState('')
const [saving, setSaving] = useState(false)
const [saved, setSaved] = useState(false)
const [error, setError] = useState(null)
const [weightUsage, setWeightUsage] = useState(null)
const today = dayjs().format('YYYY-MM-DD')
const loadUsage = () => {
api.getFeatureUsage().then(features => {
const weightFeature = features.find(f => f.feature_id === 'weight_entries')
setWeightUsage(weightFeature)
}).catch(err => console.error('Failed to load usage:', err))
}
useEffect(()=>{
api.weightStats().then(s=>{
if(s?.latest?.date===today) setInput(String(s.latest.weight))
})
loadUsage()
},[])
const handleSave = async () => {
const w=parseFloat(input); if(!w||w<20||w>300) return
setSaving(true)
try{ await api.upsertWeight(today,w); setSaved(true); onSaved?.(); setTimeout(()=>setSaved(false),2000) }
finally{ setSaving(false) }
setError(null)
try{
await api.upsertWeight(today,w)
setSaved(true)
await loadUsage() // Reload usage after save
onSaved?.()
setTimeout(()=>setSaved(false),2000)
} catch(err) {
console.error('Save failed:', err)
setError(err.message || 'Fehler beim Speichern')
setTimeout(()=>setError(null), 5000)
} finally {
setSaving(false)
}
}
const isDisabled = saving || !input || (weightUsage && !weightUsage.allowed)
const tooltipText = weightUsage && !weightUsage.allowed
? `Limit erreicht (${weightUsage.used}/${weightUsage.limit}). Kontaktiere den Admin oder warte bis zum nächsten Reset.`
: ''
return (
<div style={{display:'flex',gap:8,alignItems:'center'}}>
<input type="number" min={20} max={300} step={0.1} className="form-input"
style={{flex:1,fontSize:17,fontWeight:600,textAlign:'center'}}
placeholder="kg eingeben" value={input} onChange={e=>setInput(e.target.value)}
onKeyDown={e=>e.key==='Enter'&&handleSave()}/>
<span style={{fontSize:13,color:'var(--text3)'}}>kg</span>
<button className="btn btn-primary" style={{padding:'8px 14px'}}
onClick={handleSave} disabled={saving||!input}>
{saved?<Check size={15}/>:saving?<div className="spinner" style={{width:14,height:14}}/>:'Speichern'}
</button>
<div>
{error && (
<div style={{padding:'8px 10px',background:'var(--danger-bg)',border:'1px solid var(--danger)',borderRadius:8,fontSize:12,color:'var(--danger)',marginBottom:8}}>
{error}
</div>
)}
<div style={{display:'flex',gap:8,alignItems:'center'}}>
<input type="number" min={20} max={300} step={0.1} className="form-input"
style={{flex:1,fontSize:17,fontWeight:600,textAlign:'center'}}
placeholder="kg eingeben" value={input} onChange={e=>setInput(e.target.value)}
onKeyDown={e=>e.key==='Enter'&&!isDisabled&&handleSave()}/>
<span style={{fontSize:13,color:'var(--text3)'}}>kg</span>
<div title={tooltipText} style={{display:'inline-block'}}>
<button
className="btn btn-primary"
style={{padding:'8px 14px', cursor: isDisabled ? 'not-allowed' : 'pointer'}}
onClick={handleSave}
disabled={isDisabled}
>
{saved ? <Check size={15}/>
: saving ? <div className="spinner" style={{width:14,height:14}}/>
: (weightUsage && !weightUsage.allowed) ? '🔒 Limit'
: 'Speichern'}
</button>
</div>
</div>
</div>
)
}
+16
View File
@@ -105,6 +105,22 @@ export default function LoginScreen() {
textAlign:'center',padding:'4px 0',textDecoration:'underline'}}>
Passwort vergessen?
</button>
<div style={{
marginTop:24, paddingTop:20,
borderTop:'1px solid var(--border)',
textAlign:'center'
}}>
<span style={{color:'var(--text2)',fontSize:14}}>
Noch kein Account?{' '}
</span>
<a href="/register" style={{
color:'var(--accent)',fontWeight:600,fontSize:14,
textDecoration:'none'
}}>
Jetzt registrieren
</a>
</div>
</div>
<div style={{textAlign:'center',marginTop:20,fontSize:11,color:'var(--text3)'}}>
+499 -22
View File
@@ -18,6 +18,419 @@ function rollingAvg(arr, key, window=7) {
})
}
// ── Entry Form (Create/Update) ───────────────────────────────────────────────
function EntryForm({ onSaved }) {
const [date, setDate] = useState(dayjs().format('YYYY-MM-DD'))
const [values, setValues] = useState({ kcal: '', protein_g: '', fat_g: '', carbs_g: '' })
const [existingId, setExistingId] = useState(null)
const [loading, setLoading] = useState(false)
const [saving, setSaving] = useState(false)
const [error, setError] = useState(null)
const [success, setSuccess] = useState(null)
// Load data for selected date
useEffect(() => {
const load = async () => {
if (!date) return
setLoading(true)
setError(null)
try {
const data = await nutritionApi.getNutritionByDate(date)
if (data) {
setValues({
kcal: data.kcal || '',
protein_g: data.protein_g || '',
fat_g: data.fat_g || '',
carbs_g: data.carbs_g || ''
})
setExistingId(data.id)
} else {
setValues({ kcal: '', protein_g: '', fat_g: '', carbs_g: '' })
setExistingId(null)
}
} catch(e) {
console.error('Failed to load entry:', e)
} finally {
setLoading(false)
}
}
load()
}, [date])
const handleSave = async () => {
if (!date || !values.kcal) {
setError('Datum und Kalorien sind Pflichtfelder')
return
}
setSaving(true)
setError(null)
setSuccess(null)
try {
const result = await nutritionApi.createNutrition(
date,
parseFloat(values.kcal) || 0,
parseFloat(values.protein_g) || 0,
parseFloat(values.fat_g) || 0,
parseFloat(values.carbs_g) || 0
)
setSuccess(result.mode === 'created' ? 'Eintrag hinzugefügt' : 'Eintrag aktualisiert')
setTimeout(() => setSuccess(null), 3000)
onSaved()
} catch(e) {
if (e.message.includes('Limit erreicht')) {
setError(e.message)
} else {
setError('Speichern fehlgeschlagen: ' + e.message)
}
setTimeout(() => setError(null), 5000)
} finally {
setSaving(false)
}
}
return (
<div className="card section-gap">
<div className="card-title">Eintrag hinzufügen / bearbeiten</div>
{error && (
<div style={{padding:'8px 12px',background:'#FCEBEB',borderRadius:8,fontSize:13,color:'#D85A30',marginBottom:12}}>
{error}
</div>
)}
{success && (
<div style={{padding:'8px 12px',background:'var(--accent-light)',borderRadius:8,fontSize:13,color:'var(--accent-dark)',marginBottom:12}}>
✓ {success}
</div>
)}
<div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,marginBottom:12}}>
<div style={{gridColumn:'1 / -1'}}>
<label className="form-label">Datum</label>
<input
type="date"
className="form-input"
value={date}
onChange={e => setDate(e.target.value)}
max={dayjs().format('YYYY-MM-DD')}
style={{width:'100%'}}
/>
{existingId && !loading && (
<div style={{fontSize:11,color:'var(--accent)',marginTop:4}}>
ℹ️ Eintrag existiert bereits – wird beim Speichern aktualisiert
</div>
)}
</div>
<div>
<label className="form-label">Kalorien *</label>
<input
type="number"
className="form-input"
value={values.kcal}
onChange={e => setValues({...values, kcal: e.target.value})}
placeholder="z.B. 2000"
disabled={loading}
style={{width:'100%'}}
/>
</div>
<div>
<label className="form-label">Protein (g)</label>
<input
type="number"
className="form-input"
value={values.protein_g}
onChange={e => setValues({...values, protein_g: e.target.value})}
placeholder="z.B. 150"
disabled={loading}
style={{width:'100%'}}
/>
</div>
<div>
<label className="form-label">Fett (g)</label>
<input
type="number"
className="form-input"
value={values.fat_g}
onChange={e => setValues({...values, fat_g: e.target.value})}
placeholder="z.B. 80"
disabled={loading}
style={{width:'100%'}}
/>
</div>
<div>
<label className="form-label">Kohlenhydrate (g)</label>
<input
type="number"
className="form-input"
value={values.carbs_g}
onChange={e => setValues({...values, carbs_g: e.target.value})}
placeholder="z.B. 200"
disabled={loading}
style={{width:'100%'}}
/>
</div>
</div>
<button
className="btn btn-primary btn-full"
onClick={handleSave}
disabled={saving || loading || !date || !values.kcal}>
{saving ? (
<><div className="spinner" style={{width:14,height:14}}/> Speichere…</>
) : existingId ? (
'📝 Eintrag aktualisieren'
) : (
'➕ Eintrag hinzufügen'
)}
</button>
</div>
)
}
// ── Data Tab (Editable Entry List) ───────────────────────────────────────────
function DataTab({ entries, onUpdate }) {
const [editId, setEditId] = useState(null)
const [editValues, setEditValues] = useState({})
const [saving, setSaving] = useState(false)
const [error, setError] = useState(null)
const [filter, setFilter] = useState('30') // days to show (7, 30, 90, 'all')
const startEdit = (e) => {
setEditId(e.id)
setEditValues({
kcal: e.kcal || 0,
protein_g: e.protein_g || 0,
fat_g: e.fat_g || 0,
carbs_g: e.carbs_g || 0
})
}
const cancelEdit = () => {
setEditId(null)
setEditValues({})
setError(null)
}
const saveEdit = async (id) => {
setSaving(true)
setError(null)
try {
await nutritionApi.updateNutrition(
id,
editValues.kcal,
editValues.protein_g,
editValues.fat_g,
editValues.carbs_g
)
setEditId(null)
setEditValues({})
onUpdate()
} catch(e) {
setError('Speichern fehlgeschlagen: ' + e.message)
} finally {
setSaving(false)
}
}
const deleteEntry = async (id, date) => {
if (!confirm(`Eintrag vom ${dayjs(date).format('DD.MM.YYYY')} wirklich löschen?`)) return
try {
await nutritionApi.deleteNutrition(id)
onUpdate()
} catch(e) {
setError('Löschen fehlgeschlagen: ' + e.message)
}
}
// Filter entries by date range
const filteredEntries = filter === 'all'
? entries
: entries.filter(e => {
const daysDiff = dayjs().diff(dayjs(e.date), 'day')
return daysDiff <= parseInt(filter)
})
if (entries.length === 0) {
return (
<div className="card section-gap">
<div className="card-title">Alle Einträge (0)</div>
<p className="muted">Noch keine Ernährungsdaten. Importiere FDDB CSV oben.</p>
</div>
)
}
return (
<div className="card section-gap">
<div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:16}}>
<div className="card-title" style={{margin:0}}>
Alle Einträge ({filteredEntries.length}{filteredEntries.length !== entries.length ? ` von ${entries.length}` : ''})
</div>
<select
value={filter}
onChange={e => setFilter(e.target.value)}
style={{
padding:'6px 10px',fontSize:12,borderRadius:8,border:'1.5px solid var(--border2)',
background:'var(--surface)',color:'var(--text2)',cursor:'pointer',fontFamily:'var(--font)'
}}>
<option value="7">Letzte 7 Tage</option>
<option value="30">Letzte 30 Tage</option>
<option value="90">Letzte 90 Tage</option>
<option value="365">Letztes Jahr</option>
<option value="all">Alle anzeigen</option>
</select>
</div>
{error && (
<div style={{padding:'8px 12px',background:'#FCEBEB',borderRadius:8,fontSize:13,color:'#D85A30',marginBottom:12}}>
{error}
</div>
)}
{filteredEntries.map((e, i) => {
const isEditing = editId === e.id
return (
<div key={e.id || i} style={{
borderBottom: i < filteredEntries.length - 1 ? '1px solid var(--border)' : 'none',
padding: '12px 0'
}}>
{!isEditing ? (
<>
<div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:6}}>
<strong style={{fontSize:14}}>{dayjs(e.date).format('dd, DD. MMMM YYYY')}</strong>
<div style={{display:'flex',gap:6}}>
<button onClick={() => startEdit(e)}
style={{padding:'4px 10px',fontSize:11,borderRadius:6,border:'1px solid var(--border2)',
background:'var(--surface)',color:'var(--text2)',cursor:'pointer'}}>
✏️ Bearbeiten
</button>
<button onClick={() => deleteEntry(e.id, e.date)}
style={{padding:'4px 10px',fontSize:11,borderRadius:6,border:'1px solid #D85A30',
background:'#FCEBEB',color:'#D85A30',cursor:'pointer'}}>
🗑️
</button>
</div>
</div>
<div style={{fontSize:13, fontWeight:600, color:'#EF9F27',marginBottom:6}}>
{Math.round(e.kcal || 0)} kcal
</div>
<div style={{display:'flex', gap:12, fontSize:12, color:'var(--text2)'}}>
<span>🥩 Protein: <strong>{Math.round(e.protein_g || 0)}g</strong></span>
<span>🫙 Fett: <strong>{Math.round(e.fat_g || 0)}g</strong></span>
<span>🍞 Kohlenhydrate: <strong>{Math.round(e.carbs_g || 0)}g</strong></span>
</div>
{e.source && (
<div style={{fontSize:10, color:'var(--text3)', marginTop:4}}>
Quelle: {e.source}
</div>
)}
</>
) : (
<>
<div style={{marginBottom:8}}>
<strong style={{fontSize:14}}>{dayjs(e.date).format('dd, DD. MMMM YYYY')}</strong>
</div>
<div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8,marginBottom:10}}>
<div>
<label style={{fontSize:11,color:'var(--text3)',display:'block',marginBottom:4}}>Kalorien</label>
<input type="number" className="form-input" value={editValues.kcal}
onChange={e => setEditValues({...editValues, kcal: parseFloat(e.target.value)||0})}
style={{width:'100%'}}/>
</div>
<div>
<label style={{fontSize:11,color:'var(--text3)',display:'block',marginBottom:4}}>Protein (g)</label>
<input type="number" className="form-input" value={editValues.protein_g}
onChange={e => setEditValues({...editValues, protein_g: parseFloat(e.target.value)||0})}
style={{width:'100%'}}/>
</div>
<div>
<label style={{fontSize:11,color:'var(--text3)',display:'block',marginBottom:4}}>Fett (g)</label>
<input type="number" className="form-input" value={editValues.fat_g}
onChange={e => setEditValues({...editValues, fat_g: parseFloat(e.target.value)||0})}
style={{width:'100%'}}/>
</div>
<div>
<label style={{fontSize:11,color:'var(--text3)',display:'block',marginBottom:4}}>Kohlenhydrate (g)</label>
<input type="number" className="form-input" value={editValues.carbs_g}
onChange={e => setEditValues({...editValues, carbs_g: parseFloat(e.target.value)||0})}
style={{width:'100%'}}/>
</div>
</div>
<div style={{display:'flex',gap:8}}>
<button onClick={() => saveEdit(e.id)} disabled={saving}
className="btn btn-primary" style={{flex:1}}>
{saving ? 'Speichere…' : '✓ Speichern'}
</button>
<button onClick={cancelEdit} disabled={saving}
className="btn btn-secondary" style={{flex:1}}>
Abbrechen
</button>
</div>
</>
)}
</div>
)
})}
</div>
)
}
// ── Import History ────────────────────────────────────────────────────────────
function ImportHistory() {
const [history, setHistory] = useState([])
const [loading, setLoading] = useState(true)
useEffect(() => {
const load = async () => {
try {
const data = await nutritionApi.nutritionImportHistory()
setHistory(Array.isArray(data) ? data : [])
} catch(e) {
console.error('Failed to load import history:', e)
} finally {
setLoading(false)
}
}
load()
}, [])
if (loading) return null
if (!history.length) return null
return (
<div className="card section-gap">
<div className="card-title">Import-Historie</div>
<div style={{display:'flex',flexDirection:'column',gap:8}}>
{history.map((h, i) => (
<div key={i} style={{
padding: '10px 12px',
background: 'var(--surface2)',
borderRadius: 8,
borderLeft: '3px solid var(--accent)',
fontSize: 13
}}>
<div style={{display:'flex',justifyContent:'space-between',marginBottom:4}}>
<strong>{dayjs(h.import_date).format('DD.MM.YYYY')}</strong>
<span style={{color:'var(--text3)',fontSize:11}}>
{dayjs(h.last_created).format('HH:mm')} Uhr
</span>
</div>
<div style={{color:'var(--text2)',fontSize:12}}>
<span>{h.count} {h.count === 1 ? 'Eintrag' : 'Einträge'}</span>
{h.date_from && h.date_to && (
<span style={{marginLeft:8,color:'var(--text3)'}}>
({dayjs(h.date_from).format('DD.MM.YY')} – {dayjs(h.date_to).format('DD.MM.YY')})
</span>
)}
</div>
</div>
))}
</div>
</div>
)
}
// ── Import Panel ──────────────────────────────────────────────────────────────
function ImportPanel({ onImported }) {
const fileRef = useRef()
@@ -185,26 +598,62 @@ function OverviewCards({ data }) {
// ── Chart: Kalorien vs Gewicht ────────────────────────────────────────────────
function CaloriesVsWeight({ data }) {
const filtered = data.filter(d => d.kcal && d.weight)
const withAvg = rollingAvg(filtered.map(d=>({...d,date:dayjs(d.date).format('DD.MM')})), 'kcal')
// BUG-003 fix: Show all weight data, extrapolate kcal if missing
const filtered = data.filter(d => d.kcal || d.weight)
if (filtered.length < 3) return (
<div style={{padding:20,textAlign:'center',color:'var(--text3)',fontSize:13}}>
Zu wenig gemeinsame Daten (Gewicht + Kalorien am selben Tag nötig)
Zu wenig Daten für diese Auswertung
</div>
)
// Find last real kcal value
const lastKcalIndex = filtered.findLastIndex(d => d.kcal)
const lastKcal = lastKcalIndex >= 0 ? filtered[lastKcalIndex].kcal : null
// Extrapolate missing kcal values at the end
const withExtrapolated = filtered.map((d, i) => ({
...d,
kcal: d.kcal || (i > lastKcalIndex && lastKcal ? lastKcal : null),
isKcalExtrapolated: !d.kcal && i > lastKcalIndex && lastKcal
}))
// Format dates and calculate rolling average
const formatted = withExtrapolated.map(d => ({
...d,
date: dayjs(d.date).format('DD.MM')
}))
const withAvg = rollingAvg(formatted, 'kcal')
// Split into real and extrapolated segments for dashed lines
const realData = withAvg.map(d => ({
...d,
kcal_extrap: d.isKcalExtrapolated ? d.kcal : null,
kcal_avg_extrap: d.isKcalExtrapolated ? d.kcal_avg : null,
kcal: d.isKcalExtrapolated ? null : d.kcal,
kcal_avg: d.isKcalExtrapolated ? null : d.kcal_avg
}))
return (
<ResponsiveContainer width="100%" height={220}>
<LineChart data={withAvg} margin={{top:4,right:8,bottom:0,left:-16}}>
<LineChart data={realData} margin={{top:4,right:8,bottom:0,left:-16}}>
<CartesianGrid stroke="var(--border)" strokeDasharray="3 3"/>
<XAxis dataKey="date" tick={{fontSize:9,fill:'var(--text3)'}} tickLine={false}
interval={Math.max(0,Math.floor(withAvg.length/6)-1)}/>
interval={Math.max(0,Math.floor(realData.length/6)-1)}/>
<YAxis yAxisId="kcal" tick={{fontSize:9,fill:'var(--text3)'}} tickLine={false} domain={['auto','auto']}/>
<YAxis yAxisId="weight" orientation="right" tick={{fontSize:9,fill:'var(--text3)'}} tickLine={false} domain={['auto','auto']}/>
<Tooltip contentStyle={{background:'var(--surface)',border:'1px solid var(--border)',borderRadius:8,fontSize:11}}
formatter={(v,n)=>[`${Math.round(v)} ${n==='weight'?'kg':'kcal'}`, n==='kcal_avg'?'Ø 7T Kalorien':n==='weight'?'Gewicht':'Kalorien']}/>
<Line yAxisId="kcal" type="monotone" dataKey="kcal" stroke="#EF9F2744" strokeWidth={1} dot={false}/>
<Line yAxisId="kcal" type="monotone" dataKey="kcal_avg" stroke="#EF9F27" strokeWidth={2} dot={false} name="kcal_avg"/>
<Line yAxisId="weight" type="monotone" dataKey="weight" stroke="#378ADD" strokeWidth={2} dot={{r:3,fill:'#378ADD'}} name="weight"/>
formatter={(v,n)=>[`${Math.round(v)} ${n==='weight'?'kg':'kcal'}`, n.includes('avg')?'Ø 7T Kalorien':n==='weight'?'Gewicht':'Kalorien']}/>
{/* Real kcal values - solid lines */}
<Line yAxisId="kcal" type="monotone" dataKey="kcal" stroke="#EF9F2744" strokeWidth={1} dot={false} connectNulls={false}/>
<Line yAxisId="kcal" type="monotone" dataKey="kcal_avg" stroke="#EF9F27" strokeWidth={2} dot={false} name="kcal_avg" connectNulls={false}/>
{/* Extrapolated kcal values - dashed lines */}
<Line yAxisId="kcal" type="monotone" dataKey="kcal_extrap" stroke="#EF9F2744" strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false}/>
<Line yAxisId="kcal" type="monotone" dataKey="kcal_avg_extrap" stroke="#EF9F27" strokeWidth={2} strokeDasharray="3 3" dot={false} connectNulls={false}/>
{/* Weight - always solid */}
<Line yAxisId="weight" type="monotone" dataKey="weight" stroke="#378ADD" strokeWidth={2} dot={{r:3,fill:'#378ADD'}} name="weight" connectNulls={true}/>
</LineChart>
</ResponsiveContainer>
)
@@ -322,23 +771,28 @@ function CalorieBalance({ data, profile }) {
// ── Main Page ─────────────────────────────────────────────────────────────────
export default function NutritionPage() {
const [tab, setTab] = useState('overview')
const [inputTab, setInputTab] = useState('entry') // 'entry' or 'import'
const [analysisTab,setAnalysisTab] = useState('data')
const [corrData, setCorr] = useState([])
const [weekly, setWeekly] = useState([])
const [entries, setEntries]= useState([])
const [profile, setProf] = useState(null)
const [loading, setLoad] = useState(true)
const [hasData, setHasData]= useState(false)
const [importHistoryKey, setImportHistoryKey] = useState(Date.now()) // BUG-004 fix
const load = async () => {
setLoad(true)
try {
const [corr, wkly, prof] = await Promise.all([
const [corr, wkly, ent, prof] = await Promise.all([
nutritionApi.nutritionCorrelations(),
nutritionApi.nutritionWeekly(16),
api.getActiveProfile(),
nutritionApi.listNutrition(365), // BUG-002 fix: load raw entries
nutritionApi.getActiveProfile(),
])
setCorr(Array.isArray(corr)?corr:[])
setWeekly(Array.isArray(wkly)?wkly:[])
setEntries(Array.isArray(ent)?ent:[]) // BUG-002 fix
setProf(prof)
setHasData(Array.isArray(corr) && corr.some(d=>d.kcal))
} catch(e) { console.error('load error:', e) }
@@ -351,29 +805,52 @@ export default function NutritionPage() {
<div>
<h1 className="page-title">Ernährung</h1>
<ImportPanel onImported={load}/>
{/* Input Method Tabs */}
<div className="tabs section-gap" style={{marginBottom:0}}>
<button className={'tab'+(inputTab==='entry'?' active':'')} onClick={()=>setInputTab('entry')}>
✏️ Einzelerfassung
</button>
<button className={'tab'+(inputTab==='import'?' active':'')} onClick={()=>setInputTab('import')}>
📥 Import
</button>
</div>
{/* Entry Form */}
{inputTab==='entry' && <EntryForm onSaved={load}/>}
{/* Import Panel + History */}
{inputTab==='import' && (
<>
<ImportPanel onImported={() => { load(); setImportHistoryKey(Date.now()) }}/>
<ImportHistory key={importHistoryKey}/>
</>
)}
{loading && <div className="empty-state"><div className="spinner"/></div>}
{!loading && !hasData && (
<div className="empty-state">
<h3>Noch keine Ernährungsdaten</h3>
<p>Importiere deinen FDDB-Export oben um Auswertungen zu sehen.</p>
<p>Erfasse Daten über Einzelerfassung oder importiere deinen FDDB-Export.</p>
</div>
)}
{/* Analysis Section */}
{!loading && hasData && (
<>
<OverviewCards data={corrData}/>
<div className="tabs section-gap" style={{overflowX:'auto',flexWrap:'nowrap'}}>
<button className={'tab'+(tab==='overview'?' active':'')} onClick={()=>setTab('overview')}>Übersicht</button>
<button className={'tab'+(tab==='weight'?' active':'')} onClick={()=>setTab('weight')}>Kcal vs. Gewicht</button>
<button className={'tab'+(tab==='protein'?' active':'')} onClick={()=>setTab('protein')}>Protein vs. Mager</button>
<button className={'tab'+(tab==='balance'?' active':'')} onClick={()=>setTab('balance')}>Bilanz</button>
<button className={'tab'+(analysisTab==='data'?' active':'')} onClick={()=>setAnalysisTab('data')}>Daten</button>
<button className={'tab'+(analysisTab==='overview'?' active':'')} onClick={()=>setAnalysisTab('overview')}>Übersicht</button>
<button className={'tab'+(analysisTab==='weight'?' active':'')} onClick={()=>setAnalysisTab('weight')}>Kcal vs. Gewicht</button>
<button className={'tab'+(analysisTab==='protein'?' active':'')} onClick={()=>setAnalysisTab('protein')}>Protein vs. Mager</button>
<button className={'tab'+(analysisTab==='balance'?' active':'')} onClick={()=>setAnalysisTab('balance')}>Bilanz</button>
</div>
{tab==='overview' && (
{analysisTab==='data' && <DataTab entries={entries} onUpdate={load}/>}
{analysisTab==='overview' && (
<div className="card section-gap">
<div className="card-title">Makro-Verteilung pro Woche (Ø g/Tag)</div>
<WeeklyMacros weekly={weekly}/>
@@ -385,7 +862,7 @@ export default function NutritionPage() {
</div>
)}
{tab==='weight' && (
{analysisTab==='weight' && (
<div className="card section-gap">
<div className="card-title">Kalorien vs. Gewichtsverlauf</div>
<div style={{fontSize:11,color:'var(--text3)',marginBottom:8}}>
@@ -401,7 +878,7 @@ export default function NutritionPage() {
</div>
)}
{tab==='protein' && (
{analysisTab==='protein' && (
<div className="card section-gap">
<div className="card-title">Protein vs. Magermasse</div>
<div style={{fontSize:11,color:'var(--text3)',marginBottom:8}}>
@@ -417,7 +894,7 @@ export default function NutritionPage() {
</div>
)}
{tab==='balance' && (
{analysisTab==='balance' && (
<div className="card section-gap">
<div className="card-title">Kaloriendefizit / -überschuss</div>
<CalorieBalance data={corrData} profile={profile}/>
+182
View File
@@ -0,0 +1,182 @@
import { useState } from 'react'
import { Link } from 'react-router-dom'
import { api } from '../utils/api'
export default function Register() {
const [name, setName] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [passwordConfirm, setPasswordConfirm] = useState('')
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
const [success, setSuccess] = useState(false)
const handleSubmit = async (e) => {
e.preventDefault()
setError(null)
// Validation
if (!name || name.length < 2) {
setError('Name muss mindestens 2 Zeichen lang sein')
return
}
if (!email || !email.includes('@')) {
setError('Ungültige E-Mail-Adresse')
return
}
if (password.length < 8) {
setError('Passwort muss mindestens 8 Zeichen lang sein')
return
}
if (password !== passwordConfirm) {
setError('Passwörter stimmen nicht überein')
return
}
setLoading(true)
try {
await api.register(name, email, password)
setSuccess(true)
} catch (err) {
setError(err.message || 'Registrierung fehlgeschlagen')
} finally {
setLoading(false)
}
}
if (success) {
return (
<div style={{
maxWidth:420, margin:'0 auto', padding:'60px 20px',
textAlign:'center'
}}>
<div style={{
background:'var(--accent-light)',
border:'2px solid var(--accent)',
borderRadius:16, padding:'40px 24px', marginBottom:24
}}>
<div style={{fontSize:48, marginBottom:16}}>✓</div>
<h2 style={{marginBottom:12, color:'var(--accent-dark)'}}>
Registrierung erfolgreich!
</h2>
<p style={{color:'var(--text2)', lineHeight:1.6}}>
Wir haben dir eine E-Mail mit einem Bestätigungslink gesendet.
Bitte prüfe dein Postfach und bestätige deine E-Mail-Adresse.
</p>
</div>
<Link to="/login" className="btn btn-primary btn-full">
Zum Login
</Link>
<p style={{fontSize:12, color:'var(--text3)', marginTop:20}}>
Keine E-Mail erhalten? Prüfe auch deinen Spam-Ordner.
</p>
</div>
)
}
return (
<div style={{maxWidth:420, margin:'0 auto', padding:'40px 20px'}}>
<h1 style={{textAlign:'center', marginBottom:8}}>Registrierung</h1>
<p style={{textAlign:'center', color:'var(--text2)', marginBottom:32}}>
Erstelle deinen Mitai Jinkendo Account
</p>
<form onSubmit={handleSubmit} className="card" style={{padding:24}}>
{error && (
<div style={{
padding:'12px 16px', background:'#FCEBEB',
border:'1px solid #D85A30', borderRadius:8,
color:'#D85A30', fontSize:14, marginBottom:20
}}>
{error}
</div>
)}
<div className="form-row">
<label className="form-label">Name *</label>
<input
type="text"
className="form-input"
value={name}
onChange={e => setName(e.target.value)}
placeholder="Dein Name"
disabled={loading}
required
/>
</div>
<div className="form-row">
<label className="form-label">E-Mail *</label>
<input
type="email"
className="form-input"
value={email}
onChange={e => setEmail(e.target.value)}
placeholder="deine@email.de"
disabled={loading}
required
/>
</div>
<div className="form-row">
<label className="form-label">Passwort *</label>
<input
type="password"
className="form-input"
value={password}
onChange={e => setPassword(e.target.value)}
placeholder="Mindestens 8 Zeichen"
disabled={loading}
required
/>
</div>
<div className="form-row">
<label className="form-label">Passwort bestätigen *</label>
<input
type="password"
className="form-input"
value={passwordConfirm}
onChange={e => setPasswordConfirm(e.target.value)}
placeholder="Passwort wiederholen"
disabled={loading}
required
/>
</div>
<button
type="submit"
className="btn btn-primary btn-full"
disabled={loading}
style={{marginTop:8}}
>
{loading ? 'Registriere...' : 'Registrieren'}
</button>
<div style={{
textAlign:'center', marginTop:24,
paddingTop:20, borderTop:'1px solid var(--border)'
}}>
<span style={{color:'var(--text2)', fontSize:14}}>
Bereits registriert?{' '}
</span>
<Link to="/login" style={{
color:'var(--accent)', fontWeight:600, fontSize:14
}}>
Zum Login
</Link>
</div>
</form>
<p style={{
fontSize:11, color:'var(--text3)', textAlign:'center',
marginTop:20, lineHeight:1.6
}}>
Mit der Registrierung akzeptierst du unsere Nutzungsbedingungen
und Datenschutzerklärung.
</p>
</div>
)
}
+38 -6
View File
@@ -1,10 +1,12 @@
import { useState } from 'react'
import { Save, Download, Upload, Trash2, Plus, Check, Pencil, X, LogOut, Shield, Key } from 'lucide-react'
import { useState, useEffect } from 'react'
import { Save, Download, Upload, Trash2, Plus, Check, Pencil, X, LogOut, Shield, Key, BarChart3 } from 'lucide-react'
import { useProfile } from '../context/ProfileContext'
import { useAuth } from '../context/AuthContext'
import { Avatar } from './ProfileSelect'
import { api } from '../utils/api'
import AdminPanel from './AdminPanel'
import FeatureUsageOverview from '../components/FeatureUsageOverview'
import UsageBadge from '../components/UsageBadge'
const COLORS = ['#1D9E75','#378ADD','#D85A30','#EF9F27','#7F77DD','#D4537E','#639922','#888780']
@@ -99,6 +101,15 @@ export default function SettingsPage() {
const [pinOpen, setPinOpen] = useState(false)
const [newPin, setNewPin] = useState('')
const [pinMsg, setPinMsg] = useState(null)
const [exportUsage, setExportUsage] = useState(null) // Phase 3: Usage badge
// Load feature usage for export badges
useEffect(() => {
api.getFeatureUsage().then(features => {
const exportFeature = features.find(f => f.feature_id === 'data_export')
setExportUsage(exportFeature)
}).catch(err => console.error('Failed to load usage:', err))
}, [])
const handleLogout = async () => {
if (!confirm('Ausloggen?')) return
@@ -326,6 +337,17 @@ export default function SettingsPage() {
</div>
</div>
{/* Feature Usage Overview (Phase 3) */}
<div className="card section-gap">
<div className="card-title" style={{display:'flex',alignItems:'center',gap:6}}>
<BarChart3 size={15} color="var(--accent)"/> Kontingente
</div>
<p style={{fontSize:13,color:'var(--text2)',marginBottom:12,lineHeight:1.6}}>
Übersicht über deine Feature-Nutzung und verfügbare Kontingente.
</p>
<FeatureUsageOverview />
</div>
{/* Admin Panel */}
{isAdmin && (
<div className="card section-gap">
@@ -359,13 +381,23 @@ export default function SettingsPage() {
{canExport && <>
<button className="btn btn-primary btn-full"
onClick={()=>api.exportZip()}>
<Download size={14}/> ZIP exportieren
<span style={{fontSize:11,opacity:0.8,marginLeft:6}}>— je eine CSV pro Kategorie</span>
<div className="badge-button-layout">
<div className="badge-button-header">
<span><Download size={14}/> ZIP exportieren</span>
{exportUsage && <UsageBadge {...exportUsage} />}
</div>
<span className="badge-button-description">je eine CSV pro Kategorie</span>
</div>
</button>
<button className="btn btn-secondary btn-full"
onClick={()=>api.exportJson()}>
<Download size={14}/> JSON exportieren
<span style={{fontSize:11,opacity:0.8,marginLeft:6}}>— maschinenlesbar, alles in einer Datei</span>
<div className="badge-button-layout">
<div className="badge-button-header">
<span><Download size={14}/> JSON exportieren</span>
{exportUsage && <UsageBadge {...exportUsage} />}
</div>
<span className="badge-button-description">maschinenlesbar, alles in einer Datei</span>
</div>
</button>
</>}
</div>
+241
View File
@@ -0,0 +1,241 @@
import { useState, useEffect } from 'react'
import { Gift, AlertCircle, TrendingUp, Award } from 'lucide-react'
import { api } from '../utils/api'
export default function SubscriptionPage() {
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [subscription, setSubscription] = useState(null)
const [usage, setUsage] = useState([])
const [limits, setLimits] = useState([])
const [couponCode, setCouponCode] = useState('')
const [redeeming, setRedeeming] = useState(false)
const [couponSuccess, setCouponSuccess] = useState('')
useEffect(() => {
loadData()
}, [])
async function loadData() {
try {
setLoading(true)
const [subData, usageData, limitsData] = await Promise.all([
api.getMySubscription(),
api.getMyUsage(),
api.getMyLimits()
])
setSubscription(subData)
setUsage(usageData)
setLimits(limitsData)
setError('')
} catch (e) {
setError(e.message)
} finally {
setLoading(false)
}
}
async function handleRedeemCoupon() {
if (!couponCode.trim()) return
try {
setRedeeming(true)
setError('')
setCouponSuccess('')
await api.redeemCoupon(couponCode.trim().toUpperCase())
setCouponSuccess('Coupon erfolgreich eingelöst!')
setCouponCode('')
await loadData()
} catch (e) {
setError(e.message)
} finally {
setRedeeming(false)
}
}
if (loading) return (
<div style={{ display: 'flex', justifyContent: 'center', padding: 40 }}>
<div className="spinner" />
</div>
)
const tierColors = {
free: { bg: 'var(--surface2)', color: 'var(--text2)', icon: '🆓' },
basic: { bg: '#E3F2FD', color: '#1565C0', icon: '⭐' },
premium: { bg: '#F3E5F5', color: '#6A1B9A', icon: '👑' },
selfhosted: { bg: 'var(--accent-light)', color: 'var(--accent-dark)', icon: '🏠' }
}
const currentTier = subscription?.current_tier || 'free'
const tierStyle = tierColors[currentTier] || tierColors.free
return (
<div style={{ paddingBottom: 40 }}>
{/* Header */}
<div style={{ marginBottom: 20 }}>
<div style={{ fontSize: 20, fontWeight: 700, color: 'var(--text1)' }}>
Mein Abo
</div>
<div style={{ fontSize: 13, color: 'var(--text3)', marginTop: 4 }}>
Tier, Limits und Nutzung
</div>
</div>
{/* Messages */}
{error && (
<div style={{
padding: 12, background: 'var(--danger)', color: 'white',
borderRadius: 8, marginBottom: 16, fontSize: 14
}}>
{error}
</div>
)}
{couponSuccess && (
<div style={{
padding: 12, background: 'var(--accent)', color: 'white',
borderRadius: 8, marginBottom: 16, fontSize: 14
}}>
{couponSuccess}
</div>
)}
{/* Current Tier Card */}
<div className="card" style={{ padding: 20, marginBottom: 16 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
<div style={{
width: 48, height: 48, borderRadius: 12,
background: tierStyle.bg,
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 24
}}>
{tierStyle.icon}
</div>
<div style={{ flex: 1 }}>
<div style={{ fontSize: 12, color: 'var(--text3)', textTransform: 'uppercase', fontWeight: 600 }}>
Aktueller Tier
</div>
<div style={{ fontSize: 20, fontWeight: 700, color: tierStyle.color }}>
{currentTier.charAt(0).toUpperCase() + currentTier.slice(1)}
</div>
</div>
</div>
{subscription?.trial_ends_at && new Date(subscription.trial_ends_at) > new Date() && (
<div style={{
padding: 10, background: '#FFF3CD', borderRadius: 8,
fontSize: 13, color: '#856404', display: 'flex', gap: 8, alignItems: 'center'
}}>
<AlertCircle size={16} />
<div>
<strong>Trial aktiv:</strong> Endet am {new Date(subscription.trial_ends_at).toLocaleDateString('de-DE')}
</div>
</div>
)}
{subscription?.access_until && (
<div style={{
padding: 10, background: 'var(--accent-light)', borderRadius: 8,
fontSize: 13, color: 'var(--accent-dark)', display: 'flex', gap: 8, alignItems: 'center',
marginTop: 12
}}>
<Award size={16} />
<div>
<strong>Zugriff bis:</strong> {new Date(subscription.access_until).toLocaleDateString('de-DE')}
</div>
</div>
)}
</div>
{/* Feature Limits */}
<div className="card" style={{ padding: 20, marginBottom: 16 }}>
<div style={{
fontSize: 14, fontWeight: 600, marginBottom: 12,
display: 'flex', alignItems: 'center', gap: 6
}}>
<TrendingUp size={16} color="var(--accent)" />
Feature-Limits & Nutzung
</div>
{limits.length === 0 ? (
<div style={{ textAlign: 'center', padding: 20, color: 'var(--text3)', fontSize: 13 }}>
Keine Limits konfiguriert
</div>
) : (
<div style={{ display: 'grid', gap: 12 }}>
{limits.map(limit => {
const usageEntry = usage.find(u => u.feature_id === limit.feature_id)
const used = usageEntry?.usage_count || 0
const limitValue = limit.limit_value
const percentage = limitValue ? Math.min((used / limitValue) * 100, 100) : 0
return (
<div key={limit.feature_id} style={{
padding: 12, background: 'var(--surface)', borderRadius: 8
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
<div style={{ fontWeight: 500, fontSize: 13 }}>{limit.feature_name}</div>
<div style={{ fontSize: 13, color: 'var(--text3)' }}>
{used} / {limitValue === null ? '∞' : limitValue}
</div>
</div>
{limitValue !== null && (
<div style={{
height: 6, background: 'var(--border)', borderRadius: 3, overflow: 'hidden'
}}>
<div style={{
width: `${percentage}%`,
height: '100%',
background: percentage > 90 ? 'var(--danger)' : percentage > 70 ? '#FFA726' : 'var(--accent)',
transition: 'width 0.3s'
}} />
</div>
)}
{limit.reset_period !== 'never' && (
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 4 }}>
Reset: {limit.reset_period === 'daily' ? 'Täglich' : 'Monatlich'}
</div>
)}
</div>
)
})}
</div>
)}
</div>
{/* Coupon Redemption */}
<div className="card" style={{ padding: 20 }}>
<div style={{
fontSize: 14, fontWeight: 600, marginBottom: 12,
display: 'flex', alignItems: 'center', gap: 6
}}>
<Gift size={16} color="var(--accent)" />
Coupon einlösen
</div>
<div style={{ fontSize: 12, color: 'var(--text3)', marginBottom: 12 }}>
Hast du einen Coupon-Code? Löse ihn hier ein um Zugriff auf Premium-Features zu erhalten.
</div>
<div style={{ display: 'flex', gap: 8 }}>
<input
className="form-input"
style={{ flex: 1, textTransform: 'uppercase', fontFamily: 'monospace' }}
value={couponCode}
onChange={(e) => setCouponCode(e.target.value)}
placeholder="Z.B. PROMO-2026"
onKeyPress={(e) => e.key === 'Enter' && handleRedeemCoupon()}
/>
<button
className="btn btn-primary"
onClick={handleRedeemCoupon}
disabled={!couponCode.trim() || redeeming}
>
{redeeming ? 'Prüfen...' : 'Einlösen'}
</button>
</div>
</div>
</div>
)
}
+115
View File
@@ -0,0 +1,115 @@
import { useState, useEffect, useContext } from 'react'
import { useSearchParams, useNavigate } from 'react-router-dom'
import { AuthContext } from '../context/AuthContext'
import { api } from '../utils/api'
export default function Verify() {
const [searchParams] = useSearchParams()
const token = searchParams.get('token')
const navigate = useNavigate()
const { login } = useContext(AuthContext)
const [status, setStatus] = useState('loading') // loading | success | error
const [error, setError] = useState(null)
useEffect(() => {
const verify = async () => {
if (!token) {
setStatus('error')
setError('Kein Verifikations-Token gefunden')
return
}
try {
const result = await api.verifyEmail(token)
// Auto-login with returned token
if (result.token) {
login(result.token, result.profile)
setStatus('success')
// Redirect to dashboard after 2 seconds
setTimeout(() => {
navigate('/dashboard')
}, 2000)
} else {
setStatus('error')
setError('Verifizierung erfolgreich, aber Login fehlgeschlagen')
}
} catch (err) {
setStatus('error')
setError(err.message || 'Verifizierung fehlgeschlagen')
}
}
verify()
}, [token, login, navigate])
if (status === 'loading') {
return (
<div style={{
maxWidth:420, margin:'0 auto', padding:'60px 20px',
textAlign:'center'
}}>
<div className="spinner" style={{width:48, height:48, margin:'0 auto 24px'}}/>
<h2>E-Mail wird bestätigt...</h2>
<p style={{color:'var(--text2)'}}>Einen Moment bitte</p>
</div>
)
}
if (status === 'error') {
return (
<div style={{
maxWidth:420, margin:'0 auto', padding:'60px 20px',
textAlign:'center'
}}>
<div style={{
background:'#FCEBEB',
border:'2px solid #D85A30',
borderRadius:16, padding:'40px 24px', marginBottom:24
}}>
<div style={{fontSize:48, marginBottom:16}}>✗</div>
<h2 style={{marginBottom:12, color:'#D85A30'}}>
Verifizierung fehlgeschlagen
</h2>
<p style={{color:'var(--text2)', lineHeight:1.6}}>
{error}
</p>
</div>
<button
onClick={() => navigate('/register')}
className="btn btn-primary btn-full"
>
Zur Registrierung
</button>
</div>
)
}
// Success
return (
<div style={{
maxWidth:420, margin:'0 auto', padding:'60px 20px',
textAlign:'center'
}}>
<div style={{
background:'var(--accent-light)',
border:'2px solid var(--accent)',
borderRadius:16, padding:'40px 24px', marginBottom:24
}}>
<div style={{fontSize:48, marginBottom:16}}>✓</div>
<h2 style={{marginBottom:12, color:'var(--accent-dark)'}}>
E-Mail bestätigt!
</h2>
<p style={{color:'var(--text2)', lineHeight:1.6}}>
Dein Account wurde erfolgreich aktiviert.
Du wirst gleich zum Dashboard weitergeleitet...
</p>
</div>
<div className="spinner" style={{width:32, height:32, margin:'0 auto'}}/>
</div>
)
}
+52 -9
View File
@@ -2,6 +2,7 @@ import { useState, useEffect, useRef } from 'react'
import { Pencil, Trash2, Check, X } from 'lucide-react'
import { api } from '../utils/api'
import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid, ReferenceLine } from 'recharts'
import UsageBadge from '../components/UsageBadge'
import dayjs from 'dayjs'
import 'dayjs/locale/de'
dayjs.locale('de')
@@ -21,19 +22,42 @@ export default function WeightScreen() {
const [newNote, setNewNote] = useState('')
const [saving, setSaving] = useState(false)
const [saved, setSaved] = useState(false)
const [error, setError] = useState(null)
const [weightUsage, setWeightUsage] = useState(null) // Phase 3: Usage badge
const load = () => api.listWeight(365).then(data => setEntries(data))
useEffect(()=>{ load() },[])
const loadUsage = () => {
// Load feature usage for badge
api.getFeatureUsage().then(features => {
const weightFeature = features.find(f => f.feature_id === 'weight_entries')
setWeightUsage(weightFeature)
}).catch(err => console.error('Failed to load usage:', err))
}
useEffect(()=>{
load()
loadUsage()
},[])
const handleSave = async () => {
if (!newWeight) return
setSaving(true)
setError(null)
try {
await api.upsertWeight(newDate, parseFloat(newWeight), newNote)
setSaved(true); await load()
setSaved(true)
await load()
await loadUsage() // Reload usage after save
setTimeout(()=>setSaved(false), 2000)
setNewWeight(''); setNewNote('')
} finally { setSaving(false) }
} catch (err) {
console.error('Save failed:', err)
setError(err.message || 'Fehler beim Speichern')
setTimeout(()=>setError(null), 5000)
} finally {
setSaving(false)
}
}
const handleUpdate = async () => {
@@ -59,7 +83,10 @@ export default function WeightScreen() {
{/* Eingabe */}
<div className="card section-gap">
<div className="card-title">Eintrag hinzufügen</div>
<div className="card-title badge-container-right">
<span>Eintrag hinzufügen</span>
{weightUsage && <UsageBadge {...weightUsage} />}
</div>
<div className="form-row">
<label className="form-label">Datum</label>
<input type="date" className="form-input" style={{width:140}}
@@ -79,11 +106,27 @@ export default function WeightScreen() {
value={newNote} onChange={e=>setNewNote(e.target.value)}/>
<span className="form-unit"/>
</div>
<button className="btn btn-primary btn-full" onClick={handleSave} disabled={saving||!newWeight}>
{saved ? <><Check size={15}/> Gespeichert!</>
: saving ? <><div className="spinner" style={{width:14,height:14}}/> …</>
: 'Speichern'}
</button>
{error && (
<div style={{padding:'10px',background:'var(--danger-bg)',border:'1px solid var(--danger)',borderRadius:8,fontSize:13,color:'var(--danger)',marginBottom:12}}>
{error}
</div>
)}
<div
title={weightUsage && !weightUsage.allowed ? `Limit erreicht (${weightUsage.used}/${weightUsage.limit}). Kontaktiere den Admin oder warte bis zum nächsten Reset.` : ''}
style={{display:'inline-block',width:'100%'}}
>
<button
className="btn btn-primary btn-full"
onClick={handleSave}
disabled={saving || !newWeight || (weightUsage && !weightUsage.allowed)}
style={{cursor: (weightUsage && !weightUsage.allowed) ? 'not-allowed' : 'pointer'}}
>
{saved ? <><Check size={15}/> Gespeichert!</>
: saving ? <><div className="spinner" style={{width:14,height:14}}/> …</>
: (weightUsage && !weightUsage.allowed) ? '🔒 Limit erreicht'
: 'Speichern'}
</button>
</div>
</div>
{/* Chart */}
+51
View File
@@ -82,6 +82,11 @@ export const api = {
listNutrition: (l=365) => req(`/nutrition?limit=${l}`),
nutritionCorrelations: () => req('/nutrition/correlations'),
nutritionWeekly: (w=16) => req(`/nutrition/weekly?weeks=${w}`),
nutritionImportHistory: () => req('/nutrition/import-history'),
getNutritionByDate: (date) => req(`/nutrition/by-date/${date}`),
createNutrition: (date,kcal,protein,fat,carbs) => req(`/nutrition?date=${date}&kcal=${kcal}&protein_g=${protein}&fat_g=${fat}&carbs_g=${carbs}`,{method:'POST'}),
updateNutrition: (id,kcal,protein,fat,carbs) => req(`/nutrition/${id}?kcal=${kcal}&protein_g=${protein}&fat_g=${fat}&carbs_g=${carbs}`,{method:'PUT'}),
deleteNutrition: (id) => req(`/nutrition/${id}`,{method:'DELETE'}),
// Stats & AI
getStats: () => req('/stats'),
@@ -137,4 +142,50 @@ export const api = {
adminDeleteProfile: (id) => req(`/admin/profiles/${id}`,{method:'DELETE'}),
adminSetPermissions: (id,d) => req(`/admin/profiles/${id}/permissions`,jput(d)),
changePin: (pin) => req('/auth/pin',json({pin})),
register: (name,email,password) => req('/auth/register',json({name,email,password})),
verifyEmail: (token) => req(`/auth/verify/${token}`),
// v9c Subscription System
// User-facing
getMySubscription: () => req('/subscription/me'),
getMyUsage: () => req('/subscription/usage'),
getMyLimits: () => req('/subscription/limits'),
redeemCoupon: (code) => req('/coupons/redeem',json({code})),
getFeatureUsage: () => req('/features/usage'), // Phase 3: Usage overview
// Admin: Features
listFeatures: () => req('/features'),
createFeature: (d) => req('/features',json(d)),
updateFeature: (id,d) => req(`/features/${id}`,jput(d)),
deleteFeature: (id) => req(`/features/${id}`,{method:'DELETE'}),
// Admin: Tiers
listTiers: () => req('/tiers'),
createTier: (d) => req('/tiers',json(d)),
updateTier: (id,d) => req(`/tiers/${id}`,jput(d)),
deleteTier: (id) => req(`/tiers/${id}`,{method:'DELETE'}),
// Admin: Tier Limits (Matrix)
getTierLimitsMatrix: () => req('/tier-limits'),
updateTierLimit: (d) => req('/tier-limits',jput(d)),
updateTierLimitsBatch:(updates) => req('/tier-limits/batch',jput({updates})),
// Admin: User Restrictions
listUserRestrictions: (pid) => req(`/user-restrictions${pid?'?profile_id='+pid:''}`),
createUserRestriction:(d) => req('/user-restrictions',json(d)),
updateUserRestriction:(id,d) => req(`/user-restrictions/${id}`,jput(d)),
deleteUserRestriction:(id) => req(`/user-restrictions/${id}`,{method:'DELETE'}),
// Admin: Coupons
listCoupons: () => req('/coupons'),
createCoupon: (d) => req('/coupons',json(d)),
updateCoupon: (id,d) => req(`/coupons/${id}`,jput(d)),
deleteCoupon: (id) => req(`/coupons/${id}`,{method:'DELETE'}),
getCouponRedemptions: (id) => req(`/coupons/${id}/redemptions`),
// Admin: Access Grants
listAccessGrants: (pid,active)=> req(`/access-grants${pid?'?profile_id='+pid:''}${active?'&active_only=true':''}`),
createAccessGrant: (d) => req('/access-grants',json(d)),
updateAccessGrant: (id,d) => req(`/access-grants/${id}`,jput(d)),
revokeAccessGrant: (id) => req(`/access-grants/${id}`,{method:'DELETE'}),
}