Compare commits
183
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac4c6760d7 | ||
|
|
5796c6a21a | ||
|
|
302948a248 | ||
|
|
e3819327a9 | ||
|
|
04306a7fef | ||
|
|
b317246bcd | ||
|
|
848ba0a815 | ||
|
|
9ec774e956 | ||
|
|
9210d051a8 | ||
|
|
5a6a140dfd | ||
|
|
6f035e3706 | ||
|
|
6b64cf31c4 | ||
|
|
4b024e6d0f | ||
|
|
f506a55d7b | ||
|
|
6a7b78c3eb | ||
|
|
7dcab1d7a3 | ||
|
|
931012c16b | ||
|
|
10772d1f80 | ||
|
|
7f10286e02 | ||
|
|
1cc3b05705 | ||
|
|
1866ff9ce6 | ||
|
|
1619091640 | ||
|
|
37fd28ec5a | ||
|
|
bf87e03100 | ||
|
|
548a5a481d | ||
|
|
a55f11bc96 | ||
|
|
9634ca8909 | ||
|
|
4f53cfffab | ||
|
|
7433b19b7e | ||
|
|
4191c52298 | ||
|
|
5bd1b33f5a | ||
|
|
b73c77d811 | ||
|
|
65846042e2 | ||
|
|
2c73c3df52 | ||
|
|
4937ce4b05 | ||
|
|
d07baa260c | ||
|
|
33e27a4f3e | ||
|
|
41c7084159 | ||
|
|
6fa15f7f57 | ||
|
|
2abaac22cf | ||
|
|
1d252b5299 | ||
|
|
d7145874cf | ||
|
|
ca7d9b2e3f | ||
|
|
edd15dd556 | ||
|
|
e11953736d | ||
|
|
1b9cd6d5e6 | ||
|
|
03f4b871a9 | ||
|
|
29770503bf | ||
|
|
7a0b2097ae | ||
|
|
f87b93ce2f | ||
|
|
f2e2aff17f | ||
|
|
6916e5b808 | ||
|
|
7d627cf128 | ||
|
|
c265ab1245 | ||
|
|
b63d15fd02 | ||
|
|
0278a8e4a6 | ||
|
|
ef27660fc8 | ||
|
|
601fc80178 | ||
|
|
5adec042a4 | ||
|
|
9aeb0de936 | ||
|
|
b22481d4ce | ||
|
|
1644b34d5c | ||
|
|
b52c877367 | ||
|
|
da376a8b18 | ||
|
|
9a9c597187 | ||
|
|
b1a92c01fc | ||
|
|
b65efd3b71 | ||
|
|
9e4d6fa715 | ||
|
|
836bc4294b | ||
|
|
39d676e5c8 | ||
|
|
ef81c46bc0 | ||
|
|
40a4739349 | ||
|
|
3ff2a1bf45 | ||
|
|
3be82dc8c2 | ||
|
|
829edecbdc | ||
|
|
a4bd738e6f | ||
|
|
4d9ef5b33b | ||
|
|
d4826c8df4 | ||
|
|
967d92025c | ||
|
|
eecc00e824 | ||
|
|
d164ab932d | ||
|
|
96b0acacd2 | ||
|
|
08cead49fe | ||
|
|
df01ee3de3 | ||
|
|
410b2ce308 | ||
|
|
0aca5fda5d | ||
|
|
526da02512 | ||
|
|
51aa57f304 | ||
|
|
3dc3774d76 | ||
|
|
1cd93d521e | ||
|
|
1521c2f221 | ||
|
|
2e68b29d9c | ||
|
|
e62b05c224 | ||
|
|
ca9112ebc0 | ||
|
|
f843d71d6b | ||
|
|
9fb6e27256 | ||
|
|
49467ca6e9 | ||
|
|
913b485500 | ||
|
|
22651647cb | ||
|
|
9fa60434c1 | ||
|
|
514b68e34f | ||
|
|
961897ce2f | ||
|
|
86f7a513fe | ||
|
|
c1562a27f4 | ||
|
|
888b5c3e40 | ||
|
|
d1675dcc80 | ||
|
|
ca4411f30f | ||
|
|
770a49b5f3 | ||
|
|
b551365fb5 | ||
|
|
0ab13c282e | ||
|
|
1f1100c289 | ||
|
|
02ca9772d6 | ||
|
|
873f08042e | ||
|
|
0f072f4735 | ||
|
|
d833a60ad4 | ||
|
|
4d9c59ccf7 | ||
|
|
f2f089a223 | ||
|
|
fed51453e4 | ||
|
|
ed057fe545 | ||
|
|
4b8e6755dc | ||
|
|
d13c2c7e25 | ||
|
|
0f019f87a4 | ||
|
|
cf522190c6 | ||
|
|
329daaef1c | ||
|
|
cbcb6a2a34 | ||
|
|
baad096ead | ||
|
|
30df150b6f | ||
|
|
c59c71a1c7 | ||
|
|
405abc1973 | ||
|
|
d10f605d66 | ||
|
|
4e846605e9 | ||
|
|
32d53b447d | ||
|
|
1298bd235f | ||
|
|
ddcd2f4350 | ||
|
|
73bea5ee86 | ||
|
|
7040931816 | ||
|
|
ef8008a75d | ||
|
|
e4f49c0351 | ||
|
|
4fcde4abfb | ||
|
|
8415509f4c | ||
|
|
cd4d9124b0 | ||
|
|
cbad50a987 | ||
|
|
3745ebd6cd | ||
|
|
0210844522 | ||
|
|
5da18de708 | ||
|
|
4e592dddc5 | ||
|
|
adfa9ec139 | ||
|
|
85f5938d7d | ||
|
|
917c8937cf | ||
|
|
0c0b1ee811 | ||
|
|
a27f090616 | ||
|
|
3eae7eb43f | ||
|
|
b1a1925360 | ||
|
|
ac56974e83 | ||
|
|
5ef6a80a1f | ||
|
|
365fe3d068 | ||
|
|
72d8dd8df7 | ||
|
|
18991025bf | ||
|
|
bc4db19190 | ||
|
|
69b6f38c89 | ||
|
|
07a802dff6 | ||
|
|
7d6d9dabf2 | ||
|
|
8bb5d85c16 | ||
|
|
759d5e5162 | ||
|
|
9438b5d617 | ||
|
|
272c123952 | ||
|
|
91c8a5332f | ||
|
|
a849d5db9e | ||
|
|
ae9743d6ed | ||
|
|
ae47652d0c | ||
|
|
c002cb1e54 | ||
|
|
9387670a7b | ||
|
|
a8df7f8359 | ||
|
|
2f302b26af | ||
|
|
26f8bcf86d | ||
|
|
95c57de8d0 | ||
|
|
d4a8401a6a | ||
|
|
aaf88a6f12 | ||
|
|
b789c1bd44 | ||
|
|
5062aa8068 | ||
|
|
8a042589e7 | ||
|
|
3898b5ad45 | ||
|
|
9d15336144 |
No files matched your search
+1
-1
@@ -61,4 +61,4 @@ tmp/
|
||||
|
||||
#.claude Konfiguration
|
||||
.claude/
|
||||
.claude/settings.local.json
|
||||
.claude/settings.local.jsonfrontend/package-lock.json
|
||||
@@ -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
@@ -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
|
||||
@@ -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)}")
|
||||
+111
-1
@@ -91,9 +91,113 @@ def get_profile_count():
|
||||
print(f"Error getting profile count: {e}")
|
||||
return -1
|
||||
|
||||
def ensure_migration_table():
|
||||
"""Create migration tracking table if it doesn't exist."""
|
||||
try:
|
||||
conn = get_connection()
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
id SERIAL PRIMARY KEY,
|
||||
filename VARCHAR(255) UNIQUE NOT NULL,
|
||||
applied_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
""")
|
||||
conn.commit()
|
||||
cur.close()
|
||||
conn.close()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Error creating migration table: {e}")
|
||||
return False
|
||||
|
||||
def get_applied_migrations():
|
||||
"""Get list of already applied migrations."""
|
||||
try:
|
||||
conn = get_connection()
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT filename FROM schema_migrations ORDER BY filename")
|
||||
migrations = [row[0] for row in cur.fetchall()]
|
||||
cur.close()
|
||||
conn.close()
|
||||
return migrations
|
||||
except Exception as e:
|
||||
print(f"Error getting applied migrations: {e}")
|
||||
return []
|
||||
|
||||
def apply_migration(filepath, filename):
|
||||
"""Apply a single migration file."""
|
||||
try:
|
||||
with open(filepath, 'r') as f:
|
||||
migration_sql = f.read()
|
||||
|
||||
conn = get_connection()
|
||||
cur = conn.cursor()
|
||||
|
||||
# Execute migration
|
||||
cur.execute(migration_sql)
|
||||
|
||||
# Record migration
|
||||
cur.execute(
|
||||
"INSERT INTO schema_migrations (filename) VALUES (%s)",
|
||||
(filename,)
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
cur.close()
|
||||
conn.close()
|
||||
print(f" ✓ Applied: {filename}")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f" ✗ Failed to apply {filename}: {e}")
|
||||
return False
|
||||
|
||||
def run_migrations(migrations_dir="/app/migrations"):
|
||||
"""Run all pending migrations."""
|
||||
import glob
|
||||
import re
|
||||
|
||||
if not os.path.exists(migrations_dir):
|
||||
print("✓ No migrations directory found")
|
||||
return True
|
||||
|
||||
# Ensure migration tracking table exists
|
||||
if not ensure_migration_table():
|
||||
return False
|
||||
|
||||
# Get already applied migrations
|
||||
applied = get_applied_migrations()
|
||||
|
||||
# Get all migration files (only numbered migrations like 001_*.sql)
|
||||
all_files = sorted(glob.glob(os.path.join(migrations_dir, "*.sql")))
|
||||
migration_pattern = re.compile(r'^\d{3}_.*\.sql$')
|
||||
migration_files = [f for f in all_files if migration_pattern.match(os.path.basename(f))]
|
||||
|
||||
if not migration_files:
|
||||
print("✓ No migration files found")
|
||||
return True
|
||||
|
||||
# Apply pending migrations
|
||||
pending = []
|
||||
for filepath in migration_files:
|
||||
filename = os.path.basename(filepath)
|
||||
if filename not in applied:
|
||||
pending.append((filepath, filename))
|
||||
|
||||
if not pending:
|
||||
print(f"✓ All {len(applied)} migrations already applied")
|
||||
return True
|
||||
|
||||
print(f" Found {len(pending)} pending migration(s)...")
|
||||
for filepath, filename in pending:
|
||||
if not apply_migration(filepath, filename):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("═══════════════════════════════════════════════════════════")
|
||||
print("MITAI JINKENDO - Database Initialization (v9b)")
|
||||
print("MITAI JINKENDO - Database Initialization (v9c)")
|
||||
print("═══════════════════════════════════════════════════════════")
|
||||
|
||||
# Wait for PostgreSQL
|
||||
@@ -109,6 +213,12 @@ if __name__ == "__main__":
|
||||
else:
|
||||
print("✓ Schema already exists")
|
||||
|
||||
# Run migrations
|
||||
print("\nRunning database migrations...")
|
||||
if not run_migrations():
|
||||
print("✗ Migration failed")
|
||||
sys.exit(1)
|
||||
|
||||
# Check for migration
|
||||
print("\nChecking for SQLite data migration...")
|
||||
sqlite_db = "/app/data/bodytrack.db"
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
"""
|
||||
Training Type Profiles - Helper Functions
|
||||
Utilities for loading parameters, profiles, and running evaluations.
|
||||
|
||||
Issue: #15
|
||||
Date: 2026-03-23
|
||||
"""
|
||||
from typing import Dict, Optional, List
|
||||
from decimal import Decimal
|
||||
import logging
|
||||
|
||||
from db import get_cursor
|
||||
from profile_evaluator import TrainingProfileEvaluator
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def convert_decimals(obj):
|
||||
"""
|
||||
Recursively converts Decimal objects to float for JSON serialization.
|
||||
|
||||
PostgreSQL returns numeric values as Decimal, but psycopg2.Json() can't serialize them.
|
||||
"""
|
||||
if isinstance(obj, Decimal):
|
||||
return float(obj)
|
||||
elif isinstance(obj, dict):
|
||||
return {k: convert_decimals(v) for k, v in obj.items()}
|
||||
elif isinstance(obj, list):
|
||||
return [convert_decimals(item) for item in obj]
|
||||
return obj
|
||||
|
||||
|
||||
def load_parameters_registry(cur) -> Dict[str, Dict]:
|
||||
"""
|
||||
Loads training parameters registry from database.
|
||||
|
||||
Returns:
|
||||
Dict mapping parameter_key -> config
|
||||
"""
|
||||
cur.execute("""
|
||||
SELECT key, name_de, name_en, category, data_type, unit,
|
||||
description_de, source_field, validation_rules
|
||||
FROM training_parameters
|
||||
WHERE is_active = true
|
||||
""")
|
||||
|
||||
registry = {}
|
||||
for row in cur.fetchall():
|
||||
registry[row['key']] = dict(row)
|
||||
|
||||
return registry
|
||||
|
||||
|
||||
def load_training_type_profile(cur, training_type_id: int) -> Optional[Dict]:
|
||||
"""
|
||||
Loads training type profile for a given type ID.
|
||||
|
||||
Returns:
|
||||
Profile JSONB or None if not configured
|
||||
"""
|
||||
cur.execute(
|
||||
"SELECT profile FROM training_types WHERE id = %s",
|
||||
(training_type_id,)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if row and row['profile']:
|
||||
return row['profile']
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def load_evaluation_context(
|
||||
cur,
|
||||
profile_id: str,
|
||||
activity_date: str,
|
||||
lookback_days: int = 30
|
||||
) -> Dict:
|
||||
"""
|
||||
Loads context data for evaluation (user profile + recent activities).
|
||||
|
||||
Args:
|
||||
cur: Database cursor
|
||||
profile_id: User profile ID
|
||||
activity_date: Date of activity being evaluated
|
||||
lookback_days: How many days of history to load
|
||||
|
||||
Returns:
|
||||
{
|
||||
"user_profile": {...},
|
||||
"recent_activities": [...],
|
||||
"historical_activities": [...]
|
||||
}
|
||||
"""
|
||||
# Load user profile
|
||||
cur.execute(
|
||||
"SELECT hf_max, sleep_goal_minutes FROM profiles WHERE id = %s",
|
||||
(profile_id,)
|
||||
)
|
||||
user_row = cur.fetchone()
|
||||
user_profile = dict(user_row) if user_row else {}
|
||||
|
||||
# Load recent activities (last N days)
|
||||
cur.execute("""
|
||||
SELECT id, date, training_type_id, duration_min, hr_avg, hr_max,
|
||||
distance_km, kcal_active, rpe
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= %s::date - INTERVAL '%s days'
|
||||
AND date < %s::date
|
||||
ORDER BY date DESC
|
||||
LIMIT 50
|
||||
""", (profile_id, activity_date, lookback_days, activity_date))
|
||||
|
||||
recent_activities = [dict(r) for r in cur.fetchall()]
|
||||
|
||||
# Historical activities (same for MVP)
|
||||
historical_activities = recent_activities
|
||||
|
||||
return {
|
||||
"user_profile": user_profile,
|
||||
"recent_activities": recent_activities,
|
||||
"historical_activities": historical_activities
|
||||
}
|
||||
|
||||
|
||||
def evaluate_and_save_activity(
|
||||
cur,
|
||||
activity_id: str,
|
||||
activity_data: Dict,
|
||||
training_type_id: int,
|
||||
profile_id: str
|
||||
) -> Optional[Dict]:
|
||||
"""
|
||||
Evaluates an activity and saves the result to the database.
|
||||
|
||||
Args:
|
||||
cur: Database cursor
|
||||
activity_id: Activity ID
|
||||
activity_data: Activity data dict
|
||||
training_type_id: Training type ID
|
||||
profile_id: User profile ID
|
||||
|
||||
Returns:
|
||||
Evaluation result or None if no profile configured
|
||||
"""
|
||||
# Load profile
|
||||
profile = load_training_type_profile(cur, training_type_id)
|
||||
if not profile:
|
||||
logger.info(f"[EVALUATION] No profile for training_type {training_type_id}, skipping")
|
||||
return None
|
||||
|
||||
# Load parameters registry
|
||||
parameters = load_parameters_registry(cur)
|
||||
|
||||
# Load context
|
||||
context = load_evaluation_context(
|
||||
cur,
|
||||
profile_id,
|
||||
activity_data.get("date"),
|
||||
lookback_days=30
|
||||
)
|
||||
|
||||
# Convert Decimal values in activity_data and context
|
||||
activity_data_clean = convert_decimals(activity_data)
|
||||
context_clean = convert_decimals(context)
|
||||
|
||||
# Evaluate
|
||||
evaluator = TrainingProfileEvaluator(parameters)
|
||||
evaluation_result = evaluator.evaluate_activity(
|
||||
activity_data_clean,
|
||||
profile,
|
||||
context_clean
|
||||
)
|
||||
|
||||
# Save to database
|
||||
from psycopg2.extras import Json
|
||||
|
||||
# Convert Decimal to float for JSON serialization
|
||||
evaluation_result_clean = convert_decimals(evaluation_result)
|
||||
|
||||
cur.execute("""
|
||||
UPDATE activity_log
|
||||
SET evaluation = %s,
|
||||
quality_label = %s,
|
||||
overall_score = %s
|
||||
WHERE id = %s
|
||||
""", (
|
||||
Json(evaluation_result_clean),
|
||||
evaluation_result_clean.get("quality_label"),
|
||||
evaluation_result_clean.get("overall_score"),
|
||||
activity_id
|
||||
))
|
||||
|
||||
logger.info(
|
||||
f"[EVALUATION] Activity {activity_id}: "
|
||||
f"{evaluation_result.get('quality_label')} "
|
||||
f"(score: {evaluation_result.get('overall_score')})"
|
||||
)
|
||||
|
||||
return evaluation_result
|
||||
|
||||
|
||||
def batch_evaluate_activities(
|
||||
cur,
|
||||
profile_id: str,
|
||||
limit: Optional[int] = None
|
||||
) -> Dict:
|
||||
"""
|
||||
Re-evaluates all activities for a user.
|
||||
|
||||
Useful for:
|
||||
- Initial setup after profiles are configured
|
||||
- Re-evaluation after profile changes
|
||||
|
||||
Args:
|
||||
cur: Database cursor
|
||||
profile_id: User profile ID
|
||||
limit: Optional limit for testing
|
||||
|
||||
Returns:
|
||||
{
|
||||
"total": int,
|
||||
"evaluated": int,
|
||||
"skipped": int,
|
||||
"errors": int
|
||||
}
|
||||
"""
|
||||
# Load all activities
|
||||
query = """
|
||||
SELECT id, profile_id, date, training_type_id, duration_min,
|
||||
hr_avg, hr_max, distance_km, kcal_active, kcal_resting,
|
||||
rpe, pace_min_per_km, cadence, elevation_gain
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
ORDER BY date DESC
|
||||
"""
|
||||
params = [profile_id]
|
||||
|
||||
if limit:
|
||||
query += " LIMIT %s"
|
||||
params.append(limit)
|
||||
|
||||
cur.execute(query, params)
|
||||
activities = cur.fetchall()
|
||||
|
||||
stats = {
|
||||
"total": len(activities),
|
||||
"evaluated": 0,
|
||||
"skipped": 0,
|
||||
"errors": 0
|
||||
}
|
||||
|
||||
# Track error details
|
||||
error_details = []
|
||||
|
||||
for activity in activities:
|
||||
activity_dict = dict(activity)
|
||||
try:
|
||||
result = evaluate_and_save_activity(
|
||||
cur,
|
||||
activity_dict["id"],
|
||||
activity_dict,
|
||||
activity_dict["training_type_id"],
|
||||
profile_id
|
||||
)
|
||||
|
||||
if result:
|
||||
stats["evaluated"] += 1
|
||||
else:
|
||||
stats["skipped"] += 1
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[BATCH-EVAL] Error evaluating {activity_dict['id']}: {e}")
|
||||
error_details.append({
|
||||
"activity_id": activity_dict['id'],
|
||||
"training_type_id": activity_dict.get('training_type_id'),
|
||||
"error": str(e)
|
||||
})
|
||||
stats["errors"] += 1
|
||||
|
||||
# Add error details to stats (limit to first 10)
|
||||
if error_details:
|
||||
stats["error_details"] = error_details[:10]
|
||||
|
||||
logger.info(f"[BATCH-EVAL] Completed: {stats}")
|
||||
return stats
|
||||
@@ -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))
|
||||
+32
-1
@@ -18,6 +18,11 @@ from db import init_db
|
||||
from routers import auth, profiles, weight, circumference, caliper
|
||||
from routers import activity, nutrition, photos, insights, prompts
|
||||
from routers import admin, stats, exportdata, importdata
|
||||
from routers import subscription, coupons, features, tiers_mgmt, tier_limits
|
||||
from routers import user_restrictions, access_grants, training_types, admin_training_types
|
||||
from routers import admin_activity_mappings, sleep, rest_days
|
||||
from routers import vitals_baseline, blood_pressure # v9d Phase 2d Refactored
|
||||
from routers import evaluation # v9d/v9e Training Type Profiles (#15)
|
||||
|
||||
# ── App Configuration ─────────────────────────────────────────────────────────
|
||||
DATA_DIR = Path(os.getenv("DATA_DIR", "./data"))
|
||||
@@ -51,6 +56,13 @@ async def startup_event():
|
||||
print(f"⚠️ init_db() failed (non-fatal): {e}")
|
||||
# Don't crash on startup - can be created manually
|
||||
|
||||
# Apply v9c migration if needed
|
||||
try:
|
||||
from apply_v9c_migration import apply_migration
|
||||
apply_migration()
|
||||
except Exception as e:
|
||||
print(f"⚠️ v9c migration failed (non-fatal): {e}")
|
||||
|
||||
# ── Register Routers ──────────────────────────────────────────────────────────
|
||||
app.include_router(auth.router) # /api/auth/*
|
||||
app.include_router(profiles.router) # /api/profiles/*, /api/profile
|
||||
@@ -67,8 +79,27 @@ app.include_router(stats.router) # /api/stats
|
||||
app.include_router(exportdata.router) # /api/export/*
|
||||
app.include_router(importdata.router) # /api/import/*
|
||||
|
||||
# v9c Subscription System
|
||||
app.include_router(subscription.router) # /api/subscription/*
|
||||
app.include_router(coupons.router) # /api/coupons/*
|
||||
app.include_router(features.router) # /api/features (admin)
|
||||
app.include_router(tiers_mgmt.router) # /api/tiers (admin)
|
||||
app.include_router(tier_limits.router) # /api/tier-limits (admin)
|
||||
app.include_router(user_restrictions.router) # /api/user-restrictions (admin)
|
||||
app.include_router(access_grants.router) # /api/access-grants (admin)
|
||||
|
||||
# v9d Training Types & Sleep Module & Rest Days & Vitals
|
||||
app.include_router(training_types.router) # /api/training-types/*
|
||||
app.include_router(admin_training_types.router) # /api/admin/training-types/*
|
||||
app.include_router(admin_activity_mappings.router) # /api/admin/activity-mappings/*
|
||||
app.include_router(sleep.router) # /api/sleep/* (v9d Phase 2b)
|
||||
app.include_router(rest_days.router) # /api/rest-days/* (v9d Phase 2a)
|
||||
app.include_router(vitals_baseline.router) # /api/vitals/baseline/* (v9d Phase 2d Refactored)
|
||||
app.include_router(blood_pressure.router) # /api/blood-pressure/* (v9d Phase 2d Refactored)
|
||||
app.include_router(evaluation.router) # /api/evaluation/* (v9d/v9e Training Profiles #15)
|
||||
|
||||
# ── Health Check ──────────────────────────────────────────────────────────────
|
||||
@app.get("/")
|
||||
def root():
|
||||
"""API health check."""
|
||||
return {"status": "ok", "service": "mitai-jinkendo", "version": "v9b"}
|
||||
return {"status": "ok", "service": "mitai-jinkendo", "version": "v9c-dev"}
|
||||
@@ -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)';
|
||||
@@ -0,0 +1,86 @@
|
||||
-- Migration 004: Training Types & Categories
|
||||
-- Part of v9d: Schlaf + Sport-Vertiefung
|
||||
-- Created: 2026-03-21
|
||||
|
||||
-- ========================================
|
||||
-- 1. Create training_types table
|
||||
-- ========================================
|
||||
CREATE TABLE IF NOT EXISTS training_types (
|
||||
id SERIAL PRIMARY KEY,
|
||||
category VARCHAR(50) NOT NULL, -- Main category: 'cardio', 'strength', 'hiit', etc.
|
||||
subcategory VARCHAR(50), -- Optional: 'running', 'hypertrophy', etc.
|
||||
name_de VARCHAR(100) NOT NULL, -- German display name
|
||||
name_en VARCHAR(100) NOT NULL, -- English display name
|
||||
icon VARCHAR(10), -- Emoji icon
|
||||
sort_order INTEGER DEFAULT 0, -- For UI ordering
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- ========================================
|
||||
-- 2. Add training type columns to activity_log
|
||||
-- ========================================
|
||||
ALTER TABLE activity_log
|
||||
ADD COLUMN IF NOT EXISTS training_type_id INTEGER REFERENCES training_types(id),
|
||||
ADD COLUMN IF NOT EXISTS training_category VARCHAR(50), -- Denormalized for fast queries
|
||||
ADD COLUMN IF NOT EXISTS training_subcategory VARCHAR(50); -- Denormalized
|
||||
|
||||
-- ========================================
|
||||
-- 3. Create indexes
|
||||
-- ========================================
|
||||
CREATE INDEX IF NOT EXISTS idx_activity_training_type ON activity_log(training_type_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_activity_training_category ON activity_log(training_category);
|
||||
CREATE INDEX IF NOT EXISTS idx_training_types_category ON training_types(category);
|
||||
|
||||
-- ========================================
|
||||
-- 4. Seed training types data
|
||||
-- ========================================
|
||||
|
||||
-- Cardio (Ausdauer)
|
||||
INSERT INTO training_types (category, subcategory, name_de, name_en, icon, sort_order) VALUES
|
||||
('cardio', 'running', 'Laufen', 'Running', '🏃', 100),
|
||||
('cardio', 'cycling', 'Radfahren', 'Cycling', '🚴', 101),
|
||||
('cardio', 'swimming', 'Schwimmen', 'Swimming', '🏊', 102),
|
||||
('cardio', 'rowing', 'Rudern', 'Rowing', '🚣', 103),
|
||||
('cardio', 'other', 'Sonstiges Cardio', 'Other Cardio', '❤️', 104);
|
||||
|
||||
-- Kraft
|
||||
INSERT INTO training_types (category, subcategory, name_de, name_en, icon, sort_order) VALUES
|
||||
('strength', 'hypertrophy', 'Hypertrophie', 'Hypertrophy', '💪', 200),
|
||||
('strength', 'maxstrength', 'Maximalkraft', 'Max Strength', '🏋️', 201),
|
||||
('strength', 'endurance', 'Kraftausdauer', 'Strength Endurance', '🔁', 202),
|
||||
('strength', 'functional', 'Funktionell', 'Functional', '⚡', 203);
|
||||
|
||||
-- Schnellkraft / HIIT
|
||||
INSERT INTO training_types (category, subcategory, name_de, name_en, icon, sort_order) VALUES
|
||||
('hiit', 'hiit', 'HIIT', 'HIIT', '🔥', 300),
|
||||
('hiit', 'explosive', 'Explosiv', 'Explosive', '💥', 301),
|
||||
('hiit', 'circuit', 'Circuit Training', 'Circuit Training', '🔄', 302);
|
||||
|
||||
-- Kampfsport / Technikkraft
|
||||
INSERT INTO training_types (category, subcategory, name_de, name_en, icon, sort_order) VALUES
|
||||
('martial_arts', 'technique', 'Techniktraining', 'Technique Training', '🥋', 400),
|
||||
('martial_arts', 'sparring', 'Sparring / Wettkampf', 'Sparring / Competition', '🥊', 401),
|
||||
('martial_arts', 'strength', 'Kraft für Kampfsport', 'Martial Arts Strength', '⚔️', 402);
|
||||
|
||||
-- Mobility & Dehnung
|
||||
INSERT INTO training_types (category, subcategory, name_de, name_en, icon, sort_order) VALUES
|
||||
('mobility', 'static', 'Statisches Dehnen', 'Static Stretching', '🧘', 500),
|
||||
('mobility', 'dynamic', 'Dynamisches Dehnen', 'Dynamic Stretching', '🤸', 501),
|
||||
('mobility', 'yoga', 'Yoga', 'Yoga', '🕉️', 502),
|
||||
('mobility', 'fascia', 'Faszienarbeit', 'Fascia Work', '🎯', 503);
|
||||
|
||||
-- Erholung (aktiv)
|
||||
INSERT INTO training_types (category, subcategory, name_de, name_en, icon, sort_order) VALUES
|
||||
('recovery', 'walk', 'Spaziergang', 'Walk', '🚶', 600),
|
||||
('recovery', 'swim_light', 'Leichtes Schwimmen', 'Light Swimming', '🏊', 601),
|
||||
('recovery', 'regeneration', 'Regenerationseinheit', 'Regeneration', '💆', 602);
|
||||
|
||||
-- General / Uncategorized
|
||||
INSERT INTO training_types (category, subcategory, name_de, name_en, icon, sort_order) VALUES
|
||||
('other', NULL, 'Sonstiges', 'Other', '📝', 900);
|
||||
|
||||
-- ========================================
|
||||
-- 5. Add comment
|
||||
-- ========================================
|
||||
COMMENT ON TABLE training_types IS 'v9d: Training type categories and subcategories';
|
||||
COMMENT ON TABLE activity_log IS 'Extended in v9d with training_type_id for categorization';
|
||||
@@ -0,0 +1,24 @@
|
||||
-- Migration 005: Extended Training Types
|
||||
-- Add: Cardio (Gehen, Tanzen), Mind & Meditation category
|
||||
-- Created: 2026-03-21
|
||||
|
||||
-- ========================================
|
||||
-- Add new cardio subcategories
|
||||
-- ========================================
|
||||
INSERT INTO training_types (category, subcategory, name_de, name_en, icon, sort_order) VALUES
|
||||
('cardio', 'walk', 'Gehen', 'Walking', '🚶', 105),
|
||||
('cardio', 'dance', 'Tanzen', 'Dance', '💃', 106);
|
||||
|
||||
-- ========================================
|
||||
-- Add new category: Geist & Meditation
|
||||
-- ========================================
|
||||
INSERT INTO training_types (category, subcategory, name_de, name_en, icon, sort_order) VALUES
|
||||
('mind', 'meditation', 'Meditation', 'Meditation', '🧘♂️', 700),
|
||||
('mind', 'breathwork', 'Atemarbeit', 'Breathwork', '🫁', 701),
|
||||
('mind', 'mindfulness', 'Achtsamkeit', 'Mindfulness', '☮️', 702),
|
||||
('mind', 'visualization', 'Visualisierung', 'Visualization', '🎨', 703);
|
||||
|
||||
-- ========================================
|
||||
-- Add comment
|
||||
-- ========================================
|
||||
COMMENT ON TABLE training_types IS 'v9d Phase 1b: Extended with cardio walk/dance and mind category';
|
||||
@@ -0,0 +1,29 @@
|
||||
-- Migration 006: Training Types - Abilities Mapping
|
||||
-- Add abilities JSONB column for future AI analysis
|
||||
-- Maps to: koordinativ, konditionell, kognitiv, psychisch, taktisch
|
||||
-- Created: 2026-03-21
|
||||
|
||||
-- ========================================
|
||||
-- Add abilities column
|
||||
-- ========================================
|
||||
ALTER TABLE training_types
|
||||
ADD COLUMN IF NOT EXISTS abilities JSONB DEFAULT '{}';
|
||||
|
||||
-- ========================================
|
||||
-- Add description columns for better documentation
|
||||
-- ========================================
|
||||
ALTER TABLE training_types
|
||||
ADD COLUMN IF NOT EXISTS description_de TEXT,
|
||||
ADD COLUMN IF NOT EXISTS description_en TEXT;
|
||||
|
||||
-- ========================================
|
||||
-- Add index for abilities queries
|
||||
-- ========================================
|
||||
CREATE INDEX IF NOT EXISTS idx_training_types_abilities ON training_types USING GIN (abilities);
|
||||
|
||||
-- ========================================
|
||||
-- Comment
|
||||
-- ========================================
|
||||
COMMENT ON COLUMN training_types.abilities IS 'JSONB: Maps to athletic abilities for AI analysis (koordinativ, konditionell, kognitiv, psychisch, taktisch)';
|
||||
COMMENT ON COLUMN training_types.description_de IS 'German description for admin UI and AI context';
|
||||
COMMENT ON COLUMN training_types.description_en IS 'English description for admin UI and AI context';
|
||||
@@ -0,0 +1,121 @@
|
||||
-- Migration 007: Activity Type Mappings (Learnable System)
|
||||
-- Replaces hardcoded mappings with DB-based configurable system
|
||||
-- Created: 2026-03-21
|
||||
|
||||
-- ========================================
|
||||
-- 1. Create activity_type_mappings table
|
||||
-- ========================================
|
||||
CREATE TABLE IF NOT EXISTS activity_type_mappings (
|
||||
id SERIAL PRIMARY KEY,
|
||||
activity_type VARCHAR(100) NOT NULL,
|
||||
training_type_id INTEGER NOT NULL REFERENCES training_types(id) ON DELETE CASCADE,
|
||||
profile_id VARCHAR(36), -- NULL = global mapping, otherwise user-specific
|
||||
source VARCHAR(20) DEFAULT 'manual', -- 'manual', 'bulk', 'admin', 'default'
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT unique_activity_type_per_profile UNIQUE(activity_type, profile_id)
|
||||
);
|
||||
|
||||
-- ========================================
|
||||
-- 2. Create indexes
|
||||
-- ========================================
|
||||
CREATE INDEX IF NOT EXISTS idx_activity_type_mappings_type ON activity_type_mappings(activity_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_activity_type_mappings_profile ON activity_type_mappings(profile_id);
|
||||
|
||||
-- ========================================
|
||||
-- 3. Seed default mappings (global)
|
||||
-- ========================================
|
||||
-- Note: These are the German Apple Health workout types
|
||||
-- training_type_id references are based on existing training_types data
|
||||
|
||||
-- Helper function to get training_type_id by subcategory
|
||||
DO $$
|
||||
DECLARE
|
||||
v_running_id INTEGER;
|
||||
v_walk_id INTEGER;
|
||||
v_cycling_id INTEGER;
|
||||
v_swimming_id INTEGER;
|
||||
v_hypertrophy_id INTEGER;
|
||||
v_functional_id INTEGER;
|
||||
v_hiit_id INTEGER;
|
||||
v_yoga_id INTEGER;
|
||||
v_technique_id INTEGER;
|
||||
v_sparring_id INTEGER;
|
||||
v_rowing_id INTEGER;
|
||||
v_dance_id INTEGER;
|
||||
v_static_id INTEGER;
|
||||
v_regeneration_id INTEGER;
|
||||
v_meditation_id INTEGER;
|
||||
v_mindfulness_id INTEGER;
|
||||
BEGIN
|
||||
-- Get training_type IDs
|
||||
SELECT id INTO v_running_id FROM training_types WHERE subcategory = 'running' LIMIT 1;
|
||||
SELECT id INTO v_walk_id FROM training_types WHERE subcategory = 'walk' LIMIT 1;
|
||||
SELECT id INTO v_cycling_id FROM training_types WHERE subcategory = 'cycling' LIMIT 1;
|
||||
SELECT id INTO v_swimming_id FROM training_types WHERE subcategory = 'swimming' LIMIT 1;
|
||||
SELECT id INTO v_hypertrophy_id FROM training_types WHERE subcategory = 'hypertrophy' LIMIT 1;
|
||||
SELECT id INTO v_functional_id FROM training_types WHERE subcategory = 'functional' LIMIT 1;
|
||||
SELECT id INTO v_hiit_id FROM training_types WHERE subcategory = 'hiit' LIMIT 1;
|
||||
SELECT id INTO v_yoga_id FROM training_types WHERE subcategory = 'yoga' LIMIT 1;
|
||||
SELECT id INTO v_technique_id FROM training_types WHERE subcategory = 'technique' LIMIT 1;
|
||||
SELECT id INTO v_sparring_id FROM training_types WHERE subcategory = 'sparring' LIMIT 1;
|
||||
SELECT id INTO v_rowing_id FROM training_types WHERE subcategory = 'rowing' LIMIT 1;
|
||||
SELECT id INTO v_dance_id FROM training_types WHERE subcategory = 'dance' LIMIT 1;
|
||||
SELECT id INTO v_static_id FROM training_types WHERE subcategory = 'static' LIMIT 1;
|
||||
SELECT id INTO v_regeneration_id FROM training_types WHERE subcategory = 'regeneration' LIMIT 1;
|
||||
SELECT id INTO v_meditation_id FROM training_types WHERE subcategory = 'meditation' LIMIT 1;
|
||||
SELECT id INTO v_mindfulness_id FROM training_types WHERE subcategory = 'mindfulness' LIMIT 1;
|
||||
|
||||
-- Insert default mappings (German Apple Health names)
|
||||
INSERT INTO activity_type_mappings (activity_type, training_type_id, profile_id, source) VALUES
|
||||
-- German workout types
|
||||
('Laufen', v_running_id, NULL, 'default'),
|
||||
('Gehen', v_walk_id, NULL, 'default'),
|
||||
('Wandern', v_walk_id, NULL, 'default'),
|
||||
('Outdoor Spaziergang', v_walk_id, NULL, 'default'),
|
||||
('Innenräume Spaziergang', v_walk_id, NULL, 'default'),
|
||||
('Spaziergang', v_walk_id, NULL, 'default'),
|
||||
('Radfahren', v_cycling_id, NULL, 'default'),
|
||||
('Schwimmen', v_swimming_id, NULL, 'default'),
|
||||
('Traditionelles Krafttraining', v_hypertrophy_id, NULL, 'default'),
|
||||
('Funktionelles Krafttraining', v_functional_id, NULL, 'default'),
|
||||
('Hochintensives Intervalltraining', v_hiit_id, NULL, 'default'),
|
||||
('Yoga', v_yoga_id, NULL, 'default'),
|
||||
('Kampfsport', v_technique_id, NULL, 'default'),
|
||||
('Matrial Arts', v_technique_id, NULL, 'default'), -- Common typo
|
||||
('Boxen', v_sparring_id, NULL, 'default'),
|
||||
('Rudern', v_rowing_id, NULL, 'default'),
|
||||
('Tanzen', v_dance_id, NULL, 'default'),
|
||||
('Cardio Dance', v_dance_id, NULL, 'default'),
|
||||
('Flexibilität', v_static_id, NULL, 'default'),
|
||||
('Abwärmen', v_regeneration_id, NULL, 'default'),
|
||||
('Cooldown', v_regeneration_id, NULL, 'default'),
|
||||
('Meditation', v_meditation_id, NULL, 'default'),
|
||||
('Achtsamkeit', v_mindfulness_id, NULL, 'default'),
|
||||
('Geist & Körper', v_yoga_id, NULL, 'default')
|
||||
ON CONFLICT (activity_type, profile_id) DO NOTHING;
|
||||
|
||||
-- English workout types (for compatibility)
|
||||
INSERT INTO activity_type_mappings (activity_type, training_type_id, profile_id, source) VALUES
|
||||
('Running', v_running_id, NULL, 'default'),
|
||||
('Walking', v_walk_id, NULL, 'default'),
|
||||
('Hiking', v_walk_id, NULL, 'default'),
|
||||
('Cycling', v_cycling_id, NULL, 'default'),
|
||||
('Swimming', v_swimming_id, NULL, 'default'),
|
||||
('Traditional Strength Training', v_hypertrophy_id, NULL, 'default'),
|
||||
('Functional Strength Training', v_functional_id, NULL, 'default'),
|
||||
('High Intensity Interval Training', v_hiit_id, NULL, 'default'),
|
||||
('Martial Arts', v_technique_id, NULL, 'default'),
|
||||
('Boxing', v_sparring_id, NULL, 'default'),
|
||||
('Rowing', v_rowing_id, NULL, 'default'),
|
||||
('Dance', v_dance_id, NULL, 'default'),
|
||||
('Core Training', v_functional_id, NULL, 'default'),
|
||||
('Flexibility', v_static_id, NULL, 'default'),
|
||||
('Mindfulness', v_mindfulness_id, NULL, 'default')
|
||||
ON CONFLICT (activity_type, profile_id) DO NOTHING;
|
||||
END $$;
|
||||
|
||||
-- ========================================
|
||||
-- 4. Add comment
|
||||
-- ========================================
|
||||
COMMENT ON TABLE activity_type_mappings IS 'v9d Phase 1b: Learnable activity type to training type mappings. Replaces hardcoded mappings.';
|
||||
@@ -0,0 +1,59 @@
|
||||
-- Migration 008: Vitals, Rest Days, Weekly Goals
|
||||
-- v9d Phase 2: Sleep & Vitals Module
|
||||
-- Date: 2026-03-22
|
||||
|
||||
-- Rest Days
|
||||
CREATE TABLE IF NOT EXISTS rest_days (
|
||||
id SERIAL PRIMARY KEY,
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
date DATE NOT NULL,
|
||||
type VARCHAR(20) NOT NULL CHECK (type IN ('full_rest', 'active_recovery')),
|
||||
note TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT unique_rest_day_per_profile UNIQUE(profile_id, date)
|
||||
);
|
||||
CREATE INDEX idx_rest_days_profile_date ON rest_days(profile_id, date DESC);
|
||||
|
||||
-- Vitals (Resting HR + HRV)
|
||||
CREATE TABLE IF NOT EXISTS vitals_log (
|
||||
id SERIAL PRIMARY KEY,
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
date DATE NOT NULL,
|
||||
resting_hr INTEGER CHECK (resting_hr > 0 AND resting_hr < 200),
|
||||
hrv INTEGER CHECK (hrv > 0),
|
||||
note TEXT,
|
||||
source VARCHAR(20) DEFAULT 'manual' CHECK (source IN ('manual', 'apple_health', 'garmin')),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT unique_vitals_per_day UNIQUE(profile_id, date)
|
||||
);
|
||||
CREATE INDEX idx_vitals_profile_date ON vitals_log(profile_id, date DESC);
|
||||
|
||||
-- Extend activity_log for heart rate data
|
||||
ALTER TABLE activity_log
|
||||
ADD COLUMN IF NOT EXISTS avg_hr INTEGER CHECK (avg_hr > 0 AND avg_hr < 250),
|
||||
ADD COLUMN IF NOT EXISTS max_hr INTEGER CHECK (max_hr > 0 AND max_hr < 250);
|
||||
|
||||
-- Extend profiles for HF max and sleep goal
|
||||
ALTER TABLE profiles
|
||||
ADD COLUMN IF NOT EXISTS hf_max INTEGER CHECK (hf_max > 0 AND hf_max < 250),
|
||||
ADD COLUMN IF NOT EXISTS sleep_goal_minutes INTEGER DEFAULT 450 CHECK (sleep_goal_minutes > 0);
|
||||
|
||||
-- Weekly Goals (Soll/Ist Wochenplanung)
|
||||
CREATE TABLE IF NOT EXISTS weekly_goals (
|
||||
id SERIAL PRIMARY KEY,
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
week_start DATE NOT NULL,
|
||||
goals JSONB NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT unique_weekly_goal_per_profile UNIQUE(profile_id, week_start)
|
||||
);
|
||||
CREATE INDEX idx_weekly_goals_profile_week ON weekly_goals(profile_id, week_start DESC);
|
||||
|
||||
-- Comments for documentation
|
||||
COMMENT ON TABLE rest_days IS 'v9d Phase 2: Rest days tracking (full rest or active recovery)';
|
||||
COMMENT ON TABLE vitals_log IS 'v9d Phase 2: Daily vitals (resting HR, HRV)';
|
||||
COMMENT ON TABLE weekly_goals IS 'v9d Phase 2: Weekly training goals (Soll/Ist planning)';
|
||||
COMMENT ON COLUMN profiles.hf_max IS 'Maximum heart rate for HR zone calculation';
|
||||
COMMENT ON COLUMN profiles.sleep_goal_minutes IS 'Sleep goal in minutes (default: 450 = 7h 30min)';
|
||||
@@ -0,0 +1,31 @@
|
||||
-- Migration 009: Sleep Log Table
|
||||
-- v9d Phase 2b: Sleep Module Core
|
||||
-- Date: 2026-03-22
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sleep_log (
|
||||
id SERIAL PRIMARY KEY,
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
date DATE NOT NULL,
|
||||
bedtime TIME,
|
||||
wake_time TIME,
|
||||
duration_minutes INTEGER NOT NULL CHECK (duration_minutes > 0),
|
||||
quality INTEGER CHECK (quality >= 1 AND quality <= 5),
|
||||
wake_count INTEGER CHECK (wake_count >= 0),
|
||||
deep_minutes INTEGER CHECK (deep_minutes >= 0),
|
||||
rem_minutes INTEGER CHECK (rem_minutes >= 0),
|
||||
light_minutes INTEGER CHECK (light_minutes >= 0),
|
||||
awake_minutes INTEGER CHECK (awake_minutes >= 0),
|
||||
sleep_segments JSONB,
|
||||
note TEXT,
|
||||
source VARCHAR(20) DEFAULT 'manual' CHECK (source IN ('manual', 'apple_health', 'garmin')),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT unique_sleep_per_day UNIQUE(profile_id, date)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_sleep_profile_date ON sleep_log(profile_id, date DESC);
|
||||
|
||||
-- Comments for documentation
|
||||
COMMENT ON TABLE sleep_log IS 'v9d Phase 2b: Daily sleep tracking with phase data';
|
||||
COMMENT ON COLUMN sleep_log.date IS 'Date of the night (wake date, not bedtime date)';
|
||||
COMMENT ON COLUMN sleep_log.sleep_segments IS 'Raw phase segments: [{"phase": "deep", "start": "23:44", "duration_min": 42}, ...]';
|
||||
@@ -0,0 +1,62 @@
|
||||
-- Migration 010: Rest Days Refactoring zu JSONB
|
||||
-- v9d Phase 2a: Flexible, context-specific rest days
|
||||
-- Date: 2026-03-22
|
||||
|
||||
-- Refactor rest_days to JSONB config for flexible rest day types
|
||||
-- OLD: type VARCHAR(20) CHECK (type IN ('full_rest', 'active_recovery'))
|
||||
-- NEW: rest_config JSONB with {focus, rest_from[], allows[], intensity_max}
|
||||
|
||||
-- Drop old type column
|
||||
ALTER TABLE rest_days
|
||||
DROP COLUMN IF EXISTS type;
|
||||
|
||||
-- Add new JSONB config column
|
||||
ALTER TABLE rest_days
|
||||
ADD COLUMN IF NOT EXISTS rest_config JSONB NOT NULL DEFAULT '{"focus": "mental_rest", "rest_from": [], "allows": []}'::jsonb;
|
||||
|
||||
-- Validation function for rest_config
|
||||
CREATE OR REPLACE FUNCTION validate_rest_config(config JSONB) RETURNS BOOLEAN AS $$
|
||||
BEGIN
|
||||
-- Must have focus field
|
||||
IF NOT (config ? 'focus') THEN
|
||||
RETURN FALSE;
|
||||
END IF;
|
||||
|
||||
-- focus must be one of the allowed values
|
||||
IF NOT (config->>'focus' IN ('muscle_recovery', 'cardio_recovery', 'mental_rest', 'deload', 'injury')) THEN
|
||||
RETURN FALSE;
|
||||
END IF;
|
||||
|
||||
-- rest_from must be array if present
|
||||
IF (config ? 'rest_from') AND jsonb_typeof(config->'rest_from') != 'array' THEN
|
||||
RETURN FALSE;
|
||||
END IF;
|
||||
|
||||
-- allows must be array if present
|
||||
IF (config ? 'allows') AND jsonb_typeof(config->'allows') != 'array' THEN
|
||||
RETURN FALSE;
|
||||
END IF;
|
||||
|
||||
-- intensity_max must be number between 1-100 if present
|
||||
IF (config ? 'intensity_max') AND (
|
||||
jsonb_typeof(config->'intensity_max') != 'number' OR
|
||||
(config->>'intensity_max')::int < 1 OR
|
||||
(config->>'intensity_max')::int > 100
|
||||
) THEN
|
||||
RETURN FALSE;
|
||||
END IF;
|
||||
|
||||
RETURN TRUE;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- Add check constraint
|
||||
ALTER TABLE rest_days
|
||||
ADD CONSTRAINT valid_rest_config CHECK (validate_rest_config(rest_config));
|
||||
|
||||
-- Add comment for documentation
|
||||
COMMENT ON COLUMN rest_days.rest_config IS 'JSONB: {focus: string, rest_from: string[], allows: string[], intensity_max?: number (1-100), note?: string}';
|
||||
COMMENT ON TABLE rest_days IS 'v9d Phase 2a: Context-specific rest days (strength rest but cardio allowed, etc.)';
|
||||
|
||||
-- Create GIN index on rest_config for faster JSONB queries
|
||||
CREATE INDEX IF NOT EXISTS idx_rest_days_config ON rest_days USING GIN (rest_config);
|
||||
@@ -0,0 +1,17 @@
|
||||
-- Migration 011: Allow Multiple Rest Days per Date
|
||||
-- v9d Phase 2a: Support for multi-dimensional rest (development routes)
|
||||
-- Date: 2026-03-22
|
||||
|
||||
-- Remove UNIQUE constraint to allow multiple rest day types per date
|
||||
-- Use Case: Muscle recovery + Mental rest on same day
|
||||
-- Future: Development routes (Conditioning, Strength, Coordination, Mental, Mobility, Technique)
|
||||
|
||||
ALTER TABLE rest_days
|
||||
DROP CONSTRAINT IF EXISTS unique_rest_day_per_profile;
|
||||
|
||||
-- Add index for efficient queries (profile_id, date)
|
||||
CREATE INDEX IF NOT EXISTS idx_rest_days_profile_date_multi
|
||||
ON rest_days(profile_id, date DESC);
|
||||
|
||||
-- Comment for documentation
|
||||
COMMENT ON TABLE rest_days IS 'v9d Phase 2a: Multi-dimensional rest days - multiple entries per date allowed for different development routes (muscle, cardio, mental, coordination, technique)';
|
||||
@@ -0,0 +1,34 @@
|
||||
-- Migration 012: Unique constraint on (profile_id, date, focus)
|
||||
-- v9d Phase 2a: Prevent duplicate rest day types per date
|
||||
-- Date: 2026-03-22
|
||||
|
||||
-- Add focus column (extracted from rest_config for performance + constraints)
|
||||
ALTER TABLE rest_days
|
||||
ADD COLUMN IF NOT EXISTS focus VARCHAR(20);
|
||||
|
||||
-- Populate from existing JSONB data
|
||||
UPDATE rest_days
|
||||
SET focus = rest_config->>'focus'
|
||||
WHERE focus IS NULL;
|
||||
|
||||
-- Make NOT NULL (safe because we just populated all rows)
|
||||
ALTER TABLE rest_days
|
||||
ALTER COLUMN focus SET NOT NULL;
|
||||
|
||||
-- Add CHECK constraint for valid focus values
|
||||
ALTER TABLE rest_days
|
||||
ADD CONSTRAINT valid_focus CHECK (
|
||||
focus IN ('muscle_recovery', 'cardio_recovery', 'mental_rest', 'deload', 'injury')
|
||||
);
|
||||
|
||||
-- Add UNIQUE constraint: Same profile + date + focus = duplicate
|
||||
ALTER TABLE rest_days
|
||||
ADD CONSTRAINT unique_rest_day_per_focus
|
||||
UNIQUE (profile_id, date, focus);
|
||||
|
||||
-- Add index for efficient queries by focus
|
||||
CREATE INDEX IF NOT EXISTS idx_rest_days_focus
|
||||
ON rest_days(focus);
|
||||
|
||||
-- Comment for documentation
|
||||
COMMENT ON COLUMN rest_days.focus IS 'Extracted from rest_config.focus for performance and constraints. Prevents duplicate rest day types per date.';
|
||||
@@ -0,0 +1,145 @@
|
||||
-- Migration 013: Training Parameters Registry
|
||||
-- Training Type Profiles System - Foundation
|
||||
-- Date: 2026-03-23
|
||||
-- Issue: #15
|
||||
|
||||
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
-- TRAINING PARAMETERS REGISTRY
|
||||
-- Zentrale Definition aller messbaren Parameter für Aktivitäten
|
||||
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
CREATE TABLE IF NOT EXISTS training_parameters (
|
||||
id SERIAL PRIMARY KEY,
|
||||
key VARCHAR(50) UNIQUE NOT NULL,
|
||||
name_de VARCHAR(100) NOT NULL,
|
||||
name_en VARCHAR(100) NOT NULL,
|
||||
category VARCHAR(50) NOT NULL,
|
||||
data_type VARCHAR(20) NOT NULL,
|
||||
unit VARCHAR(20),
|
||||
description_de TEXT,
|
||||
description_en TEXT,
|
||||
source_field VARCHAR(100),
|
||||
validation_rules JSONB DEFAULT '{}'::jsonb,
|
||||
is_active BOOLEAN DEFAULT true,
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT chk_category CHECK (category IN (
|
||||
'physical', 'physiological', 'subjective', 'environmental', 'performance'
|
||||
)),
|
||||
CONSTRAINT chk_data_type CHECK (data_type IN (
|
||||
'integer', 'float', 'string', 'boolean'
|
||||
))
|
||||
);
|
||||
|
||||
CREATE INDEX idx_training_parameters_category ON training_parameters(category) WHERE is_active = true;
|
||||
CREATE INDEX idx_training_parameters_key ON training_parameters(key) WHERE is_active = true;
|
||||
|
||||
COMMENT ON TABLE training_parameters IS 'Registry of all measurable activity parameters (Training Type Profiles System)';
|
||||
COMMENT ON COLUMN training_parameters.key IS 'Unique identifier (e.g. "avg_hr", "duration_min")';
|
||||
COMMENT ON COLUMN training_parameters.category IS 'Parameter category: physical, physiological, subjective, environmental, performance';
|
||||
COMMENT ON COLUMN training_parameters.data_type IS 'Data type: integer, float, string, boolean';
|
||||
COMMENT ON COLUMN training_parameters.source_field IS 'Mapping to activity_log column name';
|
||||
COMMENT ON COLUMN training_parameters.validation_rules IS 'Min/Max/Enum for validation (JSONB)';
|
||||
|
||||
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
-- STANDARD PARAMETERS
|
||||
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
INSERT INTO training_parameters (key, name_de, name_en, category, data_type, unit, source_field, validation_rules, description_de, description_en) VALUES
|
||||
|
||||
-- Physical Parameters
|
||||
('duration_min', 'Dauer', 'Duration', 'physical', 'integer', 'min', 'duration_min',
|
||||
'{"min": 0, "max": 600}'::jsonb,
|
||||
'Trainingsdauer in Minuten',
|
||||
'Training duration in minutes'),
|
||||
|
||||
('distance_km', 'Distanz', 'Distance', 'physical', 'float', 'km', 'distance_km',
|
||||
'{"min": 0, "max": 200}'::jsonb,
|
||||
'Zurückgelegte Distanz in Kilometern',
|
||||
'Distance covered in kilometers'),
|
||||
|
||||
('kcal_active', 'Aktive Kalorien', 'Active Calories', 'physical', 'integer', 'kcal', 'kcal_active',
|
||||
'{"min": 0, "max": 5000}'::jsonb,
|
||||
'Aktiver Kalorienverbrauch',
|
||||
'Active calorie burn'),
|
||||
|
||||
('kcal_resting', 'Ruhekalorien', 'Resting Calories', 'physical', 'integer', 'kcal', 'kcal_resting',
|
||||
'{"min": 0, "max": 2000}'::jsonb,
|
||||
'Ruheumsatz während Training',
|
||||
'Resting calorie burn during training'),
|
||||
|
||||
('elevation_gain', 'Höhenmeter', 'Elevation Gain', 'physical', 'integer', 'm', 'elevation_gain',
|
||||
'{"min": 0, "max": 5000}'::jsonb,
|
||||
'Überwundene Höhenmeter',
|
||||
'Elevation gain in meters'),
|
||||
|
||||
('pace_min_per_km', 'Pace', 'Pace', 'physical', 'float', 'min/km', 'pace_min_per_km',
|
||||
'{"min": 2, "max": 20}'::jsonb,
|
||||
'Durchschnittstempo in Minuten pro Kilometer',
|
||||
'Average pace in minutes per kilometer'),
|
||||
|
||||
('cadence', 'Trittfrequenz', 'Cadence', 'physical', 'integer', 'spm', 'cadence',
|
||||
'{"min": 0, "max": 220}'::jsonb,
|
||||
'Schrittfrequenz (Schritte pro Minute)',
|
||||
'Step frequency (steps per minute)'),
|
||||
|
||||
-- Physiological Parameters
|
||||
('avg_hr', 'Durchschnittspuls', 'Average Heart Rate', 'physiological', 'integer', 'bpm', 'hr_avg',
|
||||
'{"min": 30, "max": 220}'::jsonb,
|
||||
'Durchschnittliche Herzfrequenz',
|
||||
'Average heart rate'),
|
||||
|
||||
('max_hr', 'Maximalpuls', 'Max Heart Rate', 'physiological', 'integer', 'bpm', 'hr_max',
|
||||
'{"min": 40, "max": 220}'::jsonb,
|
||||
'Maximale Herzfrequenz',
|
||||
'Maximum heart rate'),
|
||||
|
||||
('min_hr', 'Minimalpuls', 'Min Heart Rate', 'physiological', 'integer', 'bpm', 'hr_min',
|
||||
'{"min": 30, "max": 200}'::jsonb,
|
||||
'Minimale Herzfrequenz',
|
||||
'Minimum heart rate'),
|
||||
|
||||
('avg_power', 'Durchschnittsleistung', 'Average Power', 'physiological', 'integer', 'W', 'avg_power',
|
||||
'{"min": 0, "max": 1000}'::jsonb,
|
||||
'Durchschnittliche Leistung in Watt',
|
||||
'Average power output in watts'),
|
||||
|
||||
-- Subjective Parameters
|
||||
('rpe', 'RPE (Anstrengung)', 'RPE (Perceived Exertion)', 'subjective', 'integer', 'scale', 'rpe',
|
||||
'{"min": 1, "max": 10}'::jsonb,
|
||||
'Subjektive Anstrengung (Rate of Perceived Exertion)',
|
||||
'Rate of Perceived Exertion'),
|
||||
|
||||
-- Environmental Parameters
|
||||
('temperature_celsius', 'Temperatur', 'Temperature', 'environmental', 'float', '°C', 'temperature_celsius',
|
||||
'{"min": -30, "max": 50}'::jsonb,
|
||||
'Umgebungstemperatur in Celsius',
|
||||
'Ambient temperature in Celsius'),
|
||||
|
||||
('humidity_percent', 'Luftfeuchtigkeit', 'Humidity', 'environmental', 'integer', '%', 'humidity_percent',
|
||||
'{"min": 0, "max": 100}'::jsonb,
|
||||
'Relative Luftfeuchtigkeit in Prozent',
|
||||
'Relative humidity in percent'),
|
||||
|
||||
-- Performance Parameters (calculated)
|
||||
('avg_hr_percent', '% Max-HF', '% Max HR', 'performance', 'float', '%', 'avg_hr_percent',
|
||||
'{"min": 0, "max": 100}'::jsonb,
|
||||
'Durchschnittspuls als Prozent der maximalen Herzfrequenz',
|
||||
'Average heart rate as percentage of max heart rate'),
|
||||
|
||||
('kcal_per_km', 'Kalorien pro km', 'Calories per km', 'performance', 'float', 'kcal/km', 'kcal_per_km',
|
||||
'{"min": 0, "max": 1000}'::jsonb,
|
||||
'Kalorienverbrauch pro Kilometer',
|
||||
'Calorie burn per kilometer');
|
||||
|
||||
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
-- SUMMARY
|
||||
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
-- Display inserted parameters
|
||||
DO $$
|
||||
BEGIN
|
||||
RAISE NOTICE '✓ Migration 013 completed';
|
||||
RAISE NOTICE ' - Created training_parameters table';
|
||||
RAISE NOTICE ' - Inserted % standard parameters', (SELECT COUNT(*) FROM training_parameters);
|
||||
END $$;
|
||||
@@ -0,0 +1,114 @@
|
||||
-- Migration 014: Training Type Profiles & Activity Evaluation
|
||||
-- Training Type Profiles System - Schema Extensions
|
||||
-- Date: 2026-03-23
|
||||
-- Issue: #15
|
||||
|
||||
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
-- EXTEND TRAINING TYPES
|
||||
-- Add profile column for comprehensive training type configuration
|
||||
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
ALTER TABLE training_types ADD COLUMN IF NOT EXISTS profile JSONB DEFAULT NULL;
|
||||
|
||||
CREATE INDEX idx_training_types_profile_enabled ON training_types
|
||||
((profile->'rule_sets'->'minimum_requirements'->>'enabled'))
|
||||
WHERE profile IS NOT NULL;
|
||||
|
||||
COMMENT ON COLUMN training_types.profile IS 'Comprehensive training type profile with 7 dimensions (rule_sets, intensity_zones, training_effects, periodization, performance_indicators, safety, ai_context)';
|
||||
|
||||
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
-- EXTEND ACTIVITY LOG
|
||||
-- Add evaluation results and quality labels
|
||||
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS evaluation JSONB DEFAULT NULL;
|
||||
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS quality_label VARCHAR(20);
|
||||
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS overall_score FLOAT;
|
||||
|
||||
CREATE INDEX idx_activity_quality_label ON activity_log(quality_label)
|
||||
WHERE quality_label IS NOT NULL;
|
||||
|
||||
CREATE INDEX idx_activity_overall_score ON activity_log(overall_score DESC)
|
||||
WHERE overall_score IS NOT NULL;
|
||||
|
||||
CREATE INDEX idx_activity_evaluation_passed ON activity_log
|
||||
((evaluation->'rule_set_results'->'minimum_requirements'->>'passed'))
|
||||
WHERE evaluation IS NOT NULL;
|
||||
|
||||
COMMENT ON COLUMN activity_log.evaluation IS 'Complete evaluation result (7 dimensions, scores, recommendations, warnings)';
|
||||
COMMENT ON COLUMN activity_log.quality_label IS 'Quality label: excellent, good, acceptable, poor (for quick filtering)';
|
||||
COMMENT ON COLUMN activity_log.overall_score IS 'Overall quality score 0.0-1.0 (for sorting)';
|
||||
|
||||
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
-- ADD MISSING COLUMNS (if not already added by previous migrations)
|
||||
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
-- Add HR columns if not exist (might be in Migration 008)
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name='activity_log' AND column_name='hr_min') THEN
|
||||
ALTER TABLE activity_log ADD COLUMN hr_min INTEGER CHECK (hr_min > 0 AND hr_min < 200);
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- Add performance columns for calculated values
|
||||
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS avg_hr_percent FLOAT;
|
||||
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS kcal_per_km FLOAT;
|
||||
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS pace_min_per_km FLOAT;
|
||||
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS cadence INTEGER;
|
||||
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS avg_power INTEGER;
|
||||
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS elevation_gain INTEGER;
|
||||
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS temperature_celsius FLOAT;
|
||||
ALTER TABLE activity_log ADD COLUMN IF NOT EXISTS humidity_percent INTEGER;
|
||||
|
||||
COMMENT ON COLUMN activity_log.avg_hr_percent IS 'Average HR as percentage of user max HR (calculated)';
|
||||
COMMENT ON COLUMN activity_log.kcal_per_km IS 'Calories burned per kilometer (calculated)';
|
||||
|
||||
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
-- HELPER FUNCTION: Calculate avg_hr_percent
|
||||
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
CREATE OR REPLACE FUNCTION calculate_avg_hr_percent()
|
||||
RETURNS TRIGGER AS $$
|
||||
DECLARE
|
||||
user_max_hr INTEGER;
|
||||
BEGIN
|
||||
-- Get user's max HR from profile
|
||||
SELECT hf_max INTO user_max_hr
|
||||
FROM profiles
|
||||
WHERE id = NEW.profile_id;
|
||||
|
||||
-- Calculate percentage if both values exist
|
||||
IF NEW.hr_avg IS NOT NULL AND user_max_hr IS NOT NULL AND user_max_hr > 0 THEN
|
||||
NEW.avg_hr_percent := (NEW.hr_avg::float / user_max_hr::float) * 100;
|
||||
END IF;
|
||||
|
||||
-- Calculate kcal per km
|
||||
IF NEW.kcal_active IS NOT NULL AND NEW.distance_km IS NOT NULL AND NEW.distance_km > 0 THEN
|
||||
NEW.kcal_per_km := NEW.kcal_active::float / NEW.distance_km;
|
||||
END IF;
|
||||
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- Trigger for automatic calculation
|
||||
DROP TRIGGER IF EXISTS trg_calculate_performance_metrics ON activity_log;
|
||||
CREATE TRIGGER trg_calculate_performance_metrics
|
||||
BEFORE INSERT OR UPDATE ON activity_log
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION calculate_avg_hr_percent();
|
||||
|
||||
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
-- SUMMARY
|
||||
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
RAISE NOTICE '✓ Migration 014 completed';
|
||||
RAISE NOTICE ' - Extended training_types with profile column';
|
||||
RAISE NOTICE ' - Extended activity_log with evaluation columns';
|
||||
RAISE NOTICE ' - Added performance metric calculations';
|
||||
RAISE NOTICE ' - Created indexes for fast queries';
|
||||
END $$;
|
||||
@@ -0,0 +1,29 @@
|
||||
-- Migration 014: Extended Vitals (Blood Pressure, VO2 Max, SpO2, Respiratory Rate)
|
||||
-- v9d Phase 2d: Complete vitals tracking
|
||||
-- Date: 2026-03-23
|
||||
|
||||
-- Add new vitals fields
|
||||
ALTER TABLE vitals_log
|
||||
ADD COLUMN IF NOT EXISTS blood_pressure_systolic INTEGER CHECK (blood_pressure_systolic > 0 AND blood_pressure_systolic < 300),
|
||||
ADD COLUMN IF NOT EXISTS blood_pressure_diastolic INTEGER CHECK (blood_pressure_diastolic > 0 AND blood_pressure_diastolic < 200),
|
||||
ADD COLUMN IF NOT EXISTS pulse INTEGER CHECK (pulse > 0 AND pulse < 250),
|
||||
ADD COLUMN IF NOT EXISTS vo2_max DECIMAL(4,1) CHECK (vo2_max > 0 AND vo2_max < 100),
|
||||
ADD COLUMN IF NOT EXISTS spo2 INTEGER CHECK (spo2 >= 70 AND spo2 <= 100),
|
||||
ADD COLUMN IF NOT EXISTS respiratory_rate DECIMAL(4,1) CHECK (respiratory_rate > 0 AND respiratory_rate < 60),
|
||||
ADD COLUMN IF NOT EXISTS irregular_heartbeat BOOLEAN DEFAULT false,
|
||||
ADD COLUMN IF NOT EXISTS possible_afib BOOLEAN DEFAULT false;
|
||||
|
||||
-- Update source check to include omron
|
||||
ALTER TABLE vitals_log DROP CONSTRAINT IF EXISTS vitals_log_source_check;
|
||||
ALTER TABLE vitals_log ADD CONSTRAINT vitals_log_source_check
|
||||
CHECK (source IN ('manual', 'apple_health', 'garmin', 'omron'));
|
||||
|
||||
-- Comments
|
||||
COMMENT ON COLUMN vitals_log.blood_pressure_systolic IS 'Systolic blood pressure (mmHg) from Omron or manual entry';
|
||||
COMMENT ON COLUMN vitals_log.blood_pressure_diastolic IS 'Diastolic blood pressure (mmHg) from Omron or manual entry';
|
||||
COMMENT ON COLUMN vitals_log.pulse IS 'Pulse during blood pressure measurement (bpm)';
|
||||
COMMENT ON COLUMN vitals_log.vo2_max IS 'VO2 Max from Apple Watch (ml/kg/min)';
|
||||
COMMENT ON COLUMN vitals_log.spo2 IS 'Blood oxygen saturation (%) from Apple Watch';
|
||||
COMMENT ON COLUMN vitals_log.respiratory_rate IS 'Respiratory rate (breaths/min) from Apple Watch';
|
||||
COMMENT ON COLUMN vitals_log.irregular_heartbeat IS 'Irregular heartbeat detected (Omron)';
|
||||
COMMENT ON COLUMN vitals_log.possible_afib IS 'Possible atrial fibrillation (Omron)';
|
||||
@@ -0,0 +1,184 @@
|
||||
-- Migration 015: Vitals Refactoring - Trennung Baseline vs. Context-Dependent
|
||||
-- v9d Phase 2d: Architektur-Verbesserung für bessere Datenqualität
|
||||
-- Date: 2026-03-23
|
||||
|
||||
-- ══════════════════════════════════════════════════════════════════════════════
|
||||
-- STEP 1: Create new tables
|
||||
-- ══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
-- Baseline Vitals (slow-changing, once daily, morning measurement)
|
||||
CREATE TABLE IF NOT EXISTS vitals_baseline (
|
||||
id SERIAL PRIMARY KEY,
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
date DATE NOT NULL,
|
||||
|
||||
-- Core baseline vitals
|
||||
resting_hr INTEGER CHECK (resting_hr > 0 AND resting_hr < 120),
|
||||
hrv INTEGER CHECK (hrv > 0 AND hrv < 300),
|
||||
vo2_max DECIMAL(4,1) CHECK (vo2_max > 0 AND vo2_max < 100),
|
||||
spo2 INTEGER CHECK (spo2 >= 70 AND spo2 <= 100),
|
||||
respiratory_rate DECIMAL(4,1) CHECK (respiratory_rate > 0 AND respiratory_rate < 60),
|
||||
|
||||
-- Future baseline vitals (prepared for expansion)
|
||||
body_temperature DECIMAL(3,1) CHECK (body_temperature > 30 AND body_temperature < 45),
|
||||
resting_metabolic_rate INTEGER CHECK (resting_metabolic_rate > 0),
|
||||
|
||||
-- Metadata
|
||||
note TEXT,
|
||||
source VARCHAR(20) DEFAULT 'manual' CHECK (source IN ('manual', 'apple_health', 'garmin', 'withings')),
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT unique_baseline_per_day UNIQUE(profile_id, date)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_vitals_baseline_profile_date ON vitals_baseline(profile_id, date DESC);
|
||||
|
||||
COMMENT ON TABLE vitals_baseline IS 'v9d Phase 2d: Baseline vitals measured once daily (morning, fasted)';
|
||||
COMMENT ON COLUMN vitals_baseline.resting_hr IS 'Resting heart rate (bpm) - measured in the morning before getting up';
|
||||
COMMENT ON COLUMN vitals_baseline.hrv IS 'Heart rate variability (ms) - higher is better';
|
||||
COMMENT ON COLUMN vitals_baseline.vo2_max IS 'VO2 Max (ml/kg/min) - estimated by Apple Watch or lab test';
|
||||
COMMENT ON COLUMN vitals_baseline.spo2 IS 'Blood oxygen saturation (%) - baseline measurement';
|
||||
COMMENT ON COLUMN vitals_baseline.respiratory_rate IS 'Respiratory rate (breaths/min) - baseline measurement';
|
||||
|
||||
-- ══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
-- Blood Pressure Log (context-dependent, multiple times per day)
|
||||
CREATE TABLE IF NOT EXISTS blood_pressure_log (
|
||||
id SERIAL PRIMARY KEY,
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
measured_at TIMESTAMP NOT NULL,
|
||||
|
||||
-- Blood pressure measurements
|
||||
systolic INTEGER NOT NULL CHECK (systolic > 0 AND systolic < 300),
|
||||
diastolic INTEGER NOT NULL CHECK (diastolic > 0 AND diastolic < 200),
|
||||
pulse INTEGER CHECK (pulse > 0 AND pulse < 250),
|
||||
|
||||
-- Context tagging for correlation analysis
|
||||
context VARCHAR(30) CHECK (context IN (
|
||||
'morning_fasted', -- Morgens nüchtern
|
||||
'after_meal', -- Nach dem Essen
|
||||
'before_training', -- Vor dem Training
|
||||
'after_training', -- Nach dem Training
|
||||
'evening', -- Abends
|
||||
'stress', -- Bei Stress
|
||||
'resting', -- Ruhemessung
|
||||
'other' -- Sonstiges
|
||||
)),
|
||||
|
||||
-- Warning flags (Omron)
|
||||
irregular_heartbeat BOOLEAN DEFAULT false,
|
||||
possible_afib BOOLEAN DEFAULT false,
|
||||
|
||||
-- Metadata
|
||||
note TEXT,
|
||||
source VARCHAR(20) DEFAULT 'manual' CHECK (source IN ('manual', 'omron', 'apple_health', 'withings')),
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT unique_bp_measurement UNIQUE(profile_id, measured_at)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_blood_pressure_profile_datetime ON blood_pressure_log(profile_id, measured_at DESC);
|
||||
CREATE INDEX idx_blood_pressure_context ON blood_pressure_log(context) WHERE context IS NOT NULL;
|
||||
|
||||
COMMENT ON TABLE blood_pressure_log IS 'v9d Phase 2d: Blood pressure measurements (multiple per day, context-aware)';
|
||||
COMMENT ON COLUMN blood_pressure_log.context IS 'Measurement context for correlation analysis';
|
||||
COMMENT ON COLUMN blood_pressure_log.irregular_heartbeat IS 'Irregular heartbeat detected (Omron device)';
|
||||
COMMENT ON COLUMN blood_pressure_log.possible_afib IS 'Possible atrial fibrillation (Omron device)';
|
||||
|
||||
-- ══════════════════════════════════════════════════════════════════════════════
|
||||
-- STEP 2: Migrate existing data from vitals_log
|
||||
-- ══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
-- Migrate baseline vitals (RHR, HRV, VO2 Max, SpO2, Respiratory Rate)
|
||||
INSERT INTO vitals_baseline (
|
||||
profile_id, date,
|
||||
resting_hr, hrv, vo2_max, spo2, respiratory_rate,
|
||||
note, source, created_at, updated_at
|
||||
)
|
||||
SELECT
|
||||
profile_id, date,
|
||||
resting_hr, hrv, vo2_max, spo2, respiratory_rate,
|
||||
note, source, created_at, updated_at
|
||||
FROM vitals_log
|
||||
WHERE resting_hr IS NOT NULL
|
||||
OR hrv IS NOT NULL
|
||||
OR vo2_max IS NOT NULL
|
||||
OR spo2 IS NOT NULL
|
||||
OR respiratory_rate IS NOT NULL
|
||||
ON CONFLICT (profile_id, date) DO NOTHING;
|
||||
|
||||
-- Migrate blood pressure measurements
|
||||
-- Note: Use date + 08:00 as default timestamp (morning measurement)
|
||||
INSERT INTO blood_pressure_log (
|
||||
profile_id, measured_at,
|
||||
systolic, diastolic, pulse,
|
||||
irregular_heartbeat, possible_afib,
|
||||
note, source, created_at
|
||||
)
|
||||
SELECT
|
||||
profile_id,
|
||||
(date + TIME '08:00:00')::timestamp AS measured_at,
|
||||
blood_pressure_systolic,
|
||||
blood_pressure_diastolic,
|
||||
pulse,
|
||||
irregular_heartbeat,
|
||||
possible_afib,
|
||||
note,
|
||||
CASE
|
||||
WHEN source = 'manual' THEN 'manual'
|
||||
WHEN source = 'omron' THEN 'omron'
|
||||
ELSE 'manual'
|
||||
END AS source,
|
||||
created_at
|
||||
FROM vitals_log
|
||||
WHERE blood_pressure_systolic IS NOT NULL
|
||||
AND blood_pressure_diastolic IS NOT NULL
|
||||
ON CONFLICT (profile_id, measured_at) DO NOTHING;
|
||||
|
||||
-- ══════════════════════════════════════════════════════════════════════════════
|
||||
-- STEP 3: Drop old vitals_log table (backup first)
|
||||
-- ══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
-- Rename old table as backup (keep for safety, can be dropped later)
|
||||
ALTER TABLE vitals_log RENAME TO vitals_log_backup_pre_015;
|
||||
|
||||
-- Drop old index (it's on the renamed table now)
|
||||
DROP INDEX IF EXISTS idx_vitals_profile_date;
|
||||
|
||||
-- ══════════════════════════════════════════════════════════════════════════════
|
||||
-- STEP 4: Prepared for future vitals types
|
||||
-- ══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
-- Future tables (commented out, create when needed):
|
||||
|
||||
-- Glucose Log (for blood sugar tracking)
|
||||
-- CREATE TABLE glucose_log (
|
||||
-- id SERIAL PRIMARY KEY,
|
||||
-- profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
-- measured_at TIMESTAMP NOT NULL,
|
||||
-- glucose_mg_dl INTEGER NOT NULL CHECK (glucose_mg_dl > 0 AND glucose_mg_dl < 500),
|
||||
-- context VARCHAR(30) CHECK (context IN (
|
||||
-- 'fasted', 'before_meal', 'after_meal_1h', 'after_meal_2h', 'before_training', 'after_training', 'other'
|
||||
-- )),
|
||||
-- note TEXT,
|
||||
-- source VARCHAR(20) DEFAULT 'manual',
|
||||
-- created_at TIMESTAMP DEFAULT NOW(),
|
||||
-- CONSTRAINT unique_glucose_measurement UNIQUE(profile_id, measured_at)
|
||||
-- );
|
||||
|
||||
-- Temperature Log (for illness tracking)
|
||||
-- CREATE TABLE temperature_log (
|
||||
-- id SERIAL PRIMARY KEY,
|
||||
-- profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
-- measured_at TIMESTAMP NOT NULL,
|
||||
-- temperature_celsius DECIMAL(3,1) NOT NULL CHECK (temperature_celsius > 30 AND temperature_celsius < 45),
|
||||
-- measurement_location VARCHAR(20) CHECK (measurement_location IN ('oral', 'ear', 'forehead', 'armpit')),
|
||||
-- note TEXT,
|
||||
-- created_at TIMESTAMP DEFAULT NOW(),
|
||||
-- CONSTRAINT unique_temperature_measurement UNIQUE(profile_id, measured_at)
|
||||
-- );
|
||||
|
||||
-- ══════════════════════════════════════════════════════════════════════════════
|
||||
-- Migration complete
|
||||
-- ══════════════════════════════════════════════════════════════════════════════
|
||||
@@ -0,0 +1,21 @@
|
||||
-- Migration 016: Global Quality Filter Setting
|
||||
-- Issue: #31
|
||||
-- Date: 2026-03-23
|
||||
-- Description: Add quality_filter_level to profiles for consistent data views
|
||||
|
||||
-- Add quality_filter_level column to profiles
|
||||
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS quality_filter_level VARCHAR(20) DEFAULT 'all';
|
||||
|
||||
COMMENT ON COLUMN profiles.quality_filter_level IS 'Global quality filter for all activity views: all, quality, very_good, excellent';
|
||||
|
||||
-- Create index for performance (if filtering becomes common)
|
||||
CREATE INDEX IF NOT EXISTS idx_profiles_quality_filter ON profiles(quality_filter_level);
|
||||
|
||||
-- Migration tracking
|
||||
DO $$
|
||||
BEGIN
|
||||
RAISE NOTICE '✓ Migration 016: Added global quality filter setting';
|
||||
RAISE NOTICE ' - Added profiles.quality_filter_level column';
|
||||
RAISE NOTICE ' - Default: all (no filter)';
|
||||
RAISE NOTICE ' - Values: all, quality, very_good, excellent';
|
||||
END $$;
|
||||
@@ -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;
|
||||
@@ -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)
|
||||
-- ============================================================================
|
||||
@@ -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
|
||||
-- ============================================================================
|
||||
@@ -27,6 +27,7 @@ class ProfileUpdate(BaseModel):
|
||||
height: Optional[float] = None
|
||||
goal_weight: Optional[float] = None
|
||||
goal_bf_pct: Optional[float] = None
|
||||
quality_filter_level: Optional[str] = None # Issue #31: Global quality filter
|
||||
|
||||
|
||||
# ── Tracking Models ───────────────────────────────────────────────────────────
|
||||
@@ -84,6 +85,9 @@ class ActivityEntry(BaseModel):
|
||||
rpe: Optional[int] = None
|
||||
source: Optional[str] = 'manual'
|
||||
notes: Optional[str] = None
|
||||
training_type_id: Optional[int] = None # v9d: Training type categorization
|
||||
training_category: Optional[str] = None # v9d: Denormalized category
|
||||
training_subcategory: Optional[str] = None # v9d: Denormalized subcategory
|
||||
|
||||
|
||||
class NutritionDay(BaseModel):
|
||||
@@ -110,6 +114,12 @@ class PasswordResetConfirm(BaseModel):
|
||||
new_password: str
|
||||
|
||||
|
||||
class RegisterRequest(BaseModel):
|
||||
name: str
|
||||
email: str
|
||||
password: str
|
||||
|
||||
|
||||
# ── Admin Models ──────────────────────────────────────────────────────────────
|
||||
|
||||
class AdminProfileUpdate(BaseModel):
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
"""
|
||||
Training Type Profiles - Master Evaluator
|
||||
Comprehensive activity evaluation across all 7 dimensions.
|
||||
|
||||
Issue: #15
|
||||
Date: 2026-03-23
|
||||
"""
|
||||
from typing import Dict, Optional, List
|
||||
from datetime import datetime
|
||||
import logging
|
||||
|
||||
from rule_engine import RuleEvaluator, IntensityZoneEvaluator, TrainingEffectsEvaluator
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TrainingProfileEvaluator:
|
||||
"""
|
||||
Master class for comprehensive activity evaluation.
|
||||
|
||||
Evaluates an activity against a training type profile across 7 dimensions:
|
||||
1. Minimum Requirements (Quality Gates)
|
||||
2. Intensity Zones (HR zones)
|
||||
3. Training Effects (Abilities)
|
||||
4. Periodization (Frequency & Recovery)
|
||||
5. Performance Indicators (KPIs)
|
||||
6. Safety (Warnings)
|
||||
7. AI Context
|
||||
"""
|
||||
|
||||
def __init__(self, parameters_registry: Dict[str, Dict]):
|
||||
"""
|
||||
Initialize evaluator with parameter registry.
|
||||
|
||||
Args:
|
||||
parameters_registry: Dict mapping parameter_key -> config
|
||||
"""
|
||||
self.parameters_registry = parameters_registry
|
||||
self.rule_evaluator = RuleEvaluator()
|
||||
self.zone_evaluator = IntensityZoneEvaluator()
|
||||
self.effects_evaluator = TrainingEffectsEvaluator()
|
||||
|
||||
def evaluate_activity(
|
||||
self,
|
||||
activity: Dict,
|
||||
training_type_profile: Optional[Dict],
|
||||
context: Optional[Dict] = None
|
||||
) -> Dict:
|
||||
"""
|
||||
Complete evaluation of an activity against its training type profile.
|
||||
|
||||
Args:
|
||||
activity: Activity data dictionary
|
||||
training_type_profile: Training type profile (JSONB)
|
||||
context: {
|
||||
"user_profile": {...},
|
||||
"recent_activities": [...],
|
||||
"historical_activities": [...]
|
||||
}
|
||||
|
||||
Returns:
|
||||
{
|
||||
"evaluated_at": ISO timestamp,
|
||||
"profile_version": str,
|
||||
"rule_set_results": {
|
||||
"minimum_requirements": {...},
|
||||
"intensity_zones": {...},
|
||||
"training_effects": {...},
|
||||
"periodization": {...},
|
||||
"performance_indicators": {...},
|
||||
"safety": {...}
|
||||
},
|
||||
"overall_score": float (0-1),
|
||||
"quality_label": str,
|
||||
"recommendations": [str],
|
||||
"warnings": [str]
|
||||
}
|
||||
"""
|
||||
# No profile? Return unvalidated result
|
||||
if not training_type_profile:
|
||||
return self._create_unvalidated_result()
|
||||
|
||||
rule_sets = training_type_profile.get("rule_sets", {})
|
||||
context = context or {}
|
||||
|
||||
results = {
|
||||
"evaluated_at": datetime.now().isoformat(),
|
||||
"profile_version": training_type_profile.get("version", "unknown"),
|
||||
"rule_set_results": {}
|
||||
}
|
||||
|
||||
# ━━━ 1. MINIMUM REQUIREMENTS ━━━
|
||||
if "minimum_requirements" in rule_sets:
|
||||
results["rule_set_results"]["minimum_requirements"] = \
|
||||
self.rule_evaluator.evaluate_rule_set(
|
||||
rule_sets["minimum_requirements"],
|
||||
activity,
|
||||
self.parameters_registry
|
||||
)
|
||||
|
||||
# ━━━ 2. INTENSITY ZONES ━━━
|
||||
if "intensity_zones" in rule_sets:
|
||||
results["rule_set_results"]["intensity_zones"] = \
|
||||
self.zone_evaluator.evaluate(
|
||||
rule_sets["intensity_zones"],
|
||||
activity,
|
||||
context.get("user_profile", {})
|
||||
)
|
||||
|
||||
# ━━━ 3. TRAINING EFFECTS ━━━
|
||||
if "training_effects" in rule_sets:
|
||||
results["rule_set_results"]["training_effects"] = \
|
||||
self.effects_evaluator.evaluate(
|
||||
rule_sets["training_effects"],
|
||||
activity,
|
||||
results["rule_set_results"].get("intensity_zones")
|
||||
)
|
||||
|
||||
# ━━━ 4. PERIODIZATION ━━━
|
||||
if "periodization" in rule_sets:
|
||||
results["rule_set_results"]["periodization"] = \
|
||||
self._evaluate_periodization(
|
||||
rule_sets["periodization"],
|
||||
activity,
|
||||
context.get("recent_activities", [])
|
||||
)
|
||||
|
||||
# ━━━ 5. PERFORMANCE INDICATORS ━━━
|
||||
if "performance_indicators" in rule_sets:
|
||||
results["rule_set_results"]["performance_indicators"] = \
|
||||
self._evaluate_performance(
|
||||
rule_sets["performance_indicators"],
|
||||
activity,
|
||||
context.get("historical_activities", [])
|
||||
)
|
||||
|
||||
# ━━━ 6. SAFETY WARNINGS ━━━
|
||||
if "safety" in rule_sets:
|
||||
results["rule_set_results"]["safety"] = \
|
||||
self._evaluate_safety(
|
||||
rule_sets["safety"],
|
||||
activity
|
||||
)
|
||||
|
||||
# ━━━ OVERALL SCORE & QUALITY LABEL ━━━
|
||||
overall_score = self._calculate_overall_score(results["rule_set_results"])
|
||||
results["overall_score"] = overall_score
|
||||
results["quality_label"] = self._get_quality_label(overall_score)
|
||||
|
||||
# ━━━ RECOMMENDATIONS & WARNINGS ━━━
|
||||
results["recommendations"] = self._generate_recommendations(results)
|
||||
results["warnings"] = self._collect_warnings(results)
|
||||
|
||||
return results
|
||||
|
||||
def _create_unvalidated_result(self) -> Dict:
|
||||
"""Creates result for activities without profile."""
|
||||
return {
|
||||
"evaluated_at": datetime.now().isoformat(),
|
||||
"profile_version": None,
|
||||
"rule_set_results": {},
|
||||
"overall_score": None,
|
||||
"quality_label": None,
|
||||
"recommendations": ["Kein Trainingsprofil konfiguriert"],
|
||||
"warnings": []
|
||||
}
|
||||
|
||||
def _evaluate_periodization(
|
||||
self,
|
||||
config: Dict,
|
||||
activity: Dict,
|
||||
recent_activities: List[Dict]
|
||||
) -> Dict:
|
||||
"""
|
||||
Evaluates periodization compliance (frequency & recovery).
|
||||
|
||||
Simplified for MVP - full implementation later.
|
||||
"""
|
||||
if not config.get("enabled", False):
|
||||
return {"enabled": False}
|
||||
|
||||
# Basic frequency check
|
||||
training_type_id = activity.get("training_type_id")
|
||||
same_type_this_week = sum(
|
||||
1 for a in recent_activities
|
||||
if a.get("training_type_id") == training_type_id
|
||||
)
|
||||
|
||||
frequency_config = config.get("frequency", {})
|
||||
optimal = frequency_config.get("per_week_optimal", 3)
|
||||
|
||||
return {
|
||||
"enabled": True,
|
||||
"weekly_count": same_type_this_week,
|
||||
"optimal_count": optimal,
|
||||
"frequency_status": "optimal" if same_type_this_week <= optimal else "over_optimal",
|
||||
"recovery_adequate": True, # Simplified for MVP
|
||||
"warning": None
|
||||
}
|
||||
|
||||
def _evaluate_performance(
|
||||
self,
|
||||
config: Dict,
|
||||
activity: Dict,
|
||||
historical_activities: List[Dict]
|
||||
) -> Dict:
|
||||
"""
|
||||
Evaluates performance development.
|
||||
|
||||
Simplified for MVP - full implementation later.
|
||||
"""
|
||||
if not config.get("enabled", False):
|
||||
return {"enabled": False}
|
||||
|
||||
return {
|
||||
"enabled": True,
|
||||
"trend": "stable", # Simplified
|
||||
"metrics_comparison": {},
|
||||
"benchmark_level": "intermediate"
|
||||
}
|
||||
|
||||
def _evaluate_safety(self, config: Dict, activity: Dict) -> Dict:
|
||||
"""
|
||||
Evaluates safety warnings.
|
||||
"""
|
||||
if not config.get("enabled", False):
|
||||
return {"enabled": False, "warnings": []}
|
||||
|
||||
warnings_config = config.get("warnings", [])
|
||||
triggered_warnings = []
|
||||
|
||||
for warning_rule in warnings_config:
|
||||
param_key = warning_rule.get("parameter")
|
||||
operator = warning_rule.get("operator")
|
||||
threshold = warning_rule.get("value")
|
||||
severity = warning_rule.get("severity", "medium")
|
||||
message = warning_rule.get("message", "")
|
||||
|
||||
actual_value = activity.get(param_key)
|
||||
|
||||
if actual_value is not None:
|
||||
operator_func = RuleEvaluator.OPERATORS.get(operator)
|
||||
if operator_func and operator_func(actual_value, threshold):
|
||||
triggered_warnings.append({
|
||||
"severity": severity,
|
||||
"message": message,
|
||||
"parameter": param_key,
|
||||
"actual_value": actual_value,
|
||||
"threshold": threshold
|
||||
})
|
||||
|
||||
return {
|
||||
"enabled": True,
|
||||
"warnings": triggered_warnings
|
||||
}
|
||||
|
||||
def _calculate_overall_score(self, rule_set_results: Dict) -> float:
|
||||
"""
|
||||
Calculates weighted overall score.
|
||||
|
||||
Weights:
|
||||
- Minimum Requirements: 40%
|
||||
- Intensity Zones: 20%
|
||||
- Periodization: 20%
|
||||
- Performance: 10%
|
||||
- Training Effects: 10%
|
||||
"""
|
||||
weights = {
|
||||
"minimum_requirements": 0.4,
|
||||
"intensity_zones": 0.2,
|
||||
"periodization": 0.2,
|
||||
"performance_indicators": 0.1,
|
||||
"training_effects": 0.1
|
||||
}
|
||||
|
||||
total_score = 0.0
|
||||
total_weight = 0.0
|
||||
|
||||
for rule_set_name, weight in weights.items():
|
||||
result = rule_set_results.get(rule_set_name)
|
||||
if result and result.get("enabled"):
|
||||
score = result.get("score", 0.5)
|
||||
|
||||
# Special handling for different result types
|
||||
if rule_set_name == "intensity_zones":
|
||||
score = result.get("duration_quality", 0.5)
|
||||
elif rule_set_name == "periodization":
|
||||
score = 1.0 if result.get("recovery_adequate", False) else 0.5
|
||||
|
||||
total_score += score * weight
|
||||
total_weight += weight
|
||||
|
||||
return round(total_score / total_weight, 2) if total_weight > 0 else 0.5
|
||||
|
||||
def _get_quality_label(self, score: Optional[float]) -> Optional[str]:
|
||||
"""Converts score to quality label."""
|
||||
if score is None:
|
||||
return None
|
||||
|
||||
if score >= 0.9:
|
||||
return "excellent"
|
||||
elif score >= 0.7:
|
||||
return "good"
|
||||
elif score >= 0.5:
|
||||
return "acceptable"
|
||||
else:
|
||||
return "poor"
|
||||
|
||||
def _generate_recommendations(self, results: Dict) -> List[str]:
|
||||
"""Generates actionable recommendations."""
|
||||
recommendations = []
|
||||
|
||||
# Check minimum requirements
|
||||
min_req = results["rule_set_results"].get("minimum_requirements", {})
|
||||
if min_req.get("enabled") and not min_req.get("passed"):
|
||||
for failed in min_req.get("failed_rules", []):
|
||||
param = failed.get("parameter")
|
||||
actual = failed.get("actual_value")
|
||||
expected = failed.get("expected_value")
|
||||
reason = failed.get("reason", "")
|
||||
symbol = failed.get("operator_symbol", "")
|
||||
|
||||
recommendations.append(
|
||||
f"{param}: {actual} {symbol} {expected} - {reason}"
|
||||
)
|
||||
|
||||
# Check intensity zones
|
||||
zone_result = results["rule_set_results"].get("intensity_zones", {})
|
||||
if zone_result.get("enabled") and zone_result.get("recommendation"):
|
||||
recommendations.append(zone_result["recommendation"])
|
||||
|
||||
# Default recommendation if excellent
|
||||
if results.get("quality_label") == "excellent" and not recommendations:
|
||||
recommendations.append("Hervorragendes Training! Weiter so.")
|
||||
|
||||
return recommendations
|
||||
|
||||
def _collect_warnings(self, results: Dict) -> List[str]:
|
||||
"""Collects all warnings from safety checks."""
|
||||
safety_result = results["rule_set_results"].get("safety", {})
|
||||
if not safety_result.get("enabled"):
|
||||
return []
|
||||
|
||||
warnings = []
|
||||
for warning in safety_result.get("warnings", []):
|
||||
severity_icon = "🔴" if warning["severity"] == "high" else "⚠️"
|
||||
warnings.append(f"{severity_icon} {warning['message']}")
|
||||
|
||||
return warnings
|
||||
@@ -0,0 +1,450 @@
|
||||
"""
|
||||
Training Type Profile Templates
|
||||
Pre-configured profiles for common training types.
|
||||
|
||||
Issue: #15
|
||||
Date: 2026-03-23
|
||||
"""
|
||||
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
# TEMPLATE: LAUFEN (Running) - Ausdauer-fokussiert
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
TEMPLATE_RUNNING = {
|
||||
"version": "1.0",
|
||||
"name": "Laufen (Standard)",
|
||||
"description": "Ausdauerlauf mit Herzfrequenz-Zonen",
|
||||
|
||||
"rule_sets": {
|
||||
"minimum_requirements": {
|
||||
"enabled": True,
|
||||
"pass_strategy": "weighted_score",
|
||||
"pass_threshold": 0.6,
|
||||
"rules": [
|
||||
{
|
||||
"parameter": "duration_min",
|
||||
"operator": "gte",
|
||||
"value": 15,
|
||||
"weight": 5,
|
||||
"optional": False,
|
||||
"reason": "Mindestens 15 Minuten für Trainingseffekt"
|
||||
},
|
||||
{
|
||||
"parameter": "avg_hr",
|
||||
"operator": "gte",
|
||||
"value": 100,
|
||||
"weight": 3,
|
||||
"optional": False,
|
||||
"reason": "Puls muss für Ausdauerreiz erhöht sein"
|
||||
},
|
||||
{
|
||||
"parameter": "distance_km",
|
||||
"operator": "gte",
|
||||
"value": 1.0,
|
||||
"weight": 2,
|
||||
"optional": False,
|
||||
"reason": "Mindestens 1 km Distanz"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
"intensity_zones": {
|
||||
"enabled": True,
|
||||
"zones": [
|
||||
{
|
||||
"id": "regeneration",
|
||||
"name": "Regeneration",
|
||||
"color": "#4CAF50",
|
||||
"effect": "Aktive Erholung",
|
||||
"target_duration_min": 30,
|
||||
"rules": [
|
||||
{
|
||||
"parameter": "avg_hr_percent",
|
||||
"operator": "between",
|
||||
"value": [50, 60]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "grundlagenausdauer",
|
||||
"name": "Grundlagenausdauer",
|
||||
"color": "#2196F3",
|
||||
"effect": "Fettverbrennung, aerobe Basis",
|
||||
"target_duration_min": 45,
|
||||
"rules": [
|
||||
{
|
||||
"parameter": "avg_hr_percent",
|
||||
"operator": "between",
|
||||
"value": [60, 70]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "entwicklungsbereich",
|
||||
"name": "Entwicklungsbereich",
|
||||
"color": "#FF9800",
|
||||
"effect": "VO2max-Training, Laktattoleranz",
|
||||
"target_duration_min": 30,
|
||||
"rules": [
|
||||
{
|
||||
"parameter": "avg_hr_percent",
|
||||
"operator": "between",
|
||||
"value": [70, 80]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "schwellentraining",
|
||||
"name": "Schwellentraining",
|
||||
"color": "#F44336",
|
||||
"effect": "Anaerobe Schwelle, Wettkampftempo",
|
||||
"target_duration_min": 20,
|
||||
"rules": [
|
||||
{
|
||||
"parameter": "avg_hr_percent",
|
||||
"operator": "between",
|
||||
"value": [80, 90]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
"training_effects": {
|
||||
"enabled": True,
|
||||
"default_effects": {
|
||||
"primary_abilities": [
|
||||
{
|
||||
"category": "konditionell",
|
||||
"ability": "ausdauer",
|
||||
"intensity": 5
|
||||
}
|
||||
],
|
||||
"secondary_abilities": [
|
||||
{
|
||||
"category": "konditionell",
|
||||
"ability": "schnelligkeit",
|
||||
"intensity": 2
|
||||
},
|
||||
{
|
||||
"category": "koordinativ",
|
||||
"ability": "rhythmus",
|
||||
"intensity": 3
|
||||
},
|
||||
{
|
||||
"category": "psychisch",
|
||||
"ability": "willenskraft",
|
||||
"intensity": 4
|
||||
}
|
||||
]
|
||||
},
|
||||
"metabolic_focus": ["aerobic", "fat_oxidation"],
|
||||
"muscle_groups": ["legs", "core", "cardiovascular"]
|
||||
},
|
||||
|
||||
"periodization": {
|
||||
"enabled": True,
|
||||
"frequency": {
|
||||
"per_week_optimal": 3,
|
||||
"per_week_max": 5
|
||||
},
|
||||
"recovery": {
|
||||
"min_hours_between": 24
|
||||
}
|
||||
},
|
||||
|
||||
"performance_indicators": {
|
||||
"enabled": False
|
||||
},
|
||||
|
||||
"safety": {
|
||||
"enabled": True,
|
||||
"warnings": [
|
||||
{
|
||||
"parameter": "avg_hr_percent",
|
||||
"operator": "gt",
|
||||
"value": 95,
|
||||
"severity": "high",
|
||||
"message": "Herzfrequenz zu hoch - Überbelastungsrisiko"
|
||||
},
|
||||
{
|
||||
"parameter": "duration_min",
|
||||
"operator": "gt",
|
||||
"value": 180,
|
||||
"severity": "medium",
|
||||
"message": "Sehr lange Einheit - achte auf Regeneration"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
# TEMPLATE: MEDITATION - Mental-fokussiert (≤ statt ≥ bei HR!)
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
TEMPLATE_MEDITATION = {
|
||||
"version": "1.0",
|
||||
"name": "Meditation (Standard)",
|
||||
"description": "Mentales Training mit niedrigem Puls",
|
||||
|
||||
"rule_sets": {
|
||||
"minimum_requirements": {
|
||||
"enabled": True,
|
||||
"pass_strategy": "weighted_score",
|
||||
"pass_threshold": 0.6,
|
||||
"rules": [
|
||||
{
|
||||
"parameter": "duration_min",
|
||||
"operator": "gte",
|
||||
"value": 5,
|
||||
"weight": 5,
|
||||
"optional": False,
|
||||
"reason": "Mindestens 5 Minuten für Entspannungseffekt"
|
||||
},
|
||||
{
|
||||
"parameter": "avg_hr",
|
||||
"operator": "lte",
|
||||
"value": 80,
|
||||
"weight": 4,
|
||||
"optional": False,
|
||||
"reason": "Niedriger Puls zeigt Entspannung an"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
"intensity_zones": {
|
||||
"enabled": True,
|
||||
"zones": [
|
||||
{
|
||||
"id": "deep_relaxation",
|
||||
"name": "Tiefenentspannung",
|
||||
"color": "#4CAF50",
|
||||
"effect": "Parasympathikus-Aktivierung",
|
||||
"target_duration_min": 10,
|
||||
"rules": [
|
||||
{
|
||||
"parameter": "avg_hr_percent",
|
||||
"operator": "between",
|
||||
"value": [35, 45]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "light_meditation",
|
||||
"name": "Leichte Meditation",
|
||||
"color": "#2196F3",
|
||||
"effect": "Achtsamkeit, Fokus",
|
||||
"target_duration_min": 15,
|
||||
"rules": [
|
||||
{
|
||||
"parameter": "avg_hr_percent",
|
||||
"operator": "between",
|
||||
"value": [45, 55]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
"training_effects": {
|
||||
"enabled": True,
|
||||
"default_effects": {
|
||||
"primary_abilities": [
|
||||
{
|
||||
"category": "kognitiv",
|
||||
"ability": "konzentration",
|
||||
"intensity": 5
|
||||
},
|
||||
{
|
||||
"category": "psychisch",
|
||||
"ability": "stressresistenz",
|
||||
"intensity": 5
|
||||
}
|
||||
],
|
||||
"secondary_abilities": [
|
||||
{
|
||||
"category": "kognitiv",
|
||||
"ability": "wahrnehmung",
|
||||
"intensity": 4
|
||||
},
|
||||
{
|
||||
"category": "psychisch",
|
||||
"ability": "selbstvertrauen",
|
||||
"intensity": 3
|
||||
}
|
||||
]
|
||||
},
|
||||
"metabolic_focus": ["parasympathetic_activation"],
|
||||
"muscle_groups": []
|
||||
},
|
||||
|
||||
"periodization": {
|
||||
"enabled": True,
|
||||
"frequency": {
|
||||
"per_week_optimal": 5,
|
||||
"per_week_max": 7
|
||||
},
|
||||
"recovery": {
|
||||
"min_hours_between": 0
|
||||
}
|
||||
},
|
||||
|
||||
"performance_indicators": {
|
||||
"enabled": False
|
||||
},
|
||||
|
||||
"safety": {
|
||||
"enabled": True,
|
||||
"warnings": [
|
||||
{
|
||||
"parameter": "avg_hr",
|
||||
"operator": "gt",
|
||||
"value": 100,
|
||||
"severity": "medium",
|
||||
"message": "Herzfrequenz zu hoch für Meditation - bist du wirklich entspannt?"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
# TEMPLATE: KRAFTTRAINING - Kraft-fokussiert
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
TEMPLATE_STRENGTH = {
|
||||
"version": "1.0",
|
||||
"name": "Krafttraining (Standard)",
|
||||
"description": "Krafttraining mit moderater Herzfrequenz",
|
||||
|
||||
"rule_sets": {
|
||||
"minimum_requirements": {
|
||||
"enabled": True,
|
||||
"pass_strategy": "weighted_score",
|
||||
"pass_threshold": 0.5,
|
||||
"rules": [
|
||||
{
|
||||
"parameter": "duration_min",
|
||||
"operator": "gte",
|
||||
"value": 20,
|
||||
"weight": 5,
|
||||
"optional": False,
|
||||
"reason": "Mindestens 20 Minuten für Muskelreiz"
|
||||
},
|
||||
{
|
||||
"parameter": "kcal_active",
|
||||
"operator": "gte",
|
||||
"value": 100,
|
||||
"weight": 2,
|
||||
"optional": True,
|
||||
"reason": "Mindest-Kalorienverbrauch"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
"intensity_zones": {
|
||||
"enabled": False
|
||||
},
|
||||
|
||||
"training_effects": {
|
||||
"enabled": True,
|
||||
"default_effects": {
|
||||
"primary_abilities": [
|
||||
{
|
||||
"category": "konditionell",
|
||||
"ability": "kraft",
|
||||
"intensity": 5
|
||||
}
|
||||
],
|
||||
"secondary_abilities": [
|
||||
{
|
||||
"category": "koordinativ",
|
||||
"ability": "differenzierung",
|
||||
"intensity": 3
|
||||
},
|
||||
{
|
||||
"category": "psychisch",
|
||||
"ability": "willenskraft",
|
||||
"intensity": 4
|
||||
}
|
||||
]
|
||||
},
|
||||
"metabolic_focus": ["anaerobic", "muscle_growth"],
|
||||
"muscle_groups": ["full_body"]
|
||||
},
|
||||
|
||||
"periodization": {
|
||||
"enabled": True,
|
||||
"frequency": {
|
||||
"per_week_optimal": 3,
|
||||
"per_week_max": 5
|
||||
},
|
||||
"recovery": {
|
||||
"min_hours_between": 48
|
||||
}
|
||||
},
|
||||
|
||||
"performance_indicators": {
|
||||
"enabled": False
|
||||
},
|
||||
|
||||
"safety": {
|
||||
"enabled": True,
|
||||
"warnings": []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
# TEMPLATE REGISTRY
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
TEMPLATES = {
|
||||
"running": {
|
||||
"name_de": "Laufen",
|
||||
"name_en": "Running",
|
||||
"icon": "🏃",
|
||||
"categories": ["cardio", "running"],
|
||||
"template": TEMPLATE_RUNNING
|
||||
},
|
||||
"meditation": {
|
||||
"name_de": "Meditation",
|
||||
"name_en": "Meditation",
|
||||
"icon": "🧘",
|
||||
"categories": ["geist", "meditation"],
|
||||
"template": TEMPLATE_MEDITATION
|
||||
},
|
||||
"strength": {
|
||||
"name_de": "Krafttraining",
|
||||
"name_en": "Strength Training",
|
||||
"icon": "💪",
|
||||
"categories": ["kraft", "krafttraining"],
|
||||
"template": TEMPLATE_STRENGTH
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def get_template(template_key: str) -> dict:
|
||||
"""Get profile template by key."""
|
||||
template_info = TEMPLATES.get(template_key)
|
||||
if not template_info:
|
||||
return None
|
||||
return template_info["template"]
|
||||
|
||||
|
||||
def list_templates() -> list:
|
||||
"""List all available templates."""
|
||||
return [
|
||||
{
|
||||
"key": key,
|
||||
"name_de": info["name_de"],
|
||||
"name_en": info["name_en"],
|
||||
"icon": info["icon"],
|
||||
"categories": info["categories"]
|
||||
}
|
||||
for key, info in TEMPLATES.items()
|
||||
]
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
Quality Filter Helper - Data Access Layer
|
||||
|
||||
Provides consistent quality filtering across all activity queries.
|
||||
Issue: #31
|
||||
"""
|
||||
from typing import Optional, Dict
|
||||
|
||||
|
||||
def get_quality_filter_sql(profile: Dict, table_alias: str = "") -> str:
|
||||
"""
|
||||
Returns SQL WHERE clause fragment for quality filtering.
|
||||
|
||||
Args:
|
||||
profile: User profile dict with quality_filter_level
|
||||
table_alias: Optional table alias (e.g., "a." for "a.quality_label")
|
||||
|
||||
Returns:
|
||||
SQL fragment (e.g., "AND quality_label IN (...)") or empty string
|
||||
|
||||
Examples:
|
||||
>>> get_quality_filter_sql({'quality_filter_level': 'all'})
|
||||
''
|
||||
>>> get_quality_filter_sql({'quality_filter_level': 'quality'})
|
||||
"AND quality_label IN ('excellent', 'good', 'acceptable')"
|
||||
>>> get_quality_filter_sql({'quality_filter_level': 'excellent'}, 'a.')
|
||||
"AND a.quality_label = 'excellent'"
|
||||
"""
|
||||
level = profile.get('quality_filter_level', 'all')
|
||||
prefix = table_alias if table_alias else ""
|
||||
|
||||
if level == 'all':
|
||||
return '' # No filter
|
||||
elif level == 'quality':
|
||||
return f"AND {prefix}quality_label IN ('excellent', 'good', 'acceptable')"
|
||||
elif level == 'very_good':
|
||||
return f"AND {prefix}quality_label IN ('excellent', 'good')"
|
||||
elif level == 'excellent':
|
||||
return f"AND {prefix}quality_label = 'excellent'"
|
||||
else:
|
||||
# Unknown level → no filter (safe fallback)
|
||||
return ''
|
||||
|
||||
|
||||
def get_quality_filter_tuple(profile: Dict) -> tuple:
|
||||
"""
|
||||
Returns tuple of allowed quality labels for Python filtering.
|
||||
|
||||
Args:
|
||||
profile: User profile dict with quality_filter_level
|
||||
|
||||
Returns:
|
||||
Tuple of allowed quality labels or None (no filter)
|
||||
|
||||
Examples:
|
||||
>>> get_quality_filter_tuple({'quality_filter_level': 'all'})
|
||||
None
|
||||
>>> get_quality_filter_tuple({'quality_filter_level': 'quality'})
|
||||
('excellent', 'good', 'acceptable')
|
||||
"""
|
||||
level = profile.get('quality_filter_level', 'all')
|
||||
|
||||
if level == 'all':
|
||||
return None # No filter
|
||||
elif level == 'quality':
|
||||
return ('excellent', 'good', 'acceptable')
|
||||
elif level == 'very_good':
|
||||
return ('excellent', 'good')
|
||||
elif level == 'excellent':
|
||||
return ('excellent',)
|
||||
else:
|
||||
return None # Unknown level → no filter
|
||||
|
||||
|
||||
def filter_activities_by_quality(activities: list, profile: Dict) -> list:
|
||||
"""
|
||||
Filters a list of activity dicts by quality_label.
|
||||
|
||||
Useful for post-query filtering (e.g., when data already loaded).
|
||||
|
||||
Args:
|
||||
activities: List of activity dicts with quality_label field
|
||||
profile: User profile dict with quality_filter_level
|
||||
|
||||
Returns:
|
||||
Filtered list of activities
|
||||
"""
|
||||
allowed_labels = get_quality_filter_tuple(profile)
|
||||
|
||||
if allowed_labels is None:
|
||||
return activities # No filter
|
||||
|
||||
return [
|
||||
act for act in activities
|
||||
if act.get('quality_label') in allowed_labels
|
||||
]
|
||||
|
||||
|
||||
# Constants for frontend/documentation
|
||||
QUALITY_LEVELS = {
|
||||
'all': {
|
||||
'label': 'Alle',
|
||||
'icon': '📊',
|
||||
'description': 'Alle Activities (kein Filter)',
|
||||
'includes': None
|
||||
},
|
||||
'quality': {
|
||||
'label': 'Hochwertig',
|
||||
'icon': '✓',
|
||||
'description': 'Hochwertige Activities',
|
||||
'includes': ['excellent', 'good', 'acceptable']
|
||||
},
|
||||
'very_good': {
|
||||
'label': 'Sehr gut',
|
||||
'icon': '✓✓',
|
||||
'description': 'Sehr gute Activities',
|
||||
'includes': ['excellent', 'good']
|
||||
},
|
||||
'excellent': {
|
||||
'label': 'Exzellent',
|
||||
'icon': '⭐',
|
||||
'description': 'Nur exzellente Activities',
|
||||
'includes': ['excellent']
|
||||
}
|
||||
}
|
||||
@@ -8,3 +8,4 @@ pydantic==2.7.1
|
||||
bcrypt==4.1.3
|
||||
slowapi==0.1.9
|
||||
psycopg2-binary==2.9.9
|
||||
python-dateutil==2.9.0
|
||||
@@ -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}
|
||||
+338
-15
@@ -6,16 +6,29 @@ 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
|
||||
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
|
||||
from quality_filter import get_quality_filter_sql
|
||||
|
||||
# Evaluation import with error handling (Phase 1.2)
|
||||
try:
|
||||
from evaluation_helper import evaluate_and_save_activity
|
||||
EVALUATION_AVAILABLE = True
|
||||
except Exception as e:
|
||||
logger.warning(f"[AUTO-EVAL] Evaluation system not available: {e}")
|
||||
EVALUATION_AVAILABLE = False
|
||||
evaluate_and_save_activity = None
|
||||
|
||||
router = APIRouter(prefix="/api/activity", tags=["activity"])
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@router.get("")
|
||||
@@ -24,8 +37,19 @@ def list_activity(limit: int=200, x_profile_id: Optional[str]=Header(default=Non
|
||||
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))
|
||||
|
||||
# Issue #31: Apply global quality filter
|
||||
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||
profile = r2d(cur.fetchone())
|
||||
quality_filter = get_quality_filter_sql(profile)
|
||||
|
||||
cur.execute(f"""
|
||||
SELECT * FROM activity_log
|
||||
WHERE profile_id=%s
|
||||
{quality_filter}
|
||||
ORDER BY date DESC, start_time DESC
|
||||
LIMIT %s
|
||||
""", (pid, limit))
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@@ -33,6 +57,22 @@ def list_activity(limit: int=200, x_profile_id: Optional[str]=Header(default=Non
|
||||
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:
|
||||
@@ -44,6 +84,31 @@ def create_activity(e: ActivityEntry, x_profile_id: Optional[str]=Header(default
|
||||
(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 1.2: Auto-evaluation after INSERT
|
||||
if EVALUATION_AVAILABLE:
|
||||
# Load the activity data to evaluate
|
||||
cur.execute("""
|
||||
SELECT id, profile_id, date, training_type_id, duration_min,
|
||||
hr_avg, hr_max, distance_km, kcal_active, kcal_resting,
|
||||
rpe, pace_min_per_km, cadence, elevation_gain
|
||||
FROM activity_log
|
||||
WHERE id = %s
|
||||
""", (eid,))
|
||||
activity_row = cur.fetchone()
|
||||
if activity_row:
|
||||
activity_dict = dict(activity_row)
|
||||
training_type_id = activity_dict.get("training_type_id")
|
||||
if training_type_id:
|
||||
try:
|
||||
evaluate_and_save_activity(cur, eid, activity_dict, training_type_id, pid)
|
||||
logger.info(f"[AUTO-EVAL] Evaluated activity {eid} on INSERT")
|
||||
except Exception as eval_error:
|
||||
logger.error(f"[AUTO-EVAL] Failed to evaluate activity {eid}: {eval_error}")
|
||||
|
||||
# Phase 2: Increment usage counter (always for new entries)
|
||||
increment_feature_usage(pid, 'activity_entries')
|
||||
|
||||
return {"id":eid,"date":e.date}
|
||||
|
||||
|
||||
@@ -56,6 +121,28 @@ def update_activity(eid: str, e: ActivityEntry, x_profile_id: Optional[str]=Head
|
||||
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])
|
||||
|
||||
# Phase 1.2: Auto-evaluation after UPDATE
|
||||
if EVALUATION_AVAILABLE:
|
||||
# Load the updated activity data to evaluate
|
||||
cur.execute("""
|
||||
SELECT id, profile_id, date, training_type_id, duration_min,
|
||||
hr_avg, hr_max, distance_km, kcal_active, kcal_resting,
|
||||
rpe, pace_min_per_km, cadence, elevation_gain
|
||||
FROM activity_log
|
||||
WHERE id = %s
|
||||
""", (eid,))
|
||||
activity_row = cur.fetchone()
|
||||
if activity_row:
|
||||
activity_dict = dict(activity_row)
|
||||
training_type_id = activity_dict.get("training_type_id")
|
||||
if training_type_id:
|
||||
try:
|
||||
evaluate_and_save_activity(cur, eid, activity_dict, training_type_id, pid)
|
||||
logger.info(f"[AUTO-EVAL] Re-evaluated activity {eid} on UPDATE")
|
||||
except Exception as eval_error:
|
||||
logger.error(f"[AUTO-EVAL] Failed to re-evaluate activity {eid}: {eval_error}")
|
||||
|
||||
return {"id":eid}
|
||||
|
||||
|
||||
@@ -90,9 +177,151 @@ def activity_stats(x_profile_id: Optional[str]=Header(default=None), session: di
|
||||
return {"count":len(rows),"total_kcal":round(total_kcal),"total_min":round(total_min),"by_type":by_type}
|
||||
|
||||
|
||||
def get_training_type_for_activity(activity_type: str, profile_id: str = None):
|
||||
"""
|
||||
Map activity_type to training_type_id using database mappings.
|
||||
|
||||
Priority:
|
||||
1. User-specific mapping (profile_id)
|
||||
2. Global mapping (profile_id = NULL)
|
||||
3. No mapping found → returns (None, None, None)
|
||||
|
||||
Returns: (training_type_id, category, subcategory) or (None, None, None)
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Try user-specific mapping first
|
||||
if profile_id:
|
||||
cur.execute("""
|
||||
SELECT m.training_type_id, t.category, t.subcategory
|
||||
FROM activity_type_mappings m
|
||||
JOIN training_types t ON m.training_type_id = t.id
|
||||
WHERE m.activity_type = %s AND m.profile_id = %s
|
||||
LIMIT 1
|
||||
""", (activity_type, profile_id))
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
return (row['training_type_id'], row['category'], row['subcategory'])
|
||||
|
||||
# Try global mapping
|
||||
cur.execute("""
|
||||
SELECT m.training_type_id, t.category, t.subcategory
|
||||
FROM activity_type_mappings m
|
||||
JOIN training_types t ON m.training_type_id = t.id
|
||||
WHERE m.activity_type = %s AND m.profile_id IS NULL
|
||||
LIMIT 1
|
||||
""", (activity_type,))
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
return (row['training_type_id'], row['category'], row['subcategory'])
|
||||
|
||||
return (None, None, None)
|
||||
|
||||
|
||||
@router.get("/uncategorized")
|
||||
def list_uncategorized_activities(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||
"""Get activities without assigned training type, grouped by activity_type."""
|
||||
pid = get_pid(x_profile_id)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT activity_type, COUNT(*) as count,
|
||||
MIN(date) as first_date, MAX(date) as last_date
|
||||
FROM activity_log
|
||||
WHERE profile_id=%s AND training_type_id IS NULL
|
||||
GROUP BY activity_type
|
||||
ORDER BY count DESC
|
||||
""", (pid,))
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.post("/bulk-categorize")
|
||||
def bulk_categorize_activities(
|
||||
data: dict,
|
||||
x_profile_id: Optional[str]=Header(default=None),
|
||||
session: dict=Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Bulk update training type for activities.
|
||||
|
||||
Also saves the mapping to activity_type_mappings for future imports.
|
||||
|
||||
Body: {
|
||||
"activity_type": "Running",
|
||||
"training_type_id": 1,
|
||||
"training_category": "cardio",
|
||||
"training_subcategory": "running"
|
||||
}
|
||||
"""
|
||||
pid = get_pid(x_profile_id)
|
||||
activity_type = data.get('activity_type')
|
||||
training_type_id = data.get('training_type_id')
|
||||
training_category = data.get('training_category')
|
||||
training_subcategory = data.get('training_subcategory')
|
||||
|
||||
if not activity_type or not training_type_id:
|
||||
raise HTTPException(400, "activity_type and training_type_id required")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Update existing activities
|
||||
cur.execute("""
|
||||
UPDATE activity_log
|
||||
SET training_type_id = %s,
|
||||
training_category = %s,
|
||||
training_subcategory = %s
|
||||
WHERE profile_id = %s
|
||||
AND activity_type = %s
|
||||
AND training_type_id IS NULL
|
||||
""", (training_type_id, training_category, training_subcategory, pid, activity_type))
|
||||
updated_count = cur.rowcount
|
||||
|
||||
# Phase 1.2: Auto-evaluation after bulk categorization
|
||||
if EVALUATION_AVAILABLE:
|
||||
# Load all activities that were just updated and evaluate them
|
||||
cur.execute("""
|
||||
SELECT id, profile_id, date, training_type_id, duration_min,
|
||||
hr_avg, hr_max, distance_km, kcal_active, kcal_resting,
|
||||
rpe, pace_min_per_km, cadence, elevation_gain
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND activity_type = %s
|
||||
AND training_type_id = %s
|
||||
""", (pid, activity_type, training_type_id))
|
||||
|
||||
activities_to_evaluate = cur.fetchall()
|
||||
evaluated_count = 0
|
||||
for activity_row in activities_to_evaluate:
|
||||
activity_dict = dict(activity_row)
|
||||
try:
|
||||
evaluate_and_save_activity(cur, activity_dict["id"], activity_dict, training_type_id, pid)
|
||||
evaluated_count += 1
|
||||
except Exception as eval_error:
|
||||
logger.warning(f"[AUTO-EVAL] Failed to evaluate bulk-categorized activity {activity_dict['id']}: {eval_error}")
|
||||
|
||||
logger.info(f"[AUTO-EVAL] Evaluated {evaluated_count}/{updated_count} bulk-categorized activities")
|
||||
|
||||
# Save mapping for future imports (upsert)
|
||||
cur.execute("""
|
||||
INSERT INTO activity_type_mappings (activity_type, training_type_id, profile_id, source, updated_at)
|
||||
VALUES (%s, %s, %s, 'bulk', CURRENT_TIMESTAMP)
|
||||
ON CONFLICT (activity_type, profile_id)
|
||||
DO UPDATE SET
|
||||
training_type_id = EXCLUDED.training_type_id,
|
||||
source = 'bulk',
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
""", (activity_type, training_type_id, pid))
|
||||
|
||||
logger.info(f"[MAPPING] Saved bulk mapping: {activity_type} → training_type_id {training_type_id} (profile {pid})")
|
||||
|
||||
return {"updated": updated_count, "activity_type": activity_type, "mapping_saved": True}
|
||||
|
||||
|
||||
@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."""
|
||||
"""Import Apple Health workout CSV with automatic training type mapping."""
|
||||
pid = get_pid(x_profile_id)
|
||||
raw = await file.read()
|
||||
try: text = raw.decode('utf-8')
|
||||
@@ -122,16 +351,110 @@ async def import_activity_csv(file: UploadFile=File(...), x_profile_id: Optional
|
||||
def tf(v):
|
||||
try: return round(float(v),1) if v else None
|
||||
except: return None
|
||||
# Map activity_type to training_type_id using database mappings
|
||||
training_type_id, training_category, training_subcategory = get_training_type_for_activity(wtype, pid)
|
||||
|
||||
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
|
||||
# Check if entry already exists (duplicate detection by date + start_time)
|
||||
cur.execute("""
|
||||
SELECT id FROM activity_log
|
||||
WHERE profile_id = %s AND date = %s AND start_time = %s
|
||||
""", (pid, date, start))
|
||||
existing = cur.fetchone()
|
||||
|
||||
if existing:
|
||||
# Update existing entry (e.g., to add training type mapping)
|
||||
existing_id = existing['id']
|
||||
cur.execute("""
|
||||
UPDATE activity_log
|
||||
SET end_time = %s,
|
||||
activity_type = %s,
|
||||
duration_min = %s,
|
||||
kcal_active = %s,
|
||||
kcal_resting = %s,
|
||||
hr_avg = %s,
|
||||
hr_max = %s,
|
||||
distance_km = %s,
|
||||
training_type_id = %s,
|
||||
training_category = %s,
|
||||
training_subcategory = %s
|
||||
WHERE id = %s
|
||||
""", (
|
||||
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)','')),
|
||||
training_type_id, training_category, training_subcategory,
|
||||
existing_id
|
||||
))
|
||||
skipped += 1 # Count as skipped (not newly inserted)
|
||||
|
||||
# Phase 1.2: Auto-evaluation after CSV import UPDATE
|
||||
if EVALUATION_AVAILABLE and training_type_id:
|
||||
try:
|
||||
# Build activity dict for evaluation
|
||||
activity_dict = {
|
||||
"id": existing_id,
|
||||
"profile_id": pid,
|
||||
"date": date,
|
||||
"training_type_id": training_type_id,
|
||||
"duration_min": duration_min,
|
||||
"hr_avg": tf(row.get('Durchschn. Herzfrequenz (count/min)','')),
|
||||
"hr_max": tf(row.get('Max. Herzfrequenz (count/min)','')),
|
||||
"distance_km": tf(row.get('Distanz (km)','')),
|
||||
"kcal_active": kj(row.get('Aktive Energie (kJ)','')),
|
||||
"kcal_resting": kj(row.get('Ruheeinträge (kJ)','')),
|
||||
"rpe": None,
|
||||
"pace_min_per_km": None,
|
||||
"cadence": None,
|
||||
"elevation_gain": None
|
||||
}
|
||||
evaluate_and_save_activity(cur, existing_id, activity_dict, training_type_id, pid)
|
||||
logger.debug(f"[AUTO-EVAL] Re-evaluated updated activity {existing_id}")
|
||||
except Exception as eval_error:
|
||||
logger.warning(f"[AUTO-EVAL] Failed to re-evaluate updated activity {existing_id}: {eval_error}")
|
||||
else:
|
||||
# Insert new entry
|
||||
new_id = str(uuid.uuid4())
|
||||
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,training_type_id,training_category,training_subcategory,created)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,'apple_health',%s,%s,%s,CURRENT_TIMESTAMP)""",
|
||||
(new_id,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)','')),
|
||||
training_type_id,training_category,training_subcategory))
|
||||
inserted+=1
|
||||
|
||||
# Phase 1.2: Auto-evaluation after CSV import INSERT
|
||||
if EVALUATION_AVAILABLE and training_type_id:
|
||||
try:
|
||||
# Build activity dict for evaluation
|
||||
activity_dict = {
|
||||
"id": new_id,
|
||||
"profile_id": pid,
|
||||
"date": date,
|
||||
"training_type_id": training_type_id,
|
||||
"duration_min": duration_min,
|
||||
"hr_avg": tf(row.get('Durchschn. Herzfrequenz (count/min)','')),
|
||||
"hr_max": tf(row.get('Max. Herzfrequenz (count/min)','')),
|
||||
"distance_km": tf(row.get('Distanz (km)','')),
|
||||
"kcal_active": kj(row.get('Aktive Energie (kJ)','')),
|
||||
"kcal_resting": kj(row.get('Ruheeinträge (kJ)','')),
|
||||
"rpe": None,
|
||||
"pace_min_per_km": None,
|
||||
"cadence": None,
|
||||
"elevation_gain": None
|
||||
}
|
||||
evaluate_and_save_activity(cur, new_id, activity_dict, training_type_id, pid)
|
||||
logger.debug(f"[AUTO-EVAL] Evaluated imported activity {new_id}")
|
||||
except Exception as eval_error:
|
||||
logger.warning(f"[AUTO-EVAL] Failed to evaluate imported activity {new_id}: {eval_error}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Import row failed: {e}")
|
||||
skipped+=1
|
||||
return {"inserted":inserted,"skipped":skipped,"message":f"{inserted} Trainings importiert"}
|
||||
@@ -0,0 +1,219 @@
|
||||
"""
|
||||
Admin Activity Type Mappings Management - v9d Phase 1b
|
||||
|
||||
CRUD operations for activity_type_mappings (learnable system).
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from pydantic import BaseModel
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_admin
|
||||
|
||||
router = APIRouter(prefix="/api/admin/activity-mappings", tags=["admin", "activity-mappings"])
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ActivityMappingCreate(BaseModel):
|
||||
activity_type: str
|
||||
training_type_id: int
|
||||
profile_id: Optional[str] = None
|
||||
source: str = 'admin'
|
||||
|
||||
|
||||
class ActivityMappingUpdate(BaseModel):
|
||||
training_type_id: Optional[int] = None
|
||||
profile_id: Optional[str] = None
|
||||
source: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_activity_mappings(
|
||||
profile_id: Optional[str] = None,
|
||||
global_only: bool = False,
|
||||
session: dict = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Get all activity type mappings.
|
||||
|
||||
Filters:
|
||||
- profile_id: Show only mappings for specific profile
|
||||
- global_only: Show only global mappings (profile_id IS NULL)
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
query = """
|
||||
SELECT m.id, m.activity_type, m.training_type_id, m.profile_id, m.source,
|
||||
m.created_at, m.updated_at,
|
||||
t.name_de as training_type_name_de,
|
||||
t.category, t.subcategory, t.icon
|
||||
FROM activity_type_mappings m
|
||||
JOIN training_types t ON m.training_type_id = t.id
|
||||
"""
|
||||
|
||||
conditions = []
|
||||
params = []
|
||||
|
||||
if global_only:
|
||||
conditions.append("m.profile_id IS NULL")
|
||||
elif profile_id:
|
||||
conditions.append("m.profile_id = %s")
|
||||
params.append(profile_id)
|
||||
|
||||
if conditions:
|
||||
query += " WHERE " + " AND ".join(conditions)
|
||||
|
||||
query += " ORDER BY m.activity_type"
|
||||
|
||||
cur.execute(query, params)
|
||||
rows = cur.fetchall()
|
||||
|
||||
return [r2d(r) for r in rows]
|
||||
|
||||
|
||||
@router.get("/{mapping_id}")
|
||||
def get_activity_mapping(mapping_id: int, session: dict = Depends(require_admin)):
|
||||
"""Get single activity mapping by ID."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT m.id, m.activity_type, m.training_type_id, m.profile_id, m.source,
|
||||
m.created_at, m.updated_at,
|
||||
t.name_de as training_type_name_de,
|
||||
t.category, t.subcategory
|
||||
FROM activity_type_mappings m
|
||||
JOIN training_types t ON m.training_type_id = t.id
|
||||
WHERE m.id = %s
|
||||
""", (mapping_id,))
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row:
|
||||
raise HTTPException(404, "Mapping not found")
|
||||
|
||||
return r2d(row)
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_activity_mapping(data: ActivityMappingCreate, session: dict = Depends(require_admin)):
|
||||
"""
|
||||
Create new activity type mapping.
|
||||
|
||||
Note: Duplicate (activity_type, profile_id) will fail with 409 Conflict.
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
try:
|
||||
cur.execute("""
|
||||
INSERT INTO activity_type_mappings
|
||||
(activity_type, training_type_id, profile_id, source)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""", (
|
||||
data.activity_type,
|
||||
data.training_type_id,
|
||||
data.profile_id,
|
||||
data.source
|
||||
))
|
||||
|
||||
new_id = cur.fetchone()['id']
|
||||
|
||||
logger.info(f"[ADMIN] Mapping created: {data.activity_type} → training_type_id {data.training_type_id} (profile: {data.profile_id})")
|
||||
|
||||
except Exception as e:
|
||||
if 'unique_activity_type_per_profile' in str(e):
|
||||
raise HTTPException(409, f"Mapping for '{data.activity_type}' already exists (profile: {data.profile_id})")
|
||||
raise HTTPException(400, f"Failed to create mapping: {str(e)}")
|
||||
|
||||
return {"id": new_id, "message": "Mapping created"}
|
||||
|
||||
|
||||
@router.put("/{mapping_id}")
|
||||
def update_activity_mapping(
|
||||
mapping_id: int,
|
||||
data: ActivityMappingUpdate,
|
||||
session: dict = Depends(require_admin)
|
||||
):
|
||||
"""Update existing activity type mapping."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Build update query dynamically
|
||||
updates = []
|
||||
values = []
|
||||
|
||||
if data.training_type_id is not None:
|
||||
updates.append("training_type_id = %s")
|
||||
values.append(data.training_type_id)
|
||||
if data.profile_id is not None:
|
||||
updates.append("profile_id = %s")
|
||||
values.append(data.profile_id)
|
||||
if data.source is not None:
|
||||
updates.append("source = %s")
|
||||
values.append(data.source)
|
||||
|
||||
if not updates:
|
||||
raise HTTPException(400, "No fields to update")
|
||||
|
||||
updates.append("updated_at = CURRENT_TIMESTAMP")
|
||||
values.append(mapping_id)
|
||||
|
||||
cur.execute(f"""
|
||||
UPDATE activity_type_mappings
|
||||
SET {', '.join(updates)}
|
||||
WHERE id = %s
|
||||
""", values)
|
||||
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(404, "Mapping not found")
|
||||
|
||||
logger.info(f"[ADMIN] Mapping updated: {mapping_id}")
|
||||
|
||||
return {"id": mapping_id, "message": "Mapping updated"}
|
||||
|
||||
|
||||
@router.delete("/{mapping_id}")
|
||||
def delete_activity_mapping(mapping_id: int, session: dict = Depends(require_admin)):
|
||||
"""
|
||||
Delete activity type mapping.
|
||||
|
||||
This will cause future imports to NOT auto-assign training type for this activity_type.
|
||||
Existing activities with this mapping remain unchanged.
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
cur.execute("DELETE FROM activity_type_mappings WHERE id = %s", (mapping_id,))
|
||||
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(404, "Mapping not found")
|
||||
|
||||
logger.info(f"[ADMIN] Mapping deleted: {mapping_id}")
|
||||
|
||||
return {"message": "Mapping deleted"}
|
||||
|
||||
|
||||
@router.get("/stats/coverage")
|
||||
def get_mapping_coverage(session: dict = Depends(require_admin)):
|
||||
"""
|
||||
Get statistics about mapping coverage.
|
||||
|
||||
Returns how many activities are mapped vs unmapped across all profiles.
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
cur.execute("""
|
||||
SELECT
|
||||
COUNT(*) as total_activities,
|
||||
COUNT(training_type_id) as mapped_activities,
|
||||
COUNT(*) - COUNT(training_type_id) as unmapped_activities,
|
||||
COUNT(DISTINCT activity_type) as unique_activity_types,
|
||||
COUNT(DISTINCT CASE WHEN training_type_id IS NULL THEN activity_type END) as unmapped_types
|
||||
FROM activity_log
|
||||
""")
|
||||
stats = r2d(cur.fetchone())
|
||||
|
||||
return stats
|
||||
@@ -0,0 +1,409 @@
|
||||
"""
|
||||
Admin Training Types Management - v9d Phase 1b
|
||||
|
||||
CRUD operations for training types with abilities mapping preparation.
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from pydantic import BaseModel
|
||||
from psycopg2.extras import Json
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth, require_admin
|
||||
from profile_templates import list_templates, get_template
|
||||
|
||||
router = APIRouter(prefix="/api/admin/training-types", tags=["admin", "training-types"])
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TrainingTypeCreate(BaseModel):
|
||||
category: str
|
||||
subcategory: Optional[str] = None
|
||||
name_de: str
|
||||
name_en: str
|
||||
icon: Optional[str] = None
|
||||
description_de: Optional[str] = None
|
||||
description_en: Optional[str] = None
|
||||
sort_order: int = 0
|
||||
abilities: Optional[dict] = None
|
||||
profile: Optional[dict] = None # Training Type Profile (Phase 2 #15)
|
||||
|
||||
|
||||
class TrainingTypeUpdate(BaseModel):
|
||||
category: Optional[str] = None
|
||||
subcategory: Optional[str] = None
|
||||
name_de: Optional[str] = None
|
||||
name_en: Optional[str] = None
|
||||
icon: Optional[str] = None
|
||||
description_de: Optional[str] = None
|
||||
description_en: Optional[str] = None
|
||||
sort_order: Optional[int] = None
|
||||
abilities: Optional[dict] = None
|
||||
profile: Optional[dict] = None # Training Type Profile (Phase 2 #15)
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_training_types_admin(session: dict = Depends(require_admin)):
|
||||
"""
|
||||
Get all training types for admin management.
|
||||
Returns full details including abilities.
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT id, category, subcategory, name_de, name_en, icon,
|
||||
description_de, description_en, sort_order, abilities,
|
||||
profile, created_at
|
||||
FROM training_types
|
||||
ORDER BY sort_order, category, subcategory
|
||||
""")
|
||||
rows = cur.fetchall()
|
||||
|
||||
return [r2d(r) for r in rows]
|
||||
|
||||
|
||||
@router.get("/{type_id}")
|
||||
def get_training_type(type_id: int, session: dict = Depends(require_admin)):
|
||||
"""Get single training type by ID."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT id, category, subcategory, name_de, name_en, icon,
|
||||
description_de, description_en, sort_order, abilities,
|
||||
profile, created_at
|
||||
FROM training_types
|
||||
WHERE id = %s
|
||||
""", (type_id,))
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row:
|
||||
raise HTTPException(404, "Training type not found")
|
||||
|
||||
return r2d(row)
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_training_type(data: TrainingTypeCreate, session: dict = Depends(require_admin)):
|
||||
"""Create new training type."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Convert abilities and profile dict to JSONB
|
||||
abilities_json = data.abilities if data.abilities else {}
|
||||
profile_json = data.profile if data.profile else None
|
||||
|
||||
cur.execute("""
|
||||
INSERT INTO training_types
|
||||
(category, subcategory, name_de, name_en, icon,
|
||||
description_de, description_en, sort_order, abilities, profile)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""", (
|
||||
data.category,
|
||||
data.subcategory,
|
||||
data.name_de,
|
||||
data.name_en,
|
||||
data.icon,
|
||||
data.description_de,
|
||||
data.description_en,
|
||||
data.sort_order,
|
||||
Json(abilities_json),
|
||||
Json(profile_json) if profile_json else None
|
||||
))
|
||||
|
||||
new_id = cur.fetchone()['id']
|
||||
|
||||
logger.info(f"[ADMIN] Training type created: {new_id} - {data.name_de} ({data.category}/{data.subcategory})")
|
||||
|
||||
return {"id": new_id, "message": "Training type created"}
|
||||
|
||||
|
||||
@router.put("/{type_id}")
|
||||
def update_training_type(
|
||||
type_id: int,
|
||||
data: TrainingTypeUpdate,
|
||||
session: dict = Depends(require_admin)
|
||||
):
|
||||
"""Update existing training type."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Build update query dynamically
|
||||
updates = []
|
||||
values = []
|
||||
|
||||
if data.category is not None:
|
||||
updates.append("category = %s")
|
||||
values.append(data.category)
|
||||
if data.subcategory is not None:
|
||||
updates.append("subcategory = %s")
|
||||
values.append(data.subcategory)
|
||||
if data.name_de is not None:
|
||||
updates.append("name_de = %s")
|
||||
values.append(data.name_de)
|
||||
if data.name_en is not None:
|
||||
updates.append("name_en = %s")
|
||||
values.append(data.name_en)
|
||||
if data.icon is not None:
|
||||
updates.append("icon = %s")
|
||||
values.append(data.icon)
|
||||
if data.description_de is not None:
|
||||
updates.append("description_de = %s")
|
||||
values.append(data.description_de)
|
||||
if data.description_en is not None:
|
||||
updates.append("description_en = %s")
|
||||
values.append(data.description_en)
|
||||
if data.sort_order is not None:
|
||||
updates.append("sort_order = %s")
|
||||
values.append(data.sort_order)
|
||||
if data.abilities is not None:
|
||||
updates.append("abilities = %s")
|
||||
values.append(Json(data.abilities))
|
||||
if data.profile is not None:
|
||||
updates.append("profile = %s")
|
||||
values.append(Json(data.profile))
|
||||
|
||||
if not updates:
|
||||
raise HTTPException(400, "No fields to update")
|
||||
|
||||
values.append(type_id)
|
||||
|
||||
cur.execute(f"""
|
||||
UPDATE training_types
|
||||
SET {', '.join(updates)}
|
||||
WHERE id = %s
|
||||
""", values)
|
||||
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(404, "Training type not found")
|
||||
|
||||
logger.info(f"[ADMIN] Training type updated: {type_id}")
|
||||
|
||||
return {"id": type_id, "message": "Training type updated"}
|
||||
|
||||
|
||||
@router.delete("/{type_id}")
|
||||
def delete_training_type(type_id: int, session: dict = Depends(require_admin)):
|
||||
"""
|
||||
Delete training type.
|
||||
|
||||
WARNING: This will fail if any activities reference this type.
|
||||
Consider adding a soft-delete or archive mechanism if needed.
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check if any activities use this type
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as count
|
||||
FROM activity_log
|
||||
WHERE training_type_id = %s
|
||||
""", (type_id,))
|
||||
|
||||
count = cur.fetchone()['count']
|
||||
if count > 0:
|
||||
raise HTTPException(
|
||||
400,
|
||||
f"Cannot delete: {count} activities are using this training type. "
|
||||
"Please reassign or delete those activities first."
|
||||
)
|
||||
|
||||
cur.execute("DELETE FROM training_types WHERE id = %s", (type_id,))
|
||||
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(404, "Training type not found")
|
||||
|
||||
logger.info(f"[ADMIN] Training type deleted: {type_id}")
|
||||
|
||||
return {"message": "Training type deleted"}
|
||||
|
||||
|
||||
@router.get("/taxonomy/abilities")
|
||||
def get_abilities_taxonomy(session: dict = Depends(require_auth)):
|
||||
"""
|
||||
Get abilities taxonomy for UI and AI analysis.
|
||||
|
||||
This defines the 5 dimensions of athletic development.
|
||||
"""
|
||||
taxonomy = {
|
||||
"koordinativ": {
|
||||
"name_de": "Koordinative Fähigkeiten",
|
||||
"name_en": "Coordination Abilities",
|
||||
"icon": "🎯",
|
||||
"abilities": [
|
||||
{"key": "orientierung", "name_de": "Orientierung", "name_en": "Orientation"},
|
||||
{"key": "differenzierung", "name_de": "Differenzierung", "name_en": "Differentiation"},
|
||||
{"key": "kopplung", "name_de": "Kopplung", "name_en": "Coupling"},
|
||||
{"key": "gleichgewicht", "name_de": "Gleichgewicht", "name_en": "Balance"},
|
||||
{"key": "rhythmus", "name_de": "Rhythmisierung", "name_en": "Rhythm"},
|
||||
{"key": "reaktion", "name_de": "Reaktion", "name_en": "Reaction"},
|
||||
{"key": "umstellung", "name_de": "Umstellung", "name_en": "Adaptation"}
|
||||
]
|
||||
},
|
||||
"konditionell": {
|
||||
"name_de": "Konditionelle Fähigkeiten",
|
||||
"name_en": "Conditional Abilities",
|
||||
"icon": "💪",
|
||||
"abilities": [
|
||||
{"key": "kraft", "name_de": "Kraft", "name_en": "Strength"},
|
||||
{"key": "ausdauer", "name_de": "Ausdauer", "name_en": "Endurance"},
|
||||
{"key": "schnelligkeit", "name_de": "Schnelligkeit", "name_en": "Speed"},
|
||||
{"key": "flexibilitaet", "name_de": "Flexibilität", "name_en": "Flexibility"}
|
||||
]
|
||||
},
|
||||
"kognitiv": {
|
||||
"name_de": "Kognitive Fähigkeiten",
|
||||
"name_en": "Cognitive Abilities",
|
||||
"icon": "🧠",
|
||||
"abilities": [
|
||||
{"key": "konzentration", "name_de": "Konzentration", "name_en": "Concentration"},
|
||||
{"key": "aufmerksamkeit", "name_de": "Aufmerksamkeit", "name_en": "Attention"},
|
||||
{"key": "wahrnehmung", "name_de": "Wahrnehmung", "name_en": "Perception"},
|
||||
{"key": "entscheidung", "name_de": "Entscheidungsfindung", "name_en": "Decision Making"}
|
||||
]
|
||||
},
|
||||
"psychisch": {
|
||||
"name_de": "Psychische Fähigkeiten",
|
||||
"name_en": "Psychological Abilities",
|
||||
"icon": "🎭",
|
||||
"abilities": [
|
||||
{"key": "motivation", "name_de": "Motivation", "name_en": "Motivation"},
|
||||
{"key": "willenskraft", "name_de": "Willenskraft", "name_en": "Willpower"},
|
||||
{"key": "stressresistenz", "name_de": "Stressresistenz", "name_en": "Stress Resistance"},
|
||||
{"key": "selbstvertrauen", "name_de": "Selbstvertrauen", "name_en": "Self-Confidence"}
|
||||
]
|
||||
},
|
||||
"taktisch": {
|
||||
"name_de": "Taktische Fähigkeiten",
|
||||
"name_en": "Tactical Abilities",
|
||||
"icon": "♟️",
|
||||
"abilities": [
|
||||
{"key": "timing", "name_de": "Timing", "name_en": "Timing"},
|
||||
{"key": "strategie", "name_de": "Strategie", "name_en": "Strategy"},
|
||||
{"key": "antizipation", "name_de": "Antizipation", "name_en": "Anticipation"},
|
||||
{"key": "situationsanalyse", "name_de": "Situationsanalyse", "name_en": "Situation Analysis"}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
return taxonomy
|
||||
|
||||
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
# TRAINING TYPE PROFILES - Phase 2 (#15)
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
@router.get("/profiles/templates")
|
||||
def list_profile_templates(session: dict = Depends(require_admin)):
|
||||
"""
|
||||
List all available profile templates.
|
||||
|
||||
Returns templates for common training types (Running, Meditation, Strength, etc.)
|
||||
"""
|
||||
return list_templates()
|
||||
|
||||
|
||||
@router.get("/profiles/templates/{template_key}")
|
||||
def get_profile_template(template_key: str, session: dict = Depends(require_admin)):
|
||||
"""
|
||||
Get a specific profile template by key.
|
||||
|
||||
Keys: running, meditation, strength
|
||||
"""
|
||||
template = get_template(template_key)
|
||||
if not template:
|
||||
raise HTTPException(404, f"Template '{template_key}' not found")
|
||||
return template
|
||||
|
||||
|
||||
@router.post("/{type_id}/profile/apply-template")
|
||||
def apply_profile_template(
|
||||
type_id: int,
|
||||
data: dict,
|
||||
session: dict = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Apply a profile template to a training type.
|
||||
|
||||
Body: { "template_key": "running" }
|
||||
"""
|
||||
template_key = data.get("template_key")
|
||||
if not template_key:
|
||||
raise HTTPException(400, "template_key required")
|
||||
|
||||
template = get_template(template_key)
|
||||
if not template:
|
||||
raise HTTPException(404, f"Template '{template_key}' not found")
|
||||
|
||||
# Apply template to training type
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check if training type exists
|
||||
cur.execute("SELECT id, name_de FROM training_types WHERE id = %s", (type_id,))
|
||||
training_type = cur.fetchone()
|
||||
if not training_type:
|
||||
raise HTTPException(404, "Training type not found")
|
||||
|
||||
# Update profile
|
||||
cur.execute("""
|
||||
UPDATE training_types
|
||||
SET profile = %s
|
||||
WHERE id = %s
|
||||
""", (Json(template), type_id))
|
||||
|
||||
logger.info(f"[ADMIN] Applied template '{template_key}' to training type {type_id} ({training_type['name_de']})")
|
||||
|
||||
return {
|
||||
"message": f"Template '{template_key}' applied successfully",
|
||||
"training_type_id": type_id,
|
||||
"training_type_name": training_type['name_de'],
|
||||
"template_key": template_key
|
||||
}
|
||||
|
||||
|
||||
@router.get("/profiles/stats")
|
||||
def get_profile_stats(session: dict = Depends(require_admin)):
|
||||
"""
|
||||
Get statistics about configured profiles.
|
||||
|
||||
Returns count of training types with/without profiles.
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
cur.execute("""
|
||||
SELECT
|
||||
COUNT(*) as total,
|
||||
COUNT(profile) as configured,
|
||||
COUNT(*) - COUNT(profile) as unconfigured
|
||||
FROM training_types
|
||||
""")
|
||||
stats = cur.fetchone()
|
||||
|
||||
# Get list of types with profiles
|
||||
cur.execute("""
|
||||
SELECT id, name_de, category, subcategory
|
||||
FROM training_types
|
||||
WHERE profile IS NOT NULL
|
||||
ORDER BY name_de
|
||||
""")
|
||||
configured_types = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
# Get list of types without profiles
|
||||
cur.execute("""
|
||||
SELECT id, name_de, category, subcategory
|
||||
FROM training_types
|
||||
WHERE profile IS NULL
|
||||
ORDER BY name_de
|
||||
""")
|
||||
unconfigured_types = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
return {
|
||||
"total": stats['total'],
|
||||
"configured": stats['configured'],
|
||||
"unconfigured": stats['unconfigured'],
|
||||
"configured_types": configured_types,
|
||||
"unconfigured_types": unconfigured_types
|
||||
}
|
||||
+224
-2
@@ -7,7 +7,7 @@ import os
|
||||
import secrets
|
||||
import smtplib
|
||||
from typing import Optional
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from email.mime.text import MIMEText
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Header, Depends
|
||||
@@ -17,7 +17,7 @@ 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
|
||||
from models import LoginRequest, PasswordResetRequest, PasswordResetConfirm, RegisterRequest
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
limiter = Limiter(key_func=get_remote_address)
|
||||
@@ -174,3 +174,225 @@ def password_reset_confirm(req: PasswordResetConfirm):
|
||||
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(timezone.utc) + timedelta(hours=24)
|
||||
|
||||
# Create profile (inactive until verified)
|
||||
profile_id = str(secrets.token_hex(16))
|
||||
pin_hash = hash_pin(password)
|
||||
trial_ends = datetime.now(timezone.utc) + timedelta(days=14) # 14-day trial
|
||||
|
||||
cur.execute("""
|
||||
INSERT INTO profiles (
|
||||
id, name, email, pin_hash, auth_type, role, tier,
|
||||
email_verified, verification_token, verification_expires,
|
||||
trial_ends_at, created
|
||||
) VALUES (%s, %s, %s, %s, 'email', 'user', 'free', FALSE, %s, %s, %s, CURRENT_TIMESTAMP)
|
||||
""", (profile_id, name, email, pin_hash, verification_token, verification_expires, trial_ends))
|
||||
|
||||
# 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:
|
||||
# Token not found - might be already used/verified
|
||||
# Check if there's a verified profile (token was deleted after verification)
|
||||
raise HTTPException(400, "Verifikations-Link ungültig oder bereits verwendet. Falls du bereits verifiziert bist, melde dich einfach an.")
|
||||
|
||||
if prof['email_verified']:
|
||||
raise HTTPException(400, "E-Mail-Adresse bereits bestätigt")
|
||||
|
||||
# Check if token expired
|
||||
if prof['verification_expires'] and datetime.now(timezone.utc) > 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(timezone.utc) + 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']
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.post("/resend-verification")
|
||||
@limiter.limit("3/hour")
|
||||
async def resend_verification(req: dict, request: Request):
|
||||
"""Resend verification email for unverified account."""
|
||||
email = req.get('email', '').strip().lower()
|
||||
|
||||
if not email:
|
||||
raise HTTPException(400, "E-Mail-Adresse erforderlich")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Find profile by email
|
||||
cur.execute("""
|
||||
SELECT id, name, email, email_verified, verification_token, verification_expires
|
||||
FROM profiles
|
||||
WHERE email=%s
|
||||
""", (email,))
|
||||
|
||||
prof = cur.fetchone()
|
||||
|
||||
if not prof:
|
||||
# Don't leak info about existing emails
|
||||
return {"ok": True, "message": "Falls ein Account mit dieser E-Mail existiert, wurde eine Bestätigungs-E-Mail versendet."}
|
||||
|
||||
if prof['email_verified']:
|
||||
raise HTTPException(400, "E-Mail-Adresse bereits bestätigt")
|
||||
|
||||
# Generate new verification token
|
||||
verification_token = secrets.token_urlsafe(32)
|
||||
verification_expires = datetime.now(timezone.utc) + timedelta(hours=24)
|
||||
|
||||
cur.execute("""
|
||||
UPDATE profiles
|
||||
SET verification_token=%s, verification_expires=%s
|
||||
WHERE id=%s
|
||||
""", (verification_token, verification_expires, prof['id']))
|
||||
|
||||
# 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 {prof['name']},
|
||||
|
||||
du hast eine neue Bestätigungs-E-Mail angefordert.
|
||||
|
||||
Bitte bestätige deine E-Mail-Adresse, indem du auf folgenden Link klickst:
|
||||
|
||||
{verify_url}
|
||||
|
||||
Dieser Link ist 24 Stunden gültig.
|
||||
|
||||
Falls du diese E-Mail nicht angefordert hast, kannst du sie einfach ignorieren.
|
||||
|
||||
Viele Grüße
|
||||
Dein Mitai Jinkendo Team
|
||||
"""
|
||||
|
||||
try:
|
||||
send_email(
|
||||
to=email,
|
||||
subject="Neue Bestätigungs-E-Mail - Mitai Jinkendo",
|
||||
body=email_body
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"Failed to send verification email: {e}")
|
||||
raise HTTPException(500, "E-Mail konnte nicht versendet werden")
|
||||
|
||||
return {"ok": True, "message": "Bestätigungs-E-Mail wurde erneut versendet."}
|
||||
@@ -0,0 +1,412 @@
|
||||
"""
|
||||
Blood Pressure Router - v9d Phase 2d Refactored
|
||||
|
||||
Context-dependent blood pressure measurements (multiple times per day):
|
||||
- Systolic/Diastolic Blood Pressure
|
||||
- Pulse during measurement
|
||||
- Context tagging (morning_fasted, after_meal, before_training, etc.)
|
||||
- Warning flags (irregular heartbeat, AFib)
|
||||
|
||||
Endpoints:
|
||||
- GET /api/blood-pressure List BP measurements
|
||||
- GET /api/blood-pressure/by-date/{date} Get measurements for specific date
|
||||
- POST /api/blood-pressure Create BP measurement
|
||||
- PUT /api/blood-pressure/{id} Update BP measurement
|
||||
- DELETE /api/blood-pressure/{id} Delete BP measurement
|
||||
- GET /api/blood-pressure/stats Statistics and trends
|
||||
- POST /api/blood-pressure/import/omron Import Omron CSV
|
||||
"""
|
||||
from fastapi import APIRouter, HTTPException, Depends, Header, UploadFile, File
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
from datetime import datetime, timedelta
|
||||
import logging
|
||||
import csv
|
||||
import io
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth
|
||||
from routers.profiles import get_pid
|
||||
|
||||
router = APIRouter(prefix="/api/blood-pressure", tags=["blood_pressure"])
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# German month mapping for Omron dates
|
||||
GERMAN_MONTHS = {
|
||||
'Januar': '01', 'Jan.': '01', 'Jan': '01',
|
||||
'Februar': '02', 'Feb.': '02', 'Feb': '02',
|
||||
'März': '03', 'Mär.': '03', 'Mär': '03',
|
||||
'April': '04', 'Apr.': '04', 'Apr': '04',
|
||||
'Mai': '05',
|
||||
'Juni': '06', 'Jun.': '06', 'Jun': '06',
|
||||
'Juli': '07', 'Jul.': '07', 'Jul': '07',
|
||||
'August': '08', 'Aug.': '08', 'Aug': '08',
|
||||
'September': '09', 'Sep.': '09', 'Sep': '09',
|
||||
'Oktober': '10', 'Okt.': '10', 'Okt': '10',
|
||||
'November': '11', 'Nov.': '11', 'Nov': '11',
|
||||
'Dezember': '12', 'Dez.': '12', 'Dez': '12',
|
||||
}
|
||||
|
||||
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
# Pydantic Models
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
class BPEntry(BaseModel):
|
||||
measured_at: str # ISO format datetime
|
||||
systolic: int
|
||||
diastolic: int
|
||||
pulse: Optional[int] = None
|
||||
context: Optional[str] = None # morning_fasted, after_meal, etc.
|
||||
irregular_heartbeat: Optional[bool] = False
|
||||
possible_afib: Optional[bool] = False
|
||||
note: Optional[str] = None
|
||||
|
||||
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
# Helper Functions
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
def parse_omron_date(date_str: str, time_str: str) -> str:
|
||||
"""
|
||||
Parse Omron German date/time format to ISO datetime.
|
||||
Input: "13 März 2026", "08:30"
|
||||
Output: "2026-03-13 08:30:00"
|
||||
"""
|
||||
try:
|
||||
parts = date_str.strip().split()
|
||||
if len(parts) != 3:
|
||||
return None
|
||||
|
||||
day = parts[0]
|
||||
month_name = parts[1]
|
||||
year = parts[2]
|
||||
|
||||
month = GERMAN_MONTHS.get(month_name)
|
||||
if not month:
|
||||
return None
|
||||
|
||||
iso_date = f"{year}-{month}-{day.zfill(2)}"
|
||||
iso_datetime = f"{iso_date} {time_str}:00"
|
||||
|
||||
# Validate
|
||||
datetime.fromisoformat(iso_datetime)
|
||||
return iso_datetime
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error parsing Omron date: {date_str} {time_str} - {e}")
|
||||
return None
|
||||
|
||||
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
# CRUD Endpoints
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
@router.get("")
|
||||
def list_bp_measurements(
|
||||
limit: int = 90,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Get blood pressure measurements (last N entries)."""
|
||||
pid = get_pid(x_profile_id)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT * FROM blood_pressure_log
|
||||
WHERE profile_id = %s
|
||||
ORDER BY measured_at DESC
|
||||
LIMIT %s
|
||||
""", (pid, limit))
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.get("/by-date/{date}")
|
||||
def get_bp_by_date(
|
||||
date: str,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Get all BP measurements for a specific date."""
|
||||
pid = get_pid(x_profile_id)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT * FROM blood_pressure_log
|
||||
WHERE profile_id = %s
|
||||
AND DATE(measured_at) = %s
|
||||
ORDER BY measured_at ASC
|
||||
""", (pid, date))
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_bp_measurement(
|
||||
entry: BPEntry,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Create new BP measurement."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
INSERT INTO blood_pressure_log (
|
||||
profile_id, measured_at,
|
||||
systolic, diastolic, pulse,
|
||||
context, irregular_heartbeat, possible_afib,
|
||||
note, source
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, 'manual')
|
||||
RETURNING *
|
||||
""", (
|
||||
pid, entry.measured_at,
|
||||
entry.systolic, entry.diastolic, entry.pulse,
|
||||
entry.context, entry.irregular_heartbeat, entry.possible_afib,
|
||||
entry.note
|
||||
))
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
@router.put("/{entry_id}")
|
||||
def update_bp_measurement(
|
||||
entry_id: int,
|
||||
entry: BPEntry,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Update existing BP measurement."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
UPDATE blood_pressure_log
|
||||
SET measured_at = %s,
|
||||
systolic = %s,
|
||||
diastolic = %s,
|
||||
pulse = %s,
|
||||
context = %s,
|
||||
irregular_heartbeat = %s,
|
||||
possible_afib = %s,
|
||||
note = %s
|
||||
WHERE id = %s AND profile_id = %s
|
||||
RETURNING *
|
||||
""", (
|
||||
entry.measured_at,
|
||||
entry.systolic, entry.diastolic, entry.pulse,
|
||||
entry.context, entry.irregular_heartbeat, entry.possible_afib,
|
||||
entry.note,
|
||||
entry_id, pid
|
||||
))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Entry not found")
|
||||
return r2d(row)
|
||||
|
||||
|
||||
@router.delete("/{entry_id}")
|
||||
def delete_bp_measurement(
|
||||
entry_id: int,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Delete BP measurement."""
|
||||
pid = get_pid(x_profile_id)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
DELETE FROM blood_pressure_log
|
||||
WHERE id = %s AND profile_id = %s
|
||||
""", (entry_id, pid))
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(404, "Entry not found")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
# Statistics & Trends
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
@router.get("/stats")
|
||||
def get_bp_stats(
|
||||
days: int = 30,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Get blood pressure statistics and trends."""
|
||||
pid = get_pid(x_profile_id)
|
||||
cutoff_date = datetime.now() - timedelta(days=days)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT
|
||||
COUNT(*) as total_measurements,
|
||||
-- Overall averages
|
||||
AVG(systolic) as avg_systolic,
|
||||
AVG(diastolic) as avg_diastolic,
|
||||
AVG(pulse) FILTER (WHERE pulse IS NOT NULL) as avg_pulse,
|
||||
-- 7-day averages
|
||||
AVG(systolic) FILTER (WHERE measured_at >= NOW() - INTERVAL '7 days') as avg_systolic_7d,
|
||||
AVG(diastolic) FILTER (WHERE measured_at >= NOW() - INTERVAL '7 days') as avg_diastolic_7d,
|
||||
-- Context-specific averages
|
||||
AVG(systolic) FILTER (WHERE context = 'morning_fasted') as avg_systolic_morning,
|
||||
AVG(diastolic) FILTER (WHERE context = 'morning_fasted') as avg_diastolic_morning,
|
||||
AVG(systolic) FILTER (WHERE context = 'evening') as avg_systolic_evening,
|
||||
AVG(diastolic) FILTER (WHERE context = 'evening') as avg_diastolic_evening,
|
||||
-- Warning flags
|
||||
COUNT(*) FILTER (WHERE irregular_heartbeat = true) as irregular_count,
|
||||
COUNT(*) FILTER (WHERE possible_afib = true) as afib_count
|
||||
FROM blood_pressure_log
|
||||
WHERE profile_id = %s AND measured_at >= %s
|
||||
""", (pid, cutoff_date))
|
||||
|
||||
stats = r2d(cur.fetchone())
|
||||
|
||||
# Classify BP ranges (WHO/ISH guidelines)
|
||||
if stats['avg_systolic'] and stats['avg_diastolic']:
|
||||
if stats['avg_systolic'] < 120 and stats['avg_diastolic'] < 80:
|
||||
stats['bp_category'] = 'optimal'
|
||||
elif stats['avg_systolic'] < 130 and stats['avg_diastolic'] < 85:
|
||||
stats['bp_category'] = 'normal'
|
||||
elif stats['avg_systolic'] < 140 and stats['avg_diastolic'] < 90:
|
||||
stats['bp_category'] = 'high_normal'
|
||||
elif stats['avg_systolic'] < 160 and stats['avg_diastolic'] < 100:
|
||||
stats['bp_category'] = 'grade_1_hypertension'
|
||||
elif stats['avg_systolic'] < 180 and stats['avg_diastolic'] < 110:
|
||||
stats['bp_category'] = 'grade_2_hypertension'
|
||||
else:
|
||||
stats['bp_category'] = 'grade_3_hypertension'
|
||||
else:
|
||||
stats['bp_category'] = None
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
# Import: Omron CSV
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
@router.post("/import/omron")
|
||||
async def import_omron_csv(
|
||||
file: UploadFile = File(...),
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Import blood pressure measurements from Omron CSV export."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
content = await file.read()
|
||||
decoded = content.decode('utf-8')
|
||||
reader = csv.DictReader(io.StringIO(decoded))
|
||||
|
||||
inserted = 0
|
||||
updated = 0
|
||||
skipped = 0
|
||||
errors = 0
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Log available columns for debugging
|
||||
first_row = True
|
||||
|
||||
for row in reader:
|
||||
try:
|
||||
if first_row:
|
||||
logger.info(f"Omron CSV Columns: {list(row.keys())}")
|
||||
first_row = False
|
||||
|
||||
# Parse Omron German date format
|
||||
date_str = row.get('Datum', row.get('Date'))
|
||||
time_str = row.get('Zeit', row.get('Time', '08:00'))
|
||||
|
||||
if not date_str:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
measured_at = parse_omron_date(date_str, time_str)
|
||||
if not measured_at:
|
||||
errors += 1
|
||||
continue
|
||||
|
||||
# Extract measurements (support column names with/without units)
|
||||
systolic = (row.get('Systolisch (mmHg)') or row.get('Systolisch') or
|
||||
row.get('Systolic (mmHg)') or row.get('Systolic'))
|
||||
diastolic = (row.get('Diastolisch (mmHg)') or row.get('Diastolisch') or
|
||||
row.get('Diastolic (mmHg)') or row.get('Diastolic'))
|
||||
pulse = (row.get('Puls (bpm)') or row.get('Puls') or
|
||||
row.get('Pulse (bpm)') or row.get('Pulse'))
|
||||
|
||||
if not systolic or not diastolic:
|
||||
logger.warning(f"Skipped row {date_str} {time_str}: Missing BP values (sys={systolic}, dia={diastolic})")
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
# Parse warning flags (support various column names)
|
||||
irregular = (row.get('Unregelmäßiger Herzschlag festgestellt') or
|
||||
row.get('Unregelmäßiger Herzschlag') or
|
||||
row.get('Irregular Heartbeat') or '')
|
||||
afib = (row.get('Mögliches AFib') or
|
||||
row.get('Vorhofflimmern') or
|
||||
row.get('Possible AFib') or
|
||||
row.get('AFib') or '')
|
||||
|
||||
irregular_heartbeat = irregular.lower() in ['ja', 'yes', 'true', '1']
|
||||
possible_afib = afib.lower() in ['ja', 'yes', 'true', '1']
|
||||
|
||||
# Determine context based on time
|
||||
hour = int(time_str.split(':')[0])
|
||||
if 5 <= hour < 10:
|
||||
context = 'morning_fasted'
|
||||
elif 18 <= hour < 23:
|
||||
context = 'evening'
|
||||
else:
|
||||
context = 'other'
|
||||
|
||||
# Upsert
|
||||
cur.execute("""
|
||||
INSERT INTO blood_pressure_log (
|
||||
profile_id, measured_at,
|
||||
systolic, diastolic, pulse,
|
||||
context, irregular_heartbeat, possible_afib,
|
||||
source
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'omron')
|
||||
ON CONFLICT (profile_id, measured_at)
|
||||
DO UPDATE SET
|
||||
systolic = EXCLUDED.systolic,
|
||||
diastolic = EXCLUDED.diastolic,
|
||||
pulse = EXCLUDED.pulse,
|
||||
context = EXCLUDED.context,
|
||||
irregular_heartbeat = EXCLUDED.irregular_heartbeat,
|
||||
possible_afib = EXCLUDED.possible_afib
|
||||
WHERE blood_pressure_log.source != 'manual'
|
||||
RETURNING (xmax = 0) AS inserted
|
||||
""", (
|
||||
pid, measured_at,
|
||||
int(systolic), int(diastolic),
|
||||
int(pulse) if pulse else None,
|
||||
context, irregular_heartbeat, possible_afib
|
||||
))
|
||||
|
||||
result = cur.fetchone()
|
||||
if result is None:
|
||||
# WHERE clause prevented update (manual entry exists)
|
||||
skipped += 1
|
||||
elif result['inserted']:
|
||||
inserted += 1
|
||||
else:
|
||||
updated += 1
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error importing Omron row: {e}")
|
||||
errors += 1
|
||||
|
||||
return {
|
||||
"inserted": inserted,
|
||||
"updated": updated,
|
||||
"skipped": skipped,
|
||||
"errors": errors
|
||||
}
|
||||
@@ -4,16 +4,19 @@ 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
|
||||
from fastapi import APIRouter, Header, Depends, HTTPException
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth
|
||||
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("")
|
||||
@@ -31,17 +34,37 @@ def list_caliper(limit: int=100, x_profile_id: Optional[str]=Header(default=None
|
||||
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,
|
||||
@@ -50,6 +73,10 @@ def upsert_caliper(e: CaliperEntry, x_profile_id: Optional[str]=Header(default=N
|
||||
(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}
|
||||
|
||||
|
||||
|
||||
@@ -4,16 +4,19 @@ 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
|
||||
from fastapi import APIRouter, Header, Depends, HTTPException
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth
|
||||
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("")
|
||||
@@ -31,23 +34,47 @@ def list_circs(limit: int=100, x_profile_id: Optional[str]=Header(default=None),
|
||||
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}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
"""
|
||||
Coupon Management Endpoints for Mitai Jinkendo
|
||||
|
||||
Handles coupon CRUD (admin) and redemption (users).
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth, require_admin
|
||||
|
||||
router = APIRouter(prefix="/api/coupons", tags=["coupons"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_coupons(session: dict = Depends(require_admin)):
|
||||
"""Admin: List all coupons with redemption stats."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT
|
||||
c.*,
|
||||
t.name as tier_name,
|
||||
(SELECT COUNT(*) FROM coupon_redemptions WHERE coupon_id = c.id) as redemptions
|
||||
FROM coupons c
|
||||
LEFT JOIN tiers t ON t.id = c.tier_id
|
||||
ORDER BY c.created DESC
|
||||
""")
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_coupon(data: dict, session: dict = Depends(require_admin)):
|
||||
"""
|
||||
Admin: Create new coupon.
|
||||
|
||||
Required fields:
|
||||
- code: Unique coupon code
|
||||
- type: 'single_use', 'period', or 'wellpass'
|
||||
- tier_id: Target tier
|
||||
- duration_days: For period/wellpass coupons
|
||||
|
||||
Optional fields:
|
||||
- max_redemptions: NULL = unlimited
|
||||
- valid_from, valid_until: Validity period
|
||||
- description: Internal note
|
||||
"""
|
||||
code = data.get('code', '').strip().upper()
|
||||
coupon_type = data.get('type')
|
||||
tier_id = data.get('tier_id')
|
||||
duration_days = data.get('duration_days')
|
||||
max_redemptions = data.get('max_redemptions')
|
||||
valid_from = data.get('valid_from')
|
||||
valid_until = data.get('valid_until')
|
||||
description = data.get('description', '')
|
||||
|
||||
if not code:
|
||||
raise HTTPException(400, "Coupon-Code fehlt")
|
||||
if coupon_type not in ['single_use', 'period', 'wellpass']:
|
||||
raise HTTPException(400, "Ungültiger Coupon-Typ")
|
||||
if not tier_id:
|
||||
raise HTTPException(400, "Tier fehlt")
|
||||
if coupon_type in ['period', 'wellpass'] and not duration_days:
|
||||
raise HTTPException(400, "duration_days fehlt für period/wellpass Coupons")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check if code already exists
|
||||
cur.execute("SELECT id FROM coupons WHERE code = %s", (code,))
|
||||
if cur.fetchone():
|
||||
raise HTTPException(400, f"Coupon-Code '{code}' existiert bereits")
|
||||
|
||||
# Create coupon
|
||||
cur.execute("""
|
||||
INSERT INTO coupons (
|
||||
code, type, tier_id, duration_days, max_redemptions,
|
||||
valid_from, valid_until, description, created_by
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""", (
|
||||
code, coupon_type, tier_id, duration_days, max_redemptions,
|
||||
valid_from, valid_until, description, session['profile_id']
|
||||
))
|
||||
|
||||
coupon_id = cur.fetchone()['id']
|
||||
conn.commit()
|
||||
|
||||
return {"ok": True, "id": coupon_id, "code": code}
|
||||
|
||||
|
||||
@router.put("/{coupon_id}")
|
||||
def update_coupon(coupon_id: str, data: dict, session: dict = Depends(require_admin)):
|
||||
"""Admin: Update coupon."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
updates = []
|
||||
values = []
|
||||
|
||||
if 'active' in data:
|
||||
updates.append('active = %s')
|
||||
values.append(data['active'])
|
||||
if 'max_redemptions' in data:
|
||||
updates.append('max_redemptions = %s')
|
||||
values.append(data['max_redemptions'])
|
||||
if 'valid_until' in data:
|
||||
updates.append('valid_until = %s')
|
||||
values.append(data['valid_until'])
|
||||
if 'description' in data:
|
||||
updates.append('description = %s')
|
||||
values.append(data['description'])
|
||||
|
||||
if not updates:
|
||||
return {"ok": True}
|
||||
|
||||
updates.append('updated = CURRENT_TIMESTAMP')
|
||||
values.append(coupon_id)
|
||||
|
||||
cur.execute(
|
||||
f"UPDATE coupons SET {', '.join(updates)} WHERE id = %s",
|
||||
values
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.delete("/{coupon_id}")
|
||||
def delete_coupon(coupon_id: str, session: dict = Depends(require_admin)):
|
||||
"""Admin: Delete coupon (soft-delete: set active=false)."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("UPDATE coupons SET active = false WHERE id = %s", (coupon_id,))
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/{coupon_id}/redemptions")
|
||||
def get_coupon_redemptions(coupon_id: str, session: dict = Depends(require_admin)):
|
||||
"""Admin: Get all redemptions for a coupon."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT
|
||||
cr.id,
|
||||
cr.redeemed_at,
|
||||
p.name as profile_name,
|
||||
p.email as profile_email,
|
||||
ag.valid_from,
|
||||
ag.valid_until,
|
||||
ag.is_active
|
||||
FROM coupon_redemptions cr
|
||||
JOIN profiles p ON p.id = cr.profile_id
|
||||
LEFT JOIN access_grants ag ON ag.id = cr.access_grant_id
|
||||
WHERE cr.coupon_id = %s
|
||||
ORDER BY cr.redeemed_at DESC
|
||||
""", (coupon_id,))
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.post("/redeem")
|
||||
def redeem_coupon(data: dict, session: dict = Depends(require_auth)):
|
||||
"""
|
||||
User: Redeem a coupon code.
|
||||
|
||||
Creates an access_grant and handles Wellpass pause/resume logic.
|
||||
"""
|
||||
code = data.get('code', '').strip().upper()
|
||||
if not code:
|
||||
raise HTTPException(400, "Coupon-Code fehlt")
|
||||
|
||||
profile_id = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get coupon
|
||||
cur.execute("""
|
||||
SELECT * FROM coupons
|
||||
WHERE code = %s AND active = true
|
||||
""", (code,))
|
||||
coupon = cur.fetchone()
|
||||
|
||||
if not coupon:
|
||||
raise HTTPException(404, "Ungültiger Coupon-Code")
|
||||
|
||||
# Check validity period
|
||||
now = datetime.now()
|
||||
if coupon['valid_from'] and now < coupon['valid_from']:
|
||||
raise HTTPException(400, "Coupon noch nicht gültig")
|
||||
if coupon['valid_until'] and now > coupon['valid_until']:
|
||||
raise HTTPException(400, "Coupon abgelaufen")
|
||||
|
||||
# Check max redemptions
|
||||
if coupon['max_redemptions'] is not None:
|
||||
if coupon['redemption_count'] >= coupon['max_redemptions']:
|
||||
raise HTTPException(400, "Coupon bereits vollständig eingelöst")
|
||||
|
||||
# Check if user already redeemed this coupon
|
||||
cur.execute("""
|
||||
SELECT id FROM coupon_redemptions
|
||||
WHERE coupon_id = %s AND profile_id = %s
|
||||
""", (coupon['id'], profile_id))
|
||||
if cur.fetchone():
|
||||
raise HTTPException(400, "Du hast diesen Coupon bereits eingelöst")
|
||||
|
||||
# Create access grant
|
||||
valid_from = now
|
||||
valid_until = now + timedelta(days=coupon['duration_days']) if coupon['duration_days'] else None
|
||||
|
||||
# Wellpass logic: Pause existing personal grants
|
||||
if coupon['type'] == 'wellpass':
|
||||
cur.execute("""
|
||||
SELECT id, valid_until
|
||||
FROM access_grants
|
||||
WHERE profile_id = %s
|
||||
AND is_active = true
|
||||
AND granted_by != 'wellpass'
|
||||
AND valid_until > CURRENT_TIMESTAMP
|
||||
""", (profile_id,))
|
||||
active_grants = cur.fetchall()
|
||||
|
||||
for grant in active_grants:
|
||||
# Calculate remaining days
|
||||
remaining = (grant['valid_until'] - now).days
|
||||
# Pause grant
|
||||
cur.execute("""
|
||||
UPDATE access_grants
|
||||
SET is_active = false,
|
||||
paused_at = CURRENT_TIMESTAMP,
|
||||
remaining_days = %s
|
||||
WHERE id = %s
|
||||
""", (remaining, grant['id']))
|
||||
|
||||
# Insert access grant
|
||||
cur.execute("""
|
||||
INSERT INTO access_grants (
|
||||
profile_id, tier_id, granted_by, coupon_id,
|
||||
valid_from, valid_until, is_active
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, true)
|
||||
RETURNING id
|
||||
""", (
|
||||
profile_id, coupon['tier_id'],
|
||||
coupon['type'], coupon['id'],
|
||||
valid_from, valid_until
|
||||
))
|
||||
grant_id = cur.fetchone()['id']
|
||||
|
||||
# Record redemption
|
||||
cur.execute("""
|
||||
INSERT INTO coupon_redemptions (coupon_id, profile_id, access_grant_id)
|
||||
VALUES (%s, %s, %s)
|
||||
""", (coupon['id'], profile_id, grant_id))
|
||||
|
||||
# Increment coupon redemption count
|
||||
cur.execute("""
|
||||
UPDATE coupons
|
||||
SET redemption_count = redemption_count + 1
|
||||
WHERE id = %s
|
||||
""", (coupon['id'],))
|
||||
|
||||
# Log activity
|
||||
cur.execute("""
|
||||
INSERT INTO user_activity_log (profile_id, action, details)
|
||||
VALUES (%s, 'coupon_redeemed', %s)
|
||||
""", (
|
||||
profile_id,
|
||||
f'{{"coupon_code": "{code}", "tier": "{coupon["tier_id"]}", "duration_days": {coupon["duration_days"]}}}'
|
||||
))
|
||||
|
||||
conn.commit()
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"message": f"Coupon erfolgreich eingelöst: {coupon['tier_id']} für {coupon['duration_days']} Tage",
|
||||
"grant_id": grant_id,
|
||||
"valid_until": valid_until.isoformat() if valid_until else None
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
"""
|
||||
Evaluation Endpoints - Training Type Profiles
|
||||
Endpoints for activity evaluation and re-evaluation.
|
||||
|
||||
Issue: #15
|
||||
Date: 2026-03-23
|
||||
"""
|
||||
import logging
|
||||
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
|
||||
from evaluation_helper import (
|
||||
evaluate_and_save_activity,
|
||||
batch_evaluate_activities,
|
||||
load_parameters_registry
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/evaluation", tags=["evaluation"])
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@router.get("/parameters")
|
||||
def list_parameters(session: dict = Depends(require_auth)):
|
||||
"""
|
||||
List all available training parameters.
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
parameters = load_parameters_registry(cur)
|
||||
|
||||
return {
|
||||
"parameters": list(parameters.values()),
|
||||
"count": len(parameters)
|
||||
}
|
||||
|
||||
|
||||
@router.post("/activity/{activity_id}")
|
||||
def evaluate_activity(
|
||||
activity_id: str,
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Evaluates or re-evaluates a single activity.
|
||||
|
||||
Returns the evaluation result.
|
||||
"""
|
||||
profile_id = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Load activity
|
||||
cur.execute("""
|
||||
SELECT id, profile_id, date, training_type_id, duration_min,
|
||||
hr_avg, hr_max, distance_km, kcal_active, kcal_resting,
|
||||
rpe, pace_min_per_km, cadence, elevation_gain
|
||||
FROM activity_log
|
||||
WHERE id = %s AND profile_id = %s
|
||||
""", (activity_id, profile_id))
|
||||
|
||||
activity = cur.fetchone()
|
||||
if not activity:
|
||||
raise HTTPException(404, "Activity not found")
|
||||
|
||||
activity_dict = dict(activity)
|
||||
|
||||
# Evaluate
|
||||
result = evaluate_and_save_activity(
|
||||
cur,
|
||||
activity_dict["id"],
|
||||
activity_dict,
|
||||
activity_dict["training_type_id"],
|
||||
profile_id
|
||||
)
|
||||
|
||||
if not result:
|
||||
return {
|
||||
"message": "No profile configured for this training type",
|
||||
"evaluation": None
|
||||
}
|
||||
|
||||
return {
|
||||
"message": "Activity evaluated",
|
||||
"evaluation": result
|
||||
}
|
||||
|
||||
|
||||
@router.post("/batch")
|
||||
def batch_evaluate(
|
||||
limit: Optional[int] = None,
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Re-evaluates all activities for the current user.
|
||||
|
||||
Optional limit parameter for testing.
|
||||
"""
|
||||
profile_id = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
stats = batch_evaluate_activities(cur, profile_id, limit)
|
||||
|
||||
return {
|
||||
"message": "Batch evaluation completed",
|
||||
"stats": stats
|
||||
}
|
||||
|
||||
|
||||
@router.post("/batch/all")
|
||||
def batch_evaluate_all(session: dict = Depends(require_admin)):
|
||||
"""
|
||||
Admin-only: Re-evaluates all activities for all users.
|
||||
|
||||
Use with caution on large databases!
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get all profiles
|
||||
cur.execute("SELECT id FROM profiles")
|
||||
profiles = cur.fetchall()
|
||||
|
||||
total_stats = {
|
||||
"profiles": len(profiles),
|
||||
"total": 0,
|
||||
"evaluated": 0,
|
||||
"skipped": 0,
|
||||
"errors": 0
|
||||
}
|
||||
|
||||
for profile in profiles:
|
||||
profile_id = profile['id']
|
||||
stats = batch_evaluate_activities(cur, profile_id)
|
||||
|
||||
total_stats["total"] += stats["total"]
|
||||
total_stats["evaluated"] += stats["evaluated"]
|
||||
total_stats["skipped"] += stats["skipped"]
|
||||
total_stats["errors"] += stats["errors"]
|
||||
|
||||
return {
|
||||
"message": "Batch evaluation for all users completed",
|
||||
"stats": total_stats
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import os
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
@@ -17,10 +18,12 @@ from fastapi import APIRouter, HTTPException, Header, Depends
|
||||
from fastapi.responses import StreamingResponse, Response
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth
|
||||
from 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"))
|
||||
|
||||
@@ -30,13 +33,20 @@ def export_csv(x_profile_id: Optional[str]=Header(default=None), session: dict=D
|
||||
"""Export all data as CSV."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
# Check export permission
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT export_enabled FROM profiles WHERE id=%s", (pid,))
|
||||
prof = cur.fetchone()
|
||||
if not prof or not prof['export_enabled']:
|
||||
raise HTTPException(403, "Export ist für dieses Profil deaktiviert")
|
||||
# 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()
|
||||
@@ -74,6 +84,10 @@ def export_csv(x_profile_id: Optional[str]=Header(default=None), session: dict=D
|
||||
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",
|
||||
@@ -86,13 +100,20 @@ def export_json(x_profile_id: Optional[str]=Header(default=None), session: dict=
|
||||
"""Export all data as JSON."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
# Check export permission
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT export_enabled FROM profiles WHERE id=%s", (pid,))
|
||||
prof = cur.fetchone()
|
||||
if not prof or not prof['export_enabled']:
|
||||
raise HTTPException(403, "Export ist für dieses Profil deaktiviert")
|
||||
# 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 = {}
|
||||
@@ -126,6 +147,10 @@ def export_json(x_profile_id: Optional[str]=Header(default=None), session: dict=
|
||||
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",
|
||||
@@ -138,13 +163,26 @@ def export_zip(x_profile_id: Optional[str]=Header(default=None), session: dict=D
|
||||
"""Export all data as ZIP (CSV + JSON + photos) per specification."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
# Check export permission & get profile
|
||||
# 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())
|
||||
if not prof or not prof.get('export_enabled'):
|
||||
raise HTTPException(403, "Export ist für dieses Profil deaktiviert")
|
||||
|
||||
# Helper: CSV writer with UTF-8 BOM + semicolon
|
||||
def write_csv(zf, filename, rows, columns):
|
||||
@@ -297,6 +335,10 @@ Datumsformat: YYYY-MM-DD
|
||||
|
||||
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",
|
||||
|
||||
@@ -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
|
||||
@@ -8,6 +8,7 @@ import csv
|
||||
import io
|
||||
import json
|
||||
import uuid
|
||||
import logging
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
@@ -16,10 +17,12 @@ from datetime import datetime
|
||||
from fastapi import APIRouter, HTTPException, UploadFile, File, Header, Depends
|
||||
|
||||
from db import get_db, get_cursor
|
||||
from auth import require_auth
|
||||
from 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"))
|
||||
|
||||
@@ -41,6 +44,21 @@ async def import_zip(
|
||||
"""
|
||||
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)
|
||||
@@ -254,6 +272,9 @@ async def import_zip(
|
||||
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",
|
||||
|
||||
+171
-11
@@ -6,6 +6,7 @@ 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
|
||||
@@ -13,10 +14,13 @@ from datetime import datetime
|
||||
from fastapi import APIRouter, HTTPException, Header, Depends
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth, require_admin
|
||||
from 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
|
||||
from quality_filter import get_quality_filter_sql
|
||||
|
||||
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")
|
||||
@@ -64,6 +68,9 @@ def _get_profile_data(pid: str):
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||
prof = r2d(cur.fetchone())
|
||||
|
||||
# Issue #31: Get global quality filter setting
|
||||
quality_filter = get_quality_filter_sql(prof)
|
||||
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,))
|
||||
@@ -72,15 +79,36 @@ def _get_profile_data(pid: str):
|
||||
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,))
|
||||
|
||||
# Issue #31: Global quality filter (from user profile setting)
|
||||
cur.execute(f"""
|
||||
SELECT * FROM activity_log
|
||||
WHERE profile_id=%s
|
||||
{quality_filter}
|
||||
ORDER BY date DESC LIMIT 90
|
||||
""", (pid,))
|
||||
activity = [r2d(r) for r in cur.fetchall()]
|
||||
# v9d Phase 2: Sleep, Rest Days, Vitals
|
||||
cur.execute("SELECT * FROM sleep_log WHERE profile_id=%s ORDER BY date DESC LIMIT 30", (pid,))
|
||||
sleep = [r2d(r) for r in cur.fetchall()]
|
||||
cur.execute("SELECT * FROM rest_days WHERE profile_id=%s ORDER BY date DESC LIMIT 30", (pid,))
|
||||
rest_days = [r2d(r) for r in cur.fetchall()]
|
||||
# v9d Phase 2d Refactored: separate baseline and BP tables
|
||||
cur.execute("SELECT * FROM vitals_baseline WHERE profile_id=%s ORDER BY date DESC LIMIT 30", (pid,))
|
||||
vitals_baseline = [r2d(r) for r in cur.fetchall()]
|
||||
cur.execute("SELECT * FROM blood_pressure_log WHERE profile_id=%s ORDER BY measured_at DESC LIMIT 90", (pid,))
|
||||
blood_pressure = [r2d(r) for r in cur.fetchall()]
|
||||
return {
|
||||
"profile": prof,
|
||||
"weight": weight,
|
||||
"circumference": circ,
|
||||
"caliper": caliper,
|
||||
"nutrition": nutrition,
|
||||
"activity": activity
|
||||
"activity": activity,
|
||||
"sleep": sleep,
|
||||
"rest_days": rest_days,
|
||||
"vitals_baseline": vitals_baseline,
|
||||
"blood_pressure": blood_pressure
|
||||
}
|
||||
|
||||
|
||||
@@ -100,6 +128,10 @@ def _prepare_template_vars(data: dict) -> dict:
|
||||
caliper = data['caliper']
|
||||
nutrition = data['nutrition']
|
||||
activity = data['activity']
|
||||
sleep = data.get('sleep', [])
|
||||
rest_days = data.get('rest_days', [])
|
||||
vitals_baseline = data.get('vitals_baseline', [])
|
||||
blood_pressure = data.get('blood_pressure', [])
|
||||
|
||||
vars = {
|
||||
"name": prof.get('name', 'Nutzer'),
|
||||
@@ -189,6 +221,83 @@ def _prepare_template_vars(data: dict) -> dict:
|
||||
vars['activity_detail'] = "keine Daten"
|
||||
vars['activity_kcal_summary'] = "keine Daten"
|
||||
|
||||
# Sleep summary (v9d Phase 2b)
|
||||
if sleep:
|
||||
n = len(sleep)
|
||||
avg_duration = sum(float(s.get('duration_minutes',0) or 0) for s in sleep) / n
|
||||
avg_quality = sum(int(s.get('quality',0) or 0) for s in sleep if s.get('quality')) / max(sum(1 for s in sleep if s.get('quality')), 1)
|
||||
deep_data = [s for s in sleep if s.get('deep_minutes')]
|
||||
avg_deep = sum(float(s.get('deep_minutes',0)) for s in deep_data) / len(deep_data) if deep_data else 0
|
||||
vars['sleep_summary'] = f"{n} Nächte, Ø {avg_duration/60:.1f}h Schlafdauer, Qualität {avg_quality:.1f}/5"
|
||||
vars['sleep_detail'] = f"Ø {avg_duration:.0f}min gesamt, {avg_deep:.0f}min Tiefschlaf"
|
||||
vars['sleep_avg_duration'] = round(avg_duration)
|
||||
vars['sleep_avg_quality'] = round(avg_quality, 1)
|
||||
vars['sleep_nights'] = n
|
||||
else:
|
||||
vars['sleep_summary'] = "keine Daten"
|
||||
vars['sleep_detail'] = "keine Daten"
|
||||
vars['sleep_avg_duration'] = 0
|
||||
vars['sleep_avg_quality'] = 0
|
||||
vars['sleep_nights'] = 0
|
||||
|
||||
# Rest Days summary (v9d Phase 2a)
|
||||
if rest_days:
|
||||
n = len(rest_days)
|
||||
types = {}
|
||||
for rd in rest_days:
|
||||
rt = rd.get('rest_type', 'unknown')
|
||||
types[rt] = types.get(rt, 0) + 1
|
||||
type_summary = ", ".join([f"{k}: {v}x" for k, v in types.items()])
|
||||
vars['rest_days_summary'] = f"{n} Ruhetage (letzte 30d): {type_summary}"
|
||||
vars['rest_days_count'] = n
|
||||
vars['rest_days_types'] = type_summary
|
||||
else:
|
||||
vars['rest_days_summary'] = "keine Daten"
|
||||
vars['rest_days_count'] = 0
|
||||
vars['rest_days_types'] = "keine"
|
||||
|
||||
# Vitals Baseline summary (v9d Phase 2d Refactored)
|
||||
if vitals_baseline:
|
||||
n = len(vitals_baseline)
|
||||
hr_data = [v for v in vitals_baseline if v.get('resting_hr')]
|
||||
hrv_data = [v for v in vitals_baseline if v.get('hrv')]
|
||||
vo2_data = [v for v in vitals_baseline if v.get('vo2_max')]
|
||||
|
||||
avg_hr = sum(int(v.get('resting_hr')) for v in hr_data) / len(hr_data) if hr_data else 0
|
||||
avg_hrv = sum(int(v.get('hrv')) for v in hrv_data) / len(hrv_data) if hrv_data else 0
|
||||
latest_vo2 = float(vo2_data[0].get('vo2_max')) if vo2_data else 0
|
||||
|
||||
parts = []
|
||||
if avg_hr: parts.append(f"Ruhepuls Ø {avg_hr:.0f}bpm")
|
||||
if avg_hrv: parts.append(f"HRV Ø {avg_hrv:.0f}ms")
|
||||
if latest_vo2: parts.append(f"VO2 Max {latest_vo2:.1f}")
|
||||
|
||||
vars['vitals_summary'] = f"{n} Messungen: " + ", ".join(parts) if parts else "keine verwertbaren Daten"
|
||||
vars['vitals_detail'] = vars['vitals_summary']
|
||||
vars['vitals_avg_hr'] = round(avg_hr)
|
||||
vars['vitals_avg_hrv'] = round(avg_hrv)
|
||||
vars['vitals_vo2_max'] = round(latest_vo2, 1) if latest_vo2 else "k.A."
|
||||
else:
|
||||
vars['vitals_summary'] = "keine Daten"
|
||||
vars['vitals_detail'] = "keine Daten"
|
||||
vars['vitals_avg_hr'] = 0
|
||||
vars['vitals_avg_hrv'] = 0
|
||||
vars['vitals_vo2_max'] = "k.A."
|
||||
|
||||
# Blood Pressure summary (v9d Phase 2d Refactored)
|
||||
if blood_pressure:
|
||||
n = len(blood_pressure)
|
||||
bp_data = [bp for bp in blood_pressure if bp.get('systolic') and bp.get('diastolic')]
|
||||
|
||||
avg_bp_sys = sum(int(bp.get('systolic')) for bp in bp_data) / len(bp_data) if bp_data else 0
|
||||
avg_bp_dia = sum(int(bp.get('diastolic')) for bp in bp_data) / len(bp_data) if bp_data else 0
|
||||
|
||||
vars['vitals_avg_bp'] = f"{round(avg_bp_sys)}/{round(avg_bp_dia)}" if avg_bp_sys else "k.A."
|
||||
vars['bp_summary'] = f"{n} Messungen, Ø {avg_bp_sys:.0f}/{avg_bp_dia:.0f} mmHg" if avg_bp_sys else "keine Daten"
|
||||
else:
|
||||
vars['vitals_avg_bp'] = "k.A."
|
||||
vars['bp_summary'] = "keine Daten"
|
||||
|
||||
return vars
|
||||
|
||||
|
||||
@@ -251,7 +360,21 @@ def delete_ai_insight(scope: str, x_profile_id: Optional[str]=Header(default=Non
|
||||
async def analyze_with_prompt(slug: str, x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||
"""Run AI analysis with specified prompt template."""
|
||||
pid = get_pid(x_profile_id)
|
||||
check_ai_limit(pid)
|
||||
|
||||
# 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:
|
||||
@@ -294,14 +417,18 @@ async def analyze_with_prompt(slug: str, x_profile_id: Optional[str]=Header(defa
|
||||
else:
|
||||
raise HTTPException(500, "Keine KI-API konfiguriert")
|
||||
|
||||
# Save insight
|
||||
# Save insight (with history - no DELETE)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("DELETE FROM ai_insights WHERE profile_id=%s AND scope=%s", (pid, slug))
|
||||
cur.execute("INSERT INTO ai_insights (id, profile_id, scope, content, created) VALUES (%s,%s,%s,%s,CURRENT_TIMESTAMP)",
|
||||
(str(uuid.uuid4()), pid, slug, content))
|
||||
|
||||
# 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}
|
||||
|
||||
|
||||
@@ -309,7 +436,35 @@ async def analyze_with_prompt(slug: str, x_profile_id: Optional[str]=Header(defa
|
||||
async def analyze_pipeline(x_profile_id: Optional[str]=Header(default=None), session: dict=Depends(require_auth)):
|
||||
"""Run 3-stage pipeline analysis."""
|
||||
pid = get_pid(x_profile_id)
|
||||
check_ai_limit(pid)
|
||||
|
||||
# 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)
|
||||
@@ -431,15 +586,20 @@ async def analyze_pipeline(x_profile_id: Optional[str]=Header(default=None), ses
|
||||
if goals_text:
|
||||
final_content += "\n\n" + goals_text
|
||||
|
||||
# Save as 'gesamt' scope
|
||||
# Save as 'pipeline' scope (with history - no DELETE)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("DELETE FROM ai_insights WHERE profile_id=%s AND scope='gesamt'", (pid,))
|
||||
cur.execute("INSERT INTO ai_insights (id, profile_id, scope, content, created) VALUES (%s,%s,'gesamt',%s,CURRENT_TIMESTAMP)",
|
||||
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": "gesamt", "content": final_content, "stage1": stage1_results}
|
||||
|
||||
return {"scope": "pipeline", "content": final_content, "stage1": stage1_results}
|
||||
|
||||
|
||||
@router.get("/ai/usage")
|
||||
|
||||
@@ -6,16 +6,19 @@ 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
|
||||
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 ────────────────────────────────────────────────────────────────────
|
||||
@@ -30,6 +33,23 @@ def _pf(s):
|
||||
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')
|
||||
@@ -52,23 +72,88 @@ async def import_nutrition_csv(file: UploadFile=File(...), x_profile_id: Optiona
|
||||
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))
|
||||
if cur.fetchone():
|
||||
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
|
||||
return {"rows_parsed":count,"days_imported":inserted,
|
||||
|
||||
# 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."""
|
||||
@@ -80,6 +165,17 @@ def list_nutrition(limit: int=365, x_profile_id: Optional[str]=Header(default=No
|
||||
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."""
|
||||
@@ -123,7 +219,9 @@ def nutrition_weekly(weeks: int=16, x_profile_id: Optional[str]=Header(default=N
|
||||
if not rows: return []
|
||||
wm={}
|
||||
for d in rows:
|
||||
wk=datetime.strptime(d['date'],'%Y-%m-%d').strftime('%Y-W%V')
|
||||
# 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):
|
||||
@@ -131,3 +229,61 @@ def nutrition_weekly(weeks: int=16, x_profile_id: Optional[str]=Header(default=N
|
||||
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}
|
||||
@@ -5,37 +5,64 @@ 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 import APIRouter, UploadFile, File, Form, Header, HTTPException, Depends
|
||||
from fastapi.responses import FileResponse
|
||||
import aiofiles
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth, require_auth_flexible
|
||||
from 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="",
|
||||
async def upload_photo(file: UploadFile=File(...), date: str=Form(""),
|
||||
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())
|
||||
|
||||
# Convert empty string to NULL for date field
|
||||
photo_date = date if date and date.strip() else None
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("INSERT INTO photos (id,profile_id,date,path,created) VALUES (%s,%s,%s,%s,CURRENT_TIMESTAMP)",
|
||||
(fid,pid,date,str(path)))
|
||||
return {"id":fid,"date":date}
|
||||
(fid,pid,photo_date,str(path)))
|
||||
|
||||
# Phase 2: Increment usage counter
|
||||
increment_feature_usage(pid, 'photos')
|
||||
|
||||
return {"id":fid,"date":photo_date}
|
||||
|
||||
|
||||
@router.get("/{fid}")
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
"""
|
||||
Rest Days Endpoints for Mitai Jinkendo
|
||||
|
||||
Context-specific rest days with flexible JSONB configuration.
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional, Literal
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Depends, Header
|
||||
from pydantic import BaseModel, Field
|
||||
from psycopg2.extras import Json
|
||||
from psycopg2.errors import UniqueViolation
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth
|
||||
from routers.profiles import get_pid
|
||||
|
||||
router = APIRouter(prefix="/api/rest-days", tags=["rest-days"])
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ── Models ────────────────────────────────────────────────────────────────────
|
||||
|
||||
class RestConfig(BaseModel):
|
||||
focus: Literal['muscle_recovery', 'cardio_recovery', 'mental_rest', 'deload', 'injury']
|
||||
rest_from: list[str] = Field(default_factory=list, description="Training type IDs to avoid")
|
||||
allows: list[str] = Field(default_factory=list, description="Allowed activity type IDs")
|
||||
intensity_max: Optional[int] = Field(None, ge=1, le=100, description="Max HR% for allowed activities")
|
||||
note: str = ""
|
||||
|
||||
|
||||
class RestDayCreate(BaseModel):
|
||||
date: str # YYYY-MM-DD
|
||||
rest_config: RestConfig
|
||||
note: str = ""
|
||||
|
||||
|
||||
class RestDayUpdate(BaseModel):
|
||||
date: Optional[str] = None
|
||||
rest_config: Optional[RestConfig] = None
|
||||
note: Optional[str] = None
|
||||
|
||||
|
||||
class ActivityConflictCheck(BaseModel):
|
||||
date: str
|
||||
activity_type: str
|
||||
|
||||
|
||||
# ── CRUD Endpoints ────────────────────────────────────────────────────────────
|
||||
|
||||
@router.get("")
|
||||
def list_rest_days(
|
||||
limit: int = 90,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""List rest days for current profile (last N days)."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, profile_id, date, rest_config, note, created_at
|
||||
FROM rest_days
|
||||
WHERE profile_id = %s
|
||||
ORDER BY date DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(pid, limit)
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_rest_day(
|
||||
data: RestDayCreate,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Create rest day with JSONB config. Upserts by date."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
# Validate date format
|
||||
try:
|
||||
datetime.strptime(data.date, '%Y-%m-%d')
|
||||
except ValueError:
|
||||
raise HTTPException(400, "Invalid date format. Use YYYY-MM-DD")
|
||||
|
||||
# Convert RestConfig to dict for JSONB storage
|
||||
config_dict = data.rest_config.model_dump()
|
||||
focus = data.rest_config.focus
|
||||
|
||||
try:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Insert (multiple entries per date allowed, but not same focus)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO rest_days (profile_id, date, focus, rest_config, note, created_at)
|
||||
VALUES (%s, %s, %s, %s, %s, CURRENT_TIMESTAMP)
|
||||
RETURNING id, profile_id, date, focus, rest_config, note, created_at
|
||||
""",
|
||||
(pid, data.date, focus, Json(config_dict), data.note)
|
||||
)
|
||||
|
||||
result = cur.fetchone()
|
||||
return r2d(result)
|
||||
except UniqueViolation:
|
||||
# User-friendly error for duplicate focus
|
||||
focus_labels = {
|
||||
'muscle_recovery': 'Muskelregeneration',
|
||||
'cardio_recovery': 'Cardio-Erholung',
|
||||
'mental_rest': 'Mentale Erholung',
|
||||
'deload': 'Deload',
|
||||
'injury': 'Verletzungspause',
|
||||
}
|
||||
focus_label = focus_labels.get(focus, focus)
|
||||
raise HTTPException(
|
||||
400,
|
||||
f"Du hast bereits einen Ruhetag '{focus_label}' für {data.date}. Bitte wähle einen anderen Typ oder lösche den bestehenden Eintrag."
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{rest_day_id}")
|
||||
def get_rest_day(
|
||||
rest_day_id: int,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Get single rest day by ID."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, profile_id, date, rest_config, note, created_at
|
||||
FROM rest_days
|
||||
WHERE id = %s AND profile_id = %s
|
||||
""",
|
||||
(rest_day_id, pid)
|
||||
)
|
||||
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Rest day not found")
|
||||
|
||||
return r2d(row)
|
||||
|
||||
|
||||
@router.put("/{rest_day_id}")
|
||||
def update_rest_day(
|
||||
rest_day_id: int,
|
||||
data: RestDayUpdate,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Update rest day."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
# Build update fields dynamically
|
||||
updates = []
|
||||
values = []
|
||||
|
||||
if data.date:
|
||||
try:
|
||||
datetime.strptime(data.date, '%Y-%m-%d')
|
||||
except ValueError:
|
||||
raise HTTPException(400, "Invalid date format. Use YYYY-MM-DD")
|
||||
updates.append("date = %s")
|
||||
values.append(data.date)
|
||||
|
||||
if data.rest_config:
|
||||
updates.append("rest_config = %s")
|
||||
values.append(Json(data.rest_config.model_dump()))
|
||||
# Also update focus column if config changed
|
||||
updates.append("focus = %s")
|
||||
values.append(data.rest_config.focus)
|
||||
|
||||
if data.note is not None:
|
||||
updates.append("note = %s")
|
||||
values.append(data.note)
|
||||
|
||||
if not updates:
|
||||
raise HTTPException(400, "No fields to update")
|
||||
|
||||
values.extend([rest_day_id, pid])
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE rest_days
|
||||
SET {', '.join(updates)}
|
||||
WHERE id = %s AND profile_id = %s
|
||||
RETURNING id, profile_id, date, rest_config, note, created_at
|
||||
""",
|
||||
values
|
||||
)
|
||||
|
||||
result = cur.fetchone()
|
||||
if not result:
|
||||
raise HTTPException(404, "Rest day not found")
|
||||
|
||||
return r2d(result)
|
||||
|
||||
|
||||
@router.delete("/{rest_day_id}")
|
||||
def delete_rest_day(
|
||||
rest_day_id: int,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Delete rest day."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"DELETE FROM rest_days WHERE id = %s AND profile_id = %s RETURNING id",
|
||||
(rest_day_id, pid)
|
||||
)
|
||||
|
||||
result = cur.fetchone()
|
||||
if not result:
|
||||
raise HTTPException(404, "Rest day not found")
|
||||
|
||||
return {"deleted": True, "id": result['id']}
|
||||
|
||||
|
||||
# ── Stats & Validation ────────────────────────────────────────────────────────
|
||||
|
||||
@router.get("/stats")
|
||||
def get_rest_days_stats(
|
||||
weeks: int = 4,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Get rest day statistics (count per week, focus distribution)."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
cutoff_date = (datetime.now() - timedelta(weeks=weeks)).strftime('%Y-%m-%d')
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Total count
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COUNT(*) as total
|
||||
FROM rest_days
|
||||
WHERE profile_id = %s AND date >= %s
|
||||
""",
|
||||
(pid, cutoff_date)
|
||||
)
|
||||
total = cur.fetchone()['total']
|
||||
|
||||
# Count by focus type
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
rest_config->>'focus' as focus,
|
||||
COUNT(*) as count
|
||||
FROM rest_days
|
||||
WHERE profile_id = %s AND date >= %s
|
||||
GROUP BY rest_config->>'focus'
|
||||
ORDER BY count DESC
|
||||
""",
|
||||
(pid, cutoff_date)
|
||||
)
|
||||
by_focus = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
# Count by week (ISO week number)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
EXTRACT(YEAR FROM date) as year,
|
||||
EXTRACT(WEEK FROM date) as week,
|
||||
COUNT(*) as count
|
||||
FROM rest_days
|
||||
WHERE profile_id = %s AND date >= %s
|
||||
GROUP BY year, week
|
||||
ORDER BY year DESC, week DESC
|
||||
""",
|
||||
(pid, cutoff_date)
|
||||
)
|
||||
by_week = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
return {
|
||||
"total_rest_days": total,
|
||||
"weeks_analyzed": weeks,
|
||||
"by_focus": by_focus,
|
||||
"by_week": by_week
|
||||
}
|
||||
|
||||
|
||||
@router.post("/validate-activity")
|
||||
def validate_activity(
|
||||
data: ActivityConflictCheck,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Check if activity conflicts with rest day configuration.
|
||||
|
||||
Returns:
|
||||
- conflict: bool
|
||||
- severity: 'warning' | 'info' | 'none'
|
||||
- message: str
|
||||
"""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT rest_config
|
||||
FROM rest_days
|
||||
WHERE profile_id = %s AND date = %s
|
||||
""",
|
||||
(pid, data.date)
|
||||
)
|
||||
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return {"conflict": False, "severity": "none", "message": ""}
|
||||
|
||||
config = row['rest_config']
|
||||
|
||||
# Check if activity is in rest_from
|
||||
if data.activity_type in config.get('rest_from', []):
|
||||
focus_labels = {
|
||||
'muscle_recovery': 'Muskelregeneration',
|
||||
'cardio_recovery': 'Cardio-Erholung',
|
||||
'mental_rest': 'Mentale Erholung',
|
||||
'deload': 'Deload',
|
||||
'injury': 'Verletzungspause'
|
||||
}
|
||||
focus_label = focus_labels.get(config.get('focus'), 'Ruhetag')
|
||||
|
||||
return {
|
||||
"conflict": True,
|
||||
"severity": "warning",
|
||||
"message": f"Ruhetag ({focus_label}) – {data.activity_type} sollte pausiert werden. Trotzdem erfassen?"
|
||||
}
|
||||
|
||||
# Check if activity is allowed
|
||||
allows_list = config.get('allows', [])
|
||||
if allows_list and data.activity_type not in allows_list:
|
||||
return {
|
||||
"conflict": True,
|
||||
"severity": "info",
|
||||
"message": f"Aktivität nicht in erlaubten Aktivitäten. Heute: {', '.join(allows_list) or 'Keine'}."
|
||||
}
|
||||
|
||||
# Check intensity_max (if provided in request)
|
||||
intensity_max = config.get('intensity_max')
|
||||
if intensity_max:
|
||||
return {
|
||||
"conflict": False,
|
||||
"severity": "info",
|
||||
"message": f"Erlaubt bei max. {intensity_max}% HFmax."
|
||||
}
|
||||
|
||||
return {"conflict": False, "severity": "none", "message": ""}
|
||||
@@ -0,0 +1,660 @@
|
||||
"""
|
||||
Sleep Module Router (v9d Phase 2b)
|
||||
|
||||
Endpoints:
|
||||
- CRUD: list, create/upsert, update, delete
|
||||
- Stats: 7-day average, trends, phase distribution, sleep debt
|
||||
- Correlations: sleep ↔ resting HR, training, weight (Phase 2e)
|
||||
"""
|
||||
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
|
||||
from pydantic import BaseModel
|
||||
from typing import Literal
|
||||
from datetime import datetime, timedelta
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
|
||||
from auth import require_auth
|
||||
from db import get_db, get_cursor
|
||||
|
||||
router = APIRouter(prefix="/api/sleep", tags=["sleep"])
|
||||
|
||||
# ── Models ────────────────────────────────────────────────────────────────────
|
||||
|
||||
class SleepCreate(BaseModel):
|
||||
date: str # YYYY-MM-DD
|
||||
bedtime: str | None = None # HH:MM
|
||||
wake_time: str | None = None # HH:MM
|
||||
duration_minutes: int
|
||||
quality: int | None = None # 1-5
|
||||
wake_count: int | None = None
|
||||
deep_minutes: int | None = None
|
||||
rem_minutes: int | None = None
|
||||
light_minutes: int | None = None
|
||||
awake_minutes: int | None = None
|
||||
note: str = ""
|
||||
source: Literal['manual', 'apple_health', 'garmin'] = 'manual'
|
||||
|
||||
class SleepResponse(BaseModel):
|
||||
id: int
|
||||
profile_id: str
|
||||
date: str
|
||||
bedtime: str | None
|
||||
wake_time: str | None
|
||||
duration_minutes: int
|
||||
duration_formatted: str
|
||||
quality: int | None
|
||||
wake_count: int | None
|
||||
deep_minutes: int | None
|
||||
rem_minutes: int | None
|
||||
light_minutes: int | None
|
||||
awake_minutes: int | None
|
||||
sleep_segments: list | None
|
||||
sleep_efficiency: float | None
|
||||
deep_percent: float | None
|
||||
rem_percent: float | None
|
||||
note: str
|
||||
source: str
|
||||
created_at: str
|
||||
|
||||
class SleepStatsResponse(BaseModel):
|
||||
avg_duration_minutes: float
|
||||
avg_quality: float | None
|
||||
total_nights: int
|
||||
nights_below_goal: int
|
||||
sleep_goal_minutes: int
|
||||
|
||||
class SleepDebtResponse(BaseModel):
|
||||
sleep_debt_minutes: int
|
||||
sleep_debt_formatted: str
|
||||
days_analyzed: int
|
||||
sleep_goal_minutes: int
|
||||
|
||||
# ── Helper Functions ──────────────────────────────────────────────────────────
|
||||
|
||||
def format_duration(minutes: int) -> str:
|
||||
"""Convert minutes to 'Xh Ymin' format."""
|
||||
hours = minutes // 60
|
||||
mins = minutes % 60
|
||||
return f"{hours}h {mins}min"
|
||||
|
||||
def calculate_sleep_efficiency(duration_min: int, awake_min: int | None) -> float | None:
|
||||
"""Sleep efficiency = duration / (duration + awake) * 100."""
|
||||
if awake_min is None or awake_min == 0:
|
||||
return None
|
||||
total = duration_min + awake_min
|
||||
return round((duration_min / total) * 100, 1) if total > 0 else None
|
||||
|
||||
def calculate_phase_percent(phase_min: int | None, duration_min: int) -> float | None:
|
||||
"""Calculate phase percentage of total duration."""
|
||||
if phase_min is None or duration_min == 0:
|
||||
return None
|
||||
return round((phase_min / duration_min) * 100, 1)
|
||||
|
||||
def row_to_sleep_response(row: dict) -> SleepResponse:
|
||||
"""Convert DB row to SleepResponse."""
|
||||
return SleepResponse(
|
||||
id=row['id'],
|
||||
profile_id=row['profile_id'],
|
||||
date=str(row['date']),
|
||||
bedtime=str(row['bedtime']) if row['bedtime'] else None,
|
||||
wake_time=str(row['wake_time']) if row['wake_time'] else None,
|
||||
duration_minutes=row['duration_minutes'],
|
||||
duration_formatted=format_duration(row['duration_minutes']),
|
||||
quality=row['quality'],
|
||||
wake_count=row['wake_count'],
|
||||
deep_minutes=row['deep_minutes'],
|
||||
rem_minutes=row['rem_minutes'],
|
||||
light_minutes=row['light_minutes'],
|
||||
awake_minutes=row['awake_minutes'],
|
||||
sleep_segments=row['sleep_segments'],
|
||||
sleep_efficiency=calculate_sleep_efficiency(row['duration_minutes'], row['awake_minutes']),
|
||||
deep_percent=calculate_phase_percent(row['deep_minutes'], row['duration_minutes']),
|
||||
rem_percent=calculate_phase_percent(row['rem_minutes'], row['duration_minutes']),
|
||||
note=row['note'] or "",
|
||||
source=row['source'],
|
||||
created_at=str(row['created_at'])
|
||||
)
|
||||
|
||||
# ── CRUD Endpoints ────────────────────────────────────────────────────────────
|
||||
|
||||
@router.get("")
|
||||
def list_sleep(
|
||||
limit: int = 90,
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""List sleep entries for current profile (last N days)."""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT * FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
ORDER BY date DESC
|
||||
LIMIT %s
|
||||
""", (pid, limit))
|
||||
rows = cur.fetchall()
|
||||
|
||||
return [row_to_sleep_response(row) for row in rows]
|
||||
|
||||
@router.get("/by-date/{date}")
|
||||
def get_sleep_by_date(
|
||||
date: str,
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Get sleep entry for specific date."""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT * FROM sleep_log
|
||||
WHERE profile_id = %s AND date = %s
|
||||
""", (pid, date))
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row:
|
||||
raise HTTPException(404, "No sleep entry for this date")
|
||||
|
||||
return row_to_sleep_response(row)
|
||||
|
||||
@router.post("")
|
||||
def create_sleep(
|
||||
data: SleepCreate,
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Create or update sleep entry (upsert by date)."""
|
||||
pid = session['profile_id']
|
||||
|
||||
# Convert empty strings to None for TIME fields
|
||||
bedtime = data.bedtime if data.bedtime else None
|
||||
wake_time = data.wake_time if data.wake_time else None
|
||||
|
||||
# Plausibility check: sleep phases (deep+rem+light) should sum to duration
|
||||
# Note: awake_minutes is NOT part of sleep duration (tracked separately)
|
||||
if any([data.deep_minutes, data.rem_minutes, data.light_minutes]):
|
||||
sleep_phase_sum = (data.deep_minutes or 0) + (data.rem_minutes or 0) + (data.light_minutes or 0)
|
||||
diff = abs(data.duration_minutes - sleep_phase_sum)
|
||||
if diff > 5:
|
||||
raise HTTPException(
|
||||
400,
|
||||
f"Plausibilitätsprüfung fehlgeschlagen: Schlafphasen-Summe ({sleep_phase_sum} min) weicht um {diff} min von Schlafdauer ({data.duration_minutes} min) ab. Max. Toleranz: 5 min. Hinweis: Wachphasen werden nicht zur Schlafdauer gezählt."
|
||||
)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Upsert: INSERT ... ON CONFLICT DO UPDATE
|
||||
cur.execute("""
|
||||
INSERT INTO sleep_log (
|
||||
profile_id, date, bedtime, wake_time, duration_minutes,
|
||||
quality, wake_count, deep_minutes, rem_minutes, light_minutes,
|
||||
awake_minutes, note, source, updated_at
|
||||
) VALUES (
|
||||
%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, CURRENT_TIMESTAMP
|
||||
)
|
||||
ON CONFLICT (profile_id, date) DO UPDATE SET
|
||||
bedtime = EXCLUDED.bedtime,
|
||||
wake_time = EXCLUDED.wake_time,
|
||||
duration_minutes = EXCLUDED.duration_minutes,
|
||||
quality = EXCLUDED.quality,
|
||||
wake_count = EXCLUDED.wake_count,
|
||||
deep_minutes = EXCLUDED.deep_minutes,
|
||||
rem_minutes = EXCLUDED.rem_minutes,
|
||||
light_minutes = EXCLUDED.light_minutes,
|
||||
awake_minutes = EXCLUDED.awake_minutes,
|
||||
note = EXCLUDED.note,
|
||||
source = EXCLUDED.source,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
RETURNING *
|
||||
""", (
|
||||
pid, data.date, bedtime, wake_time, data.duration_minutes,
|
||||
data.quality, data.wake_count, data.deep_minutes, data.rem_minutes,
|
||||
data.light_minutes, data.awake_minutes, data.note, data.source
|
||||
))
|
||||
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
|
||||
return row_to_sleep_response(row)
|
||||
|
||||
@router.put("/{id}")
|
||||
def update_sleep(
|
||||
id: int,
|
||||
data: SleepCreate,
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Update existing sleep entry by ID."""
|
||||
pid = session['profile_id']
|
||||
|
||||
# Convert empty strings to None for TIME fields
|
||||
bedtime = data.bedtime if data.bedtime else None
|
||||
wake_time = data.wake_time if data.wake_time else None
|
||||
|
||||
# Plausibility check: sleep phases (deep+rem+light) should sum to duration
|
||||
# Note: awake_minutes is NOT part of sleep duration (tracked separately)
|
||||
if any([data.deep_minutes, data.rem_minutes, data.light_minutes]):
|
||||
sleep_phase_sum = (data.deep_minutes or 0) + (data.rem_minutes or 0) + (data.light_minutes or 0)
|
||||
diff = abs(data.duration_minutes - sleep_phase_sum)
|
||||
if diff > 5:
|
||||
raise HTTPException(
|
||||
400,
|
||||
f"Plausibilitätsprüfung fehlgeschlagen: Schlafphasen-Summe ({sleep_phase_sum} min) weicht um {diff} min von Schlafdauer ({data.duration_minutes} min) ab. Max. Toleranz: 5 min. Hinweis: Wachphasen werden nicht zur Schlafdauer gezählt."
|
||||
)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
cur.execute("""
|
||||
UPDATE sleep_log SET
|
||||
date = %s,
|
||||
bedtime = %s,
|
||||
wake_time = %s,
|
||||
duration_minutes = %s,
|
||||
quality = %s,
|
||||
wake_count = %s,
|
||||
deep_minutes = %s,
|
||||
rem_minutes = %s,
|
||||
light_minutes = %s,
|
||||
awake_minutes = %s,
|
||||
note = %s,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = %s AND profile_id = %s
|
||||
RETURNING *
|
||||
""", (
|
||||
data.date, bedtime, wake_time, data.duration_minutes,
|
||||
data.quality, data.wake_count, data.deep_minutes, data.rem_minutes,
|
||||
data.light_minutes, data.awake_minutes, data.note, id, pid
|
||||
))
|
||||
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Sleep entry not found")
|
||||
|
||||
conn.commit()
|
||||
|
||||
return row_to_sleep_response(row)
|
||||
|
||||
@router.delete("/{id}")
|
||||
def delete_sleep(
|
||||
id: int,
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Delete sleep entry."""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
DELETE FROM sleep_log
|
||||
WHERE id = %s AND profile_id = %s
|
||||
""", (id, pid))
|
||||
conn.commit()
|
||||
|
||||
return {"deleted": id}
|
||||
|
||||
# ── Stats Endpoints ───────────────────────────────────────────────────────────
|
||||
|
||||
@router.get("/stats")
|
||||
def get_sleep_stats(
|
||||
days: int = 7,
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Get sleep statistics (average duration, quality, nights below goal)."""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get sleep goal from profile
|
||||
cur.execute("SELECT sleep_goal_minutes FROM profiles WHERE id = %s", (pid,))
|
||||
profile = cur.fetchone()
|
||||
sleep_goal = profile['sleep_goal_minutes'] if profile and profile['sleep_goal_minutes'] else 450
|
||||
|
||||
# Calculate stats
|
||||
cur.execute("""
|
||||
SELECT
|
||||
AVG(duration_minutes)::FLOAT as avg_duration,
|
||||
AVG(quality)::FLOAT as avg_quality,
|
||||
COUNT(*) as total_nights,
|
||||
COUNT(CASE WHEN duration_minutes < %s THEN 1 END) as nights_below_goal
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '%s days'
|
||||
""", (sleep_goal, pid, days))
|
||||
|
||||
stats = cur.fetchone()
|
||||
|
||||
return SleepStatsResponse(
|
||||
avg_duration_minutes=round(stats['avg_duration'], 1) if stats['avg_duration'] else 0,
|
||||
avg_quality=round(stats['avg_quality'], 1) if stats['avg_quality'] else None,
|
||||
total_nights=stats['total_nights'],
|
||||
nights_below_goal=stats['nights_below_goal'],
|
||||
sleep_goal_minutes=sleep_goal
|
||||
)
|
||||
|
||||
@router.get("/debt")
|
||||
def get_sleep_debt(
|
||||
days: int = 14,
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Calculate sleep debt over last N days."""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get sleep goal
|
||||
cur.execute("SELECT sleep_goal_minutes FROM profiles WHERE id = %s", (pid,))
|
||||
profile = cur.fetchone()
|
||||
sleep_goal = profile['sleep_goal_minutes'] if profile and profile['sleep_goal_minutes'] else 450
|
||||
|
||||
# Calculate debt
|
||||
cur.execute("""
|
||||
SELECT
|
||||
SUM(%s - duration_minutes) as debt_minutes,
|
||||
COUNT(*) as nights_analyzed
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '%s days'
|
||||
""", (sleep_goal, pid, days))
|
||||
|
||||
result = cur.fetchone()
|
||||
|
||||
debt_min = int(result['debt_minutes']) if result['debt_minutes'] else 0
|
||||
nights = result['nights_analyzed'] if result['nights_analyzed'] else 0
|
||||
|
||||
# Format debt
|
||||
if debt_min == 0:
|
||||
formatted = "0 – kein Defizit"
|
||||
elif debt_min > 0:
|
||||
formatted = f"+{format_duration(debt_min)}"
|
||||
else:
|
||||
formatted = f"−{format_duration(abs(debt_min))}"
|
||||
|
||||
return SleepDebtResponse(
|
||||
sleep_debt_minutes=debt_min,
|
||||
sleep_debt_formatted=formatted,
|
||||
days_analyzed=nights,
|
||||
sleep_goal_minutes=sleep_goal
|
||||
)
|
||||
|
||||
@router.get("/trend")
|
||||
def get_sleep_trend(
|
||||
days: int = 30,
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Get sleep duration and quality trend over time."""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT
|
||||
date,
|
||||
duration_minutes,
|
||||
quality
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '%s days'
|
||||
ORDER BY date ASC
|
||||
""", (pid, days))
|
||||
rows = cur.fetchall()
|
||||
|
||||
return [
|
||||
{
|
||||
"date": str(row['date']),
|
||||
"duration_minutes": row['duration_minutes'],
|
||||
"quality": row['quality']
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
@router.get("/phases")
|
||||
def get_sleep_phases(
|
||||
days: int = 30,
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Get sleep phase distribution (deep, REM, light, awake) over time."""
|
||||
pid = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT
|
||||
date,
|
||||
deep_minutes,
|
||||
rem_minutes,
|
||||
light_minutes,
|
||||
awake_minutes,
|
||||
duration_minutes
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '%s days'
|
||||
AND (deep_minutes IS NOT NULL OR rem_minutes IS NOT NULL)
|
||||
ORDER BY date ASC
|
||||
""", (pid, days))
|
||||
rows = cur.fetchall()
|
||||
|
||||
return [
|
||||
{
|
||||
"date": str(row['date']),
|
||||
"deep_minutes": row['deep_minutes'],
|
||||
"rem_minutes": row['rem_minutes'],
|
||||
"light_minutes": row['light_minutes'],
|
||||
"awake_minutes": row['awake_minutes'],
|
||||
"deep_percent": calculate_phase_percent(row['deep_minutes'], row['duration_minutes']),
|
||||
"rem_percent": calculate_phase_percent(row['rem_minutes'], row['duration_minutes'])
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
# ── Import Endpoints ──────────────────────────────────────────────────────────
|
||||
|
||||
@router.post("/import/apple-health")
|
||||
async def import_apple_health_sleep(
|
||||
file: UploadFile = File(...),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Import sleep data from Apple Health CSV export.
|
||||
|
||||
Expected CSV format:
|
||||
Start,End,Duration (hr),Value,Source
|
||||
2026-03-14 22:44:23,2026-03-14 23:00:19,0.266,Kern,Apple Watch
|
||||
|
||||
- Aggregates segments by night (wake date)
|
||||
- Maps German phase names: Kern→light, REM→rem, Tief→deep, Wach→awake
|
||||
- Stores raw segments in JSONB
|
||||
- Does NOT overwrite manual entries (source='manual')
|
||||
"""
|
||||
pid = session['profile_id']
|
||||
|
||||
# Read CSV
|
||||
content = await file.read()
|
||||
csv_text = content.decode('utf-8-sig') # Handle BOM
|
||||
reader = csv.DictReader(io.StringIO(csv_text))
|
||||
|
||||
# Phase mapping (German → English)
|
||||
phase_map = {
|
||||
'Kern': 'light',
|
||||
'REM': 'rem',
|
||||
'Tief': 'deep',
|
||||
'Wach': 'awake',
|
||||
'Schlafend': None # Ignore initial sleep entry
|
||||
}
|
||||
|
||||
# Parse segments
|
||||
segments = []
|
||||
for row in reader:
|
||||
phase_de = row['Value'].strip()
|
||||
phase_en = phase_map.get(phase_de)
|
||||
|
||||
if phase_en is None: # Skip "Schlafend"
|
||||
continue
|
||||
|
||||
start_dt = datetime.strptime(row['Start'], '%Y-%m-%d %H:%M:%S')
|
||||
end_dt = datetime.strptime(row['End'], '%Y-%m-%d %H:%M:%S')
|
||||
duration_hr = float(row['Duration (hr)'])
|
||||
duration_min = int(duration_hr * 60)
|
||||
|
||||
segments.append({
|
||||
'start': start_dt,
|
||||
'end': end_dt,
|
||||
'duration_min': duration_min,
|
||||
'phase': phase_en
|
||||
})
|
||||
|
||||
# Sort segments chronologically
|
||||
segments.sort(key=lambda s: s['start'])
|
||||
|
||||
# Group segments into nights (gap-based)
|
||||
# If gap between segments > 2 hours → new night
|
||||
nights = []
|
||||
current_night = None
|
||||
|
||||
for seg in segments:
|
||||
# Start new night if:
|
||||
# 1. First segment
|
||||
# 2. Gap > 2 hours since last segment
|
||||
if current_night is None or (seg['start'] - current_night['wake_time']).total_seconds() > 7200:
|
||||
current_night = {
|
||||
'bedtime': seg['start'],
|
||||
'wake_time': seg['end'],
|
||||
'segments': [],
|
||||
'deep_minutes': 0,
|
||||
'rem_minutes': 0,
|
||||
'light_minutes': 0,
|
||||
'awake_minutes': 0
|
||||
}
|
||||
nights.append(current_night)
|
||||
|
||||
# Add segment to current night
|
||||
current_night['segments'].append(seg)
|
||||
current_night['wake_time'] = max(current_night['wake_time'], seg['end'])
|
||||
current_night['bedtime'] = min(current_night['bedtime'], seg['start'])
|
||||
|
||||
# Sum phases
|
||||
if seg['phase'] == 'deep':
|
||||
current_night['deep_minutes'] += seg['duration_min']
|
||||
elif seg['phase'] == 'rem':
|
||||
current_night['rem_minutes'] += seg['duration_min']
|
||||
elif seg['phase'] == 'light':
|
||||
current_night['light_minutes'] += seg['duration_min']
|
||||
elif seg['phase'] == 'awake':
|
||||
current_night['awake_minutes'] += seg['duration_min']
|
||||
|
||||
# Convert nights list to dict with wake_date as key
|
||||
nights_dict = {}
|
||||
for night in nights:
|
||||
wake_date = night['wake_time'].date() # Date when you woke up
|
||||
nights_dict[wake_date] = night
|
||||
|
||||
# Insert nights
|
||||
imported = 0
|
||||
skipped = 0
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
for date, night in nights_dict.items():
|
||||
# Calculate sleep duration (deep + rem + light, WITHOUT awake)
|
||||
# Note: awake_minutes tracked separately, not part of sleep duration
|
||||
duration_minutes = (
|
||||
night['deep_minutes'] +
|
||||
night['rem_minutes'] +
|
||||
night['light_minutes']
|
||||
)
|
||||
|
||||
# Calculate wake_count (number of awake segments)
|
||||
wake_count = sum(1 for seg in night['segments'] if seg['phase'] == 'awake')
|
||||
|
||||
# Prepare JSONB segments with full datetime
|
||||
sleep_segments = [
|
||||
{
|
||||
'phase': seg['phase'],
|
||||
'start': seg['start'].isoformat(), # Full datetime: 2026-03-21T22:30:00
|
||||
'end': seg['end'].isoformat(), # Full datetime: 2026-03-21T23:15:00
|
||||
'duration_min': seg['duration_min']
|
||||
}
|
||||
for seg in night['segments']
|
||||
]
|
||||
|
||||
# Check if manual entry exists - do NOT overwrite
|
||||
cur.execute("""
|
||||
SELECT id, source FROM sleep_log
|
||||
WHERE profile_id = %s AND date = %s
|
||||
""", (pid, date))
|
||||
existing = cur.fetchone()
|
||||
|
||||
if existing and existing['source'] == 'manual':
|
||||
skipped += 1
|
||||
continue # Skip - don't overwrite manual entries
|
||||
|
||||
# Upsert (only if not manual)
|
||||
# If entry exists and is NOT manual → update
|
||||
# If entry doesn't exist → insert
|
||||
if existing:
|
||||
# Update existing non-manual entry
|
||||
cur.execute("""
|
||||
UPDATE sleep_log SET
|
||||
bedtime = %s,
|
||||
wake_time = %s,
|
||||
duration_minutes = %s,
|
||||
wake_count = %s,
|
||||
deep_minutes = %s,
|
||||
rem_minutes = %s,
|
||||
light_minutes = %s,
|
||||
awake_minutes = %s,
|
||||
sleep_segments = %s,
|
||||
source = 'apple_health',
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = %s AND profile_id = %s
|
||||
""", (
|
||||
night['bedtime'].time(),
|
||||
night['wake_time'].time(),
|
||||
duration_minutes,
|
||||
wake_count,
|
||||
night['deep_minutes'],
|
||||
night['rem_minutes'],
|
||||
night['light_minutes'],
|
||||
night['awake_minutes'],
|
||||
json.dumps(sleep_segments),
|
||||
existing['id'],
|
||||
pid
|
||||
))
|
||||
else:
|
||||
# Insert new entry
|
||||
cur.execute("""
|
||||
INSERT INTO sleep_log (
|
||||
profile_id, date, bedtime, wake_time, duration_minutes,
|
||||
wake_count, deep_minutes, rem_minutes, light_minutes, awake_minutes,
|
||||
sleep_segments, source, created_at, updated_at
|
||||
) VALUES (
|
||||
%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'apple_health', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||
)
|
||||
""", (
|
||||
pid,
|
||||
date,
|
||||
night['bedtime'].time(),
|
||||
night['wake_time'].time(),
|
||||
duration_minutes,
|
||||
wake_count,
|
||||
night['deep_minutes'],
|
||||
night['rem_minutes'],
|
||||
night['light_minutes'],
|
||||
night['awake_minutes'],
|
||||
json.dumps(sleep_segments)
|
||||
))
|
||||
|
||||
imported += 1
|
||||
|
||||
conn.commit()
|
||||
|
||||
return {
|
||||
"imported": imported,
|
||||
"skipped": skipped,
|
||||
"total_nights": len(nights_dict),
|
||||
"message": f"{imported} Nächte importiert, {skipped} übersprungen (manuelle Einträge)"
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
"""
|
||||
User Subscription Endpoints for Mitai Jinkendo
|
||||
|
||||
User-facing subscription info (own tier, usage, limits).
|
||||
"""
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth, get_effective_tier, check_feature_access
|
||||
|
||||
router = APIRouter(prefix="/api/subscription", tags=["subscription"])
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
def get_my_subscription(session: dict = Depends(require_auth)):
|
||||
"""
|
||||
Get current user's subscription info.
|
||||
|
||||
Returns:
|
||||
- tier: Current effective tier (considers access_grants)
|
||||
- profile_tier: Base tier from profile
|
||||
- trial_ends_at: Trial expiration (if applicable)
|
||||
- email_verified: Email verification status
|
||||
- active_grants: List of active access grants (coupons, trials)
|
||||
"""
|
||||
profile_id = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get profile info
|
||||
cur.execute("""
|
||||
SELECT tier, trial_ends_at, email_verified
|
||||
FROM profiles
|
||||
WHERE id = %s
|
||||
""", (profile_id,))
|
||||
profile = cur.fetchone()
|
||||
|
||||
if not profile:
|
||||
return {"error": "Profile not found"}
|
||||
|
||||
# Get effective tier (considers access_grants)
|
||||
effective_tier = get_effective_tier(profile_id)
|
||||
|
||||
# Get active access grants
|
||||
cur.execute("""
|
||||
SELECT
|
||||
ag.id,
|
||||
ag.tier_id,
|
||||
ag.granted_by,
|
||||
ag.valid_from,
|
||||
ag.valid_until,
|
||||
ag.is_active,
|
||||
ag.paused_by,
|
||||
ag.remaining_days,
|
||||
t.name as tier_name
|
||||
FROM access_grants ag
|
||||
JOIN tiers t ON t.id = ag.tier_id
|
||||
WHERE ag.profile_id = %s
|
||||
AND ag.valid_until > CURRENT_TIMESTAMP
|
||||
ORDER BY ag.valid_until DESC
|
||||
""", (profile_id,))
|
||||
grants = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
# Get tier info
|
||||
cur.execute("""
|
||||
SELECT id, name, description, price_monthly_cents, price_yearly_cents
|
||||
FROM tiers
|
||||
WHERE id = %s
|
||||
""", (effective_tier,))
|
||||
tier_info = r2d(cur.fetchone())
|
||||
|
||||
return {
|
||||
"tier": effective_tier,
|
||||
"tier_info": tier_info,
|
||||
"profile_tier": profile['tier'],
|
||||
"trial_ends_at": profile['trial_ends_at'].isoformat() if profile['trial_ends_at'] else None,
|
||||
"email_verified": profile['email_verified'],
|
||||
"active_grants": grants
|
||||
}
|
||||
|
||||
|
||||
@router.get("/usage")
|
||||
def get_my_usage(session: dict = Depends(require_auth)):
|
||||
"""
|
||||
Get current user's feature usage.
|
||||
|
||||
Returns list of features with current usage and limits.
|
||||
"""
|
||||
profile_id = session['profile_id']
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get all active features
|
||||
cur.execute("""
|
||||
SELECT id, name, category, limit_type, reset_period
|
||||
FROM features
|
||||
WHERE active = true
|
||||
ORDER BY category, name
|
||||
""")
|
||||
features = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
# Get usage for each feature
|
||||
usage_list = []
|
||||
for feature in features:
|
||||
access = check_feature_access(profile_id, feature['id'])
|
||||
usage_list.append({
|
||||
"feature_id": feature['id'],
|
||||
"feature_name": feature['name'],
|
||||
"category": feature['category'],
|
||||
"limit_type": feature['limit_type'],
|
||||
"reset_period": feature['reset_period'],
|
||||
"allowed": access['allowed'],
|
||||
"limit": access['limit'],
|
||||
"used": access['used'],
|
||||
"remaining": access['remaining'],
|
||||
"reason": access['reason']
|
||||
})
|
||||
|
||||
return {
|
||||
"tier": get_effective_tier(profile_id),
|
||||
"features": usage_list
|
||||
}
|
||||
|
||||
|
||||
@router.get("/limits")
|
||||
def get_my_limits(session: dict = Depends(require_auth)):
|
||||
"""
|
||||
Get all feature limits for current tier.
|
||||
|
||||
Simplified view - just shows what's allowed/not allowed.
|
||||
"""
|
||||
profile_id = session['profile_id']
|
||||
tier_id = get_effective_tier(profile_id)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get all features with their limits for this tier
|
||||
cur.execute("""
|
||||
SELECT
|
||||
f.id,
|
||||
f.name,
|
||||
f.category,
|
||||
f.limit_type,
|
||||
COALESCE(tl.limit_value, f.default_limit) as limit_value
|
||||
FROM features f
|
||||
LEFT JOIN tier_limits tl ON tl.feature_id = f.id AND tl.tier_id = %s
|
||||
WHERE f.active = true
|
||||
ORDER BY f.category, f.name
|
||||
""", (tier_id,))
|
||||
|
||||
features = []
|
||||
for row in cur.fetchall():
|
||||
rd = r2d(row)
|
||||
limit = rd['limit_value']
|
||||
|
||||
# Interpret limit
|
||||
if limit is None:
|
||||
status = "unlimited"
|
||||
elif limit == 0:
|
||||
status = "disabled"
|
||||
elif rd['limit_type'] == 'boolean':
|
||||
status = "enabled" if limit == 1 else "disabled"
|
||||
else:
|
||||
status = f"limit: {limit}"
|
||||
|
||||
features.append({
|
||||
"feature_id": rd['id'],
|
||||
"feature_name": rd['name'],
|
||||
"category": rd['category'],
|
||||
"limit": limit,
|
||||
"status": status
|
||||
})
|
||||
|
||||
# Get tier info
|
||||
cur.execute("SELECT name, description FROM tiers WHERE id = %s", (tier_id,))
|
||||
tier = cur.fetchone()
|
||||
|
||||
return {
|
||||
"tier_id": tier_id,
|
||||
"tier_name": tier['name'] if tier else tier_id,
|
||||
"tier_description": tier['description'] if tier else '',
|
||||
"features": features
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
"""
|
||||
Tier Limits Management Endpoints for Mitai Jinkendo
|
||||
|
||||
Admin-only matrix editor for Tier x Feature limits.
|
||||
"""
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_admin
|
||||
|
||||
router = APIRouter(prefix="/api/tier-limits", tags=["tier-limits"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def get_tier_limits_matrix(session: dict = Depends(require_admin)):
|
||||
"""
|
||||
Admin: Get complete Tier x Feature matrix.
|
||||
|
||||
Returns:
|
||||
{
|
||||
"tiers": [{id, name}, ...],
|
||||
"features": [{id, name, category}, ...],
|
||||
"limits": {
|
||||
"tier_id:feature_id": limit_value,
|
||||
...
|
||||
}
|
||||
}
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get all tiers (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}
|
||||
@@ -0,0 +1,117 @@
|
||||
"""
|
||||
Tier Management Endpoints for Mitai Jinkendo
|
||||
|
||||
Admin-only CRUD for subscription tiers.
|
||||
"""
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_admin
|
||||
|
||||
router = APIRouter(prefix="/api/tiers", tags=["tiers"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_tiers(session: dict = Depends(require_admin)):
|
||||
"""Admin: List all tiers."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT * FROM tiers
|
||||
ORDER BY sort_order
|
||||
""")
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_tier(data: dict, session: dict = Depends(require_admin)):
|
||||
"""
|
||||
Admin: Create new tier.
|
||||
|
||||
Required fields:
|
||||
- id: Tier ID (e.g., 'enterprise')
|
||||
- name: Display name
|
||||
- price_monthly_cents, price_yearly_cents: Prices (NULL for free tiers)
|
||||
"""
|
||||
tier_id = data.get('id', '').strip()
|
||||
name = data.get('name', '').strip()
|
||||
description = data.get('description', '')
|
||||
price_monthly_cents = data.get('price_monthly_cents')
|
||||
price_yearly_cents = data.get('price_yearly_cents')
|
||||
sort_order = data.get('sort_order', 99)
|
||||
|
||||
if not tier_id or not name:
|
||||
raise HTTPException(400, "ID und Name fehlen")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check if ID already exists
|
||||
cur.execute("SELECT id FROM tiers WHERE id = %s", (tier_id,))
|
||||
if cur.fetchone():
|
||||
raise HTTPException(400, f"Tier '{tier_id}' existiert bereits")
|
||||
|
||||
# Create tier
|
||||
cur.execute("""
|
||||
INSERT INTO tiers (
|
||||
id, name, description, price_monthly_cents, price_yearly_cents, sort_order
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
""", (tier_id, name, description, price_monthly_cents, price_yearly_cents, sort_order))
|
||||
|
||||
conn.commit()
|
||||
|
||||
return {"ok": True, "id": tier_id}
|
||||
|
||||
|
||||
@router.put("/{tier_id}")
|
||||
def update_tier(tier_id: str, data: dict, session: dict = Depends(require_admin)):
|
||||
"""Admin: Update tier."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
updates = []
|
||||
values = []
|
||||
|
||||
if 'name' in data:
|
||||
updates.append('name = %s')
|
||||
values.append(data['name'])
|
||||
if 'description' in data:
|
||||
updates.append('description = %s')
|
||||
values.append(data['description'])
|
||||
if 'price_monthly_cents' in data:
|
||||
updates.append('price_monthly_cents = %s')
|
||||
values.append(data['price_monthly_cents'])
|
||||
if 'price_yearly_cents' in data:
|
||||
updates.append('price_yearly_cents = %s')
|
||||
values.append(data['price_yearly_cents'])
|
||||
if 'active' in data:
|
||||
updates.append('active = %s')
|
||||
values.append(data['active'])
|
||||
if 'sort_order' in data:
|
||||
updates.append('sort_order = %s')
|
||||
values.append(data['sort_order'])
|
||||
|
||||
if not updates:
|
||||
return {"ok": True}
|
||||
|
||||
updates.append('updated = CURRENT_TIMESTAMP')
|
||||
values.append(tier_id)
|
||||
|
||||
cur.execute(
|
||||
f"UPDATE tiers SET {', '.join(updates)} WHERE id = %s",
|
||||
values
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.delete("/{tier_id}")
|
||||
def delete_tier(tier_id: str, session: dict = Depends(require_admin)):
|
||||
"""Admin: Delete tier (soft-delete: set active=false)."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("UPDATE tiers SET active = false WHERE id = %s", (tier_id,))
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
Training Types API - v9d
|
||||
|
||||
Provides hierarchical list of training categories and subcategories
|
||||
for activity classification.
|
||||
"""
|
||||
from fastapi import APIRouter, Depends
|
||||
from db import get_db, get_cursor
|
||||
from auth import require_auth
|
||||
|
||||
router = APIRouter(prefix="/api/training-types", tags=["training-types"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_training_types(session: dict = Depends(require_auth)):
|
||||
"""
|
||||
Get all training types, grouped by category.
|
||||
|
||||
Returns hierarchical structure:
|
||||
{
|
||||
"cardio": [
|
||||
{"id": 1, "subcategory": "running", "name_de": "Laufen", ...},
|
||||
...
|
||||
],
|
||||
"strength": [...],
|
||||
...
|
||||
}
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT id, category, subcategory, name_de, name_en, icon, sort_order
|
||||
FROM training_types
|
||||
ORDER BY sort_order, category, subcategory
|
||||
""")
|
||||
rows = cur.fetchall()
|
||||
|
||||
# Group by category
|
||||
grouped = {}
|
||||
for row in rows:
|
||||
cat = row['category']
|
||||
if cat not in grouped:
|
||||
grouped[cat] = []
|
||||
grouped[cat].append({
|
||||
'id': row['id'],
|
||||
'category': row['category'],
|
||||
'subcategory': row['subcategory'],
|
||||
'name_de': row['name_de'],
|
||||
'name_en': row['name_en'],
|
||||
'icon': row['icon'],
|
||||
'sort_order': row['sort_order']
|
||||
})
|
||||
|
||||
return grouped
|
||||
|
||||
|
||||
@router.get("/flat")
|
||||
def list_training_types_flat(session: dict = Depends(require_auth)):
|
||||
"""
|
||||
Get all training types as flat list (for simple dropdown).
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT id, category, subcategory, name_de, name_en, icon
|
||||
FROM training_types
|
||||
ORDER BY sort_order
|
||||
""")
|
||||
rows = cur.fetchall()
|
||||
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
|
||||
@router.get("/categories")
|
||||
def list_categories(session: dict = Depends(require_auth)):
|
||||
"""
|
||||
Get list of unique categories with metadata.
|
||||
"""
|
||||
categories = {
|
||||
'cardio': {
|
||||
'name_de': 'Cardio (Ausdauer)',
|
||||
'name_en': 'Cardio (Endurance)',
|
||||
'icon': '❤️',
|
||||
'color': '#EF4444'
|
||||
},
|
||||
'strength': {
|
||||
'name_de': 'Kraft',
|
||||
'name_en': 'Strength',
|
||||
'icon': '💪',
|
||||
'color': '#3B82F6'
|
||||
},
|
||||
'hiit': {
|
||||
'name_de': 'Schnellkraft / HIIT',
|
||||
'name_en': 'Power / HIIT',
|
||||
'icon': '🔥',
|
||||
'color': '#F59E0B'
|
||||
},
|
||||
'martial_arts': {
|
||||
'name_de': 'Kampfsport',
|
||||
'name_en': 'Martial Arts',
|
||||
'icon': '🥋',
|
||||
'color': '#8B5CF6'
|
||||
},
|
||||
'mobility': {
|
||||
'name_de': 'Mobility & Dehnung',
|
||||
'name_en': 'Mobility & Stretching',
|
||||
'icon': '🧘',
|
||||
'color': '#10B981'
|
||||
},
|
||||
'recovery': {
|
||||
'name_de': 'Erholung (aktiv)',
|
||||
'name_en': 'Recovery (active)',
|
||||
'icon': '💆',
|
||||
'color': '#6B7280'
|
||||
},
|
||||
'mind': {
|
||||
'name_de': 'Geist & Meditation',
|
||||
'name_en': 'Mind & Meditation',
|
||||
'icon': '🧘♂️',
|
||||
'color': '#A78BFA'
|
||||
},
|
||||
'other': {
|
||||
'name_de': 'Sonstiges',
|
||||
'name_en': 'Other',
|
||||
'icon': '📝',
|
||||
'color': '#9CA3AF'
|
||||
}
|
||||
}
|
||||
return categories
|
||||
@@ -0,0 +1,140 @@
|
||||
"""
|
||||
User Restrictions Management Endpoints for Mitai Jinkendo
|
||||
|
||||
Admin-only user-specific feature overrides.
|
||||
"""
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_admin
|
||||
|
||||
router = APIRouter(prefix="/api/user-restrictions", tags=["user-restrictions"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_user_restrictions(profile_id: str = None, session: dict = Depends(require_admin)):
|
||||
"""
|
||||
Admin: List user restrictions.
|
||||
|
||||
Optional query param: ?profile_id=... (filter by user)
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
if profile_id:
|
||||
cur.execute("""
|
||||
SELECT
|
||||
ur.*,
|
||||
f.name as feature_name,
|
||||
f.category as feature_category,
|
||||
p.name as profile_name
|
||||
FROM user_feature_restrictions ur
|
||||
JOIN features f ON f.id = ur.feature_id
|
||||
JOIN profiles p ON p.id = ur.profile_id
|
||||
WHERE ur.profile_id = %s
|
||||
ORDER BY f.category, f.name
|
||||
""", (profile_id,))
|
||||
else:
|
||||
cur.execute("""
|
||||
SELECT
|
||||
ur.*,
|
||||
f.name as feature_name,
|
||||
f.category as feature_category,
|
||||
p.name as profile_name,
|
||||
p.email as profile_email
|
||||
FROM user_feature_restrictions ur
|
||||
JOIN features f ON f.id = ur.feature_id
|
||||
JOIN profiles p ON p.id = ur.profile_id
|
||||
ORDER BY p.name, f.category, f.name
|
||||
""")
|
||||
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_user_restriction(data: dict, session: dict = Depends(require_admin)):
|
||||
"""
|
||||
Admin: Create user-specific feature restriction.
|
||||
|
||||
Body:
|
||||
{
|
||||
"profile_id": "uuid",
|
||||
"feature_id": "weight_entries",
|
||||
"limit_value": 10, // NULL = unlimited, 0 = disabled
|
||||
"reason": "Spam prevention"
|
||||
}
|
||||
"""
|
||||
profile_id = data.get('profile_id')
|
||||
feature_id = data.get('feature_id')
|
||||
limit_value = data.get('limit_value')
|
||||
reason = data.get('reason', '')
|
||||
|
||||
if not profile_id or not feature_id:
|
||||
raise HTTPException(400, "profile_id und feature_id fehlen")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check if restriction already exists
|
||||
cur.execute("""
|
||||
SELECT id FROM user_feature_restrictions
|
||||
WHERE profile_id = %s AND feature_id = %s
|
||||
""", (profile_id, feature_id))
|
||||
|
||||
if cur.fetchone():
|
||||
raise HTTPException(400, "Einschränkung existiert bereits (nutze PUT zum Aktualisieren)")
|
||||
|
||||
# Create restriction
|
||||
cur.execute("""
|
||||
INSERT INTO user_feature_restrictions (
|
||||
profile_id, feature_id, limit_value, reason, created_by
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""", (profile_id, feature_id, limit_value, reason, session['profile_id']))
|
||||
|
||||
restriction_id = cur.fetchone()['id']
|
||||
conn.commit()
|
||||
|
||||
return {"ok": True, "id": restriction_id}
|
||||
|
||||
|
||||
@router.put("/{restriction_id}")
|
||||
def update_user_restriction(restriction_id: str, data: dict, session: dict = Depends(require_admin)):
|
||||
"""Admin: Update user restriction."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
updates = []
|
||||
values = []
|
||||
|
||||
if 'limit_value' in data:
|
||||
updates.append('limit_value = %s')
|
||||
values.append(data['limit_value'])
|
||||
if 'reason' in data:
|
||||
updates.append('reason = %s')
|
||||
values.append(data['reason'])
|
||||
|
||||
if not updates:
|
||||
return {"ok": True}
|
||||
|
||||
updates.append('updated = CURRENT_TIMESTAMP')
|
||||
values.append(restriction_id)
|
||||
|
||||
cur.execute(
|
||||
f"UPDATE user_feature_restrictions SET {', '.join(updates)} WHERE id = %s",
|
||||
values
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.delete("/{restriction_id}")
|
||||
def delete_user_restriction(restriction_id: str, session: dict = Depends(require_admin)):
|
||||
"""Admin: Delete user restriction (reverts to tier limit)."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("DELETE FROM user_feature_restrictions WHERE id = %s", (restriction_id,))
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
@@ -0,0 +1,681 @@
|
||||
"""
|
||||
Vitals Router - Resting HR + HRV Tracking
|
||||
v9d Phase 2: Vitals Module
|
||||
|
||||
Endpoints:
|
||||
- GET /api/vitals List vitals (with limit)
|
||||
- GET /api/vitals/by-date/{date} Get vitals for specific date
|
||||
- POST /api/vitals Create/update vitals (upsert)
|
||||
- PUT /api/vitals/{id} Update vitals
|
||||
- DELETE /api/vitals/{id} Delete vitals
|
||||
- GET /api/vitals/stats Get vitals statistics
|
||||
- POST /api/vitals/import/omron Import Omron CSV
|
||||
- POST /api/vitals/import/apple-health Import Apple Health CSV
|
||||
"""
|
||||
from fastapi import APIRouter, HTTPException, Depends, Header, UploadFile, File
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
from datetime import datetime, timedelta
|
||||
import logging
|
||||
import csv
|
||||
import io
|
||||
from dateutil import parser as date_parser
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth
|
||||
|
||||
router = APIRouter(prefix="/api/vitals", tags=["vitals"])
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# German month mapping for Omron dates
|
||||
GERMAN_MONTHS = {
|
||||
'Januar': '01', 'Jan.': '01',
|
||||
'Februar': '02', 'Feb.': '02',
|
||||
'März': '03',
|
||||
'April': '04', 'Apr.': '04',
|
||||
'Mai': '05',
|
||||
'Juni': '06',
|
||||
'Juli': '07',
|
||||
'August': '08', 'Aug.': '08',
|
||||
'September': '09', 'Sep.': '09',
|
||||
'Oktober': '10', 'Okt.': '10',
|
||||
'November': '11', 'Nov.': '11',
|
||||
'Dezember': '12', 'Dez.': '12'
|
||||
}
|
||||
|
||||
|
||||
class VitalsEntry(BaseModel):
|
||||
date: str
|
||||
resting_hr: Optional[int] = None
|
||||
hrv: Optional[int] = None
|
||||
blood_pressure_systolic: Optional[int] = None
|
||||
blood_pressure_diastolic: Optional[int] = None
|
||||
pulse: Optional[int] = None
|
||||
vo2_max: Optional[float] = None
|
||||
spo2: Optional[int] = None
|
||||
respiratory_rate: Optional[float] = None
|
||||
irregular_heartbeat: Optional[bool] = None
|
||||
possible_afib: Optional[bool] = None
|
||||
note: Optional[str] = None
|
||||
|
||||
|
||||
class VitalsUpdate(BaseModel):
|
||||
date: Optional[str] = None
|
||||
resting_hr: Optional[int] = None
|
||||
hrv: Optional[int] = None
|
||||
blood_pressure_systolic: Optional[int] = None
|
||||
blood_pressure_diastolic: Optional[int] = None
|
||||
pulse: Optional[int] = None
|
||||
vo2_max: Optional[float] = None
|
||||
spo2: Optional[int] = None
|
||||
respiratory_rate: Optional[float] = None
|
||||
irregular_heartbeat: Optional[bool] = None
|
||||
possible_afib: Optional[bool] = None
|
||||
note: Optional[str] = None
|
||||
|
||||
|
||||
def get_pid(x_profile_id: Optional[str], session: dict) -> str:
|
||||
"""Extract profile_id from session (never from header for security)."""
|
||||
return session['profile_id']
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_vitals(
|
||||
limit: int = 90,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Get vitals entries for current profile."""
|
||||
pid = get_pid(x_profile_id, session)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, profile_id, date, resting_hr, hrv,
|
||||
blood_pressure_systolic, blood_pressure_diastolic, pulse,
|
||||
vo2_max, spo2, respiratory_rate,
|
||||
irregular_heartbeat, possible_afib,
|
||||
note, source, created_at, updated_at
|
||||
FROM vitals_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_vitals_by_date(
|
||||
date: str,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Get vitals entry for a specific date."""
|
||||
pid = get_pid(x_profile_id, session)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, profile_id, date, resting_hr, hrv,
|
||||
blood_pressure_systolic, blood_pressure_diastolic, pulse,
|
||||
vo2_max, spo2, respiratory_rate,
|
||||
irregular_heartbeat, possible_afib,
|
||||
note, source, created_at, updated_at
|
||||
FROM vitals_log
|
||||
WHERE profile_id = %s AND date = %s
|
||||
""",
|
||||
(pid, date)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Keine Vitalwerte für dieses Datum gefunden")
|
||||
return r2d(row)
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_vitals(
|
||||
entry: VitalsEntry,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Create or update vitals entry (upsert)."""
|
||||
pid = get_pid(x_profile_id, session)
|
||||
|
||||
# Validation: at least one vital must be provided
|
||||
has_data = any([
|
||||
entry.resting_hr, entry.hrv, entry.blood_pressure_systolic,
|
||||
entry.blood_pressure_diastolic, entry.vo2_max, entry.spo2,
|
||||
entry.respiratory_rate
|
||||
])
|
||||
if not has_data:
|
||||
raise HTTPException(400, "Mindestens ein Vitalwert muss angegeben werden")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Upsert: insert or update if date already exists
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO vitals_log (
|
||||
profile_id, date, resting_hr, hrv,
|
||||
blood_pressure_systolic, blood_pressure_diastolic, pulse,
|
||||
vo2_max, spo2, respiratory_rate,
|
||||
irregular_heartbeat, possible_afib,
|
||||
note, source
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'manual')
|
||||
ON CONFLICT (profile_id, date)
|
||||
DO UPDATE SET
|
||||
resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_log.resting_hr),
|
||||
hrv = COALESCE(EXCLUDED.hrv, vitals_log.hrv),
|
||||
blood_pressure_systolic = COALESCE(EXCLUDED.blood_pressure_systolic, vitals_log.blood_pressure_systolic),
|
||||
blood_pressure_diastolic = COALESCE(EXCLUDED.blood_pressure_diastolic, vitals_log.blood_pressure_diastolic),
|
||||
pulse = COALESCE(EXCLUDED.pulse, vitals_log.pulse),
|
||||
vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_log.vo2_max),
|
||||
spo2 = COALESCE(EXCLUDED.spo2, vitals_log.spo2),
|
||||
respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_log.respiratory_rate),
|
||||
irregular_heartbeat = COALESCE(EXCLUDED.irregular_heartbeat, vitals_log.irregular_heartbeat),
|
||||
possible_afib = COALESCE(EXCLUDED.possible_afib, vitals_log.possible_afib),
|
||||
note = COALESCE(EXCLUDED.note, vitals_log.note),
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
RETURNING id, profile_id, date, resting_hr, hrv,
|
||||
blood_pressure_systolic, blood_pressure_diastolic, pulse,
|
||||
vo2_max, spo2, respiratory_rate,
|
||||
irregular_heartbeat, possible_afib,
|
||||
note, source, created_at, updated_at
|
||||
""",
|
||||
(pid, entry.date, entry.resting_hr, entry.hrv,
|
||||
entry.blood_pressure_systolic, entry.blood_pressure_diastolic, entry.pulse,
|
||||
entry.vo2_max, entry.spo2, entry.respiratory_rate,
|
||||
entry.irregular_heartbeat, entry.possible_afib,
|
||||
entry.note)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
|
||||
logger.info(f"[VITALS] Upserted vitals for {pid} on {entry.date}")
|
||||
return r2d(row)
|
||||
|
||||
|
||||
@router.put("/{vitals_id}")
|
||||
def update_vitals(
|
||||
vitals_id: int,
|
||||
updates: VitalsUpdate,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Update existing vitals entry."""
|
||||
pid = get_pid(x_profile_id, session)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check ownership
|
||||
cur.execute(
|
||||
"SELECT id FROM vitals_log WHERE id = %s AND profile_id = %s",
|
||||
(vitals_id, pid)
|
||||
)
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Eintrag nicht gefunden")
|
||||
|
||||
# Build update query dynamically
|
||||
fields = []
|
||||
values = []
|
||||
|
||||
if updates.date is not None:
|
||||
fields.append("date = %s")
|
||||
values.append(updates.date)
|
||||
if updates.resting_hr is not None:
|
||||
fields.append("resting_hr = %s")
|
||||
values.append(updates.resting_hr)
|
||||
if updates.hrv is not None:
|
||||
fields.append("hrv = %s")
|
||||
values.append(updates.hrv)
|
||||
if updates.blood_pressure_systolic is not None:
|
||||
fields.append("blood_pressure_systolic = %s")
|
||||
values.append(updates.blood_pressure_systolic)
|
||||
if updates.blood_pressure_diastolic is not None:
|
||||
fields.append("blood_pressure_diastolic = %s")
|
||||
values.append(updates.blood_pressure_diastolic)
|
||||
if updates.pulse is not None:
|
||||
fields.append("pulse = %s")
|
||||
values.append(updates.pulse)
|
||||
if updates.vo2_max is not None:
|
||||
fields.append("vo2_max = %s")
|
||||
values.append(updates.vo2_max)
|
||||
if updates.spo2 is not None:
|
||||
fields.append("spo2 = %s")
|
||||
values.append(updates.spo2)
|
||||
if updates.respiratory_rate is not None:
|
||||
fields.append("respiratory_rate = %s")
|
||||
values.append(updates.respiratory_rate)
|
||||
if updates.irregular_heartbeat is not None:
|
||||
fields.append("irregular_heartbeat = %s")
|
||||
values.append(updates.irregular_heartbeat)
|
||||
if updates.possible_afib is not None:
|
||||
fields.append("possible_afib = %s")
|
||||
values.append(updates.possible_afib)
|
||||
if updates.note is not None:
|
||||
fields.append("note = %s")
|
||||
values.append(updates.note)
|
||||
|
||||
if not fields:
|
||||
raise HTTPException(400, "Keine Änderungen angegeben")
|
||||
|
||||
fields.append("updated_at = CURRENT_TIMESTAMP")
|
||||
values.append(vitals_id)
|
||||
|
||||
query = f"""
|
||||
UPDATE vitals_log
|
||||
SET {', '.join(fields)}
|
||||
WHERE id = %s
|
||||
RETURNING id, profile_id, date, resting_hr, hrv,
|
||||
blood_pressure_systolic, blood_pressure_diastolic, pulse,
|
||||
vo2_max, spo2, respiratory_rate,
|
||||
irregular_heartbeat, possible_afib,
|
||||
note, source, created_at, updated_at
|
||||
"""
|
||||
|
||||
cur.execute(query, values)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
|
||||
return r2d(row)
|
||||
|
||||
|
||||
@router.delete("/{vitals_id}")
|
||||
def delete_vitals(
|
||||
vitals_id: int,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Delete vitals entry."""
|
||||
pid = get_pid(x_profile_id, session)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check ownership and delete
|
||||
cur.execute(
|
||||
"DELETE FROM vitals_log WHERE id = %s AND profile_id = %s RETURNING id",
|
||||
(vitals_id, pid)
|
||||
)
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Eintrag nicht gefunden")
|
||||
|
||||
conn.commit()
|
||||
logger.info(f"[VITALS] Deleted vitals {vitals_id} for {pid}")
|
||||
return {"message": "Eintrag gelöscht"}
|
||||
|
||||
|
||||
@router.get("/stats")
|
||||
def get_vitals_stats(
|
||||
days: int = 30,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Get vitals statistics over the last N days.
|
||||
|
||||
Returns:
|
||||
- avg_resting_hr (7d and 30d)
|
||||
- avg_hrv (7d and 30d)
|
||||
- trend (increasing/decreasing/stable)
|
||||
- latest values
|
||||
"""
|
||||
pid = get_pid(x_profile_id, session)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get latest entry
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT date, resting_hr, hrv
|
||||
FROM vitals_log
|
||||
WHERE profile_id = %s AND date >= CURRENT_DATE - INTERVAL '%s days'
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
(pid, days)
|
||||
)
|
||||
latest = cur.fetchone()
|
||||
|
||||
# Get averages (7d and 30d)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '7 days' THEN resting_hr END) as avg_hr_7d,
|
||||
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '30 days' THEN resting_hr END) as avg_hr_30d,
|
||||
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '7 days' THEN hrv END) as avg_hrv_7d,
|
||||
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '30 days' THEN hrv END) as avg_hrv_30d,
|
||||
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '7 days' THEN blood_pressure_systolic END) as avg_bp_sys_7d,
|
||||
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '30 days' THEN blood_pressure_systolic END) as avg_bp_sys_30d,
|
||||
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '7 days' THEN blood_pressure_diastolic END) as avg_bp_dia_7d,
|
||||
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '30 days' THEN blood_pressure_diastolic END) as avg_bp_dia_30d,
|
||||
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '7 days' THEN spo2 END) as avg_spo2_7d,
|
||||
AVG(CASE WHEN date >= CURRENT_DATE - INTERVAL '30 days' THEN spo2 END) as avg_spo2_30d,
|
||||
COUNT(*) as total_entries
|
||||
FROM vitals_log
|
||||
WHERE profile_id = %s AND date >= CURRENT_DATE - INTERVAL '%s days'
|
||||
""",
|
||||
(pid, max(days, 30))
|
||||
)
|
||||
stats_row = cur.fetchone()
|
||||
|
||||
# Get latest VO2 Max
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT vo2_max
|
||||
FROM vitals_log
|
||||
WHERE profile_id = %s AND vo2_max IS NOT NULL
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
(pid,)
|
||||
)
|
||||
vo2_row = cur.fetchone()
|
||||
latest_vo2 = vo2_row['vo2_max'] if vo2_row else None
|
||||
|
||||
# Get entries for trend calculation (last 14 days)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT date, resting_hr, hrv
|
||||
FROM vitals_log
|
||||
WHERE profile_id = %s AND date >= CURRENT_DATE - INTERVAL '14 days'
|
||||
ORDER BY date ASC
|
||||
""",
|
||||
(pid,)
|
||||
)
|
||||
entries = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
# Simple trend calculation (compare first half vs second half)
|
||||
trend_hr = "stable"
|
||||
trend_hrv = "stable"
|
||||
|
||||
if len(entries) >= 4:
|
||||
mid = len(entries) // 2
|
||||
first_half_hr = [e['resting_hr'] for e in entries[:mid] if e['resting_hr']]
|
||||
second_half_hr = [e['resting_hr'] for e in entries[mid:] if e['resting_hr']]
|
||||
|
||||
if first_half_hr and second_half_hr:
|
||||
avg_first = sum(first_half_hr) / len(first_half_hr)
|
||||
avg_second = sum(second_half_hr) / len(second_half_hr)
|
||||
diff = avg_second - avg_first
|
||||
|
||||
if diff > 2:
|
||||
trend_hr = "increasing"
|
||||
elif diff < -2:
|
||||
trend_hr = "decreasing"
|
||||
|
||||
first_half_hrv = [e['hrv'] for e in entries[:mid] if e['hrv']]
|
||||
second_half_hrv = [e['hrv'] for e in entries[mid:] if e['hrv']]
|
||||
|
||||
if first_half_hrv and second_half_hrv:
|
||||
avg_first_hrv = sum(first_half_hrv) / len(first_half_hrv)
|
||||
avg_second_hrv = sum(second_half_hrv) / len(second_half_hrv)
|
||||
diff_hrv = avg_second_hrv - avg_first_hrv
|
||||
|
||||
if diff_hrv > 5:
|
||||
trend_hrv = "increasing"
|
||||
elif diff_hrv < -5:
|
||||
trend_hrv = "decreasing"
|
||||
|
||||
return {
|
||||
"latest": r2d(latest) if latest else None,
|
||||
"avg_resting_hr_7d": round(stats_row['avg_hr_7d'], 1) if stats_row['avg_hr_7d'] else None,
|
||||
"avg_resting_hr_30d": round(stats_row['avg_hr_30d'], 1) if stats_row['avg_hr_30d'] else None,
|
||||
"avg_hrv_7d": round(stats_row['avg_hrv_7d'], 1) if stats_row['avg_hrv_7d'] else None,
|
||||
"avg_hrv_30d": round(stats_row['avg_hrv_30d'], 1) if stats_row['avg_hrv_30d'] else None,
|
||||
"avg_bp_systolic_7d": round(stats_row['avg_bp_sys_7d'], 1) if stats_row['avg_bp_sys_7d'] else None,
|
||||
"avg_bp_systolic_30d": round(stats_row['avg_bp_sys_30d'], 1) if stats_row['avg_bp_sys_30d'] else None,
|
||||
"avg_bp_diastolic_7d": round(stats_row['avg_bp_dia_7d'], 1) if stats_row['avg_bp_dia_7d'] else None,
|
||||
"avg_bp_diastolic_30d": round(stats_row['avg_bp_dia_30d'], 1) if stats_row['avg_bp_dia_30d'] else None,
|
||||
"avg_spo2_7d": round(stats_row['avg_spo2_7d'], 1) if stats_row['avg_spo2_7d'] else None,
|
||||
"avg_spo2_30d": round(stats_row['avg_spo2_30d'], 1) if stats_row['avg_spo2_30d'] else None,
|
||||
"latest_vo2_max": float(latest_vo2) if latest_vo2 else None,
|
||||
"total_entries": stats_row['total_entries'],
|
||||
"trend_resting_hr": trend_hr,
|
||||
"trend_hrv": trend_hrv,
|
||||
"period_days": days
|
||||
}
|
||||
|
||||
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
# Import Endpoints
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
|
||||
def parse_omron_date(date_str: str) -> str:
|
||||
"""
|
||||
Parse Omron German date format to YYYY-MM-DD.
|
||||
|
||||
Examples:
|
||||
- "13 März 2026" -> "2026-03-13"
|
||||
- "28 Feb. 2026" -> "2026-02-28"
|
||||
"""
|
||||
parts = date_str.strip().split()
|
||||
if len(parts) != 3:
|
||||
raise ValueError(f"Invalid date format: {date_str}")
|
||||
|
||||
day = parts[0].zfill(2)
|
||||
month_str = parts[1]
|
||||
year = parts[2]
|
||||
|
||||
# Map German month to number
|
||||
month = GERMAN_MONTHS.get(month_str)
|
||||
if not month:
|
||||
raise ValueError(f"Unknown month: {month_str}")
|
||||
|
||||
return f"{year}-{month}-{day}"
|
||||
|
||||
|
||||
@router.post("/import/omron")
|
||||
async def import_omron_csv(
|
||||
file: UploadFile = File(...),
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Import Omron blood pressure CSV export.
|
||||
|
||||
Expected format:
|
||||
Datum,Zeit,Systolisch (mmHg),Diastolisch (mmHg),Puls (bpm),...
|
||||
"""
|
||||
pid = get_pid(x_profile_id, session)
|
||||
|
||||
# Read file
|
||||
content = await file.read()
|
||||
content_str = content.decode('utf-8')
|
||||
|
||||
# Parse CSV
|
||||
reader = csv.DictReader(io.StringIO(content_str))
|
||||
|
||||
inserted = 0
|
||||
updated = 0
|
||||
skipped = 0
|
||||
errors = []
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
for row_num, row in enumerate(reader, start=2):
|
||||
try:
|
||||
# Parse date
|
||||
date_str = parse_omron_date(row['Datum'])
|
||||
|
||||
# Parse values
|
||||
systolic = int(row['Systolisch (mmHg)']) if row['Systolisch (mmHg)'] and row['Systolisch (mmHg)'] != '-' else None
|
||||
diastolic = int(row['Diastolisch (mmHg)']) if row['Diastolisch (mmHg)'] and row['Diastolisch (mmHg)'] != '-' else None
|
||||
pulse = int(row['Puls (bpm)']) if row['Puls (bpm)'] and row['Puls (bpm)'] != '-' else None
|
||||
|
||||
# Skip if no data
|
||||
if not systolic and not diastolic and not pulse:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
# Parse flags (optional columns)
|
||||
irregular = row.get('Unregelmäßiger Herzschlag festgestellt', '').strip() not in ('', '-', ' ')
|
||||
afib = row.get('Mögliches AFib', '').strip() not in ('', '-', ' ')
|
||||
|
||||
# Upsert
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO vitals_log (
|
||||
profile_id, date, blood_pressure_systolic, blood_pressure_diastolic,
|
||||
pulse, irregular_heartbeat, possible_afib, source
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, 'omron')
|
||||
ON CONFLICT (profile_id, date)
|
||||
DO UPDATE SET
|
||||
blood_pressure_systolic = COALESCE(EXCLUDED.blood_pressure_systolic, vitals_log.blood_pressure_systolic),
|
||||
blood_pressure_diastolic = COALESCE(EXCLUDED.blood_pressure_diastolic, vitals_log.blood_pressure_diastolic),
|
||||
pulse = COALESCE(EXCLUDED.pulse, vitals_log.pulse),
|
||||
irregular_heartbeat = COALESCE(EXCLUDED.irregular_heartbeat, vitals_log.irregular_heartbeat),
|
||||
possible_afib = COALESCE(EXCLUDED.possible_afib, vitals_log.possible_afib),
|
||||
source = CASE WHEN vitals_log.source = 'manual' THEN vitals_log.source ELSE 'omron' END,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
RETURNING (xmax = 0) AS inserted
|
||||
""",
|
||||
(pid, date_str, systolic, diastolic, pulse, irregular, afib)
|
||||
)
|
||||
|
||||
result = cur.fetchone()
|
||||
if result['inserted']:
|
||||
inserted += 1
|
||||
else:
|
||||
updated += 1
|
||||
|
||||
except Exception as e:
|
||||
errors.append(f"Zeile {row_num}: {str(e)}")
|
||||
logger.error(f"[OMRON-IMPORT] Error at row {row_num}: {e}")
|
||||
continue
|
||||
|
||||
conn.commit()
|
||||
|
||||
logger.info(f"[OMRON-IMPORT] {pid}: {inserted} inserted, {updated} updated, {skipped} skipped, {len(errors)} errors")
|
||||
|
||||
return {
|
||||
"message": "Omron CSV Import abgeschlossen",
|
||||
"inserted": inserted,
|
||||
"updated": updated,
|
||||
"skipped": skipped,
|
||||
"errors": errors[:10] # Limit to first 10 errors
|
||||
}
|
||||
|
||||
|
||||
@router.post("/import/apple-health")
|
||||
async def import_apple_health_csv(
|
||||
file: UploadFile = File(...),
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
Import Apple Health vitals CSV export.
|
||||
|
||||
Expected columns:
|
||||
- Datum/Uhrzeit
|
||||
- Ruhepuls (count/min)
|
||||
- Herzfrequenzvariabilität (ms)
|
||||
- VO2 max (ml/(kg·min))
|
||||
- Blutsauerstoffsättigung (%)
|
||||
- Atemfrequenz (count/min)
|
||||
"""
|
||||
pid = get_pid(x_profile_id, session)
|
||||
|
||||
# Read file
|
||||
content = await file.read()
|
||||
content_str = content.decode('utf-8')
|
||||
|
||||
# Parse CSV
|
||||
reader = csv.DictReader(io.StringIO(content_str))
|
||||
|
||||
inserted = 0
|
||||
updated = 0
|
||||
skipped = 0
|
||||
errors = []
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
for row_num, row in enumerate(reader, start=2):
|
||||
try:
|
||||
# Parse date (format: "2026-02-21 00:00:00")
|
||||
date_str = row.get('Datum/Uhrzeit', '').split()[0] # Extract date part
|
||||
if not date_str:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
# Parse values (columns might be empty)
|
||||
resting_hr = None
|
||||
hrv = None
|
||||
vo2_max = None
|
||||
spo2 = None
|
||||
respiratory_rate = None
|
||||
|
||||
if 'Ruhepuls (count/min)' in row and row['Ruhepuls (count/min)']:
|
||||
resting_hr = int(float(row['Ruhepuls (count/min)']))
|
||||
|
||||
if 'Herzfrequenzvariabilität (ms)' in row and row['Herzfrequenzvariabilität (ms)']:
|
||||
hrv = int(float(row['Herzfrequenzvariabilität (ms)']))
|
||||
|
||||
if 'VO2 max (ml/(kg·min))' in row and row['VO2 max (ml/(kg·min))']:
|
||||
vo2_max = float(row['VO2 max (ml/(kg·min))'])
|
||||
|
||||
if 'Blutsauerstoffsättigung (%)' in row and row['Blutsauerstoffsättigung (%)']:
|
||||
spo2 = int(float(row['Blutsauerstoffsättigung (%)']))
|
||||
|
||||
if 'Atemfrequenz (count/min)' in row and row['Atemfrequenz (count/min)']:
|
||||
respiratory_rate = float(row['Atemfrequenz (count/min)'])
|
||||
|
||||
# Skip if no vitals data
|
||||
if not any([resting_hr, hrv, vo2_max, spo2, respiratory_rate]):
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
# Upsert
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO vitals_log (
|
||||
profile_id, date, resting_hr, hrv, vo2_max, spo2,
|
||||
respiratory_rate, source
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, 'apple_health')
|
||||
ON CONFLICT (profile_id, date)
|
||||
DO UPDATE SET
|
||||
resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_log.resting_hr),
|
||||
hrv = COALESCE(EXCLUDED.hrv, vitals_log.hrv),
|
||||
vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_log.vo2_max),
|
||||
spo2 = COALESCE(EXCLUDED.spo2, vitals_log.spo2),
|
||||
respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_log.respiratory_rate),
|
||||
source = CASE WHEN vitals_log.source = 'manual' THEN vitals_log.source ELSE 'apple_health' END,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
RETURNING (xmax = 0) AS inserted
|
||||
""",
|
||||
(pid, date_str, resting_hr, hrv, vo2_max, spo2, respiratory_rate)
|
||||
)
|
||||
|
||||
result = cur.fetchone()
|
||||
if result['inserted']:
|
||||
inserted += 1
|
||||
else:
|
||||
updated += 1
|
||||
|
||||
except Exception as e:
|
||||
errors.append(f"Zeile {row_num}: {str(e)}")
|
||||
logger.error(f"[APPLE-HEALTH-IMPORT] Error at row {row_num}: {e}")
|
||||
continue
|
||||
|
||||
conn.commit()
|
||||
|
||||
logger.info(f"[APPLE-HEALTH-IMPORT] {pid}: {inserted} inserted, {updated} updated, {skipped} skipped, {len(errors)} errors")
|
||||
|
||||
return {
|
||||
"message": "Apple Health CSV Import abgeschlossen",
|
||||
"inserted": inserted,
|
||||
"updated": updated,
|
||||
"skipped": skipped,
|
||||
"errors": errors[:10] # Limit to first 10 errors
|
||||
}
|
||||
@@ -0,0 +1,414 @@
|
||||
"""
|
||||
Vitals Baseline Router - v9d Phase 2d Refactored
|
||||
|
||||
Baseline vitals measured once daily (morning, fasted):
|
||||
- Resting Heart Rate (RHR)
|
||||
- Heart Rate Variability (HRV)
|
||||
- VO2 Max
|
||||
- SpO2 (Blood Oxygen Saturation)
|
||||
- Respiratory Rate
|
||||
|
||||
Endpoints:
|
||||
- GET /api/vitals/baseline List baseline vitals
|
||||
- GET /api/vitals/baseline/by-date/{date} Get entry for specific date
|
||||
- POST /api/vitals/baseline Create/update baseline entry (upsert)
|
||||
- PUT /api/vitals/baseline/{id} Update baseline entry
|
||||
- DELETE /api/vitals/baseline/{id} Delete baseline entry
|
||||
- GET /api/vitals/baseline/stats Statistics and trends
|
||||
- POST /api/vitals/baseline/import/apple-health Import Apple Health CSV
|
||||
"""
|
||||
from fastapi import APIRouter, HTTPException, Depends, Header, UploadFile, File
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
from datetime import datetime, timedelta
|
||||
import logging
|
||||
import csv
|
||||
import io
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth
|
||||
from routers.profiles import get_pid
|
||||
|
||||
router = APIRouter(prefix="/api/vitals/baseline", tags=["vitals_baseline"])
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
# Pydantic Models
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
class BaselineEntry(BaseModel):
|
||||
date: str
|
||||
resting_hr: Optional[int] = None
|
||||
hrv: Optional[int] = None
|
||||
vo2_max: Optional[float] = None
|
||||
spo2: Optional[int] = None
|
||||
respiratory_rate: Optional[float] = None
|
||||
body_temperature: Optional[float] = None
|
||||
resting_metabolic_rate: Optional[int] = None
|
||||
note: Optional[str] = None
|
||||
|
||||
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
# CRUD Endpoints
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
@router.get("")
|
||||
def list_baseline_vitals(
|
||||
limit: int = 90,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Get baseline vitals (last N days)."""
|
||||
pid = get_pid(x_profile_id)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT * FROM vitals_baseline
|
||||
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_baseline_by_date(
|
||||
date: str,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Get baseline entry for specific date."""
|
||||
pid = get_pid(x_profile_id)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT * FROM vitals_baseline
|
||||
WHERE profile_id = %s AND date = %s
|
||||
""", (pid, date))
|
||||
row = cur.fetchone()
|
||||
return r2d(row) if row else None
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_or_update_baseline(
|
||||
entry: BaselineEntry,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Create or update baseline entry (upsert on date)."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
# Build dynamic update columns (only non-None fields)
|
||||
fields = []
|
||||
values = [pid, entry.date]
|
||||
|
||||
if entry.resting_hr is not None:
|
||||
fields.append("resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_baseline.resting_hr)")
|
||||
values.append(entry.resting_hr)
|
||||
if entry.hrv is not None:
|
||||
fields.append("hrv = COALESCE(EXCLUDED.hrv, vitals_baseline.hrv)")
|
||||
values.append(entry.hrv)
|
||||
if entry.vo2_max is not None:
|
||||
fields.append("vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_baseline.vo2_max)")
|
||||
values.append(entry.vo2_max)
|
||||
if entry.spo2 is not None:
|
||||
fields.append("spo2 = COALESCE(EXCLUDED.spo2, vitals_baseline.spo2)")
|
||||
values.append(entry.spo2)
|
||||
if entry.respiratory_rate is not None:
|
||||
fields.append("respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_baseline.respiratory_rate)")
|
||||
values.append(entry.respiratory_rate)
|
||||
if entry.body_temperature is not None:
|
||||
fields.append("body_temperature = COALESCE(EXCLUDED.body_temperature, vitals_baseline.body_temperature)")
|
||||
values.append(entry.body_temperature)
|
||||
if entry.resting_metabolic_rate is not None:
|
||||
fields.append("resting_metabolic_rate = COALESCE(EXCLUDED.resting_metabolic_rate, vitals_baseline.resting_metabolic_rate)")
|
||||
values.append(entry.resting_metabolic_rate)
|
||||
if entry.note:
|
||||
fields.append("note = COALESCE(EXCLUDED.note, vitals_baseline.note)")
|
||||
values.append(entry.note)
|
||||
|
||||
# At least one field must be provided
|
||||
if not fields:
|
||||
raise HTTPException(400, "At least one baseline vital must be provided")
|
||||
|
||||
# Build value placeholders
|
||||
placeholders = ", ".join([f"${i}" for i in range(1, len(values) + 1)])
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
query = f"""
|
||||
INSERT INTO vitals_baseline (profile_id, date, {', '.join([f.split('=')[0].strip() for f in fields])})
|
||||
VALUES ($1, $2, {', '.join([f'${i}' for i in range(3, len(values) + 1)])})
|
||||
ON CONFLICT (profile_id, date)
|
||||
DO UPDATE SET {', '.join(fields)}, updated_at = NOW()
|
||||
RETURNING *
|
||||
"""
|
||||
cur.execute(query, values)
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
@router.put("/{entry_id}")
|
||||
def update_baseline(
|
||||
entry_id: int,
|
||||
entry: BaselineEntry,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Update existing baseline entry."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
# Build SET clause dynamically
|
||||
updates = []
|
||||
values = []
|
||||
idx = 1
|
||||
|
||||
if entry.resting_hr is not None:
|
||||
updates.append(f"resting_hr = ${idx}")
|
||||
values.append(entry.resting_hr)
|
||||
idx += 1
|
||||
if entry.hrv is not None:
|
||||
updates.append(f"hrv = ${idx}")
|
||||
values.append(entry.hrv)
|
||||
idx += 1
|
||||
if entry.vo2_max is not None:
|
||||
updates.append(f"vo2_max = ${idx}")
|
||||
values.append(entry.vo2_max)
|
||||
idx += 1
|
||||
if entry.spo2 is not None:
|
||||
updates.append(f"spo2 = ${idx}")
|
||||
values.append(entry.spo2)
|
||||
idx += 1
|
||||
if entry.respiratory_rate is not None:
|
||||
updates.append(f"respiratory_rate = ${idx}")
|
||||
values.append(entry.respiratory_rate)
|
||||
idx += 1
|
||||
if entry.note:
|
||||
updates.append(f"note = ${idx}")
|
||||
values.append(entry.note)
|
||||
idx += 1
|
||||
|
||||
if not updates:
|
||||
raise HTTPException(400, "No fields to update")
|
||||
|
||||
updates.append("updated_at = NOW()")
|
||||
values.extend([entry_id, pid])
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
query = f"""
|
||||
UPDATE vitals_baseline
|
||||
SET {', '.join(updates)}
|
||||
WHERE id = ${idx} AND profile_id = ${idx + 1}
|
||||
RETURNING *
|
||||
"""
|
||||
cur.execute(query, values)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Entry not found")
|
||||
return r2d(row)
|
||||
|
||||
|
||||
@router.delete("/{entry_id}")
|
||||
def delete_baseline(
|
||||
entry_id: int,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Delete baseline entry."""
|
||||
pid = get_pid(x_profile_id)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
DELETE FROM vitals_baseline
|
||||
WHERE id = %s AND profile_id = %s
|
||||
""", (entry_id, pid))
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(404, "Entry not found")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
# Statistics & Trends
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
@router.get("/stats")
|
||||
def get_baseline_stats(
|
||||
days: int = 30,
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Get baseline vitals statistics and trends."""
|
||||
pid = get_pid(x_profile_id)
|
||||
cutoff_date = (datetime.now() - timedelta(days=days)).date()
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT
|
||||
COUNT(*) as total_entries,
|
||||
-- Resting HR
|
||||
AVG(resting_hr) FILTER (WHERE date >= %s - INTERVAL '7 days') as avg_rhr_7d,
|
||||
AVG(resting_hr) FILTER (WHERE date >= %s - INTERVAL '30 days') as avg_rhr_30d,
|
||||
-- HRV
|
||||
AVG(hrv) FILTER (WHERE date >= %s - INTERVAL '7 days') as avg_hrv_7d,
|
||||
AVG(hrv) FILTER (WHERE date >= %s - INTERVAL '30 days') as avg_hrv_30d,
|
||||
-- Latest values
|
||||
(SELECT vo2_max FROM vitals_baseline WHERE profile_id = %s AND vo2_max IS NOT NULL ORDER BY date DESC LIMIT 1) as latest_vo2_max,
|
||||
AVG(spo2) FILTER (WHERE date >= %s - INTERVAL '7 days') as avg_spo2_7d
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s AND date >= %s
|
||||
""", (cutoff_date, cutoff_date, cutoff_date, cutoff_date, pid, cutoff_date, pid, cutoff_date))
|
||||
|
||||
stats = r2d(cur.fetchone())
|
||||
|
||||
# Calculate trends (7d vs 30d)
|
||||
if stats['avg_rhr_7d'] and stats['avg_rhr_30d']:
|
||||
if stats['avg_rhr_7d'] < stats['avg_rhr_30d'] - 2:
|
||||
stats['trend_rhr'] = 'decreasing' # Good!
|
||||
elif stats['avg_rhr_7d'] > stats['avg_rhr_30d'] + 2:
|
||||
stats['trend_rhr'] = 'increasing' # Warning
|
||||
else:
|
||||
stats['trend_rhr'] = 'stable'
|
||||
else:
|
||||
stats['trend_rhr'] = None
|
||||
|
||||
if stats['avg_hrv_7d'] and stats['avg_hrv_30d']:
|
||||
if stats['avg_hrv_7d'] > stats['avg_hrv_30d'] + 5:
|
||||
stats['trend_hrv'] = 'increasing' # Good!
|
||||
elif stats['avg_hrv_7d'] < stats['avg_hrv_30d'] - 5:
|
||||
stats['trend_hrv'] = 'decreasing' # Warning
|
||||
else:
|
||||
stats['trend_hrv'] = 'stable'
|
||||
else:
|
||||
stats['trend_hrv'] = None
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
# Import: Apple Health CSV
|
||||
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
def safe_int(value):
|
||||
"""Safely parse string to int, handling decimals."""
|
||||
if not value or value == '':
|
||||
return None
|
||||
try:
|
||||
# If it has a decimal point, parse as float first then round to int
|
||||
if '.' in str(value):
|
||||
return int(float(value))
|
||||
return int(value)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
def safe_float(value):
|
||||
"""Safely parse string to float."""
|
||||
if not value or value == '':
|
||||
return None
|
||||
try:
|
||||
return float(value)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
@router.post("/import/apple-health")
|
||||
async def import_apple_health_baseline(
|
||||
file: UploadFile = File(...),
|
||||
x_profile_id: Optional[str] = Header(default=None),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""Import baseline vitals from Apple Health CSV export."""
|
||||
pid = get_pid(x_profile_id)
|
||||
|
||||
content = await file.read()
|
||||
decoded = content.decode('utf-8')
|
||||
reader = csv.DictReader(io.StringIO(decoded))
|
||||
|
||||
inserted = 0
|
||||
updated = 0
|
||||
skipped = 0
|
||||
errors = 0
|
||||
error_details = [] # Collect error messages
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Log available columns for debugging
|
||||
first_row = True
|
||||
|
||||
for row in reader:
|
||||
try:
|
||||
if first_row:
|
||||
logger.info(f"CSV Columns: {list(row.keys())}")
|
||||
first_row = False
|
||||
|
||||
# Support both English and German column names
|
||||
date_raw = row.get('Start') or row.get('Datum/Uhrzeit')
|
||||
date = date_raw[:10] if date_raw else None
|
||||
if not date:
|
||||
logger.warning(f"Skipped row (no date): Start='{row.get('Start')}', Datum/Uhrzeit='{row.get('Datum/Uhrzeit')}'")
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
# Extract baseline vitals (support English + German column names)
|
||||
rhr = row.get('Resting Heart Rate') or row.get('Ruhepuls (count/min)')
|
||||
hrv = row.get('Heart Rate Variability') or row.get('Herzfrequenzvariabilität (ms)')
|
||||
vo2 = row.get('VO2 Max') or row.get('VO2 max (ml/(kg·min))')
|
||||
spo2 = row.get('Oxygen Saturation') or row.get('Blutsauerstoffsättigung (%)')
|
||||
resp_rate = row.get('Respiratory Rate') or row.get('Atemfrequenz (count/min)')
|
||||
|
||||
# Skip if no baseline vitals
|
||||
if not any([rhr, hrv, vo2, spo2, resp_rate]):
|
||||
logger.warning(f"Skipped row {date} (no vitals): RHR={rhr}, HRV={hrv}, VO2={vo2}, SpO2={spo2}, RespRate={resp_rate}")
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
# Upsert
|
||||
cur.execute("""
|
||||
INSERT INTO vitals_baseline (
|
||||
profile_id, date,
|
||||
resting_hr, hrv, vo2_max, spo2, respiratory_rate,
|
||||
source
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, 'apple_health')
|
||||
ON CONFLICT (profile_id, date)
|
||||
DO UPDATE SET
|
||||
resting_hr = COALESCE(EXCLUDED.resting_hr, vitals_baseline.resting_hr),
|
||||
hrv = COALESCE(EXCLUDED.hrv, vitals_baseline.hrv),
|
||||
vo2_max = COALESCE(EXCLUDED.vo2_max, vitals_baseline.vo2_max),
|
||||
spo2 = COALESCE(EXCLUDED.spo2, vitals_baseline.spo2),
|
||||
respiratory_rate = COALESCE(EXCLUDED.respiratory_rate, vitals_baseline.respiratory_rate),
|
||||
updated_at = NOW()
|
||||
WHERE vitals_baseline.source != 'manual'
|
||||
RETURNING (xmax = 0) AS inserted
|
||||
""", (
|
||||
pid, date,
|
||||
safe_int(rhr),
|
||||
safe_int(hrv),
|
||||
safe_float(vo2),
|
||||
safe_int(spo2),
|
||||
safe_float(resp_rate)
|
||||
))
|
||||
|
||||
result = cur.fetchone()
|
||||
if result is None:
|
||||
# WHERE clause prevented update (manual entry exists)
|
||||
skipped += 1
|
||||
elif result['inserted']:
|
||||
inserted += 1
|
||||
else:
|
||||
updated += 1
|
||||
|
||||
except Exception as e:
|
||||
import traceback
|
||||
error_msg = f"Row {date if 'date' in locals() else 'unknown'}: {str(e)}"
|
||||
error_details.append(error_msg)
|
||||
logger.error(f"{error_msg}\n{traceback.format_exc()}")
|
||||
errors += 1
|
||||
|
||||
return {
|
||||
"inserted": inserted,
|
||||
"updated": updated,
|
||||
"skipped": skipped,
|
||||
"errors": errors,
|
||||
"error_details": error_details[:10] # Return first 10 errors
|
||||
}
|
||||
@@ -4,16 +4,19 @@ 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
|
||||
from fastapi import APIRouter, Header, Depends, HTTPException
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth
|
||||
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("")
|
||||
@@ -31,17 +34,44 @@ def list_weight(limit: int=365, x_profile_id: Optional[str]=Header(default=None)
|
||||
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}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
"""
|
||||
Training Type Profiles - Rule Engine
|
||||
Flexible rule evaluation system for activity quality assessment.
|
||||
|
||||
Issue: #15
|
||||
Date: 2026-03-23
|
||||
"""
|
||||
from typing import Any, Dict, List, Optional, Callable
|
||||
from datetime import datetime
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RuleEvaluator:
|
||||
"""
|
||||
Generic rule evaluator for arbitrary parameters and operators.
|
||||
|
||||
Supports flexible rule definitions with various operators:
|
||||
- gte, lte, gt, lt: Comparison operators
|
||||
- eq, neq: Equality operators
|
||||
- between: Range checks
|
||||
- in, not_in: Set membership
|
||||
"""
|
||||
|
||||
# Operator definitions
|
||||
OPERATORS: Dict[str, Callable[[Any, Any], bool]] = {
|
||||
"gte": lambda actual, expected: actual is not None and actual >= expected,
|
||||
"lte": lambda actual, expected: actual is not None and actual <= expected,
|
||||
"gt": lambda actual, expected: actual is not None and actual > expected,
|
||||
"lt": lambda actual, expected: actual is not None and actual < expected,
|
||||
"eq": lambda actual, expected: actual == expected,
|
||||
"neq": lambda actual, expected: actual != expected,
|
||||
"between": lambda actual, expected: actual is not None and expected[0] <= actual <= expected[1],
|
||||
"in": lambda actual, expected: actual in expected,
|
||||
"not_in": lambda actual, expected: actual not in expected,
|
||||
}
|
||||
|
||||
OPERATOR_SYMBOLS = {
|
||||
"gte": "≥",
|
||||
"lte": "≤",
|
||||
"gt": ">",
|
||||
"lt": "<",
|
||||
"eq": "=",
|
||||
"neq": "≠",
|
||||
"between": "⟷",
|
||||
"in": "∈",
|
||||
"not_in": "∉",
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def evaluate_rule(
|
||||
cls,
|
||||
rule: Dict,
|
||||
activity: Dict,
|
||||
parameters_registry: Dict[str, Dict]
|
||||
) -> Dict:
|
||||
"""
|
||||
Evaluates a single rule against an activity.
|
||||
|
||||
Args:
|
||||
rule: {
|
||||
"parameter": str,
|
||||
"operator": str,
|
||||
"value": Any,
|
||||
"weight": int,
|
||||
"optional": bool,
|
||||
"reason": str
|
||||
}
|
||||
activity: Activity data dictionary
|
||||
parameters_registry: Mapping parameter_key -> config
|
||||
|
||||
Returns:
|
||||
{
|
||||
"passed": bool,
|
||||
"actual_value": Any,
|
||||
"expected_value": Any,
|
||||
"parameter": str,
|
||||
"operator": str,
|
||||
"operator_symbol": str,
|
||||
"reason": str,
|
||||
"weight": int,
|
||||
"skipped": bool (optional),
|
||||
"error": str (optional)
|
||||
}
|
||||
"""
|
||||
param_key = rule.get("parameter")
|
||||
operator = rule.get("operator")
|
||||
expected_value = rule.get("value")
|
||||
weight = rule.get("weight", 1)
|
||||
reason = rule.get("reason", "")
|
||||
optional = rule.get("optional", False)
|
||||
|
||||
# Get parameter configuration
|
||||
param_config = parameters_registry.get(param_key)
|
||||
if not param_config:
|
||||
return {
|
||||
"passed": False,
|
||||
"parameter": param_key,
|
||||
"error": f"Unknown parameter: {param_key}"
|
||||
}
|
||||
|
||||
# Extract value from activity
|
||||
source_field = param_config.get("source_field", param_key)
|
||||
actual_value = activity.get(source_field)
|
||||
|
||||
# Optional and not provided? → Pass
|
||||
if optional and actual_value is None:
|
||||
return {
|
||||
"passed": True,
|
||||
"actual_value": None,
|
||||
"expected_value": expected_value,
|
||||
"parameter": param_key,
|
||||
"operator": operator,
|
||||
"operator_symbol": cls.OPERATOR_SYMBOLS.get(operator, operator),
|
||||
"reason": "Optional parameter not provided",
|
||||
"weight": weight,
|
||||
"skipped": True
|
||||
}
|
||||
|
||||
# Required but not provided? → Fail
|
||||
if actual_value is None:
|
||||
return {
|
||||
"passed": False,
|
||||
"actual_value": None,
|
||||
"expected_value": expected_value,
|
||||
"parameter": param_key,
|
||||
"operator": operator,
|
||||
"operator_symbol": cls.OPERATOR_SYMBOLS.get(operator, operator),
|
||||
"reason": reason or "Required parameter missing",
|
||||
"weight": weight
|
||||
}
|
||||
|
||||
# Apply operator
|
||||
operator_func = cls.OPERATORS.get(operator)
|
||||
if not operator_func:
|
||||
return {
|
||||
"passed": False,
|
||||
"parameter": param_key,
|
||||
"error": f"Unknown operator: {operator}"
|
||||
}
|
||||
|
||||
try:
|
||||
passed = operator_func(actual_value, expected_value)
|
||||
except Exception as e:
|
||||
logger.error(f"[RULE-ENGINE] Error evaluating rule {param_key}: {e}")
|
||||
return {
|
||||
"passed": False,
|
||||
"parameter": param_key,
|
||||
"error": f"Evaluation error: {str(e)}"
|
||||
}
|
||||
|
||||
return {
|
||||
"passed": passed,
|
||||
"actual_value": actual_value,
|
||||
"expected_value": expected_value,
|
||||
"parameter": param_key,
|
||||
"operator": operator,
|
||||
"operator_symbol": cls.OPERATOR_SYMBOLS.get(operator, operator),
|
||||
"reason": reason,
|
||||
"weight": weight
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def evaluate_rule_set(
|
||||
cls,
|
||||
rule_set: Dict,
|
||||
activity: Dict,
|
||||
parameters_registry: Dict[str, Dict]
|
||||
) -> Dict:
|
||||
"""
|
||||
Evaluates a complete rule set (e.g., minimum_requirements).
|
||||
|
||||
Args:
|
||||
rule_set: {
|
||||
"enabled": bool,
|
||||
"pass_strategy": str,
|
||||
"pass_threshold": float,
|
||||
"rules": [...]
|
||||
}
|
||||
activity: Activity data
|
||||
parameters_registry: Parameter configurations
|
||||
|
||||
Returns:
|
||||
{
|
||||
"enabled": bool,
|
||||
"passed": bool,
|
||||
"score": float (0-1),
|
||||
"rule_results": [...],
|
||||
"pass_strategy": str,
|
||||
"pass_threshold": float,
|
||||
"failed_rules": [...]
|
||||
}
|
||||
"""
|
||||
if not rule_set.get("enabled", False):
|
||||
return {
|
||||
"enabled": False,
|
||||
"passed": True,
|
||||
"score": 1.0,
|
||||
"rule_results": [],
|
||||
"failed_rules": []
|
||||
}
|
||||
|
||||
rules = rule_set.get("rules", [])
|
||||
pass_strategy = rule_set.get("pass_strategy", "weighted_score")
|
||||
pass_threshold = rule_set.get("pass_threshold", 0.6)
|
||||
|
||||
rule_results = []
|
||||
failed_rules = []
|
||||
total_weight = 0
|
||||
passed_weight = 0
|
||||
|
||||
# Evaluate each rule
|
||||
for rule in rules:
|
||||
result = cls.evaluate_rule(rule, activity, parameters_registry)
|
||||
rule_results.append(result)
|
||||
|
||||
if result.get("skipped"):
|
||||
continue
|
||||
|
||||
if result.get("error"):
|
||||
logger.warning(f"[RULE-ENGINE] Rule error: {result['error']}")
|
||||
continue
|
||||
|
||||
weight = result.get("weight", 1)
|
||||
total_weight += weight
|
||||
|
||||
if result["passed"]:
|
||||
passed_weight += weight
|
||||
else:
|
||||
failed_rules.append(result)
|
||||
|
||||
# Calculate score
|
||||
score = passed_weight / total_weight if total_weight > 0 else 1.0
|
||||
|
||||
# Apply pass strategy
|
||||
if pass_strategy == "all_must_pass":
|
||||
passed = all(
|
||||
r["passed"] for r in rule_results
|
||||
if not r.get("skipped") and not r.get("error")
|
||||
)
|
||||
elif pass_strategy == "weighted_score":
|
||||
passed = score >= pass_threshold
|
||||
elif pass_strategy == "at_least_n":
|
||||
n = rule_set.get("at_least_n", 1)
|
||||
passed_count = sum(
|
||||
1 for r in rule_results
|
||||
if r["passed"] and not r.get("skipped")
|
||||
)
|
||||
passed = passed_count >= n
|
||||
else:
|
||||
passed = False
|
||||
logger.warning(f"[RULE-ENGINE] Unknown pass strategy: {pass_strategy}")
|
||||
|
||||
return {
|
||||
"enabled": True,
|
||||
"passed": passed,
|
||||
"score": round(score, 2),
|
||||
"rule_results": rule_results,
|
||||
"failed_rules": failed_rules,
|
||||
"pass_strategy": pass_strategy,
|
||||
"pass_threshold": pass_threshold
|
||||
}
|
||||
|
||||
|
||||
class IntensityZoneEvaluator:
|
||||
"""
|
||||
Evaluates heart rate zones and time distribution.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def evaluate(
|
||||
zone_config: Dict,
|
||||
activity: Dict,
|
||||
user_profile: Dict
|
||||
) -> Dict:
|
||||
"""
|
||||
Evaluates which HR zone the activity was in.
|
||||
|
||||
Args:
|
||||
zone_config: intensity_zones configuration
|
||||
activity: Activity data (with hr_avg)
|
||||
user_profile: User profile (with hf_max)
|
||||
|
||||
Returns:
|
||||
{
|
||||
"enabled": bool,
|
||||
"dominant_zone": str,
|
||||
"avg_hr_percent": float,
|
||||
"zone_color": str,
|
||||
"zone_effect": str,
|
||||
"duration_quality": float (0-1),
|
||||
"recommendation": str
|
||||
}
|
||||
"""
|
||||
if not zone_config.get("enabled", False):
|
||||
return {"enabled": False}
|
||||
|
||||
avg_hr = activity.get("hr_avg")
|
||||
user_max_hr = user_profile.get("hf_max", 180) # Default 180 if not set
|
||||
|
||||
if not avg_hr or not user_max_hr:
|
||||
return {
|
||||
"enabled": True,
|
||||
"dominant_zone": "unknown",
|
||||
"avg_hr_percent": None,
|
||||
"recommendation": "Herzfrequenz-Daten fehlen"
|
||||
}
|
||||
|
||||
avg_hr_percent = (avg_hr / user_max_hr) * 100
|
||||
|
||||
# Find matching zone
|
||||
zones = zone_config.get("zones", [])
|
||||
dominant_zone = None
|
||||
|
||||
for zone in zones:
|
||||
zone_rules = zone.get("rules", [])
|
||||
for rule in zone_rules:
|
||||
if rule["parameter"] == "avg_hr_percent":
|
||||
min_percent, max_percent = rule["value"]
|
||||
if min_percent <= avg_hr_percent <= max_percent:
|
||||
dominant_zone = zone
|
||||
break
|
||||
if dominant_zone:
|
||||
break
|
||||
|
||||
if not dominant_zone:
|
||||
return {
|
||||
"enabled": True,
|
||||
"dominant_zone": "out_of_range",
|
||||
"avg_hr_percent": round(avg_hr_percent, 1),
|
||||
"recommendation": "Herzfrequenz außerhalb definierter Zonen"
|
||||
}
|
||||
|
||||
# Check duration quality
|
||||
duration = activity.get("duration_min", 0)
|
||||
target_duration = dominant_zone.get("target_duration_min", 30)
|
||||
duration_quality = min(duration / target_duration, 1.0) if target_duration > 0 else 1.0
|
||||
|
||||
recommendation = f"Training in Zone '{dominant_zone['name']}' (Effekt: {dominant_zone['effect']})."
|
||||
if duration < target_duration:
|
||||
recommendation += f" Für optimale Wirkung: {target_duration}min empfohlen."
|
||||
|
||||
return {
|
||||
"enabled": True,
|
||||
"dominant_zone": dominant_zone.get("id"),
|
||||
"dominant_zone_name": dominant_zone.get("name"),
|
||||
"avg_hr_percent": round(avg_hr_percent, 1),
|
||||
"zone_color": dominant_zone.get("color"),
|
||||
"zone_effect": dominant_zone.get("effect"),
|
||||
"duration_quality": round(duration_quality, 2),
|
||||
"target_duration_min": target_duration,
|
||||
"actual_duration_min": duration,
|
||||
"recommendation": recommendation
|
||||
}
|
||||
|
||||
|
||||
class TrainingEffectsEvaluator:
|
||||
"""
|
||||
Evaluates which abilities are trained by the activity.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def evaluate(
|
||||
effects_config: Dict,
|
||||
activity: Dict,
|
||||
intensity_zone_result: Optional[Dict] = None
|
||||
) -> Dict:
|
||||
"""
|
||||
Evaluates training effects (abilities trained).
|
||||
|
||||
Args:
|
||||
effects_config: training_effects configuration
|
||||
activity: Activity data
|
||||
intensity_zone_result: Result from intensity zone evaluation
|
||||
|
||||
Returns:
|
||||
{
|
||||
"enabled": bool,
|
||||
"abilities_trained": [...],
|
||||
"total_training_load": float
|
||||
}
|
||||
"""
|
||||
if not effects_config.get("enabled", False):
|
||||
return {"enabled": False}
|
||||
|
||||
abilities_trained = []
|
||||
|
||||
# Use default effects if no conditional matching
|
||||
default_effects = effects_config.get("default_effects", {})
|
||||
primary_abilities = default_effects.get("primary_abilities", [])
|
||||
secondary_abilities = default_effects.get("secondary_abilities", [])
|
||||
|
||||
# Calculate quality factor (simplified for now)
|
||||
quality_factor = 1.0
|
||||
|
||||
# Primary abilities
|
||||
for ability in primary_abilities:
|
||||
abilities_trained.append({
|
||||
"category": ability["category"],
|
||||
"ability": ability["ability"],
|
||||
"intensity": ability["intensity"],
|
||||
"quality": quality_factor,
|
||||
"contribution": ability["intensity"] * quality_factor,
|
||||
"type": "primary"
|
||||
})
|
||||
|
||||
# Secondary abilities
|
||||
for ability in secondary_abilities:
|
||||
abilities_trained.append({
|
||||
"category": ability["category"],
|
||||
"ability": ability["ability"],
|
||||
"intensity": ability["intensity"],
|
||||
"quality": quality_factor * 0.7, # Secondary = 70%
|
||||
"contribution": ability["intensity"] * quality_factor * 0.7,
|
||||
"type": "secondary"
|
||||
})
|
||||
|
||||
total_training_load = sum(a["contribution"] for a in abilities_trained)
|
||||
|
||||
return {
|
||||
"enabled": True,
|
||||
"abilities_trained": abilities_trained,
|
||||
"total_training_load": round(total_training_load, 2),
|
||||
"metabolic_focus": effects_config.get("metabolic_focus", []),
|
||||
"muscle_groups": effects_config.get("muscle_groups", [])
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Generated
+6766
File diff suppressed because it is too large.
Load diff
+80
-10
@@ -1,6 +1,6 @@
|
||||
import { useEffect } from 'react'
|
||||
import { BrowserRouter, Routes, Route, NavLink, useNavigate } from 'react-router-dom'
|
||||
import { LayoutDashboard, PlusSquare, TrendingUp, BarChart2, Settings } from 'lucide-react'
|
||||
import { LayoutDashboard, PlusSquare, TrendingUp, BarChart2, Settings, LogOut } from 'lucide-react'
|
||||
import { ProfileProvider, useProfile } from './context/ProfileContext'
|
||||
import { AuthProvider, useAuth } from './context/AuthContext'
|
||||
import { setProfileId } from './utils/api'
|
||||
@@ -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,18 @@ 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 AdminTrainingTypesPage from './pages/AdminTrainingTypesPage'
|
||||
import AdminActivityMappingsPage from './pages/AdminActivityMappingsPage'
|
||||
import AdminTrainingProfiles from './pages/AdminTrainingProfiles'
|
||||
import SubscriptionPage from './pages/SubscriptionPage'
|
||||
import SleepPage from './pages/SleepPage'
|
||||
import RestDaysPage from './pages/RestDaysPage'
|
||||
import VitalsPage from './pages/VitalsPage'
|
||||
import './app.css'
|
||||
|
||||
function Nav() {
|
||||
@@ -42,10 +56,17 @@ function Nav() {
|
||||
}
|
||||
|
||||
function AppShell() {
|
||||
const { session, loading: authLoading, needsSetup } = useAuth()
|
||||
const { session, loading: authLoading, needsSetup, logout } = useAuth()
|
||||
const { activeProfile, loading: profileLoading } = useProfile()
|
||||
const nav = useNavigate()
|
||||
|
||||
const handleLogout = () => {
|
||||
if (confirm('Wirklich abmelden?')) {
|
||||
logout()
|
||||
window.location.href = '/'
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(()=>{
|
||||
if (session?.profile_id) {
|
||||
setProfileId(session.profile_id)
|
||||
@@ -53,9 +74,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}}>
|
||||
@@ -94,12 +132,32 @@ function AppShell() {
|
||||
<div className="app-shell">
|
||||
<header className="app-header">
|
||||
<span className="app-logo">Mitai Jinkendo</span>
|
||||
<NavLink to="/settings" style={{textDecoration:'none'}}>
|
||||
{activeProfile
|
||||
? <Avatar profile={activeProfile} size={30}/>
|
||||
: <div style={{width:30,height:30,borderRadius:'50%',background:'var(--accent)'}}/>
|
||||
}
|
||||
</NavLink>
|
||||
<div style={{display:'flex', gap:12, alignItems:'center'}}>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
title="Abmelden"
|
||||
style={{
|
||||
background:'none',
|
||||
border:'none',
|
||||
cursor:'pointer',
|
||||
padding:6,
|
||||
display:'flex',
|
||||
alignItems:'center',
|
||||
color:'var(--text2)',
|
||||
transition:'color 0.15s'
|
||||
}}
|
||||
onMouseEnter={e => e.currentTarget.style.color = '#D85A30'}
|
||||
onMouseLeave={e => e.currentTarget.style.color = 'var(--text2)'}
|
||||
>
|
||||
<LogOut size={18}/>
|
||||
</button>
|
||||
<NavLink to="/settings" style={{textDecoration:'none'}}>
|
||||
{activeProfile
|
||||
? <Avatar profile={activeProfile} size={30}/>
|
||||
: <div style={{width:30,height:30,borderRadius:'50%',background:'var(--accent)'}}/>
|
||||
}
|
||||
</NavLink>
|
||||
</div>
|
||||
</header>
|
||||
<main className="app-main">
|
||||
<Routes>
|
||||
@@ -110,11 +168,23 @@ function AppShell() {
|
||||
<Route path="/circum" element={<CircumScreen/>}/>
|
||||
<Route path="/caliper" element={<CaliperScreen/>}/>
|
||||
<Route path="/history" element={<History/>}/>
|
||||
<Route path="/sleep" element={<SleepPage/>}/>
|
||||
<Route path="/rest-days" element={<RestDaysPage/>}/>
|
||||
<Route path="/vitals" element={<VitalsPage/>}/>
|
||||
<Route path="/nutrition" element={<NutritionPage/>}/>
|
||||
<Route path="/activity" element={<ActivityPage/>}/>
|
||||
<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="/admin/training-types" element={<AdminTrainingTypesPage/>}/>
|
||||
<Route path="/admin/activity-mappings" element={<AdminActivityMappingsPage/>}/>
|
||||
<Route path="/admin/training-profiles" element={<AdminTrainingProfiles/>}/>
|
||||
<Route path="/subscription" element={<SubscriptionPage/>}/>
|
||||
</Routes>
|
||||
</main>
|
||||
<Nav/>
|
||||
|
||||
@@ -130,6 +130,10 @@ body { font-family: var(--font); background: var(--bg); color: var(--text1); -we
|
||||
.empty-state h3 { font-size: 16px; color: var(--text2); margin-bottom: 6px; }
|
||||
.spinner { width: 20px; height: 20px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin 0.7s linear infinite; display: inline-block; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
@keyframes slideDown {
|
||||
from { transform: translate(-50%, -20px); opacity: 0; }
|
||||
to { transform: translate(-50%, 0); opacity: 1; }
|
||||
}
|
||||
|
||||
/* Additional vars */
|
||||
:root {
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { api } from '../utils/api'
|
||||
import TrainingTypeSelect from './TrainingTypeSelect'
|
||||
|
||||
/**
|
||||
* BulkCategorize - UI for categorizing existing activities without training type
|
||||
*
|
||||
* Shows uncategorized activities grouped by activity_type,
|
||||
* allows bulk assignment of training type to all activities of same type.
|
||||
*/
|
||||
export default function BulkCategorize({ onComplete }) {
|
||||
const [uncategorized, setUncategorized] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [assignments, setAssignments] = useState({})
|
||||
const [saving, setSaving] = useState(null)
|
||||
|
||||
useEffect(() => {
|
||||
loadUncategorized()
|
||||
}, [])
|
||||
|
||||
const loadUncategorized = () => {
|
||||
setLoading(true)
|
||||
api.listUncategorizedActivities()
|
||||
.then(data => {
|
||||
setUncategorized(data)
|
||||
setLoading(false)
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('Failed to load uncategorized activities:', err)
|
||||
setLoading(false)
|
||||
})
|
||||
}
|
||||
|
||||
const handleAssignment = (activityType, typeId, category, subcategory) => {
|
||||
setAssignments(prev => ({
|
||||
...prev,
|
||||
[activityType]: {
|
||||
training_type_id: typeId,
|
||||
training_category: category,
|
||||
training_subcategory: subcategory
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
const handleSave = async (activityType) => {
|
||||
const assignment = assignments[activityType]
|
||||
if (!assignment || !assignment.training_type_id) {
|
||||
alert('Bitte wähle einen Trainingstyp aus')
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(activityType)
|
||||
try {
|
||||
const result = await api.bulkCategorizeActivities({
|
||||
activity_type: activityType,
|
||||
...assignment
|
||||
})
|
||||
|
||||
// Remove from list
|
||||
setUncategorized(prev => prev.filter(u => u.activity_type !== activityType))
|
||||
setAssignments(prev => {
|
||||
const newAssignments = { ...prev }
|
||||
delete newAssignments[activityType]
|
||||
return newAssignments
|
||||
})
|
||||
|
||||
// Show success message
|
||||
console.log(`✓ ${result.updated} activities categorized`)
|
||||
|
||||
} catch (err) {
|
||||
console.error('Failed to categorize:', err)
|
||||
alert('Kategorisierung fehlgeschlagen: ' + err.message)
|
||||
} finally {
|
||||
setSaving(null)
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{ textAlign: 'center', padding: 20 }}>
|
||||
<div className="spinner" style={{ width: 24, height: 24, margin: '0 auto' }} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (uncategorized.length === 0) {
|
||||
return (
|
||||
<div style={{
|
||||
textAlign: 'center',
|
||||
padding: 40,
|
||||
color: 'var(--text3)',
|
||||
fontSize: 14
|
||||
}}>
|
||||
<div style={{ fontSize: 32, marginBottom: 8 }}>✓</div>
|
||||
<div>Alle Aktivitäten sind kategorisiert</div>
|
||||
{onComplete && (
|
||||
<button
|
||||
onClick={onComplete}
|
||||
className="btn btn-secondary"
|
||||
style={{ marginTop: 16 }}
|
||||
>
|
||||
Schließen
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ maxWidth: 600, margin: '0 auto' }}>
|
||||
<div style={{
|
||||
marginBottom: 20,
|
||||
padding: 16,
|
||||
background: 'var(--surface)',
|
||||
borderRadius: 8,
|
||||
fontSize: 13,
|
||||
color: 'var(--text2)'
|
||||
}}>
|
||||
<strong style={{ color: 'var(--text1)' }}>
|
||||
{uncategorized.reduce((sum, u) => sum + u.count, 0)} Aktivitäten
|
||||
</strong> ohne Trainingstyp gefunden. Weise jedem Aktivitätstyp einen Trainingstyp zu.
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
{uncategorized.map(item => (
|
||||
<div
|
||||
key={item.activity_type}
|
||||
className="card"
|
||||
style={{ padding: 16 }}
|
||||
>
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'flex-start',
|
||||
marginBottom: 12
|
||||
}}>
|
||||
<div>
|
||||
<div style={{ fontWeight: 600, fontSize: 14, marginBottom: 4 }}>
|
||||
{item.activity_type}
|
||||
</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--text3)' }}>
|
||||
{item.count} Einheiten
|
||||
{item.first_date && item.last_date && (
|
||||
<> · {item.first_date} bis {item.last_date}</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TrainingTypeSelect
|
||||
value={assignments[item.activity_type]?.training_type_id || null}
|
||||
onChange={(typeId, category, subcategory) =>
|
||||
handleAssignment(item.activity_type, typeId, category, subcategory)
|
||||
}
|
||||
required={false}
|
||||
/>
|
||||
|
||||
<button
|
||||
onClick={() => handleSave(item.activity_type)}
|
||||
disabled={
|
||||
!assignments[item.activity_type]?.training_type_id ||
|
||||
saving === item.activity_type
|
||||
}
|
||||
className="btn btn-primary btn-full"
|
||||
style={{ marginTop: 12 }}
|
||||
>
|
||||
{saving === item.activity_type ? (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'center' }}>
|
||||
<div className="spinner" style={{ width: 14, height: 14 }} />
|
||||
Speichere...
|
||||
</div>
|
||||
) : (
|
||||
`${item.count} Einheiten kategorisieren`
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{onComplete && (
|
||||
<button
|
||||
onClick={onComplete}
|
||||
className="btn btn-secondary btn-full"
|
||||
style={{ marginTop: 16 }}
|
||||
>
|
||||
Später fortsetzen
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { useState } from 'react'
|
||||
import { api } from '../utils/api'
|
||||
|
||||
export default function EmailVerificationBanner({ profile }) {
|
||||
const [resending, setResending] = useState(false)
|
||||
const [success, setSuccess] = useState(false)
|
||||
const [error, setError] = useState(null)
|
||||
|
||||
// Only show if email is not verified
|
||||
if (!profile || profile.email_verified !== false) return null
|
||||
|
||||
const handleResend = async () => {
|
||||
if (!profile.email) return
|
||||
|
||||
setResending(true)
|
||||
setError(null)
|
||||
setSuccess(false)
|
||||
|
||||
try {
|
||||
await api.resendVerification(profile.email)
|
||||
setSuccess(true)
|
||||
setTimeout(() => setSuccess(false), 5000)
|
||||
} catch (err) {
|
||||
setError(err.message || 'Fehler beim Versenden')
|
||||
setTimeout(() => setError(null), 5000)
|
||||
} finally {
|
||||
setResending(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
background: '#FFF4E6',
|
||||
border: '2px solid #F59E0B',
|
||||
borderRadius: 12,
|
||||
padding: '16px 20px',
|
||||
marginBottom: 20,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 16,
|
||||
flexWrap: 'wrap'
|
||||
}}>
|
||||
<div style={{
|
||||
fontSize: 32,
|
||||
lineHeight: 1
|
||||
}}>
|
||||
📧
|
||||
</div>
|
||||
<div style={{flex: 1, minWidth: 200}}>
|
||||
<div style={{
|
||||
fontWeight: 700,
|
||||
fontSize: 15,
|
||||
color: '#D97706',
|
||||
marginBottom: 4
|
||||
}}>
|
||||
E-Mail-Adresse noch nicht bestätigt
|
||||
</div>
|
||||
<div style={{
|
||||
fontSize: 13,
|
||||
color: 'var(--text2)',
|
||||
lineHeight: 1.4
|
||||
}}>
|
||||
Bitte prüfe dein Postfach und klicke auf den Bestätigungslink.
|
||||
{success && (
|
||||
<span style={{color:'var(--accent)', fontWeight:600, marginLeft:4}}>
|
||||
✓ Neue E-Mail versendet!
|
||||
</span>
|
||||
)}
|
||||
{error && (
|
||||
<span style={{color:'var(--danger)', fontWeight:600, marginLeft:4}}>
|
||||
✗ {error}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleResend}
|
||||
disabled={resending || success}
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
borderRadius: 8,
|
||||
background: success ? 'var(--accent)' : '#F59E0B',
|
||||
color: 'white',
|
||||
fontWeight: 600,
|
||||
fontSize: 13,
|
||||
border: 'none',
|
||||
cursor: resending || success ? 'not-allowed' : 'pointer',
|
||||
whiteSpace: 'nowrap',
|
||||
opacity: resending || success ? 0.6 : 1
|
||||
}}
|
||||
>
|
||||
{resending ? 'Sende...' : success ? '✓ Versendet' : 'Neue E-Mail senden'}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Trash2, Plus, ChevronDown, ChevronUp } from 'lucide-react'
|
||||
import '../app.css'
|
||||
|
||||
const OPERATORS = [
|
||||
{ value: 'gte', label: '≥ Größer gleich', types: ['integer', 'float'] },
|
||||
{ value: 'lte', label: '≤ Kleiner gleich', types: ['integer', 'float'] },
|
||||
{ value: 'gt', label: '> Größer', types: ['integer', 'float'] },
|
||||
{ value: 'lt', label: '< Kleiner', types: ['integer', 'float'] },
|
||||
{ value: 'eq', label: '= Gleich', types: ['integer', 'float', 'string'] },
|
||||
{ value: 'neq', label: '≠ Ungleich', types: ['integer', 'float', 'string'] },
|
||||
{ value: 'between', label: '⟷ Zwischen', types: ['integer', 'float'] },
|
||||
]
|
||||
|
||||
const PASS_STRATEGIES = [
|
||||
{ value: 'weighted_score', label: 'Gewichteter Score' },
|
||||
{ value: 'all_must_pass', label: 'Alle müssen erfüllt sein' },
|
||||
{ value: 'at_least_n', label: 'Mindestens N Regeln' },
|
||||
]
|
||||
|
||||
export default function ProfileBuilder({ trainingType, onSave, onCancel, parameters }) {
|
||||
const [profile, setProfile] = useState(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [expandedSections, setExpandedSections] = useState({ minReq: true })
|
||||
const [successMessage, setSuccessMessage] = useState(null)
|
||||
|
||||
useEffect(() => {
|
||||
// Initialize or load existing profile
|
||||
if (trainingType.profile) {
|
||||
setProfile(trainingType.profile)
|
||||
} else {
|
||||
// Create empty profile structure
|
||||
setProfile({
|
||||
version: '1.0',
|
||||
name: `${trainingType.name_de} (Profil)`,
|
||||
description: '',
|
||||
rule_sets: {
|
||||
minimum_requirements: {
|
||||
enabled: true,
|
||||
pass_strategy: 'weighted_score',
|
||||
pass_threshold: 0.6,
|
||||
rules: []
|
||||
},
|
||||
intensity_zones: {
|
||||
enabled: false,
|
||||
zones: []
|
||||
},
|
||||
training_effects: {
|
||||
enabled: false,
|
||||
default_effects: {
|
||||
primary_abilities: [],
|
||||
secondary_abilities: []
|
||||
}
|
||||
},
|
||||
periodization: {
|
||||
enabled: false,
|
||||
frequency: {
|
||||
per_week_optimal: 3,
|
||||
per_week_max: 5
|
||||
},
|
||||
recovery: {
|
||||
min_hours_between: 24
|
||||
}
|
||||
},
|
||||
performance_indicators: {
|
||||
enabled: false
|
||||
},
|
||||
safety: {
|
||||
enabled: false,
|
||||
warnings: []
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}, [trainingType])
|
||||
|
||||
const toggleSection = (section) => {
|
||||
setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }))
|
||||
}
|
||||
|
||||
const updateRuleSet = (key, updates) => {
|
||||
setProfile(prev => ({
|
||||
...prev,
|
||||
rule_sets: {
|
||||
...prev.rule_sets,
|
||||
[key]: {
|
||||
...prev.rule_sets[key],
|
||||
...updates
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
const addRule = () => {
|
||||
const newRule = {
|
||||
parameter: parameters[0]?.key || 'duration_min',
|
||||
operator: 'gte',
|
||||
value: 0,
|
||||
weight: 3,
|
||||
optional: false,
|
||||
reason: ''
|
||||
}
|
||||
|
||||
setProfile(prev => ({
|
||||
...prev,
|
||||
rule_sets: {
|
||||
...prev.rule_sets,
|
||||
minimum_requirements: {
|
||||
...prev.rule_sets.minimum_requirements,
|
||||
rules: [...prev.rule_sets.minimum_requirements.rules, newRule]
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
const updateRule = (index, updates) => {
|
||||
setProfile(prev => {
|
||||
const rules = [...prev.rule_sets.minimum_requirements.rules]
|
||||
rules[index] = { ...rules[index], ...updates }
|
||||
return {
|
||||
...prev,
|
||||
rule_sets: {
|
||||
...prev.rule_sets,
|
||||
minimum_requirements: {
|
||||
...prev.rule_sets.minimum_requirements,
|
||||
rules
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const removeRule = (index) => {
|
||||
setProfile(prev => ({
|
||||
...prev,
|
||||
rule_sets: {
|
||||
...prev.rule_sets,
|
||||
minimum_requirements: {
|
||||
...prev.rule_sets.minimum_requirements,
|
||||
rules: prev.rule_sets.minimum_requirements.rules.filter((_, i) => i !== index)
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
await onSave(profile)
|
||||
setSuccessMessage('✓ Profil gespeichert!')
|
||||
setTimeout(() => {
|
||||
setSuccessMessage(null)
|
||||
}, 2000)
|
||||
} catch (err) {
|
||||
// Error is already handled by parent
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!profile) return <div className="spinner" />
|
||||
|
||||
const minReq = profile.rule_sets.minimum_requirements
|
||||
|
||||
return (
|
||||
<div style={{ background: 'var(--surface)', borderRadius: '12px', padding: '20px' }}>
|
||||
<div style={{ marginBottom: '20px' }}>
|
||||
<h3 style={{ marginBottom: '8px' }}>
|
||||
{trainingType.icon} {trainingType.name_de} - Profil konfigurieren
|
||||
</h3>
|
||||
<p style={{ fontSize: '13px', color: 'var(--text2)' }}>
|
||||
Definiere Mindestanforderungen und Bewertungskriterien für diesen Trainingstyp
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Success Message */}
|
||||
{successMessage && (
|
||||
<div style={{
|
||||
padding: '12px',
|
||||
background: 'var(--accent)',
|
||||
color: 'white',
|
||||
borderRadius: '8px',
|
||||
marginBottom: '16px',
|
||||
fontSize: '14px',
|
||||
fontWeight: '600'
|
||||
}}>
|
||||
{successMessage}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Minimum Requirements */}
|
||||
<div className="card" style={{ marginBottom: '16px' }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
cursor: 'pointer'
|
||||
}}
|
||||
onClick={() => toggleSection('minReq')}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<h4 style={{ margin: 0 }}>Mindestanforderungen</h4>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '13px' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={minReq.enabled}
|
||||
onChange={(e) => {
|
||||
e.stopPropagation()
|
||||
updateRuleSet('minimum_requirements', { enabled: e.target.checked })
|
||||
}}
|
||||
/>
|
||||
Aktiviert
|
||||
</label>
|
||||
</div>
|
||||
{expandedSections.minReq ? <ChevronUp size={18} /> : <ChevronDown size={18} />}
|
||||
</div>
|
||||
|
||||
{expandedSections.minReq && minReq.enabled && (
|
||||
<div style={{ marginTop: '16px' }}>
|
||||
{/* Strategy */}
|
||||
<div style={{ marginBottom: '16px', paddingBottom: '16px', borderBottom: '1px solid var(--border)' }}>
|
||||
<div className="form-row" style={{ marginBottom: '8px' }}>
|
||||
<label className="form-label">Pass-Strategie</label>
|
||||
<select
|
||||
className="form-select"
|
||||
value={minReq.pass_strategy}
|
||||
onChange={(e) => updateRuleSet('minimum_requirements', { pass_strategy: e.target.value })}
|
||||
>
|
||||
{PASS_STRATEGIES.map(s => (
|
||||
<option key={s.value} value={s.value}>{s.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{minReq.pass_strategy === 'weighted_score' && (
|
||||
<div className="form-row">
|
||||
<label className="form-label">Threshold (Score 0-1)</label>
|
||||
<input
|
||||
type="number"
|
||||
className="form-input"
|
||||
step="0.1"
|
||||
min="0"
|
||||
max="1"
|
||||
value={minReq.pass_threshold}
|
||||
onChange={(e) => updateRuleSet('minimum_requirements', { pass_threshold: parseFloat(e.target.value) })}
|
||||
/>
|
||||
<span className="form-unit">{(minReq.pass_threshold * 100).toFixed(0)}%</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Rules */}
|
||||
<div style={{ marginBottom: '16px' }}>
|
||||
<div style={{ fontWeight: '600', fontSize: '14px', marginBottom: '12px' }}>
|
||||
Regeln ({minReq.rules.length})
|
||||
</div>
|
||||
|
||||
{minReq.rules.map((rule, idx) => {
|
||||
const param = parameters.find(p => p.key === rule.parameter)
|
||||
const availableOps = OPERATORS.filter(op =>
|
||||
param ? op.types.includes(param.data_type) : true
|
||||
)
|
||||
const useWeights = minReq.pass_strategy === 'weighted_score'
|
||||
|
||||
return (
|
||||
<div
|
||||
key={idx}
|
||||
style={{
|
||||
background: 'var(--surface2)',
|
||||
padding: '12px',
|
||||
borderRadius: '8px',
|
||||
marginBottom: '8px'
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '12px' }}>
|
||||
<div style={{ fontSize: '12px', fontWeight: '600', color: 'var(--text2)' }}>
|
||||
Regel {idx + 1}
|
||||
</div>
|
||||
<button
|
||||
className="btn"
|
||||
onClick={() => removeRule(idx)}
|
||||
style={{ padding: '4px 8px', minWidth: 'auto', fontSize: '11px' }}
|
||||
title="Regel löschen"
|
||||
>
|
||||
<Trash2 size={12} /> Löschen
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Parameter */}
|
||||
<div style={{ marginBottom: '8px' }}>
|
||||
<label style={{ fontSize: '11px', color: 'var(--text3)', fontWeight: '600', display: 'block', marginBottom: '4px' }}>
|
||||
WAS soll geprüft werden?
|
||||
</label>
|
||||
<select
|
||||
className="form-select"
|
||||
value={rule.parameter}
|
||||
onChange={(e) => updateRule(idx, { parameter: e.target.value })}
|
||||
style={{ fontSize: '13px', width: '100%' }}
|
||||
>
|
||||
{parameters.map(p => (
|
||||
<option key={p.key} value={p.key}>
|
||||
{p.name_de} ({p.unit || p.data_type})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Operator + Value */}
|
||||
<div style={{ marginBottom: '8px' }}>
|
||||
<label style={{ fontSize: '11px', color: 'var(--text3)', fontWeight: '600', display: 'block', marginBottom: '4px' }}>
|
||||
BEDINGUNG
|
||||
</label>
|
||||
<div style={{ display: 'flex', gap: '8px', alignItems: 'flex-start' }}>
|
||||
<select
|
||||
className="form-select"
|
||||
value={rule.operator}
|
||||
onChange={(e) => updateRule(idx, { operator: e.target.value })}
|
||||
style={{ fontSize: '13px', flex: rule.operator === 'between' ? '0 0 80px' : '0 0 100px' }}
|
||||
>
|
||||
{availableOps.map(op => (
|
||||
<option key={op.value} value={op.value}>{op.label}</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
{rule.operator === 'between' ? (
|
||||
<div style={{ flex: 1, display: 'flex', gap: '4px' }}>
|
||||
<input
|
||||
type="number"
|
||||
className="form-input"
|
||||
placeholder="Min"
|
||||
value={Array.isArray(rule.value) ? rule.value[0] : 0}
|
||||
onChange={(e) => updateRule(idx, {
|
||||
value: [parseFloat(e.target.value) || 0, Array.isArray(rule.value) ? rule.value[1] : 0]
|
||||
})}
|
||||
style={{ fontSize: '13px', flex: 1 }}
|
||||
/>
|
||||
<input
|
||||
type="number"
|
||||
className="form-input"
|
||||
placeholder="Max"
|
||||
value={Array.isArray(rule.value) ? rule.value[1] : 0}
|
||||
onChange={(e) => updateRule(idx, {
|
||||
value: [Array.isArray(rule.value) ? rule.value[0] : 0, parseFloat(e.target.value) || 0]
|
||||
})}
|
||||
style={{ fontSize: '13px', flex: 1 }}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<input
|
||||
type="number"
|
||||
className="form-input"
|
||||
placeholder="z.B. 90"
|
||||
value={rule.value}
|
||||
onChange={(e) => updateRule(idx, { value: parseFloat(e.target.value) || 0 })}
|
||||
style={{ fontSize: '13px', flex: 1 }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Weight - nur bei weighted_score */}
|
||||
{useWeights && (
|
||||
<div style={{ marginBottom: '8px', paddingTop: '8px', borderTop: '1px dashed var(--border)' }}>
|
||||
<label style={{ fontSize: '11px', color: 'var(--text3)', fontWeight: '600', display: 'block', marginBottom: '4px' }}>
|
||||
WICHTIGKEIT dieser Regel (1 = unwichtig, 10 = sehr wichtig)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
className="form-input"
|
||||
placeholder="1-10"
|
||||
min="1"
|
||||
max="10"
|
||||
value={rule.weight}
|
||||
onChange={(e) => updateRule(idx, { weight: parseInt(e.target.value) || 1 })}
|
||||
style={{ fontSize: '13px', width: '80px' }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Reason */}
|
||||
<div style={{ marginBottom: '8px' }}>
|
||||
<label style={{ fontSize: '11px', color: 'var(--text3)', fontWeight: '600', display: 'block', marginBottom: '4px' }}>
|
||||
Begründung (optional)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
placeholder="z.B. 'Techniktraining sollte ruhig sein'"
|
||||
value={rule.reason}
|
||||
onChange={(e) => updateRule(idx, { reason: e.target.value })}
|
||||
style={{ fontSize: '12px', width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Optional Checkbox */}
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '12px', color: 'var(--text2)' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={rule.optional}
|
||||
onChange={(e) => updateRule(idx, { optional: e.target.checked })}
|
||||
/>
|
||||
Optional (Regel wird übersprungen wenn Parameter fehlt)
|
||||
</label>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
<button
|
||||
className="btn btn-secondary btn-full"
|
||||
onClick={addRule}
|
||||
style={{ marginTop: '8px' }}
|
||||
>
|
||||
<Plus size={14} /> Regel hinzufügen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Other Rule Sets - Future Features */}
|
||||
<div className="card" style={{ marginBottom: '16px', padding: '12px', background: 'var(--surface2)' }}>
|
||||
<div style={{ fontSize: '13px', color: 'var(--text2)' }}>
|
||||
<strong>Weitere Dimensionen</strong> (Analyse & Entwicklung, folgen später):
|
||||
<br />
|
||||
<span style={{ fontSize: '12px', lineHeight: '1.6', display: 'block', marginTop: '4px' }}>
|
||||
• <strong>Intensitätszonen:</strong> HF-Zonen-Verteilung analysieren<br />
|
||||
• <strong>Training Effects:</strong> Fähigkeitenentwicklung tracken<br />
|
||||
• <strong>Periodization:</strong> Frequenz & Recovery planen<br />
|
||||
• <strong>Performance:</strong> Fortschritt messen (Benchmarks, Trends)<br />
|
||||
• <strong>Safety:</strong> Warnungen bei Überbelastung
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div style={{ display: 'flex', gap: '12px', marginTop: '20px' }}>
|
||||
<button
|
||||
className="btn btn-primary"
|
||||
onClick={handleSave}
|
||||
disabled={loading}
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
💾 {loading ? 'Speichern...' : 'Profil speichern'}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-secondary"
|
||||
onClick={onCancel}
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { api } from '../utils/api'
|
||||
import dayjs from 'dayjs'
|
||||
import 'dayjs/locale/de'
|
||||
dayjs.locale('de')
|
||||
|
||||
const FOCUS_ICONS = {
|
||||
muscle_recovery: '💪',
|
||||
cardio_recovery: '🏃',
|
||||
mental_rest: '🧘',
|
||||
deload: '📉',
|
||||
injury: '🩹',
|
||||
}
|
||||
|
||||
const FOCUS_LABELS = {
|
||||
muscle_recovery: 'Muskelregeneration',
|
||||
cardio_recovery: 'Cardio-Erholung',
|
||||
mental_rest: 'Mentale Erholung',
|
||||
deload: 'Deload',
|
||||
injury: 'Verletzungspause',
|
||||
}
|
||||
|
||||
const FOCUS_COLORS = {
|
||||
muscle_recovery: '#D85A30',
|
||||
cardio_recovery: '#378ADD',
|
||||
mental_rest: '#7B68EE',
|
||||
deload: '#E67E22',
|
||||
injury: '#E74C3C',
|
||||
}
|
||||
|
||||
export default function RestDaysWidget() {
|
||||
const [todayRestDays, setTodayRestDays] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const nav = useNavigate()
|
||||
|
||||
useEffect(() => {
|
||||
loadTodayRestDays()
|
||||
}, [])
|
||||
|
||||
const loadTodayRestDays = async () => {
|
||||
try {
|
||||
const today = dayjs().format('YYYY-MM-DD')
|
||||
const allRestDays = await api.listRestDays(7) // Last 7 days
|
||||
const todayOnly = allRestDays.filter(d => d.date === today)
|
||||
setTodayRestDays(todayOnly)
|
||||
} catch (err) {
|
||||
console.error('Failed to load rest days:', err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="card">
|
||||
<div className="card-title">🛌 Ruhetage</div>
|
||||
<div style={{ padding: '20px 0', textAlign: 'center', color: 'var(--text3)' }}>
|
||||
Lädt...
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="card">
|
||||
<div className="card-title">🛌 Ruhetage</div>
|
||||
|
||||
{todayRestDays.length === 0 ? (
|
||||
<div style={{ padding: '12px 0', color: 'var(--text3)', fontSize: 13 }}>
|
||||
Heute kein Ruhetag geplant
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||
{todayRestDays.map(day => {
|
||||
const focus = day.rest_config?.focus || 'mental_rest'
|
||||
const icon = FOCUS_ICONS[focus] || '📅'
|
||||
const label = FOCUS_LABELS[focus] || focus
|
||||
const color = FOCUS_COLORS[focus] || '#888'
|
||||
|
||||
return (
|
||||
<div
|
||||
key={day.id}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 10,
|
||||
padding: '8px 10px',
|
||||
borderRadius: 8,
|
||||
background: `${color}14`,
|
||||
border: `1px solid ${color}`,
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: 20 }}>{icon}</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 13, fontWeight: 600, color }}>
|
||||
{label}
|
||||
</div>
|
||||
{day.note && (
|
||||
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 2 }}>
|
||||
{day.note}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
className="btn btn-secondary btn-full"
|
||||
style={{ marginTop: 12, fontSize: 13 }}
|
||||
onClick={() => nav('/rest-days')}
|
||||
>
|
||||
Ruhetage verwalten
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Moon, Plus } from 'lucide-react'
|
||||
import { api } from '../utils/api'
|
||||
|
||||
/**
|
||||
* SleepWidget - Dashboard widget for sleep tracking (v9d Phase 2b)
|
||||
*
|
||||
* Shows:
|
||||
* - Last night's sleep (if exists)
|
||||
* - 7-day average
|
||||
* - Quick action button to add entry or view details
|
||||
*/
|
||||
export default function SleepWidget() {
|
||||
const nav = useNavigate()
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [lastNight, setLastNight] = useState(null)
|
||||
const [stats, setStats] = useState(null)
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [])
|
||||
|
||||
const load = () => {
|
||||
Promise.all([
|
||||
api.listSleep(1), // Get last entry
|
||||
api.getSleepStats(7).catch(() => null) // Stats optional
|
||||
]).then(([sleepData, statsData]) => {
|
||||
setLastNight(sleepData[0] || null)
|
||||
setStats(statsData)
|
||||
setLoading(false)
|
||||
}).catch(err => {
|
||||
console.error('Failed to load sleep widget:', err)
|
||||
setLoading(false)
|
||||
})
|
||||
}
|
||||
|
||||
const formatDuration = (minutes) => {
|
||||
const h = Math.floor(minutes / 60)
|
||||
const m = minutes % 60
|
||||
return `${h}h ${m}min`
|
||||
}
|
||||
|
||||
const renderStars = (quality) => {
|
||||
if (!quality) return '—'
|
||||
return '★'.repeat(quality) + '☆'.repeat(5 - quality)
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="card" style={{ padding: 16 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
|
||||
<Moon size={16} color="var(--accent)" />
|
||||
<div style={{ fontWeight: 600, fontSize: 14 }}>Schlaf</div>
|
||||
</div>
|
||||
<div style={{ textAlign: 'center', padding: 20 }}>
|
||||
<div className="spinner" style={{ width: 20, height: 20, margin: '0 auto' }} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="card" style={{ padding: 16 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
|
||||
<Moon size={16} color="var(--accent)" />
|
||||
<div style={{ fontWeight: 600, fontSize: 14 }}>Schlaf</div>
|
||||
</div>
|
||||
|
||||
{lastNight ? (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
<div style={{ fontSize: 12, color: 'var(--text3)' }}>Letzte Nacht:</div>
|
||||
<div style={{ fontSize: 16, fontWeight: 700 }}>
|
||||
{lastNight.duration_formatted} {lastNight.quality && `· ${renderStars(lastNight.quality)}`}
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--text3)' }}>
|
||||
{new Date(lastNight.date).toLocaleDateString('de-DE', { weekday: 'short', day: '2-digit', month: '2-digit' })}
|
||||
</div>
|
||||
|
||||
{stats && stats.total_nights > 0 && (
|
||||
<div style={{ marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--border)' }}>
|
||||
<div style={{ fontSize: 11, color: 'var(--text3)' }}>Ø 7 Tage:</div>
|
||||
<div style={{ fontSize: 13, fontWeight: 600 }}>
|
||||
{formatDuration(Math.round(stats.avg_duration_minutes))}
|
||||
{stats.avg_quality && ` · ${stats.avg_quality.toFixed(1)}/5`}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ textAlign: 'center', padding: '12px 0', color: 'var(--text3)' }}>
|
||||
<div style={{ fontSize: 12, marginBottom: 12 }}>Noch keine Einträge erfasst</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={() => nav('/sleep')}
|
||||
className="btn btn-secondary btn-full"
|
||||
style={{ marginTop: 12, fontSize: 12 }}
|
||||
>
|
||||
{lastNight ? (
|
||||
<>Zur Übersicht</>
|
||||
) : (
|
||||
<>
|
||||
<Plus size={14} /> Schlaf erfassen
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { PieChart, Pie, Cell, ResponsiveContainer, Legend, Tooltip } from 'recharts'
|
||||
import { api } from '../utils/api'
|
||||
import { useProfile } from '../context/ProfileContext'
|
||||
|
||||
/**
|
||||
* TrainingTypeDistribution - Pie chart showing activity distribution by type
|
||||
*
|
||||
* @param {number} days - Number of days to analyze (default: 28)
|
||||
*/
|
||||
export default function TrainingTypeDistribution({ days = 28 }) {
|
||||
const { activeProfile } = useProfile() // Issue #31: Trigger reload on quality filter change
|
||||
const [data, setData] = useState([])
|
||||
const [categories, setCategories] = useState({})
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([
|
||||
api.listActivity(days),
|
||||
api.getTrainingCategories()
|
||||
]).then(([activities, cats]) => {
|
||||
setCategories(cats)
|
||||
|
||||
// Group by training_category
|
||||
const grouped = {}
|
||||
activities.forEach(act => {
|
||||
const cat = act.training_category || 'other'
|
||||
if (!grouped[cat]) grouped[cat] = 0
|
||||
grouped[cat]++
|
||||
})
|
||||
|
||||
// Convert to chart data
|
||||
const chartData = Object.entries(grouped).map(([cat, count]) => ({
|
||||
name: cats[cat]?.name_de || 'Sonstiges',
|
||||
value: count,
|
||||
color: cats[cat]?.color || '#9CA3AF',
|
||||
icon: cats[cat]?.icon || '📝'
|
||||
}))
|
||||
|
||||
setData(chartData.sort((a, b) => b.value - a.value))
|
||||
setLoading(false)
|
||||
}).catch(err => {
|
||||
console.error('Failed to load training type distribution:', err)
|
||||
setLoading(false)
|
||||
})
|
||||
}, [days, activeProfile?.quality_filter_level]) // Issue #31: Reload when quality filter changes
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{textAlign:'center', padding:20}}>
|
||||
<div className="spinner" style={{width:24, height:24, margin:'0 auto'}}/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (data.length === 0) {
|
||||
return (
|
||||
<div style={{textAlign:'center', padding:20, color:'var(--text3)', fontSize:13}}>
|
||||
Keine Aktivitäten in den letzten {days} Tagen
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const total = data.reduce((sum, d) => sum + d.value, 0)
|
||||
|
||||
return (
|
||||
<div>
|
||||
<ResponsiveContainer width="100%" height={200}>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={data}
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
innerRadius={50}
|
||||
outerRadius={80}
|
||||
paddingAngle={2}
|
||||
dataKey="value"
|
||||
>
|
||||
{data.map((entry, index) => (
|
||||
<Cell key={`cell-${index}`} fill={entry.color} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip
|
||||
formatter={(value) => `${value} Einheiten (${Math.round(value/total*100)}%)`}
|
||||
contentStyle={{
|
||||
background:'var(--surface)',
|
||||
border:'1px solid var(--border)',
|
||||
borderRadius:8,
|
||||
fontSize:12
|
||||
}}
|
||||
/>
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
|
||||
{/* Legend */}
|
||||
<div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, marginTop:12}}>
|
||||
{data.map((entry, i) => (
|
||||
<div key={i} style={{display:'flex', alignItems:'center', gap:6, fontSize:12}}>
|
||||
<div style={{
|
||||
width:12, height:12, borderRadius:'50%',
|
||||
background:entry.color, flexShrink:0
|
||||
}}/>
|
||||
<span style={{color:'var(--text2)'}}>
|
||||
{entry.icon} {entry.name}
|
||||
</span>
|
||||
<span style={{marginLeft:'auto', fontWeight:600, color:'var(--text1)'}}>
|
||||
{entry.value}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div style={{
|
||||
marginTop:12, padding:'8px 12px',
|
||||
background:'var(--surface)', borderRadius:8,
|
||||
fontSize:12, color:'var(--text3)', textAlign:'center'
|
||||
}}>
|
||||
Gesamt: <strong style={{color:'var(--text1)'}}>{total}</strong> Einheiten in {days} Tagen
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { api } from '../utils/api'
|
||||
|
||||
/**
|
||||
* TrainingTypeSelect - Two-level dropdown for training type selection
|
||||
*
|
||||
* @param {number|null} value - Selected training_type_id
|
||||
* @param {function} onChange - Callback (training_type_id, category, subcategory) => void
|
||||
* @param {boolean} required - Is selection required?
|
||||
*/
|
||||
export default function TrainingTypeSelect({ value, onChange, required = false }) {
|
||||
const [types, setTypes] = useState({}) // Grouped by category
|
||||
const [categories, setCategories] = useState({}) // Category metadata
|
||||
const [selectedCategory, setSelectedCategory] = useState('')
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([
|
||||
api.listTrainingTypes(),
|
||||
api.getTrainingCategories()
|
||||
]).then(([typesData, catsData]) => {
|
||||
setTypes(typesData)
|
||||
setCategories(catsData)
|
||||
|
||||
// If value is set, find and select the category
|
||||
if (value) {
|
||||
for (const cat in typesData) {
|
||||
const found = typesData[cat].find(t => t.id === value)
|
||||
if (found) {
|
||||
setSelectedCategory(cat)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setLoading(false)
|
||||
}).catch(err => {
|
||||
console.error('Failed to load training types:', err)
|
||||
setLoading(false)
|
||||
})
|
||||
}, [value])
|
||||
|
||||
const handleCategoryChange = (cat) => {
|
||||
setSelectedCategory(cat)
|
||||
// Auto-select first subcategory if available
|
||||
if (types[cat] && types[cat].length > 0) {
|
||||
const firstType = types[cat][0]
|
||||
onChange(firstType.id, firstType.category, firstType.subcategory)
|
||||
} else {
|
||||
onChange(null, null, null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleTypeChange = (typeId) => {
|
||||
const type = Object.values(types)
|
||||
.flat()
|
||||
.find(t => t.id === parseInt(typeId))
|
||||
|
||||
if (type) {
|
||||
onChange(type.id, type.category, type.subcategory)
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return <div style={{fontSize:13, color:'var(--text3)'}}>Lade Trainingstypen...</div>
|
||||
}
|
||||
|
||||
const availableCategories = Object.keys(categories)
|
||||
const availableTypes = selectedCategory ? (types[selectedCategory] || []) : []
|
||||
|
||||
return (
|
||||
<div style={{display:'flex', gap:8, flexDirection:'column'}}>
|
||||
{/* Category dropdown */}
|
||||
<div>
|
||||
<label className="form-label">Kategorie</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={selectedCategory}
|
||||
onChange={(e) => handleCategoryChange(e.target.value)}
|
||||
required={required}
|
||||
style={{width:'100%', boxSizing:'border-box'}}
|
||||
>
|
||||
<option value="">-- Wähle Kategorie --</option>
|
||||
{availableCategories.map(cat => (
|
||||
<option key={cat} value={cat}>
|
||||
{categories[cat].icon} {categories[cat].name_de}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Subcategory dropdown (conditional) */}
|
||||
{selectedCategory && availableTypes.length > 0 && (
|
||||
<div>
|
||||
<label className="form-label">Untertyp</label>
|
||||
<select
|
||||
className="form-input"
|
||||
value={value || ''}
|
||||
onChange={(e) => handleTypeChange(e.target.value)}
|
||||
required={required}
|
||||
style={{width:'100%', boxSizing:'border-box'}}
|
||||
>
|
||||
<option value="">-- Wähle Untertyp --</option>
|
||||
{availableTypes.map(type => (
|
||||
<option key={type.id} value={type.id}>
|
||||
{type.icon} {type.name_de}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
|
||||
export default function TrialBanner({ profile }) {
|
||||
const [daysLeft, setDaysLeft] = useState(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!profile?.trial_ends_at) {
|
||||
setDaysLeft(null)
|
||||
return
|
||||
}
|
||||
|
||||
const trialEnd = new Date(profile.trial_ends_at)
|
||||
const now = new Date()
|
||||
const diff = trialEnd - now
|
||||
const days = Math.ceil(diff / (1000 * 60 * 60 * 24))
|
||||
|
||||
setDaysLeft(days)
|
||||
}, [profile])
|
||||
|
||||
// No trial or trial ended
|
||||
if (daysLeft === null || daysLeft <= 0) return null
|
||||
|
||||
// Determine severity
|
||||
const isUrgent = daysLeft <= 3
|
||||
const isWarning = daysLeft <= 7
|
||||
|
||||
const bgColor = isUrgent ? '#FCEBEB' : isWarning ? '#FFF4E6' : 'var(--accent-light)'
|
||||
const borderColor = isUrgent ? '#D85A30' : isWarning ? '#F59E0B' : 'var(--accent)'
|
||||
const textColor = isUrgent ? '#D85A30' : isWarning ? '#D97706' : 'var(--accent-dark)'
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
background: bgColor,
|
||||
border: `2px solid ${borderColor}`,
|
||||
borderRadius: 12,
|
||||
padding: '16px 20px',
|
||||
marginBottom: 20,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
flexWrap: 'wrap',
|
||||
gap: 12
|
||||
}}>
|
||||
<div style={{flex: 1, minWidth: 200}}>
|
||||
<div style={{
|
||||
fontWeight: 700,
|
||||
fontSize: 15,
|
||||
color: textColor,
|
||||
marginBottom: 4
|
||||
}}>
|
||||
{isUrgent && '⚠️ '}
|
||||
Deine Trial endet {daysLeft === 1 ? 'morgen' : `in ${daysLeft} Tagen`}
|
||||
</div>
|
||||
<div style={{
|
||||
fontSize: 13,
|
||||
color: 'var(--text2)',
|
||||
lineHeight: 1.4
|
||||
}}>
|
||||
{isUrgent
|
||||
? 'Upgrade jetzt um weiterhin alle Features nutzen zu können'
|
||||
: 'Wähle ein Abo um unbegrenzt Zugriff zu erhalten'
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a
|
||||
href="mailto:mitai@jinkendo.de?subject=Abo-Anfrage%20für%20Mitai%20Jinkendo&body=Hallo,%0A%0Aich%20möchte%20gerne%20ein%20Abo%20für%20Mitai%20Jinkendo%20abschließen.%0A%0AMein%20Profil:%20"
|
||||
style={{
|
||||
padding: '10px 20px',
|
||||
borderRadius: 8,
|
||||
background: isUrgent ? '#D85A30' : 'var(--accent)',
|
||||
color: 'white',
|
||||
fontWeight: 600,
|
||||
fontSize: 14,
|
||||
textDecoration: 'none',
|
||||
whiteSpace: 'nowrap',
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
display: 'inline-block'
|
||||
}}
|
||||
>
|
||||
{isUrgent ? 'Kontakt aufnehmen' : 'Abo anfragen'}
|
||||
</a>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -86,6 +86,18 @@ export function AuthProvider({ children }) {
|
||||
return data
|
||||
}
|
||||
|
||||
const setAuthFromToken = (token, profile) => {
|
||||
// Direct token/profile set (for email verification auto-login)
|
||||
localStorage.setItem(TOKEN_KEY, token)
|
||||
localStorage.setItem(PROFILE_KEY, profile.id)
|
||||
setSession({
|
||||
token,
|
||||
profile_id: profile.id,
|
||||
role: profile.role || 'user',
|
||||
profile
|
||||
})
|
||||
}
|
||||
|
||||
const logout = async () => {
|
||||
const token = localStorage.getItem(TOKEN_KEY)
|
||||
if (token) {
|
||||
@@ -102,7 +114,7 @@ export function AuthProvider({ children }) {
|
||||
return (
|
||||
<AuthContext.Provider value={{
|
||||
session, loading, needsSetup,
|
||||
login, setup, logout,
|
||||
login, setup, logout, setAuthFromToken,
|
||||
isAdmin, canUseAI, canExport,
|
||||
token: session?.token,
|
||||
profileId: session?.profile_id,
|
||||
|
||||
@@ -2,6 +2,9 @@ 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 TrainingTypeSelect from '../components/TrainingTypeSelect'
|
||||
import BulkCategorize from '../components/BulkCategorize'
|
||||
import dayjs from 'dayjs'
|
||||
import 'dayjs/locale/de'
|
||||
dayjs.locale('de')
|
||||
@@ -17,7 +20,10 @@ function empty() {
|
||||
date: dayjs().format('YYYY-MM-DD'),
|
||||
activity_type: 'Traditionelles Krafttraining',
|
||||
duration_min: '', kcal_active: '',
|
||||
hr_avg: '', hr_max: '', rpe: '', notes: ''
|
||||
hr_avg: '', hr_max: '', rpe: '', notes: '',
|
||||
training_type_id: null,
|
||||
training_category: null,
|
||||
training_subcategory: null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,7 +85,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>
|
||||
@@ -88,11 +94,19 @@ function EntryForm({ form, setForm, onSave, onCancel, saveLabel='Speichern' }) {
|
||||
<input type="date" className="form-input" style={{width:140}} value={form.date} onChange={e=>set('date',e.target.value)}/>
|
||||
<span className="form-unit"/>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Trainingsart</label>
|
||||
<select className="form-select" value={form.activity_type} onChange={e=>set('activity_type',e.target.value)}>
|
||||
{ACTIVITY_TYPES.map(t=><option key={t} value={t}>{t}</option>)}
|
||||
</select>
|
||||
<div style={{marginBottom:12}}>
|
||||
<TrainingTypeSelect
|
||||
value={form.training_type_id}
|
||||
onChange={(typeId, category, subcategory) => {
|
||||
setForm(f => ({
|
||||
...f,
|
||||
training_type_id: typeId,
|
||||
training_category: category,
|
||||
training_subcategory: subcategory
|
||||
}))
|
||||
}}
|
||||
required={false}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Dauer</label>
|
||||
@@ -130,8 +144,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 +176,53 @@ 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 [categories, setCategories] = useState({}) // v9d: Training categories
|
||||
|
||||
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()
|
||||
api.getTrainingCategories().then(setCategories).catch(err => console.error('Failed to load categories:', err))
|
||||
},[])
|
||||
|
||||
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 () => {
|
||||
@@ -202,6 +261,7 @@ export default function ActivityPage() {
|
||||
<button className={'tab'+(tab==='list'?' active':'')} onClick={()=>setTab('list')}>Verlauf</button>
|
||||
<button className={'tab'+(tab==='add'?' active':'')} onClick={()=>setTab('add')}>+ Manuell</button>
|
||||
<button className={'tab'+(tab==='import'?' active':'')} onClick={()=>setTab('import')}>Import</button>
|
||||
<button className={'tab'+(tab==='categorize'?' active':'')} onClick={()=>setTab('categorize')}>Kategorisieren</button>
|
||||
<button className={'tab'+(tab==='stats'?' active':'')} onClick={()=>setTab('stats')}>Statistik</button>
|
||||
</div>
|
||||
|
||||
@@ -223,11 +283,22 @@ export default function ActivityPage() {
|
||||
|
||||
{tab==='import' && <ImportPanel onImported={load}/>}
|
||||
|
||||
{tab==='categorize' && (
|
||||
<div className="card section-gap">
|
||||
<div className="card-title">🏷️ Aktivitäten kategorisieren</div>
|
||||
<BulkCategorize onComplete={() => { load(); setTab('list'); }} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{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>
|
||||
)}
|
||||
|
||||
@@ -282,7 +353,86 @@ export default function ActivityPage() {
|
||||
<div>
|
||||
<div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start'}}>
|
||||
<div style={{flex:1}}>
|
||||
<div style={{fontSize:14,fontWeight:600}}>{e.activity_type}</div>
|
||||
<div style={{display:'flex',alignItems:'center',gap:6,marginBottom:2}}>
|
||||
{/* Evaluation Status Indicator */}
|
||||
{e.quality_label ? (
|
||||
<div
|
||||
style={{
|
||||
display:'inline-flex',
|
||||
alignItems:'center',
|
||||
justifyContent:'center',
|
||||
width:18,
|
||||
height:18,
|
||||
borderRadius:9,
|
||||
background: e.quality_label === 'excellent' || e.quality_label === 'good' ? '#1D9E75' :
|
||||
e.quality_label === 'acceptable' ? '#EF9F27' : '#D85A30',
|
||||
color:'white',
|
||||
fontSize:10,
|
||||
fontWeight:700,
|
||||
flexShrink:0
|
||||
}}
|
||||
title={`Evaluation: ${e.quality_label} (Score: ${e.overall_score || 'n/a'})`}
|
||||
>
|
||||
✓
|
||||
</div>
|
||||
) : e.training_type_id ? (
|
||||
<div
|
||||
style={{
|
||||
display:'inline-flex',
|
||||
alignItems:'center',
|
||||
justifyContent:'center',
|
||||
width:18,
|
||||
height:18,
|
||||
borderRadius:9,
|
||||
background:'#EF9F27',
|
||||
color:'white',
|
||||
fontSize:10,
|
||||
fontWeight:700,
|
||||
flexShrink:0
|
||||
}}
|
||||
title="Trainingstyp zugeordnet, aber nicht evaluiert (kein Profil konfiguriert)"
|
||||
>
|
||||
⚠
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
style={{
|
||||
display:'inline-flex',
|
||||
alignItems:'center',
|
||||
justifyContent:'center',
|
||||
width:18,
|
||||
height:18,
|
||||
borderRadius:9,
|
||||
background:'#888780',
|
||||
color:'white',
|
||||
fontSize:10,
|
||||
fontWeight:700,
|
||||
flexShrink:0
|
||||
}}
|
||||
title="Kein Trainingstyp zugeordnet"
|
||||
>
|
||||
✕
|
||||
</div>
|
||||
)}
|
||||
<div style={{fontSize:14,fontWeight:600}}>{e.activity_type}</div>
|
||||
{e.training_category && categories[e.training_category] && (
|
||||
<div style={{
|
||||
display:'inline-flex',
|
||||
alignItems:'center',
|
||||
gap:3,
|
||||
padding:'2px 6px',
|
||||
background:categories[e.training_category].color + '22',
|
||||
border:`1px solid ${categories[e.training_category].color}`,
|
||||
borderRadius:4,
|
||||
fontSize:10,
|
||||
fontWeight:600,
|
||||
color:categories[e.training_category].color
|
||||
}}>
|
||||
<span>{categories[e.training_category].icon}</span>
|
||||
<span>{categories[e.training_category].name_de}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div style={{fontSize:11,color:'var(--text3)',marginBottom:4}}>
|
||||
{dayjs(e.date).format('dd, DD. MMMM YYYY')}
|
||||
{e.start_time && e.start_time.length>10 && ` · ${e.start_time.slice(11,16)}`}
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Pencil, Trash2, Plus, Save, X, ArrowLeft, TrendingUp } from 'lucide-react'
|
||||
import { api } from '../utils/api'
|
||||
|
||||
/**
|
||||
* AdminActivityMappingsPage - Manage activity_type → training_type mappings
|
||||
* v9d Phase 1b - Learnable system (replaces hardcoded mappings)
|
||||
*/
|
||||
export default function AdminActivityMappingsPage() {
|
||||
const nav = useNavigate()
|
||||
const [mappings, setMappings] = useState([])
|
||||
const [trainingTypes, setTrainingTypes] = useState([])
|
||||
const [coverage, setCoverage] = useState(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [editingId, setEditingId] = useState(null)
|
||||
const [formData, setFormData] = useState(null)
|
||||
const [error, setError] = useState(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [filter, setFilter] = useState('all') // 'all', 'global', 'user'
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [filter])
|
||||
|
||||
const load = () => {
|
||||
setLoading(true)
|
||||
Promise.all([
|
||||
api.adminListActivityMappings(null, filter === 'global'),
|
||||
api.listTrainingTypesFlat(),
|
||||
api.adminGetMappingCoverage()
|
||||
]).then(([mappingsData, typesData, coverageData]) => {
|
||||
setMappings(mappingsData)
|
||||
setTrainingTypes(typesData)
|
||||
setCoverage(coverageData)
|
||||
setLoading(false)
|
||||
}).catch(err => {
|
||||
console.error('Failed to load mappings:', err)
|
||||
setError(err.message)
|
||||
setLoading(false)
|
||||
})
|
||||
}
|
||||
|
||||
const startCreate = () => {
|
||||
setFormData({
|
||||
activity_type: '',
|
||||
training_type_id: trainingTypes[0]?.id || null,
|
||||
profile_id: '',
|
||||
source: 'admin'
|
||||
})
|
||||
setEditingId('new')
|
||||
}
|
||||
|
||||
const startEdit = (mapping) => {
|
||||
setFormData({
|
||||
activity_type: mapping.activity_type,
|
||||
training_type_id: mapping.training_type_id,
|
||||
profile_id: mapping.profile_id || '',
|
||||
source: mapping.source
|
||||
})
|
||||
setEditingId(mapping.id)
|
||||
}
|
||||
|
||||
const cancelEdit = () => {
|
||||
setEditingId(null)
|
||||
setFormData(null)
|
||||
setError(null)
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!formData.activity_type || !formData.training_type_id) {
|
||||
setError('Activity Type und Training Type sind Pflichtfelder')
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
...formData,
|
||||
profile_id: formData.profile_id || null
|
||||
}
|
||||
|
||||
if (editingId === 'new') {
|
||||
await api.adminCreateActivityMapping(payload)
|
||||
} else {
|
||||
await api.adminUpdateActivityMapping(editingId, {
|
||||
training_type_id: payload.training_type_id,
|
||||
profile_id: payload.profile_id,
|
||||
source: payload.source
|
||||
})
|
||||
}
|
||||
await load()
|
||||
cancelEdit()
|
||||
} catch (err) {
|
||||
console.error('Save failed:', err)
|
||||
setError(err.message)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id, activityType) => {
|
||||
if (!confirm(`Mapping für "${activityType}" wirklich löschen?\n\nZukünftige Imports werden diesen Typ nicht mehr automatisch zuordnen.`)) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await api.adminDeleteActivityMapping(id)
|
||||
await load()
|
||||
} catch (err) {
|
||||
alert('Löschen fehlgeschlagen: ' + err.message)
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{ padding: 20, textAlign: 'center' }}>
|
||||
<div className="spinner" style={{ width: 32, height: 32, margin: '0 auto' }} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const coveragePercent = coverage ? Math.round((coverage.mapped_activities / coverage.total_activities) * 100) : 0
|
||||
|
||||
return (
|
||||
<div style={{ padding: '16px 16px 80px' }}>
|
||||
<div style={{ marginBottom: 20, display: 'flex', alignItems: 'center', gap: 12 }}>
|
||||
<button
|
||||
onClick={() => nav('/settings')}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
padding: 6,
|
||||
display: 'flex',
|
||||
color: 'var(--text2)'
|
||||
}}
|
||||
>
|
||||
<ArrowLeft size={20} />
|
||||
</button>
|
||||
<h1 style={{ margin: 0, fontSize: 20, fontWeight: 700 }}>Activity-Mappings</h1>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="card" style={{ padding: 12, marginBottom: 16, background: '#FCEBEB', color: '#D85A30' }}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Coverage Stats */}
|
||||
{coverage && (
|
||||
<div className="card" style={{ padding: 16, marginBottom: 16 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
|
||||
<TrendingUp size={16} color="var(--accent)" />
|
||||
<div style={{ fontWeight: 600, fontSize: 14 }}>Mapping-Abdeckung</div>
|
||||
</div>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, fontSize: 12 }}>
|
||||
<div style={{ textAlign: 'center', padding: 8, background: 'var(--surface)', borderRadius: 6 }}>
|
||||
<div style={{ fontSize: 18, fontWeight: 700, color: 'var(--accent)' }}>{coveragePercent}%</div>
|
||||
<div style={{ color: 'var(--text3)' }}>Zugeordnet</div>
|
||||
</div>
|
||||
<div style={{ textAlign: 'center', padding: 8, background: 'var(--surface)', borderRadius: 6 }}>
|
||||
<div style={{ fontSize: 18, fontWeight: 700 }}>{coverage.mapped_activities}</div>
|
||||
<div style={{ color: 'var(--text3)' }}>Mit Typ</div>
|
||||
</div>
|
||||
<div style={{ textAlign: 'center', padding: 8, background: 'var(--surface)', borderRadius: 6 }}>
|
||||
<div style={{ fontSize: 18, fontWeight: 700, color: '#D85A30' }}>{coverage.unmapped_activities}</div>
|
||||
<div style={{ color: 'var(--text3)' }}>Ohne Typ</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ marginTop: 8, fontSize: 11, color: 'var(--text3)' }}>
|
||||
{coverage.unmapped_types} verschiedene Activity-Types noch nicht gemappt
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Filter */}
|
||||
<div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
|
||||
<button
|
||||
onClick={() => setFilter('all')}
|
||||
className={filter === 'all' ? 'btn btn-primary' : 'btn btn-secondary'}
|
||||
style={{ flex: 1, fontSize: 12 }}
|
||||
>
|
||||
Alle ({mappings.length})
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setFilter('global')}
|
||||
className={filter === 'global' ? 'btn btn-primary' : 'btn btn-secondary'}
|
||||
style={{ flex: 1, fontSize: 12 }}
|
||||
>
|
||||
Global
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Create new button */}
|
||||
<button
|
||||
onClick={startCreate}
|
||||
className="btn btn-primary btn-full"
|
||||
style={{ marginBottom: 16 }}
|
||||
>
|
||||
<Plus size={16} /> Neues Mapping anlegen
|
||||
</button>
|
||||
|
||||
{/* New mapping form (only shown when creating) */}
|
||||
{editingId === 'new' && formData && (
|
||||
<div className="card" style={{ padding: 16, marginBottom: 16, border: '2px solid var(--accent)' }}>
|
||||
<div style={{ fontWeight: 600, marginBottom: 12 }}>➕ Neues Mapping</div>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
|
||||
<div>
|
||||
<div className="form-label">Activity Type * (exakt wie in CSV)</div>
|
||||
<input
|
||||
className="form-input"
|
||||
value={formData.activity_type}
|
||||
onChange={e => setFormData({ ...formData, activity_type: e.target.value })}
|
||||
placeholder="z.B. Traditionelles Krafttraining"
|
||||
style={{ width: '100%' }}
|
||||
autoFocus
|
||||
/>
|
||||
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 4 }}>
|
||||
Groß-/Kleinschreibung beachten! Muss exakt mit CSV übereinstimmen.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="form-label">Training Type *</div>
|
||||
<select
|
||||
className="form-input"
|
||||
value={formData.training_type_id}
|
||||
onChange={e => setFormData({ ...formData, training_type_id: parseInt(e.target.value) })}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
{trainingTypes.map(type => (
|
||||
<option key={type.id} value={type.id}>
|
||||
{type.icon} {type.name_de} ({type.category})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="form-label">Profil-ID (leer = global)</div>
|
||||
<input
|
||||
className="form-input"
|
||||
value={formData.profile_id}
|
||||
onChange={e => setFormData({ ...formData, profile_id: e.target.value })}
|
||||
placeholder="Leer lassen für globales Mapping"
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 4 }}>
|
||||
Global = für alle User, sonst user-spezifisch
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className="btn btn-primary"
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<div className="spinner" style={{ width: 14, height: 14 }} />
|
||||
Speichere...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save size={16} /> Speichern
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
onClick={cancelEdit}
|
||||
disabled={saving}
|
||||
className="btn btn-secondary"
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
<X size={16} /> Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* List with inline editing */}
|
||||
{mappings.length === 0 ? (
|
||||
<div className="card" style={{ padding: 40, textAlign: 'center', color: 'var(--text3)' }}>
|
||||
Keine Mappings gefunden
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{mappings.map(mapping => {
|
||||
const isEditing = editingId === mapping.id
|
||||
|
||||
return (
|
||||
<div
|
||||
key={mapping.id}
|
||||
className="card"
|
||||
style={{
|
||||
padding: 12,
|
||||
border: isEditing ? '2px solid var(--accent)' : undefined
|
||||
}}
|
||||
>
|
||||
{isEditing && formData ? (
|
||||
/* Inline edit form */
|
||||
<div>
|
||||
<div style={{ fontWeight: 600, marginBottom: 12, color: 'var(--accent)' }}>
|
||||
✏️ Mapping bearbeiten
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
<div>
|
||||
<div className="form-label">Activity Type (nicht änderbar)</div>
|
||||
<input
|
||||
className="form-input"
|
||||
value={formData.activity_type}
|
||||
disabled
|
||||
style={{ width: '100%', background: 'var(--surface2)' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="form-label">Training Type *</div>
|
||||
<select
|
||||
className="form-input"
|
||||
value={formData.training_type_id}
|
||||
onChange={e => setFormData({ ...formData, training_type_id: parseInt(e.target.value) })}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
{trainingTypes.map(type => (
|
||||
<option key={type.id} value={type.id}>
|
||||
{type.icon} {type.name_de} ({type.category})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="form-label">Profil-ID (leer = global)</div>
|
||||
<input
|
||||
className="form-input"
|
||||
value={formData.profile_id}
|
||||
onChange={e => setFormData({ ...formData, profile_id: e.target.value })}
|
||||
placeholder="Leer lassen für globales Mapping"
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className="btn btn-primary"
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
{saving ? (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, justifyContent: 'center' }}>
|
||||
<div className="spinner" style={{ width: 14, height: 14 }} />
|
||||
Speichere...
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Save size={16} /> Speichern
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
onClick={cancelEdit}
|
||||
disabled={saving}
|
||||
className="btn btn-secondary"
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
<X size={16} /> Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
/* Normal view */
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8
|
||||
}}>
|
||||
<div style={{ fontSize: 18 }}>{mapping.icon}</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 13, fontWeight: 600 }}>
|
||||
{mapping.activity_type}
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--text3)' }}>
|
||||
→ {mapping.training_type_name_de}
|
||||
{mapping.profile_id && <> · User-spezifisch</>}
|
||||
{!mapping.profile_id && <> · Global</>}
|
||||
{mapping.source && <> · {mapping.source}</>}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => startEdit(mapping)}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
padding: 6,
|
||||
color: 'var(--accent)'
|
||||
}}
|
||||
title="Bearbeiten"
|
||||
>
|
||||
<Pencil size={16} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(mapping.id, mapping.activity_type)}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
padding: 6,
|
||||
color: '#D85A30'
|
||||
}}
|
||||
title="Löschen"
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{
|
||||
marginTop: 20,
|
||||
padding: 12,
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: 8,
|
||||
fontSize: 12,
|
||||
color: 'var(--text3)'
|
||||
}}>
|
||||
<strong>💡 Tipp:</strong> Das System lernt automatisch! Wenn du im Tab "Kategorisieren" Aktivitäten zuordnest, wird das Mapping gespeichert und beim nächsten Import automatisch angewendet.
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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,70 @@ 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>
|
||||
|
||||
{/* v9d Training Types 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)"/> Trainingstypen (v9d)
|
||||
</div>
|
||||
<div style={{fontSize:12,color:'var(--text3)',marginBottom:12,lineHeight:1.5}}>
|
||||
Verwalte Trainingstypen, Kategorien und Activity-Mappings (lernendes System).
|
||||
</div>
|
||||
<div style={{display:'grid',gap:8}}>
|
||||
<Link to="/admin/training-types">
|
||||
<button className="btn btn-secondary btn-full">
|
||||
🏋️ Trainingstypen verwalten
|
||||
</button>
|
||||
</Link>
|
||||
<Link to="/admin/activity-mappings">
|
||||
<button className="btn btn-secondary btn-full">
|
||||
🔗 Activity-Mappings (lernendes System)
|
||||
</button>
|
||||
</Link>
|
||||
<Link to="/admin/training-profiles">
|
||||
<button className="btn btn-secondary btn-full">
|
||||
⭐ Training Type Profiles (#15)
|
||||
</button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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,307 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { api } from '../utils/api'
|
||||
import '../app.css'
|
||||
|
||||
export default function AdminTrainingProfiles() {
|
||||
const [stats, setStats] = useState(null)
|
||||
const [trainingTypes, setTrainingTypes] = useState([])
|
||||
const [templates, setTemplates] = useState([])
|
||||
const [selectedType, setSelectedType] = useState(null)
|
||||
const [editingProfile, setEditingProfile] = useState(null)
|
||||
const [profileJson, setProfileJson] = useState('')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [success, setSuccess] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [])
|
||||
|
||||
const load = async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
const [typesData, statsData, templatesData] = await Promise.all([
|
||||
api.adminListTrainingTypes(),
|
||||
api.getProfileStats(),
|
||||
api.getProfileTemplates()
|
||||
])
|
||||
setTrainingTypes(typesData)
|
||||
setStats(statsData)
|
||||
setTemplates(templatesData)
|
||||
} catch (e) {
|
||||
setError(e.message)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const openEditor = (type) => {
|
||||
setSelectedType(type)
|
||||
setEditingProfile(type.profile || null)
|
||||
setProfileJson(JSON.stringify(type.profile || {}, null, 2))
|
||||
setError('')
|
||||
setSuccess('')
|
||||
}
|
||||
|
||||
const closeEditor = () => {
|
||||
setSelectedType(null)
|
||||
setEditingProfile(null)
|
||||
setProfileJson('')
|
||||
}
|
||||
|
||||
const saveProfile = async () => {
|
||||
try {
|
||||
// Validate JSON
|
||||
const profile = JSON.parse(profileJson)
|
||||
|
||||
// Update training type
|
||||
await api.adminUpdateTrainingType(selectedType.id, { profile })
|
||||
|
||||
setSuccess(`Profil für "${selectedType.name_de}" gespeichert`)
|
||||
closeEditor()
|
||||
load()
|
||||
} catch (e) {
|
||||
setError(e.message || 'Ungültiges JSON')
|
||||
}
|
||||
}
|
||||
|
||||
const applyTemplate = async (typeId, templateKey) => {
|
||||
if (!confirm(`Template "${templateKey}" auf diesen Trainingstyp anwenden?`)) return
|
||||
|
||||
try {
|
||||
await api.applyProfileTemplate(typeId, templateKey)
|
||||
setSuccess('Template erfolgreich angewendet')
|
||||
load()
|
||||
} catch (e) {
|
||||
setError(e.message)
|
||||
}
|
||||
}
|
||||
|
||||
const batchReEvaluate = async () => {
|
||||
if (!confirm('Alle Aktivitäten neu evaluieren? Das kann einige Sekunden dauern.')) return
|
||||
|
||||
try {
|
||||
const result = await api.batchEvaluateActivities()
|
||||
|
||||
let message = `Batch-Evaluation abgeschlossen: ${result.stats.evaluated} evaluiert, ` +
|
||||
`${result.stats.skipped} übersprungen, ${result.stats.errors} Fehler`
|
||||
|
||||
// Show error details if available
|
||||
if (result.stats.error_details && result.stats.error_details.length > 0) {
|
||||
message += '\n\nErste Fehler:\n' + result.stats.error_details.map(err =>
|
||||
`- Aktivität ${err.activity_id} (Typ: ${err.training_type_id || 'keine'}): ${err.error}`
|
||||
).join('\n')
|
||||
}
|
||||
|
||||
if (result.stats.errors > 0) {
|
||||
setError(message)
|
||||
} else {
|
||||
setSuccess(message)
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e.message)
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) return <div className="spinner" />
|
||||
|
||||
return (
|
||||
<div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto', paddingBottom: '100px' }}>
|
||||
<h1>Training Type Profiles</h1>
|
||||
<p style={{ color: 'var(--text2)', marginBottom: '24px' }}>
|
||||
Konfiguriere Bewertungsprofile für Trainingstypen
|
||||
</p>
|
||||
|
||||
{error && (
|
||||
<div style={{
|
||||
padding: '12px',
|
||||
background: 'var(--danger)',
|
||||
color: 'white',
|
||||
borderRadius: '8px',
|
||||
marginBottom: '16px'
|
||||
}}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{success && (
|
||||
<div style={{
|
||||
padding: '12px',
|
||||
background: 'var(--accent)',
|
||||
color: 'white',
|
||||
borderRadius: '8px',
|
||||
marginBottom: '16px'
|
||||
}}>
|
||||
{success}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Statistics */}
|
||||
{stats && (
|
||||
<div className="card" style={{ marginBottom: '24px' }}>
|
||||
<h3>Übersicht</h3>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px', marginTop: '16px' }}>
|
||||
<div>
|
||||
<div style={{ fontSize: '32px', fontWeight: '600', color: 'var(--accent)' }}>{stats.total}</div>
|
||||
<div style={{ color: 'var(--text2)', fontSize: '14px' }}>Trainingstypen gesamt</div>
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ fontSize: '32px', fontWeight: '600', color: 'var(--accent)' }}>{stats.configured}</div>
|
||||
<div style={{ color: 'var(--text2)', fontSize: '14px' }}>Profile konfiguriert</div>
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ fontSize: '32px', fontWeight: '600', color: 'var(--text3)' }}>{stats.unconfigured}</div>
|
||||
<div style={{ color: 'var(--text2)', fontSize: '14px' }}>Noch keine Profile</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={batchReEvaluate}
|
||||
className="btn btn-primary"
|
||||
style={{ marginTop: '16px', width: '100%' }}
|
||||
>
|
||||
🔄 Alle Aktivitäten neu evaluieren
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Training Types List */}
|
||||
<div className="card">
|
||||
<h3>Trainingstypen</h3>
|
||||
|
||||
<div style={{ marginTop: '16px' }}>
|
||||
{trainingTypes.map(type => (
|
||||
<div
|
||||
key={type.id}
|
||||
style={{
|
||||
padding: '16px',
|
||||
borderBottom: '1px solid var(--border)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '16px'
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: '24px' }}>{type.icon || '📊'}</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontWeight: '500', marginBottom: '4px' }}>
|
||||
{type.name_de}
|
||||
{type.profile && (
|
||||
<span style={{
|
||||
marginLeft: '8px',
|
||||
padding: '2px 8px',
|
||||
background: 'var(--accent)',
|
||||
color: 'white',
|
||||
borderRadius: '4px',
|
||||
fontSize: '12px'
|
||||
}}>
|
||||
✓ Profil
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ fontSize: '14px', color: 'var(--text2)' }}>
|
||||
{type.category} {type.subcategory && `· ${type.subcategory}`}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
|
||||
{/* Template Buttons */}
|
||||
{templates.map(template => (
|
||||
<button
|
||||
key={template.key}
|
||||
onClick={() => applyTemplate(type.id, template.key)}
|
||||
className="btn"
|
||||
style={{ padding: '6px 12px', fontSize: '13px' }}
|
||||
title={`Template "${template.name_de}" anwenden`}
|
||||
>
|
||||
{template.icon} {template.name_de}
|
||||
</button>
|
||||
))}
|
||||
|
||||
<button
|
||||
onClick={() => openEditor(type)}
|
||||
className="btn btn-primary"
|
||||
style={{ padding: '6px 16px' }}
|
||||
>
|
||||
{type.profile ? '✏️ Bearbeiten' : '➕ Profil erstellen'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Profile Editor Modal */}
|
||||
{selectedType && (
|
||||
<div style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
background: 'rgba(0,0,0,0.7)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 1000,
|
||||
padding: '20px'
|
||||
}}>
|
||||
<div style={{
|
||||
background: 'var(--bg)',
|
||||
borderRadius: '12px',
|
||||
maxWidth: '900px',
|
||||
width: '100%',
|
||||
maxHeight: '90vh',
|
||||
overflow: 'auto',
|
||||
padding: '24px'
|
||||
}}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
|
||||
<h2>{selectedType.icon} {selectedType.name_de} - Profil bearbeiten</h2>
|
||||
<button onClick={closeEditor} className="btn" style={{ padding: '8px 16px' }}>✕ Schließen</button>
|
||||
</div>
|
||||
|
||||
<p style={{ color: 'var(--text2)', marginBottom: '16px' }}>
|
||||
JSON-basierter Editor. Siehe Dokumentation für vollständige Struktur.
|
||||
</p>
|
||||
|
||||
<textarea
|
||||
value={profileJson}
|
||||
onChange={(e) => setProfileJson(e.target.value)}
|
||||
style={{
|
||||
width: '100%',
|
||||
minHeight: '400px',
|
||||
padding: '12px',
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '13px',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '8px',
|
||||
background: 'var(--surface)',
|
||||
color: 'var(--text1)',
|
||||
resize: 'vertical'
|
||||
}}
|
||||
/>
|
||||
|
||||
<div style={{ display: 'flex', gap: '12px', marginTop: '16px' }}>
|
||||
<button onClick={saveProfile} className="btn btn-primary" style={{ flex: 1 }}>
|
||||
💾 Profil speichern
|
||||
</button>
|
||||
<button onClick={closeEditor} className="btn" style={{ flex: 1 }}>
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{selectedType.profile && (
|
||||
<div style={{ marginTop: '16px', padding: '12px', background: 'var(--surface2)', borderRadius: '8px' }}>
|
||||
<strong>Aktuelles Profil:</strong>
|
||||
<div style={{ fontSize: '13px', color: 'var(--text2)', marginTop: '8px' }}>
|
||||
Version: {selectedType.profile.version || 'n/a'}
|
||||
<br />
|
||||
Regel-Sets: {selectedType.profile.rule_sets ? Object.keys(selectedType.profile.rule_sets).join(', ') : 'keine'}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,548 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Pencil, Trash2, Plus, Save, X, ArrowLeft, Settings } from 'lucide-react'
|
||||
import { api } from '../utils/api'
|
||||
import ProfileBuilder from '../components/ProfileBuilder'
|
||||
|
||||
/**
|
||||
* AdminTrainingTypesPage - CRUD for training types
|
||||
* v9d Phase 1b - Basic CRUD without abilities mapping
|
||||
*/
|
||||
export default function AdminTrainingTypesPage() {
|
||||
const nav = useNavigate()
|
||||
const [types, setTypes] = useState([])
|
||||
const [categories, setCategories] = useState({})
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [editingId, setEditingId] = useState(null)
|
||||
const [formData, setFormData] = useState(null)
|
||||
const [error, setError] = useState(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [editingProfileId, setEditingProfileId] = useState(null)
|
||||
const [parameters, setParameters] = useState([])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [])
|
||||
|
||||
const load = () => {
|
||||
setLoading(true)
|
||||
Promise.all([
|
||||
api.adminListTrainingTypes(),
|
||||
api.getTrainingCategories(),
|
||||
api.getTrainingParameters()
|
||||
]).then(([typesData, catsData, paramsData]) => {
|
||||
setTypes(typesData)
|
||||
setCategories(catsData)
|
||||
setParameters(paramsData.parameters || [])
|
||||
setLoading(false)
|
||||
}).catch(err => {
|
||||
console.error('Failed to load training types:', err)
|
||||
setError(err.message)
|
||||
setLoading(false)
|
||||
})
|
||||
}
|
||||
|
||||
const startCreate = () => {
|
||||
setFormData({
|
||||
category: 'cardio',
|
||||
subcategory: '',
|
||||
name_de: '',
|
||||
name_en: '',
|
||||
icon: '',
|
||||
description_de: '',
|
||||
description_en: '',
|
||||
sort_order: 0
|
||||
})
|
||||
setEditingId('new')
|
||||
}
|
||||
|
||||
const startEdit = (type) => {
|
||||
setFormData({
|
||||
category: type.category,
|
||||
subcategory: type.subcategory || '',
|
||||
name_de: type.name_de,
|
||||
name_en: type.name_en,
|
||||
icon: type.icon || '',
|
||||
description_de: type.description_de || '',
|
||||
description_en: type.description_en || '',
|
||||
sort_order: type.sort_order
|
||||
})
|
||||
setEditingId(type.id)
|
||||
}
|
||||
|
||||
const cancelEdit = () => {
|
||||
setEditingId(null)
|
||||
setFormData(null)
|
||||
setError(null)
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!formData.name_de || !formData.name_en) {
|
||||
setError('Name (DE) und Name (EN) sind Pflichtfelder')
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
if (editingId === 'new') {
|
||||
await api.adminCreateTrainingType(formData)
|
||||
} else {
|
||||
await api.adminUpdateTrainingType(editingId, formData)
|
||||
}
|
||||
await load()
|
||||
cancelEdit()
|
||||
} catch (err) {
|
||||
console.error('Save failed:', err)
|
||||
setError(err.message)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id, name) => {
|
||||
if (!confirm(`Trainingstyp "${name}" wirklich löschen?\n\nHinweis: Löschen ist nur möglich wenn keine Aktivitäten diesen Typ verwenden.`)) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await api.adminDeleteTrainingType(id)
|
||||
await load()
|
||||
} catch (err) {
|
||||
alert('Löschen fehlgeschlagen: ' + err.message)
|
||||
}
|
||||
}
|
||||
|
||||
const startEditProfile = (typeId) => {
|
||||
setEditingProfileId(typeId)
|
||||
setEditingId(null) // Close type editor if open
|
||||
setFormData(null)
|
||||
}
|
||||
|
||||
const cancelEditProfile = () => {
|
||||
setEditingProfileId(null)
|
||||
}
|
||||
|
||||
const handleSaveProfile = async (profile) => {
|
||||
try {
|
||||
await api.adminUpdateTrainingType(editingProfileId, { profile })
|
||||
await load()
|
||||
// Success message is shown by ProfileBuilder component
|
||||
// Don't close editor immediately - let user see success message
|
||||
setTimeout(() => {
|
||||
setEditingProfileId(null)
|
||||
}, 2000)
|
||||
} catch (err) {
|
||||
// Error will be thrown to ProfileBuilder
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Group by category
|
||||
const grouped = {}
|
||||
types.forEach(type => {
|
||||
if (!grouped[type.category]) {
|
||||
grouped[type.category] = []
|
||||
}
|
||||
grouped[type.category].push(type)
|
||||
})
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{ padding: 20, textAlign: 'center' }}>
|
||||
<div className="spinner" style={{ width: 32, height: 32, margin: '0 auto' }} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ padding: '16px 16px 80px' }}>
|
||||
<div style={{ marginBottom: 20, display: 'flex', alignItems: 'center', gap: 12 }}>
|
||||
<button
|
||||
onClick={() => nav('/settings')}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
padding: 6,
|
||||
display: 'flex',
|
||||
color: 'var(--text2)'
|
||||
}}
|
||||
>
|
||||
<ArrowLeft size={20} />
|
||||
</button>
|
||||
<h1 style={{ margin: 0, fontSize: 20, fontWeight: 700 }}>Trainingstypen verwalten</h1>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="card" style={{ padding: 12, marginBottom: 16, background: '#FCEBEB', color: '#D85A30' }}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Create new button */}
|
||||
{!editingId && (
|
||||
<button
|
||||
onClick={startCreate}
|
||||
className="btn btn-primary btn-full"
|
||||
style={{ marginBottom: 16 }}
|
||||
>
|
||||
<Plus size={16} /> Neuen Trainingstyp anlegen
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Edit form (only for new type creation, at top) */}
|
||||
{editingId === 'new' && formData && (
|
||||
<div className="card" style={{ padding: 16, marginBottom: 16 }}>
|
||||
<div style={{ fontWeight: 600, marginBottom: 12 }}>
|
||||
{editingId === 'new' ? '➕ Neuer Trainingstyp' : '✏️ Trainingstyp bearbeiten'}
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
|
||||
<div>
|
||||
<div className="form-label">Kategorie *</div>
|
||||
<select
|
||||
className="form-input"
|
||||
value={formData.category}
|
||||
onChange={e => setFormData({ ...formData, category: e.target.value })}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
{Object.keys(categories).map(cat => (
|
||||
<option key={cat} value={cat}>
|
||||
{categories[cat].icon} {categories[cat].name_de}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="form-label">Subkategorie</div>
|
||||
<input
|
||||
className="form-input"
|
||||
value={formData.subcategory}
|
||||
onChange={e => setFormData({ ...formData, subcategory: e.target.value })}
|
||||
placeholder="z.B. running, hypertrophy, meditation"
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 4 }}>
|
||||
Kleingeschrieben, ohne Leerzeichen, eindeutig
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="form-label">Name (Deutsch) *</div>
|
||||
<input
|
||||
className="form-input"
|
||||
value={formData.name_de}
|
||||
onChange={e => setFormData({ ...formData, name_de: e.target.value })}
|
||||
placeholder="z.B. Laufen"
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="form-label">Name (English) *</div>
|
||||
<input
|
||||
className="form-input"
|
||||
value={formData.name_en}
|
||||
onChange={e => setFormData({ ...formData, name_en: e.target.value })}
|
||||
placeholder="e.g. Running"
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="form-label">Icon (Emoji)</div>
|
||||
<input
|
||||
className="form-input"
|
||||
value={formData.icon}
|
||||
onChange={e => setFormData({ ...formData, icon: e.target.value })}
|
||||
placeholder="🏃"
|
||||
maxLength={10}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="form-label">Sortierung</div>
|
||||
<input
|
||||
type="number"
|
||||
className="form-input"
|
||||
value={formData.sort_order}
|
||||
onChange={e => setFormData({ ...formData, sort_order: parseInt(e.target.value) })}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
<div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 4 }}>
|
||||
Niedrigere Zahlen werden zuerst angezeigt
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="form-label">Beschreibung (Deutsch)</div>
|
||||
<textarea
|
||||
className="form-input"
|
||||
value={formData.description_de}
|
||||
onChange={e => setFormData({ ...formData, description_de: e.target.value })}
|
||||
placeholder="Optional: Beschreibung für KI-Analyse"
|
||||
rows={4}
|
||||
style={{ width: '100%', resize: 'vertical' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="form-label">Beschreibung (English)</div>
|
||||
<textarea
|
||||
className="form-input"
|
||||
value={formData.description_en}
|
||||
onChange={e => setFormData({ ...formData, description_en: e.target.value })}
|
||||
placeholder="Optional: Description for AI analysis"
|
||||
rows={4}
|
||||
style={{ width: '100%', resize: 'vertical' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className="btn btn-primary"
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<div className="spinner" style={{ width: 14, height: 14 }} />
|
||||
Speichere...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save size={16} /> Speichern
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
onClick={cancelEdit}
|
||||
disabled={saving}
|
||||
className="btn btn-secondary"
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
<X size={16} /> Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* List grouped by category */}
|
||||
{Object.entries(grouped).sort((a, b) => {
|
||||
const orderA = categories[a[0]]?.sort_order || 999
|
||||
const orderB = categories[b[0]]?.sort_order || 999
|
||||
return orderA - orderB
|
||||
}).map(([cat, catTypes]) => (
|
||||
<div key={cat} className="card" style={{ padding: 16, marginBottom: 12 }}>
|
||||
<div style={{
|
||||
fontWeight: 600,
|
||||
fontSize: 14,
|
||||
marginBottom: 12,
|
||||
color: categories[cat]?.color || 'var(--text1)'
|
||||
}}>
|
||||
{categories[cat]?.icon} {categories[cat]?.name_de}
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{catTypes.sort((a, b) => a.sort_order - b.sort_order).map(type => (
|
||||
<div key={type.id}>
|
||||
{/* Type Row */}
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
padding: 8,
|
||||
background: 'var(--surface)',
|
||||
borderRadius: 6
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: 18 }}>{type.icon}</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 13, fontWeight: 500 }}>
|
||||
{type.name_de} <span style={{ color: 'var(--text3)' }}>/ {type.name_en}</span>
|
||||
{type.profile && (
|
||||
<span style={{
|
||||
marginLeft: 8,
|
||||
padding: '2px 6px',
|
||||
background: 'var(--accent)',
|
||||
color: 'white',
|
||||
borderRadius: 4,
|
||||
fontSize: 10
|
||||
}}>
|
||||
✓ Profil
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{type.subcategory && (
|
||||
<div style={{ fontSize: 11, color: 'var(--text3)' }}>
|
||||
Subkategorie: {type.subcategory}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => startEditProfile(type.id)}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
padding: 6,
|
||||
color: 'var(--accent)'
|
||||
}}
|
||||
title="Profil konfigurieren"
|
||||
>
|
||||
<Settings size={16} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => startEdit(type)}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
padding: 6,
|
||||
color: 'var(--accent)'
|
||||
}}
|
||||
title="Bearbeiten"
|
||||
>
|
||||
<Pencil size={16} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(type.id, type.name_de)}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
padding: 6,
|
||||
color: '#D85A30'
|
||||
}}
|
||||
title="Löschen"
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Inline Profile Builder */}
|
||||
{editingProfileId === type.id && (
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<ProfileBuilder
|
||||
trainingType={type}
|
||||
parameters={parameters}
|
||||
onSave={handleSaveProfile}
|
||||
onCancel={cancelEditProfile}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Inline Type Editor */}
|
||||
{editingId === type.id && formData && (
|
||||
<div style={{ marginTop: 8, padding: 16, background: 'var(--surface2)', borderRadius: 8 }}>
|
||||
<div style={{ fontWeight: 600, marginBottom: 12 }}>✏️ Trainingstyp bearbeiten</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
|
||||
<div>
|
||||
<div className="form-label">Kategorie *</div>
|
||||
<select
|
||||
className="form-input"
|
||||
value={formData.category}
|
||||
onChange={e => setFormData({ ...formData, category: e.target.value })}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
{Object.keys(categories).map(cat => (
|
||||
<option key={cat} value={cat}>
|
||||
{categories[cat].icon} {categories[cat].name_de}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="form-label">Subkategorie</div>
|
||||
<input
|
||||
className="form-input"
|
||||
value={formData.subcategory}
|
||||
onChange={e => setFormData({ ...formData, subcategory: e.target.value })}
|
||||
placeholder="z.B. running, hypertrophy, meditation"
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="form-label">Name (Deutsch) *</div>
|
||||
<input
|
||||
className="form-input"
|
||||
value={formData.name_de}
|
||||
onChange={e => setFormData({ ...formData, name_de: e.target.value })}
|
||||
placeholder="z.B. Laufen"
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="form-label">Name (English) *</div>
|
||||
<input
|
||||
className="form-input"
|
||||
value={formData.name_en}
|
||||
onChange={e => setFormData({ ...formData, name_en: e.target.value })}
|
||||
placeholder="e.g. Running"
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="form-label">Icon (Emoji)</div>
|
||||
<input
|
||||
className="form-input"
|
||||
value={formData.icon}
|
||||
onChange={e => setFormData({ ...formData, icon: e.target.value })}
|
||||
placeholder="🏃"
|
||||
maxLength={10}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="form-label">Sortierung</div>
|
||||
<input
|
||||
type="number"
|
||||
className="form-input"
|
||||
value={formData.sort_order}
|
||||
onChange={e => setFormData({ ...formData, sort_order: parseInt(e.target.value) })}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button onClick={handleSave} disabled={saving} className="btn btn-primary" style={{ flex: 1 }}>
|
||||
{saving ? <><div className="spinner" style={{ width: 14, height: 14 }} /> Speichere...</> : <><Save size={16} /> Speichern</>}
|
||||
</button>
|
||||
<button onClick={cancelEdit} disabled={saving} className="btn btn-secondary" style={{ flex: 1 }}>
|
||||
<X size={16} /> Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<div style={{
|
||||
marginTop: 20,
|
||||
padding: 12,
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: 8,
|
||||
fontSize: 12,
|
||||
color: 'var(--text3)'
|
||||
}}>
|
||||
<strong>Hinweis:</strong> Das Fähigkeiten-Mapping (koordinativ, konditionell, etc.) wird in einer späteren Version hinzugefügt.
|
||||
</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>
|
||||
)
|
||||
}
|
||||
@@ -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')
|
||||
@@ -56,7 +57,11 @@ function PromptEditor({ prompt, onSave, onCancel }) {
|
||||
'{{weight_trend}}','{{weight_aktuell}}','{{kf_aktuell}}','{{caliper_summary}}',
|
||||
'{{circ_summary}}','{{nutrition_summary}}','{{nutrition_detail}}',
|
||||
'{{protein_ziel_low}}','{{protein_ziel_high}}','{{activity_summary}}',
|
||||
'{{activity_kcal_summary}}','{{activity_detail}}']
|
||||
'{{activity_kcal_summary}}','{{activity_detail}}',
|
||||
'{{sleep_summary}}','{{sleep_detail}}','{{sleep_avg_duration}}','{{sleep_avg_quality}}',
|
||||
'{{rest_days_summary}}','{{rest_days_count}}','{{rest_days_types}}',
|
||||
'{{vitals_summary}}','{{vitals_detail}}','{{vitals_avg_hr}}','{{vitals_avg_hrv}}',
|
||||
'{{vitals_avg_bp}}','{{vitals_vo2_max}}','{{bp_summary}}']
|
||||
|
||||
return (
|
||||
<div className="card section-gap">
|
||||
@@ -114,6 +119,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 +129,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 +191,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 +244,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 +258,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 +309,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 +320,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 && (
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -45,6 +45,27 @@ const ENTRIES = [
|
||||
to: '/activity',
|
||||
color: '#D4537E',
|
||||
},
|
||||
{
|
||||
icon: '🌙',
|
||||
label: 'Schlaf',
|
||||
sub: 'Schlafdaten erfassen oder Apple Health importieren',
|
||||
to: '/sleep',
|
||||
color: '#7B68EE',
|
||||
},
|
||||
{
|
||||
icon: '🛌',
|
||||
label: 'Ruhetage',
|
||||
sub: 'Kraft-, Cardio-, oder Entspannungs-Ruhetag erfassen',
|
||||
to: '/rest-days',
|
||||
color: '#9B59B6',
|
||||
},
|
||||
{
|
||||
icon: '❤️',
|
||||
label: 'Vitalwerte',
|
||||
sub: 'Ruhepuls und HRV morgens erfassen',
|
||||
to: '/vitals',
|
||||
color: '#E74C3C',
|
||||
},
|
||||
{
|
||||
icon: '📖',
|
||||
label: 'Messanleitung',
|
||||
|
||||
@@ -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 */}
|
||||
|
||||
@@ -8,6 +8,11 @@ import {
|
||||
import { api } from '../utils/api'
|
||||
import { useProfile } from '../context/ProfileContext'
|
||||
import { getBfCategory } from '../utils/calc'
|
||||
import TrialBanner from '../components/TrialBanner'
|
||||
import EmailVerificationBanner from '../components/EmailVerificationBanner'
|
||||
import TrainingTypeDistribution from '../components/TrainingTypeDistribution'
|
||||
import SleepWidget from '../components/SleepWidget'
|
||||
import RestDaysWidget from '../components/RestDaysWidget'
|
||||
import { getInterpretation, getStatusColor, getStatusBg } from '../utils/interpret'
|
||||
import Markdown from '../utils/Markdown'
|
||||
import dayjs from 'dayjs'
|
||||
@@ -27,32 +32,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>
|
||||
)
|
||||
}
|
||||
@@ -202,6 +250,12 @@ export default function Dashboard() {
|
||||
setNutrition(n); setActivities(a)
|
||||
setInsights(Array.isArray(ins)?ins:[])
|
||||
setLoading(false)
|
||||
}).catch(err => {
|
||||
console.error('Dashboard load failed:', err)
|
||||
// Set empty data on error so UI can still render
|
||||
setStats(null); setWeights([]); setCalipers([]); setCircs([])
|
||||
setNutrition([]); setActivities([]); setInsights([])
|
||||
setLoading(false)
|
||||
})
|
||||
|
||||
const runPipeline = async () => {
|
||||
@@ -215,7 +269,12 @@ export default function Dashboard() {
|
||||
} finally { setPipelineLoading(false) }
|
||||
}
|
||||
|
||||
useEffect(()=>{ load() },[])
|
||||
useEffect(()=>{
|
||||
console.log('[Dashboard] Component mounted, loading data...')
|
||||
load()
|
||||
},[])
|
||||
|
||||
console.log('[Dashboard] Rendering, loading=', loading, 'activeProfile=', activeProfile?.name)
|
||||
|
||||
if (loading) return <div className="empty-state"><div className="spinner"/></div>
|
||||
|
||||
@@ -259,6 +318,8 @@ export default function Dashboard() {
|
||||
|
||||
const hasAnyData = latestW||latestCal||nutrition.length>0
|
||||
|
||||
console.log('[Dashboard] hasAnyData=', hasAnyData, 'latestW=', !!latestW, 'latestCal=', !!latestCal, 'nutrition.length=', nutrition.length)
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Header greeting */}
|
||||
@@ -272,6 +333,12 @@ export default function Dashboard() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Email Verification Banner */}
|
||||
{activeProfile && <EmailVerificationBanner profile={activeProfile}/>}
|
||||
|
||||
{/* Trial Banner */}
|
||||
{activeProfile && <TrialBanner profile={activeProfile}/>}
|
||||
|
||||
{!hasAnyData && (
|
||||
<div className="empty-state">
|
||||
<h3>Willkommen bei Mitai Jinkendo!</h3>
|
||||
@@ -406,6 +473,30 @@ export default function Dashboard() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Sleep Widget */}
|
||||
<div style={{marginBottom:16}}>
|
||||
<SleepWidget/>
|
||||
</div>
|
||||
|
||||
{/* Rest Days Widget */}
|
||||
<div style={{marginBottom:16}}>
|
||||
<RestDaysWidget/>
|
||||
</div>
|
||||
|
||||
{/* Training Type Distribution */}
|
||||
{activities.length > 0 && (
|
||||
<div className="card section-gap" style={{marginBottom:16}}>
|
||||
<div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:12}}>
|
||||
<div style={{fontWeight:600,fontSize:13}}>🏋️ Trainingstyp-Verteilung</div>
|
||||
<button style={{background:'none',border:'none',fontSize:12,color:'var(--accent)',cursor:'pointer'}}
|
||||
onClick={()=>nav('/activity')}>
|
||||
Details →
|
||||
</button>
|
||||
</div>
|
||||
<TrainingTypeDistribution days={28} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Latest AI insight */}
|
||||
<div className="card section-gap">
|
||||
<div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8}}>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
import { useProfile } from '../context/ProfileContext'
|
||||
import {
|
||||
LineChart, Line, BarChart, Bar,
|
||||
XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid,
|
||||
@@ -10,6 +11,7 @@ import { api } from '../utils/api'
|
||||
import { getBfCategory } from '../utils/calc'
|
||||
import { getInterpretation, getStatusColor, getStatusBg } from '../utils/interpret'
|
||||
import Markdown from '../utils/Markdown'
|
||||
import TrainingTypeDistribution from '../components/TrainingTypeDistribution'
|
||||
import dayjs from 'dayjs'
|
||||
import 'dayjs/locale/de'
|
||||
dayjs.locale('de')
|
||||
@@ -585,13 +587,15 @@ function NutritionSection({ nutrition, weights, profile, insights, onRequest, lo
|
||||
}
|
||||
|
||||
// ── Activity Section ──────────────────────────────────────────────────────────
|
||||
function ActivitySection({ activities, insights, onRequest, loadingSlug, filterActiveSlugs }) {
|
||||
function ActivitySection({ activities, insights, onRequest, loadingSlug, filterActiveSlugs, globalQualityLevel }) {
|
||||
const [period, setPeriod] = useState(30)
|
||||
if (!activities?.length) return (
|
||||
<EmptySection text="Noch keine Aktivitätsdaten." to="/activity" toLabel="Aktivität erfassen"/>
|
||||
)
|
||||
const cutoff = dayjs().subtract(period,'day').format('YYYY-MM-DD')
|
||||
const filtA = activities.filter(d=>period===9999||d.date>=cutoff)
|
||||
|
||||
// Issue #31: Backend already filters by global quality level - only filter by period here
|
||||
const filtA = activities.filter(d => period === 9999 || d.date >= cutoff)
|
||||
|
||||
const byDate={}
|
||||
filtA.forEach(a=>{ byDate[a.date]=(byDate[a.date]||0)+(a.kcal_active||0) })
|
||||
@@ -619,6 +623,28 @@ function ActivitySection({ activities, insights, onRequest, loadingSlug, filterA
|
||||
<div>
|
||||
<SectionHeader title="🏋️ Aktivität" to="/activity" toLabel="Alle Einträge" lastUpdated={activities[0]?.date}/>
|
||||
<PeriodSelector value={period} onChange={setPeriod}/>
|
||||
|
||||
{/* Issue #31: Show active global quality filter */}
|
||||
{globalQualityLevel && globalQualityLevel !== 'all' && (
|
||||
<div style={{
|
||||
marginBottom:12, padding:'8px 12px', borderRadius:8,
|
||||
background:'var(--surface2)', border:'1px solid var(--border)',
|
||||
fontSize:12, color:'var(--text2)', display:'flex', alignItems:'center', gap:8
|
||||
}}>
|
||||
<span>
|
||||
{globalQualityLevel === 'quality' && '✓ Filter: Hochwertig (excellent, good, acceptable)'}
|
||||
{globalQualityLevel === 'very_good' && '✓✓ Filter: Sehr gut (excellent, good)'}
|
||||
{globalQualityLevel === 'excellent' && '⭐ Filter: Exzellent (nur excellent)'}
|
||||
</span>
|
||||
<a href="/settings" style={{
|
||||
marginLeft:'auto', color:'var(--accent)', textDecoration:'none',
|
||||
fontSize:11, fontWeight:500, whiteSpace:'nowrap'
|
||||
}}>
|
||||
Hier ändern →
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{display:'flex',gap:6,marginBottom:12}}>
|
||||
{[['Trainings',filtA.length,'var(--text1)'],['Kcal',totalKcal,'#EF9F27'],
|
||||
['Stunden',Math.round(totalMin/60*10)/10,'#378ADD'],
|
||||
@@ -653,6 +679,10 @@ function ActivitySection({ activities, insights, onRequest, loadingSlug, filterA
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="card" style={{marginBottom:12}}>
|
||||
<div style={{fontSize:12,fontWeight:600,color:'var(--text3)',marginBottom:8}}>Trainingstyp-Verteilung</div>
|
||||
<TrainingTypeDistribution days={period === 9999 ? 365 : period} />
|
||||
</div>
|
||||
<div style={{marginBottom:12}}>
|
||||
<div style={{fontSize:12,fontWeight:600,color:'var(--text3)',marginBottom:8}}>BEWERTUNG</div>
|
||||
{actRules.map((item,i)=><RuleCard key={i} item={item}/>)}
|
||||
@@ -894,6 +924,7 @@ const TABS = [
|
||||
]
|
||||
|
||||
export default function History() {
|
||||
const { activeProfile } = useProfile() // Issue #31: Get global quality filter
|
||||
const location = useLocation?.() || {}
|
||||
const [tab, setTab] = useState((location.state?.tab)||'body')
|
||||
const [weights, setWeights] = useState([])
|
||||
@@ -962,7 +993,7 @@ export default function History() {
|
||||
</div>
|
||||
{tab==='body' && <BodySection weights={weights} calipers={calipers} circs={circs} profile={profile} {...sp}/>}
|
||||
{tab==='nutrition' && <NutritionSection nutrition={nutrition} weights={weights} profile={profile} {...sp}/>}
|
||||
{tab==='activity' && <ActivitySection activities={activities} {...sp}/>}
|
||||
{tab==='activity' && <ActivitySection activities={activities} globalQualityLevel={activeProfile?.quality_filter_level} {...sp}/>}
|
||||
{tab==='correlation' && <CorrelationSection corrData={corrData} profile={profile} {...sp}/>}
|
||||
{tab==='photos' && <PhotoGrid/>}
|
||||
</div>
|
||||
|
||||
@@ -33,6 +33,8 @@ export default function LoginScreen() {
|
||||
setLoading(true); setError(null)
|
||||
try {
|
||||
await login({ email: email.trim().toLowerCase(), password: password })
|
||||
// Redirect to dashboard after successful login
|
||||
window.location.href = '/'
|
||||
} catch(e) {
|
||||
setError(e.message || 'Ungültige E-Mail oder Passwort')
|
||||
} finally { setLoading(false) }
|
||||
@@ -105,6 +107,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)'}}>
|
||||
|
||||
@@ -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}/>
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,507 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Pencil, Trash2, Check, X } from 'lucide-react'
|
||||
import { api } from '../utils/api'
|
||||
import dayjs from 'dayjs'
|
||||
import 'dayjs/locale/de'
|
||||
dayjs.locale('de')
|
||||
|
||||
// Quick Mode Presets
|
||||
const PRESETS = [
|
||||
{
|
||||
id: 'muscle_recovery',
|
||||
icon: '💪',
|
||||
label: 'Kraft-Ruhetag',
|
||||
description: 'Muskelregeneration – Kraft & HIIT pausieren, Cardio erlaubt',
|
||||
color: '#D85A30',
|
||||
config: {
|
||||
focus: 'muscle_recovery',
|
||||
rest_from: ['strength', 'hiit'],
|
||||
allows: ['cardio_low', 'meditation', 'mobility', 'walk'],
|
||||
intensity_max: 60,
|
||||
}
|
||||
},
|
||||
{
|
||||
id: 'cardio_recovery',
|
||||
icon: '🏃',
|
||||
label: 'Cardio-Ruhetag',
|
||||
description: 'Ausdauererholung – Cardio pausieren, Kraft & Mobility erlaubt',
|
||||
color: '#378ADD',
|
||||
config: {
|
||||
focus: 'cardio_recovery',
|
||||
rest_from: ['cardio', 'cardio_low', 'cardio_high'],
|
||||
allows: ['strength', 'mobility', 'meditation'],
|
||||
intensity_max: 70,
|
||||
}
|
||||
},
|
||||
{
|
||||
id: 'mental_rest',
|
||||
icon: '🧘',
|
||||
label: 'Entspannungstag',
|
||||
description: 'Mentale Erholung – Nur Meditation & Spaziergang',
|
||||
color: '#7B68EE',
|
||||
config: {
|
||||
focus: 'mental_rest',
|
||||
rest_from: ['strength', 'cardio', 'hiit', 'power'],
|
||||
allows: ['meditation', 'walk'],
|
||||
intensity_max: 40,
|
||||
}
|
||||
},
|
||||
{
|
||||
id: 'deload',
|
||||
icon: '📉',
|
||||
label: 'Deload',
|
||||
description: 'Reduzierte Intensität – Alles erlaubt, max 70% Last',
|
||||
color: '#E67E22',
|
||||
config: {
|
||||
focus: 'deload',
|
||||
rest_from: [],
|
||||
allows: ['strength', 'cardio', 'mobility', 'meditation'],
|
||||
intensity_max: 70,
|
||||
}
|
||||
},
|
||||
]
|
||||
|
||||
const FOCUS_LABELS = {
|
||||
muscle_recovery: 'Muskelregeneration',
|
||||
cardio_recovery: 'Cardio-Erholung',
|
||||
mental_rest: 'Mentale Erholung',
|
||||
deload: 'Deload',
|
||||
injury: 'Verletzungspause',
|
||||
}
|
||||
|
||||
export default function RestDaysPage() {
|
||||
const [restDays, setRestDays] = useState([])
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
const [formData, setFormData] = useState({
|
||||
date: dayjs().format('YYYY-MM-DD'),
|
||||
preset: null,
|
||||
note: '',
|
||||
})
|
||||
const [editing, setEditing] = useState(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState(null)
|
||||
const [toast, setToast] = useState(null)
|
||||
|
||||
useEffect(() => {
|
||||
loadRestDays()
|
||||
}, [])
|
||||
|
||||
const loadRestDays = async () => {
|
||||
try {
|
||||
const data = await api.listRestDays(90)
|
||||
setRestDays(data)
|
||||
} catch (err) {
|
||||
console.error('Failed to load rest days:', err)
|
||||
setError('Fehler beim Laden der Ruhetage')
|
||||
}
|
||||
}
|
||||
|
||||
const showToast = (message, duration = 2000) => {
|
||||
setToast(message)
|
||||
setTimeout(() => setToast(null), duration)
|
||||
}
|
||||
|
||||
const handlePresetSelect = (preset) => {
|
||||
setFormData(f => ({ ...f, preset: preset.id }))
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!formData.preset) {
|
||||
setError('Bitte wähle einen Ruhetag-Typ')
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const preset = PRESETS.find(p => p.id === formData.preset)
|
||||
await api.createRestDay({
|
||||
date: formData.date,
|
||||
rest_config: preset.config,
|
||||
note: formData.note,
|
||||
})
|
||||
|
||||
showToast('✓ Ruhetag gespeichert')
|
||||
await loadRestDays()
|
||||
setShowForm(false)
|
||||
setFormData({
|
||||
date: dayjs().format('YYYY-MM-DD'),
|
||||
preset: null,
|
||||
note: '',
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('Save failed:', err)
|
||||
setError(err.message || 'Fehler beim Speichern')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id) => {
|
||||
if (!confirm('Ruhetag löschen?')) return
|
||||
|
||||
try {
|
||||
await api.deleteRestDay(id)
|
||||
showToast('✓ Gelöscht')
|
||||
await loadRestDays()
|
||||
} catch (err) {
|
||||
console.error('Delete failed:', err)
|
||||
setError(err.message || 'Fehler beim Löschen')
|
||||
}
|
||||
}
|
||||
|
||||
const startEdit = (day) => {
|
||||
setEditing({
|
||||
...day,
|
||||
note: day.note || '',
|
||||
})
|
||||
}
|
||||
|
||||
const cancelEdit = () => {
|
||||
setEditing(null)
|
||||
}
|
||||
|
||||
const handleUpdate = async () => {
|
||||
try {
|
||||
await api.updateRestDay(editing.id, {
|
||||
note: editing.note,
|
||||
})
|
||||
showToast('✓ Aktualisiert')
|
||||
setEditing(null)
|
||||
await loadRestDays()
|
||||
} catch (err) {
|
||||
console.error('Update failed:', err)
|
||||
setError(err.message || 'Fehler beim Aktualisieren')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="page-title">Ruhetage</h1>
|
||||
|
||||
{/* Toast Notification */}
|
||||
{toast && (
|
||||
<div style={{
|
||||
position: 'fixed',
|
||||
top: 70,
|
||||
left: '50%',
|
||||
transform: 'translateX(-50%)',
|
||||
background: 'var(--accent)',
|
||||
color: 'white',
|
||||
padding: '10px 20px',
|
||||
borderRadius: 8,
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
zIndex: 1000,
|
||||
animation: 'slideDown 0.3s ease',
|
||||
}}>
|
||||
{toast}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* New Entry Form */}
|
||||
{!showForm ? (
|
||||
<button
|
||||
className="btn btn-primary btn-full"
|
||||
style={{ marginBottom: 16 }}
|
||||
onClick={() => setShowForm(true)}
|
||||
>
|
||||
+ Ruhetag erfassen
|
||||
</button>
|
||||
) : (
|
||||
<div className="card" style={{ marginBottom: 16 }}>
|
||||
<div className="card-title">Neuer Ruhetag</div>
|
||||
|
||||
{/* Date */}
|
||||
<div className="form-row">
|
||||
<label className="form-label">Datum</label>
|
||||
<input
|
||||
type="date"
|
||||
className="form-input"
|
||||
style={{ width: 140 }}
|
||||
value={formData.date}
|
||||
onChange={e => setFormData(f => ({ ...f, date: e.target.value }))}
|
||||
/>
|
||||
<span className="form-unit" />
|
||||
</div>
|
||||
|
||||
{/* Presets */}
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<label className="form-label" style={{ marginBottom: 8 }}>Typ wählen:</label>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{PRESETS.map(preset => (
|
||||
<button
|
||||
key={preset.id}
|
||||
onClick={() => handlePresetSelect(preset)}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 12,
|
||||
padding: '12px 14px',
|
||||
borderRadius: 10,
|
||||
border: formData.preset === preset.id
|
||||
? `2px solid ${preset.color}`
|
||||
: '1.5px solid var(--border)',
|
||||
background: formData.preset === preset.id
|
||||
? `${preset.color}14`
|
||||
: 'var(--surface)',
|
||||
cursor: 'pointer',
|
||||
textAlign: 'left',
|
||||
transition: 'all 0.15s',
|
||||
}}
|
||||
>
|
||||
<div style={{
|
||||
fontSize: 24,
|
||||
width: 40,
|
||||
height: 40,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
borderRadius: 8,
|
||||
background: `${preset.color}22`,
|
||||
flexShrink: 0,
|
||||
}}>
|
||||
{preset.icon}
|
||||
</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
color: formData.preset === preset.id ? preset.color : 'var(--text1)',
|
||||
marginBottom: 2,
|
||||
}}>
|
||||
{preset.label}
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--text3)' }}>
|
||||
{preset.description}
|
||||
</div>
|
||||
</div>
|
||||
{formData.preset === preset.id && (
|
||||
<Check size={18} style={{ color: preset.color, flexShrink: 0 }} />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Note */}
|
||||
<div className="form-row" style={{ marginTop: 16 }}>
|
||||
<label className="form-label">Notiz</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
placeholder="optional"
|
||||
value={formData.note}
|
||||
onChange={e => setFormData(f => ({ ...f, note: e.target.value }))}
|
||||
/>
|
||||
<span className="form-unit" />
|
||||
</div>
|
||||
|
||||
{/* Error */}
|
||||
{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>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
|
||||
<button
|
||||
className="btn btn-primary"
|
||||
style={{ flex: 1 }}
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? '...' : 'Speichern'}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-secondary"
|
||||
style={{ flex: 1 }}
|
||||
onClick={() => {
|
||||
setShowForm(false)
|
||||
setFormData({
|
||||
date: dayjs().format('YYYY-MM-DD'),
|
||||
preset: null,
|
||||
note: '',
|
||||
})
|
||||
setError(null)
|
||||
}}
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* List */}
|
||||
<div className="section-gap">
|
||||
<div className="card-title" style={{ marginBottom: 8 }}>
|
||||
Verlauf ({restDays.length})
|
||||
</div>
|
||||
|
||||
{restDays.length === 0 && (
|
||||
<p className="muted">Noch keine Ruhetage erfasst.</p>
|
||||
)}
|
||||
|
||||
{restDays.map(day => {
|
||||
const isEditing = editing?.id === day.id
|
||||
const focus = day.rest_config?.focus || 'mental_rest'
|
||||
const preset = PRESETS.find(p => p.id === focus)
|
||||
const isToday = day.date === dayjs().format('YYYY-MM-DD')
|
||||
|
||||
return (
|
||||
<div key={day.id} className="card" style={{
|
||||
marginBottom: 8,
|
||||
border: isToday ? '2px solid var(--accent)' : undefined,
|
||||
background: isToday ? 'var(--accent)08' : undefined,
|
||||
}}>
|
||||
{isEditing ? (
|
||||
<div>
|
||||
<div style={{ fontWeight: 600, fontSize: 14, marginBottom: 8 }}>
|
||||
{dayjs(day.date).format('DD. MMMM YYYY')}
|
||||
</div>
|
||||
<div className="form-row">
|
||||
<label className="form-label">Notiz</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
value={editing.note}
|
||||
onChange={e => setEditing(d => ({ ...d, note: e.target.value }))}
|
||||
/>
|
||||
<span className="form-unit" />
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
|
||||
<button
|
||||
className="btn btn-primary"
|
||||
style={{ flex: 1 }}
|
||||
onClick={handleUpdate}
|
||||
>
|
||||
<Check size={13} /> Speichern
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-secondary"
|
||||
style={{ flex: 1 }}
|
||||
onClick={cancelEdit}
|
||||
>
|
||||
<X size={13} /> Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginBottom: 8,
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<div style={{ fontWeight: 600, fontSize: 14 }}>
|
||||
{dayjs(day.date).format('DD. MMMM YYYY')}
|
||||
</div>
|
||||
{isToday && (
|
||||
<span style={{
|
||||
padding: '2px 8px',
|
||||
borderRadius: 4,
|
||||
background: 'var(--accent)',
|
||||
color: 'white',
|
||||
fontSize: 11,
|
||||
fontWeight: 600,
|
||||
}}>
|
||||
HEUTE
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 6 }}>
|
||||
<button
|
||||
className="btn btn-secondary"
|
||||
style={{ padding: '5px 8px' }}
|
||||
onClick={() => startEdit(day)}
|
||||
>
|
||||
<Pencil size={13} />
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-danger"
|
||||
style={{ padding: '5px 8px' }}
|
||||
onClick={() => handleDelete(day.id)}
|
||||
>
|
||||
<Trash2 size={13} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Preset Badge */}
|
||||
<div style={{
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
gap: 6,
|
||||
padding: '4px 10px',
|
||||
borderRadius: 6,
|
||||
background: `${preset?.color || '#888'}22`,
|
||||
border: `1px solid ${preset?.color || '#888'}`,
|
||||
fontSize: 12,
|
||||
fontWeight: 600,
|
||||
color: preset?.color || '#888',
|
||||
marginBottom: day.note ? 8 : 0,
|
||||
}}>
|
||||
<span style={{ fontSize: 14 }}>{preset?.icon || '📅'}</span>
|
||||
{FOCUS_LABELS[focus] || focus}
|
||||
</div>
|
||||
|
||||
{/* Note */}
|
||||
{day.note && (
|
||||
<p style={{
|
||||
fontSize: 12,
|
||||
color: 'var(--text2)',
|
||||
fontStyle: 'italic',
|
||||
marginTop: 6,
|
||||
}}>
|
||||
"{day.note}"
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Details (collapsible, optional for later) */}
|
||||
{day.rest_config && (
|
||||
<div style={{
|
||||
marginTop: 8,
|
||||
padding: 8,
|
||||
background: 'var(--bg)',
|
||||
borderRadius: 6,
|
||||
fontSize: 11,
|
||||
color: 'var(--text3)',
|
||||
}}>
|
||||
{day.rest_config.rest_from?.length > 0 && (
|
||||
<div>
|
||||
<strong>Pausiert:</strong> {day.rest_config.rest_from.join(', ')}
|
||||
</div>
|
||||
)}
|
||||
{day.rest_config.allows?.length > 0 && (
|
||||
<div>
|
||||
<strong>Erlaubt:</strong> {day.rest_config.allows.join(', ')}
|
||||
</div>
|
||||
)}
|
||||
{day.rest_config.intensity_max && (
|
||||
<div>
|
||||
<strong>Max Intensität:</strong> {day.rest_config.intensity_max}% HFmax
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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
|
||||
@@ -191,6 +202,16 @@ export default function SettingsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleQualityFilterChange = async (level) => {
|
||||
// Issue #31: Update global quality filter
|
||||
await api.updateActiveProfile({ quality_filter_level: level })
|
||||
await refreshProfiles()
|
||||
const updated = profiles.find(p => p.id === activeProfile?.id)
|
||||
if (updated) setActiveProfile({...updated, quality_filter_level: level})
|
||||
setSaved(true)
|
||||
setTimeout(() => setSaved(false), 2000)
|
||||
}
|
||||
|
||||
const handleSave = async (form, profileId) => {
|
||||
const data = {}
|
||||
if (form.name) data.name = form.name
|
||||
@@ -326,6 +347,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 +391,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>
|
||||
@@ -423,6 +465,48 @@ export default function SettingsPage() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Issue #31: Global Quality Filter */}
|
||||
<div className="card section-gap">
|
||||
<div className="card-title">Datenqualität</div>
|
||||
<p style={{fontSize:13,color:'var(--text2)',marginBottom:12,lineHeight:1.6}}>
|
||||
Qualitätsfilter wirkt auf <strong>alle Ansichten</strong>: Dashboard, Charts, Statistiken und KI-Analysen.
|
||||
</p>
|
||||
<div style={{marginBottom:8}}>
|
||||
<label style={{fontSize:12,fontWeight:600,color:'var(--text3)',display:'block',marginBottom:6}}>
|
||||
QUALITÄTSFILTER (GLOBAL)
|
||||
</label>
|
||||
<select
|
||||
className="form-select"
|
||||
value={activeProfile?.quality_filter_level || 'all'}
|
||||
onChange={e => handleQualityFilterChange(e.target.value)}
|
||||
style={{width:'100%',fontSize:13}}>
|
||||
<option value="all">📊 Alle Activities</option>
|
||||
<option value="quality">✓ Hochwertig (excellent, good, acceptable)</option>
|
||||
<option value="very_good">✓✓ Sehr gut (excellent, good)</option>
|
||||
<option value="excellent">⭐ Exzellent (nur excellent)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div style={{padding:'10px 12px',background:'var(--surface2)',borderRadius:8,fontSize:11,
|
||||
color:'var(--text3)',lineHeight:1.5}}>
|
||||
<div style={{fontWeight:600,marginBottom:4,color:'var(--text2)'}}>Aktuell: {
|
||||
{
|
||||
'all': '📊 Alle Activities (kein Filter)',
|
||||
'quality': '✓ Hochwertig (excellent, good, acceptable)',
|
||||
'very_good': '✓✓ Sehr gut (excellent, good)',
|
||||
'excellent': '⭐ Exzellent (nur excellent)'
|
||||
}[activeProfile?.quality_filter_level || 'all']
|
||||
}</div>
|
||||
Diese Einstellung wirkt auf:
|
||||
<ul style={{margin:'6px 0 0 20px',padding:0}}>
|
||||
<li>Dashboard Charts</li>
|
||||
<li>Verlauf & Auswertungen</li>
|
||||
<li>Trainingstyp-Verteilung</li>
|
||||
<li>KI-Analysen & Pipeline</li>
|
||||
<li>Alle Statistiken</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{saved && (
|
||||
<div style={{position:'fixed',bottom:80,left:'50%',transform:'translateX(-50%)',
|
||||
background:'var(--accent)',color:'white',padding:'8px 20px',borderRadius:20,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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>
|
||||
)
|
||||
}
|
||||
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user