Compare commits
498
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
09439ad1a5 | ||
|
|
365ce49c6a | ||
|
|
ff95ef63c7 | ||
|
|
e4e2f23d7f | ||
|
|
9bc0cf70da | ||
|
|
bc91396885 | ||
|
|
7f833b2cb1 | ||
|
|
3d498d03c1 | ||
|
|
c0c512e942 | ||
|
|
096d896166 | ||
|
|
de99856a28 | ||
|
|
97f9aa696e | ||
|
|
b617212145 | ||
|
|
4493b140bd | ||
|
|
87c4cbc4b4 | ||
|
|
f6c5f96768 | ||
|
|
e5f6e6c10d | ||
|
|
c0cb995a7b | ||
|
|
8c8f595385 | ||
|
|
932bceb1e1 | ||
|
|
3e916c082c | ||
|
|
c152721fe8 | ||
|
|
296e79c3b3 | ||
|
|
45e4e64f15 | ||
|
|
f04318f76a | ||
|
|
ab616ba044 | ||
|
|
f0e6fd04fb | ||
|
|
e7dedd527f | ||
|
|
75736dadec | ||
|
|
49e9c9c214 | ||
|
|
8d56c352fc | ||
|
|
00437a92ab | ||
|
|
24f60c0a6d | ||
|
|
fdaf4471da | ||
|
|
6e952f9277 | ||
|
|
952cb90973 | ||
|
|
ebea9946a7 | ||
|
|
bd694b30a6 | ||
|
|
9fb04af7df | ||
|
|
430a928df6 | ||
|
|
c63ec5f700 | ||
|
|
b7f2e2adbe | ||
|
|
bbc59457ac | ||
|
|
190c0dd7fa | ||
|
|
a4376d1cd8 | ||
|
|
a639d08037 | ||
|
|
630a3de88a | ||
|
|
6d0e2de66d | ||
|
|
1fa0edb3b5 | ||
|
|
ac31c5e014 | ||
|
|
422a117026 | ||
|
|
d51bfd3daa | ||
|
|
c2b2c71ccd | ||
|
|
7e8422cbd7 | ||
|
|
922c846b03 | ||
|
|
7deca6c64d | ||
|
|
fac76c28da | ||
|
|
6016eec250 | ||
|
|
c95b4e185d | ||
|
|
fe28cce921 | ||
|
|
b888f5d3c8 | ||
|
|
cab5758b0d | ||
|
|
d9bcaaaac6 | ||
|
|
84c1fa3c1d | ||
|
|
2b8bebd381 | ||
|
|
2f70a39052 | ||
|
|
7d22b052dd | ||
|
|
e3ef18674a | ||
|
|
dc59596f01 | ||
|
|
a7058c30be | ||
|
|
2101080719 | ||
|
|
5aae999a65 | ||
|
|
dc87e7f3b8 | ||
|
|
c607cd1833 | ||
|
|
e2a132353d | ||
|
|
2ce0874dcb | ||
|
|
16dc08cd7d | ||
|
|
c588372f3a | ||
|
|
585f189b13 | ||
|
|
acd4830795 | ||
|
|
ac2e7cf5bb | ||
|
|
0725461056 | ||
|
|
ce4666a535 | ||
|
|
1f8791f4dd | ||
|
|
ca562b7130 | ||
|
|
b5be6e21a5 | ||
|
|
3f5b9b8b58 | ||
|
|
c04e72a397 | ||
|
|
5bbea036c2 | ||
|
|
10f608438c | ||
|
|
485aec40a0 | ||
|
|
57800b686a | ||
|
|
fbaaf08e29 | ||
|
|
5bf8895fb3 | ||
|
|
ffdf9074c3 | ||
|
|
ffb30eaff5 | ||
|
|
0c19e0c0ed | ||
|
|
b00f6ac512 | ||
|
|
81681f0de3 | ||
|
|
645967a2ab | ||
|
|
c762495b6f | ||
|
|
6cdc159a94 | ||
|
|
650313347f | ||
|
|
087e8dd885 | ||
|
|
b7afa98639 | ||
|
|
a04e7cc042 | ||
|
|
c21a624a50 | ||
|
|
56273795a0 | ||
|
|
4c22f999c4 | ||
|
|
176be3233e | ||
|
|
d4500ca00c | ||
|
|
f81171a1f5 | ||
|
|
782f79fe04 | ||
|
|
5b4688fa30 | ||
|
|
fb6d37ecfd | ||
|
|
ffa99f10fb | ||
|
|
a441537dca | ||
|
|
285184ba89 | ||
|
|
5b7d7ec3bb | ||
|
|
befa060671 | ||
|
|
dba6814bc2 | ||
|
|
2bc1ca4daf | ||
|
|
dc34d3d2f2 | ||
|
|
7ede0e3fe8 | ||
|
|
504581838c | ||
|
|
26110d44b4 | ||
|
|
6c23973c5d | ||
|
|
b4558b0582 | ||
|
|
432f7ba49f | ||
|
|
6b2ad9fa1c | ||
|
|
e1d7670971 | ||
|
|
c79cc9eafb | ||
|
|
255d1d61c5 | ||
|
|
dd395180a3 | ||
|
|
0e89850df8 | ||
|
|
eb8b503faa | ||
|
|
294b3b2ece | ||
|
|
8e67175ed2 | ||
|
|
d7aa0eb3af | ||
|
|
cb72f342f9 | ||
|
|
623f34c184 | ||
|
|
b7e7817392 | ||
|
|
068a8e7a88 | ||
|
|
97defaf704 | ||
|
|
370f0d46c7 | ||
|
|
c90e30806b | ||
|
|
ab29a85903 | ||
|
|
3604ebc781 | ||
|
|
e479627f0f | ||
|
|
169dbba092 | ||
|
|
42cc583b9b | ||
|
|
7ffa8f039b | ||
|
|
1c7b5e0653 | ||
|
|
327319115d | ||
|
|
efde158dd4 | ||
|
|
a6701bf7b2 | ||
|
|
befc310958 | ||
|
|
112226938d | ||
|
|
8da577fe58 | ||
|
|
b09a7b200a | ||
|
|
05d15264c8 | ||
|
|
78437b649f | ||
|
|
6f20915d73 | ||
|
|
202c36fad7 | ||
|
|
cc76ae677b | ||
|
|
63bd103b2c | ||
|
|
14c4ea13d9 | ||
|
|
9fa6c5dea7 | ||
|
|
949301a91d | ||
|
|
43e6c3e7f4 | ||
|
|
e3e635d9f5 | ||
|
|
289b132b8f | ||
|
|
919eae6053 | ||
|
|
91bafc6af1 | ||
|
|
10ea560fcf | ||
|
|
b230a03fdd | ||
|
|
02394ea19c | ||
|
|
dd3a4111fc | ||
|
|
4817fd2b29 | ||
|
|
53969f8768 | ||
|
|
6f94154b9e | ||
|
|
7d4f6fe726 | ||
|
|
4f365e9a69 | ||
|
|
bf0b32b536 | ||
|
|
09e6a5fbfb | ||
|
|
56933431f6 | ||
|
|
12d516c881 | ||
|
|
979e734bd9 | ||
|
|
448f6ad4f4 | ||
|
|
e4a2b63a48 | ||
|
|
ce4cd7daf1 | ||
|
|
9ab36145e5 | ||
|
|
eb5c099eca | ||
|
|
37ea1f8537 | ||
|
|
79cb3e0100 | ||
|
|
378bf434fc | ||
|
|
3116fbbc91 | ||
|
|
dfcdfbe335 | ||
|
|
029530e078 | ||
|
|
ba5d460e92 | ||
|
|
34ea51b8bd | ||
|
|
6ab0a8b631 | ||
|
|
6a961ce88f | ||
|
|
d14157f7ad | ||
|
|
f312dd0dbb | ||
|
|
2f64656d4d | ||
|
|
9d22e7e8af | ||
|
|
0a1da37197 | ||
|
|
495f218f9a | ||
|
|
fac8820208 | ||
|
|
217990d417 | ||
|
|
1960ae4924 | ||
|
|
bcb867da69 | ||
|
|
398c645a98 | ||
|
|
7db98a4fa6 | ||
|
|
ce37afb2bb | ||
|
|
db90f397e8 | ||
|
|
498ad7a47f | ||
|
|
9e95fd8416 | ||
|
|
ca4f722b47 | ||
|
|
1c00238414 | ||
|
|
448d19b840 | ||
|
|
caebc37da0 | ||
|
|
6a3a782bff | ||
|
|
2f51b26418 | ||
|
|
92cc309489 | ||
|
|
1fdf91cb50 | ||
|
|
80d57918ae | ||
|
|
d97925d5a1 | ||
|
|
4a11d20c4d | ||
|
|
2303c04123 | ||
|
|
2c978bf948 | ||
|
|
210671059a | ||
|
|
1f4ee5021e | ||
|
|
1e758696fd | ||
|
|
a039a0fad3 | ||
|
|
b3cc588293 | ||
|
|
c9e4b6aa02 | ||
|
|
8be87bfdfb | ||
|
|
484c25575d | ||
|
|
bbee44ecdc | ||
|
|
043bed4323 | ||
|
|
640ef81257 | ||
|
|
65ee5f898f | ||
|
|
27a8af7008 | ||
|
|
14d80fc903 | ||
|
|
87464ff138 | ||
|
|
e3f1e399c2 | ||
|
|
3dd10d3dc7 | ||
|
|
5be52bcfeb | ||
|
|
75f0a5dd6e | ||
|
|
906a3b7cdd | ||
|
|
337667fc07 | ||
|
|
ae93b9d428 | ||
|
|
8398368ed7 | ||
|
|
cd2609da7c | ||
|
|
39db23d417 | ||
|
|
582f125897 | ||
|
|
f46c367c27 | ||
|
|
21bdd9f2ba | ||
|
|
713f7475c9 | ||
|
|
6e651b5bb5 | ||
|
|
f37936c84d | ||
|
|
159fcab17a | ||
|
|
d06d3d84de | ||
|
|
b0f80e0be7 | ||
|
|
adb5dcea88 | ||
|
|
da803da816 | ||
|
|
e799edbae4 | ||
|
|
15bd6cddeb | ||
|
|
19414614bf | ||
|
|
4a2bebe249 | ||
|
|
c0a50dedcd | ||
|
|
c56d2b2201 | ||
|
|
7daa2e40c7 | ||
|
|
ae6bd0d865 | ||
|
|
a43a9f129f | ||
|
|
3ad1a19dce | ||
|
|
a9114bc40a | ||
|
|
555ff62b56 | ||
|
|
7f94a41965 | ||
|
|
8b287ca6c9 | ||
|
|
97e57481f9 | ||
|
|
811ba8b3dc | ||
|
|
b90c738fbb | ||
|
|
dfaf24d74c | ||
|
|
0f2b85c6de | ||
|
|
f4d1fd4de1 | ||
|
|
ba92d66880 | ||
|
|
afc70b5a95 | ||
|
|
84dad07e15 | ||
|
|
7f2ba4fbad | ||
|
|
4ba03c2a94 | ||
|
|
8036c99883 | ||
|
|
b058b0fd6f | ||
|
|
7dda520c9b | ||
|
|
0a3e76128a | ||
|
|
5249cd6939 | ||
|
|
2f3314cd36 | ||
|
|
31e2c24a8a | ||
|
|
7be7266477 | ||
|
|
33653fdfd4 | ||
|
|
95dcf080e5 | ||
|
|
2e0838ca08 | ||
|
|
1b7fdb1739 | ||
|
|
b23e361791 | ||
|
|
053a9e18cf | ||
|
|
6f7303c0d5 | ||
|
|
7f7edce62d | ||
|
|
6627b5eee7 | ||
|
|
5e7ef718e0 | ||
|
|
0c4264de44 | ||
|
|
7a8a5aee98 | ||
|
|
c8cf375399 | ||
|
|
500de132b9 | ||
|
|
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
@@ -27,3 +27,9 @@ ALLOWED_ORIGINS=https://mitai.jinkendo.de
|
||||
# ── Pfade ───────────────────────────────────────────────────────
|
||||
PHOTOS_DIR=/app/photos
|
||||
ENVIRONMENT=production
|
||||
|
||||
# ── Gitea API (lokal, für scripts/gitea/gitea_api.py – niemals committen) ──
|
||||
GITEA_BASE_URL=http://192.168.2.144:3000
|
||||
GITEA_OWNER=Lars
|
||||
GITEA_REPO=mitai-jinkendo
|
||||
GITEA_TOKEN=
|
||||
@@ -13,7 +13,8 @@ jobs:
|
||||
set -e
|
||||
echo "=== Deploying to DEVELOPMENT ==="
|
||||
cd /home/lars/docker/bodytrack-dev
|
||||
git pull origin develop
|
||||
git fetch origin develop
|
||||
git reset --hard origin/develop
|
||||
docker compose -f docker-compose.dev-env.yml build --no-cache
|
||||
docker compose -f docker-compose.dev-env.yml up -d
|
||||
sleep 5
|
||||
|
||||
@@ -13,7 +13,9 @@ jobs:
|
||||
set -e
|
||||
echo "=== Deploying to PRODUCTION ==="
|
||||
cd /home/lars/docker/bodytrack
|
||||
git pull origin main
|
||||
# Arbeitskopie = exakt origin/main (vermeidet Abbruch bei lokalem package-lock o. ä.)
|
||||
git fetch origin main
|
||||
git reset --hard origin/main
|
||||
docker compose -f docker-compose.yml build --no-cache
|
||||
docker compose -f docker-compose.yml up -d
|
||||
sleep 5
|
||||
|
||||
+5
-1
@@ -61,4 +61,8 @@ tmp/
|
||||
|
||||
#.claude Konfiguration
|
||||
.claude/
|
||||
.claude/settings.local.json
|
||||
|
||||
# Cursor MCP mit Secrets (Example: .cursor/mcp.json.example)
|
||||
.cursor/mcp.json
|
||||
.claude/settings.local.json
|
||||
frontend/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,48 @@
|
||||
"""
|
||||
Calculation Engine for Phase 0b - Goal-Aware Placeholders
|
||||
|
||||
This package contains all metric calculation functions for:
|
||||
- Body metrics (K1-K5 from visualization concept)
|
||||
- Nutrition metrics (E1-E5)
|
||||
- Activity metrics (A1-A8)
|
||||
- Recovery metrics (S1)
|
||||
- Correlations (C1-C7)
|
||||
- Scores (Goal Progress Score with Dynamic Focus Areas)
|
||||
|
||||
All calculations are designed to work with Dynamic Focus Areas v2.0.
|
||||
"""
|
||||
|
||||
from .body_metrics import *
|
||||
from .nutrition_metrics import *
|
||||
from .activity_metrics import *
|
||||
from .recovery_metrics import *
|
||||
from .correlation_metrics import *
|
||||
from .scores import *
|
||||
|
||||
__all__ = [
|
||||
# Body
|
||||
'calculate_weight_7d_median',
|
||||
'calculate_weight_28d_slope',
|
||||
'calculate_fm_28d_change',
|
||||
'calculate_lbm_28d_change',
|
||||
'calculate_body_progress_score',
|
||||
|
||||
# Nutrition
|
||||
'calculate_energy_balance_7d',
|
||||
'calculate_protein_g_per_kg',
|
||||
'calculate_nutrition_score',
|
||||
|
||||
# Activity
|
||||
'calculate_training_minutes_week',
|
||||
'calculate_activity_score',
|
||||
|
||||
# Recovery
|
||||
'calculate_recovery_score_v2',
|
||||
|
||||
# Correlations
|
||||
'calculate_lag_correlation',
|
||||
|
||||
# Meta Scores
|
||||
'calculate_goal_progress_score',
|
||||
'calculate_data_quality_score',
|
||||
]
|
||||
@@ -0,0 +1,646 @@
|
||||
"""
|
||||
Activity Metrics Calculation Engine
|
||||
|
||||
Implements A1-A8 from visualization concept:
|
||||
- A1: Training volume per week
|
||||
- A2: Intensity distribution
|
||||
- A3: Training quality matrix
|
||||
- A4: Ability balance radar
|
||||
- A5: Load monitoring (proxy-based)
|
||||
- A6: Activity goal alignment score
|
||||
- A7: Rest day compliance
|
||||
- A8: VO2max development
|
||||
|
||||
All calculations work with training_types abilities system.
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, List
|
||||
import statistics
|
||||
|
||||
from db import get_db, get_cursor
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# A1: Training Volume Calculations
|
||||
# ============================================================================
|
||||
|
||||
def calculate_training_minutes_week(profile_id: str) -> Optional[int]:
|
||||
"""Calculate total training minutes last 7 days"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT SUM(duration_min) as total_minutes
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
return int(row['total_minutes']) if row and row['total_minutes'] else None
|
||||
|
||||
|
||||
def calculate_training_frequency_7d(profile_id: str) -> Optional[int]:
|
||||
"""Calculate number of training sessions last 7 days"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as session_count
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
return int(row['session_count']) if row else None
|
||||
|
||||
|
||||
def calculate_quality_sessions_pct(profile_id: str) -> Optional[int]:
|
||||
"""Calculate percentage of quality sessions (good or better) last 28 days"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT
|
||||
COUNT(*) as total,
|
||||
COUNT(*) FILTER (WHERE quality_label IN ('excellent', 'very_good', 'good')) as quality_count
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
if not row or row['total'] == 0:
|
||||
return None
|
||||
|
||||
pct = (row['quality_count'] / row['total']) * 100
|
||||
return int(pct)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# A2: Intensity Distribution (Proxy-based)
|
||||
# ============================================================================
|
||||
|
||||
def calculate_intensity_proxy_distribution(profile_id: str) -> Optional[Dict]:
|
||||
"""
|
||||
Calculate intensity distribution (proxy until HR zones available)
|
||||
Returns dict: {'low': X, 'moderate': Y, 'high': Z} in minutes
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT duration_min, hr_avg, hr_max
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
|
||||
activities = cur.fetchall()
|
||||
|
||||
if not activities:
|
||||
return None
|
||||
|
||||
low_min = 0
|
||||
moderate_min = 0
|
||||
high_min = 0
|
||||
|
||||
for activity in activities:
|
||||
duration = activity['duration_min']
|
||||
avg_hr = activity['hr_avg']
|
||||
max_hr = activity['hr_max']
|
||||
|
||||
# Simple proxy classification
|
||||
if avg_hr:
|
||||
# Rough HR-based classification (assumes max HR ~190)
|
||||
if avg_hr < 120:
|
||||
low_min += duration
|
||||
elif avg_hr < 150:
|
||||
moderate_min += duration
|
||||
else:
|
||||
high_min += duration
|
||||
else:
|
||||
# Fallback: assume moderate
|
||||
moderate_min += duration
|
||||
|
||||
return {
|
||||
'low': low_min,
|
||||
'moderate': moderate_min,
|
||||
'high': high_min
|
||||
}
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# A4: Ability Balance Calculations
|
||||
# ============================================================================
|
||||
|
||||
def calculate_ability_balance(profile_id: str) -> Optional[Dict]:
|
||||
"""
|
||||
Calculate ability balance from training_types.abilities
|
||||
Returns dict with scores per ability dimension (0-100)
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT a.duration_min, tt.abilities
|
||||
FROM activity_log a
|
||||
JOIN training_types tt ON a.training_category = tt.category
|
||||
WHERE a.profile_id = %s
|
||||
AND a.date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
AND tt.abilities IS NOT NULL
|
||||
""", (profile_id,))
|
||||
|
||||
activities = cur.fetchall()
|
||||
|
||||
if not activities:
|
||||
return None
|
||||
|
||||
# Accumulate ability load (duration × ability weight)
|
||||
ability_loads = {
|
||||
'strength': 0,
|
||||
'endurance': 0,
|
||||
'mental': 0,
|
||||
'coordination': 0,
|
||||
'mobility': 0
|
||||
}
|
||||
|
||||
for activity in activities:
|
||||
duration = activity['duration_min']
|
||||
abilities = activity['abilities'] # JSONB
|
||||
|
||||
if not abilities:
|
||||
continue
|
||||
|
||||
for ability, weight in abilities.items():
|
||||
if ability in ability_loads:
|
||||
ability_loads[ability] += duration * weight
|
||||
|
||||
# Normalize to 0-100 scale
|
||||
max_load = max(ability_loads.values()) if ability_loads else 1
|
||||
if max_load == 0:
|
||||
return None
|
||||
|
||||
normalized = {
|
||||
ability: int((load / max_load) * 100)
|
||||
for ability, load in ability_loads.items()
|
||||
}
|
||||
|
||||
return normalized
|
||||
|
||||
|
||||
def calculate_ability_balance_strength(profile_id: str) -> Optional[int]:
|
||||
"""Get strength ability score"""
|
||||
balance = calculate_ability_balance(profile_id)
|
||||
return balance['strength'] if balance else None
|
||||
|
||||
|
||||
def calculate_ability_balance_endurance(profile_id: str) -> Optional[int]:
|
||||
"""Get endurance ability score"""
|
||||
balance = calculate_ability_balance(profile_id)
|
||||
return balance['endurance'] if balance else None
|
||||
|
||||
|
||||
def calculate_ability_balance_mental(profile_id: str) -> Optional[int]:
|
||||
"""Get mental ability score"""
|
||||
balance = calculate_ability_balance(profile_id)
|
||||
return balance['mental'] if balance else None
|
||||
|
||||
|
||||
def calculate_ability_balance_coordination(profile_id: str) -> Optional[int]:
|
||||
"""Get coordination ability score"""
|
||||
balance = calculate_ability_balance(profile_id)
|
||||
return balance['coordination'] if balance else None
|
||||
|
||||
|
||||
def calculate_ability_balance_mobility(profile_id: str) -> Optional[int]:
|
||||
"""Get mobility ability score"""
|
||||
balance = calculate_ability_balance(profile_id)
|
||||
return balance['mobility'] if balance else None
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# A5: Load Monitoring (Proxy-based)
|
||||
# ============================================================================
|
||||
|
||||
def calculate_proxy_internal_load_7d(profile_id: str) -> Optional[int]:
|
||||
"""
|
||||
Calculate proxy internal load (last 7 days)
|
||||
Formula: duration × intensity_factor × quality_factor
|
||||
"""
|
||||
intensity_factors = {'low': 1.0, 'moderate': 1.5, 'high': 2.0}
|
||||
quality_factors = {
|
||||
'excellent': 1.15,
|
||||
'very_good': 1.05,
|
||||
'good': 1.0,
|
||||
'acceptable': 0.9,
|
||||
'poor': 0.75,
|
||||
'excluded': 0.0
|
||||
}
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT duration_min, hr_avg, rpe
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
""", (profile_id,))
|
||||
|
||||
activities = cur.fetchall()
|
||||
|
||||
if not activities:
|
||||
return None
|
||||
|
||||
total_load = 0
|
||||
|
||||
for activity in activities:
|
||||
duration = activity['duration_min']
|
||||
avg_hr = activity['hr_avg']
|
||||
# Map RPE to quality (rpe 8-10 = excellent, 6-7 = good, 4-5 = moderate, <4 = poor)
|
||||
rpe = activity.get('rpe')
|
||||
if rpe and rpe >= 8:
|
||||
quality = 'excellent'
|
||||
elif rpe and rpe >= 6:
|
||||
quality = 'good'
|
||||
elif rpe and rpe >= 4:
|
||||
quality = 'moderate'
|
||||
else:
|
||||
quality = 'good' # default
|
||||
|
||||
# Determine intensity
|
||||
if avg_hr:
|
||||
if avg_hr < 120:
|
||||
intensity = 'low'
|
||||
elif avg_hr < 150:
|
||||
intensity = 'moderate'
|
||||
else:
|
||||
intensity = 'high'
|
||||
else:
|
||||
intensity = 'moderate'
|
||||
|
||||
load = float(duration) * intensity_factors[intensity] * quality_factors.get(quality, 1.0)
|
||||
total_load += load
|
||||
|
||||
return int(total_load)
|
||||
|
||||
|
||||
def calculate_monotony_score(profile_id: str) -> Optional[float]:
|
||||
"""
|
||||
Calculate training monotony (last 7 days)
|
||||
Monotony = mean daily load / std dev daily load
|
||||
Higher = more monotonous
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT date, SUM(duration_min) as daily_duration
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
GROUP BY date
|
||||
ORDER BY date
|
||||
""", (profile_id,))
|
||||
|
||||
daily_loads = [float(row['daily_duration']) for row in cur.fetchall() if row['daily_duration']]
|
||||
|
||||
if len(daily_loads) < 4:
|
||||
return None
|
||||
|
||||
mean_load = sum(daily_loads) / len(daily_loads)
|
||||
std_dev = statistics.stdev(daily_loads)
|
||||
|
||||
if std_dev == 0:
|
||||
return None
|
||||
|
||||
monotony = mean_load / std_dev
|
||||
return round(monotony, 2)
|
||||
|
||||
|
||||
def calculate_strain_score(profile_id: str) -> Optional[int]:
|
||||
"""
|
||||
Calculate training strain (last 7 days)
|
||||
Strain = weekly load × monotony
|
||||
"""
|
||||
weekly_load = calculate_proxy_internal_load_7d(profile_id)
|
||||
monotony = calculate_monotony_score(profile_id)
|
||||
|
||||
if weekly_load is None or monotony is None:
|
||||
return None
|
||||
|
||||
strain = weekly_load * monotony
|
||||
return int(strain)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# A6: Activity Goal Alignment Score (Dynamic Focus Areas)
|
||||
# ============================================================================
|
||||
|
||||
def calculate_activity_score(profile_id: str, focus_weights: Optional[Dict] = None) -> Optional[int]:
|
||||
"""
|
||||
Activity goal alignment score 0-100
|
||||
Weighted by user's activity-related focus areas
|
||||
"""
|
||||
if focus_weights is None:
|
||||
from calculations.scores import get_user_focus_weights
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
# Activity-related focus areas (English keys from DB)
|
||||
# Strength training
|
||||
strength = focus_weights.get('strength', 0)
|
||||
strength_endurance = focus_weights.get('strength_endurance', 0)
|
||||
power = focus_weights.get('power', 0)
|
||||
total_strength = strength + strength_endurance + power
|
||||
|
||||
# Endurance training
|
||||
aerobic = focus_weights.get('aerobic_endurance', 0)
|
||||
anaerobic = focus_weights.get('anaerobic_endurance', 0)
|
||||
cardiovascular = focus_weights.get('cardiovascular_health', 0)
|
||||
total_cardio = aerobic + anaerobic + cardiovascular
|
||||
|
||||
# Mobility/Coordination
|
||||
flexibility = focus_weights.get('flexibility', 0)
|
||||
mobility = focus_weights.get('mobility', 0)
|
||||
balance = focus_weights.get('balance', 0)
|
||||
reaction = focus_weights.get('reaction', 0)
|
||||
rhythm = focus_weights.get('rhythm', 0)
|
||||
coordination = focus_weights.get('coordination', 0)
|
||||
total_ability = flexibility + mobility + balance + reaction + rhythm + coordination
|
||||
|
||||
total_activity_weight = total_strength + total_cardio + total_ability
|
||||
|
||||
if total_activity_weight == 0:
|
||||
return None # No activity goals
|
||||
|
||||
components = []
|
||||
|
||||
# 1. Weekly minutes (general activity volume)
|
||||
minutes = calculate_training_minutes_week(profile_id)
|
||||
if minutes is not None:
|
||||
# WHO: 150-300 min/week
|
||||
if 150 <= minutes <= 300:
|
||||
minutes_score = 100
|
||||
elif minutes < 150:
|
||||
minutes_score = max(40, (minutes / 150) * 100)
|
||||
else:
|
||||
minutes_score = max(80, 100 - ((minutes - 300) / 10))
|
||||
|
||||
# Volume relevant for all activity types (20% base weight)
|
||||
components.append(('minutes', minutes_score, total_activity_weight * 0.2))
|
||||
|
||||
# 2. Quality sessions (always relevant)
|
||||
quality_pct = calculate_quality_sessions_pct(profile_id)
|
||||
if quality_pct is not None:
|
||||
# Quality gets 10% base weight
|
||||
components.append(('quality', quality_pct, total_activity_weight * 0.1))
|
||||
|
||||
# 3. Strength presence (if strength focus active)
|
||||
if total_strength > 0:
|
||||
strength_score = _score_strength_presence(profile_id)
|
||||
if strength_score is not None:
|
||||
components.append(('strength', strength_score, total_strength))
|
||||
|
||||
# 4. Cardio presence (if cardio focus active)
|
||||
if total_cardio > 0:
|
||||
cardio_score = _score_cardio_presence(profile_id)
|
||||
if cardio_score is not None:
|
||||
components.append(('cardio', cardio_score, total_cardio))
|
||||
|
||||
# 5. Ability balance (if mobility/coordination focus active)
|
||||
if total_ability > 0:
|
||||
balance_score = _score_ability_balance(profile_id)
|
||||
if balance_score is not None:
|
||||
components.append(('balance', balance_score, total_ability))
|
||||
|
||||
if not components:
|
||||
return None
|
||||
|
||||
# Weighted average
|
||||
total_score = sum(score * weight for _, score, weight in components)
|
||||
total_weight = sum(weight for _, _, weight in components)
|
||||
|
||||
return int(total_score / total_weight)
|
||||
|
||||
|
||||
def _score_strength_presence(profile_id: str) -> Optional[int]:
|
||||
"""Score strength training presence (0-100)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT COUNT(DISTINCT date) as strength_days
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
AND training_category = 'strength'
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
|
||||
strength_days = row['strength_days']
|
||||
|
||||
# Target: 2-4 days/week
|
||||
if 2 <= strength_days <= 4:
|
||||
return 100
|
||||
elif strength_days == 1:
|
||||
return 60
|
||||
elif strength_days == 5:
|
||||
return 85
|
||||
elif strength_days == 0:
|
||||
return 0
|
||||
else:
|
||||
return 70
|
||||
|
||||
|
||||
def _score_cardio_presence(profile_id: str) -> Optional[int]:
|
||||
"""Score cardio training presence (0-100)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT COUNT(DISTINCT date) as cardio_days, SUM(duration_min) as cardio_minutes
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
AND training_category = 'cardio'
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
|
||||
cardio_days = row['cardio_days']
|
||||
cardio_minutes = row['cardio_minutes'] or 0
|
||||
|
||||
# Target: 3-5 days/week, 150+ minutes
|
||||
day_score = min(100, (cardio_days / 4) * 100)
|
||||
minute_score = min(100, (cardio_minutes / 150) * 100)
|
||||
|
||||
return int((day_score + minute_score) / 2)
|
||||
|
||||
|
||||
def _score_ability_balance(profile_id: str) -> Optional[int]:
|
||||
"""Score ability balance (0-100)"""
|
||||
balance = calculate_ability_balance(profile_id)
|
||||
|
||||
if not balance:
|
||||
return None
|
||||
|
||||
# Good balance = all abilities > 40, std_dev < 30
|
||||
values = list(balance.values())
|
||||
min_value = min(values)
|
||||
std_dev = statistics.stdev(values) if len(values) > 1 else 0
|
||||
|
||||
# Score based on minimum coverage and balance
|
||||
min_score = min(100, min_value * 2) # Want all > 50
|
||||
balance_score = max(0, 100 - (std_dev * 2)) # Want low std_dev
|
||||
|
||||
return int((min_score + balance_score) / 2)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# A7: Rest Day Compliance
|
||||
# ============================================================================
|
||||
|
||||
def calculate_rest_day_compliance(profile_id: str) -> Optional[int]:
|
||||
"""
|
||||
Calculate rest day compliance percentage (last 28 days)
|
||||
Returns percentage of planned rest days that were respected
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get planned rest days
|
||||
cur.execute("""
|
||||
SELECT date, rest_config->>'focus' as rest_type
|
||||
FROM rest_days
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
|
||||
rest_days = {row['date']: row['rest_type'] for row in cur.fetchall()}
|
||||
|
||||
if not rest_days:
|
||||
return None
|
||||
|
||||
# Check if training occurred on rest days
|
||||
cur.execute("""
|
||||
SELECT date, training_category
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
|
||||
training_days = {}
|
||||
for row in cur.fetchall():
|
||||
if row['date'] not in training_days:
|
||||
training_days[row['date']] = []
|
||||
training_days[row['date']].append(row['training_category'])
|
||||
|
||||
# Count compliance
|
||||
compliant = 0
|
||||
total = len(rest_days)
|
||||
|
||||
for rest_date, rest_type in rest_days.items():
|
||||
if rest_date not in training_days:
|
||||
# Full rest = compliant
|
||||
compliant += 1
|
||||
else:
|
||||
# Check if training violates rest type
|
||||
categories = training_days[rest_date]
|
||||
if rest_type == 'strength_rest' and 'strength' not in categories:
|
||||
compliant += 1
|
||||
elif rest_type == 'cardio_rest' and 'cardio' not in categories:
|
||||
compliant += 1
|
||||
# If rest_type == 'recovery', any training = non-compliant
|
||||
|
||||
compliance_pct = (compliant / total) * 100
|
||||
return int(compliance_pct)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# A8: VO2max Development
|
||||
# ============================================================================
|
||||
|
||||
def calculate_vo2max_trend_28d(profile_id: str) -> Optional[float]:
|
||||
"""Calculate VO2max trend (change over 28 days)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT vo2_max, date
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND vo2_max IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
ORDER BY date DESC
|
||||
""", (profile_id,))
|
||||
|
||||
measurements = cur.fetchall()
|
||||
|
||||
if len(measurements) < 2:
|
||||
return None
|
||||
|
||||
recent = measurements[0]['vo2_max']
|
||||
oldest = measurements[-1]['vo2_max']
|
||||
|
||||
change = recent - oldest
|
||||
return round(change, 1)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Data Quality Assessment
|
||||
# ============================================================================
|
||||
|
||||
def calculate_activity_data_quality(profile_id: str) -> Dict[str, any]:
|
||||
"""
|
||||
Assess data quality for activity metrics
|
||||
Returns dict with quality score and details
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Activity entries last 28 days
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as total,
|
||||
COUNT(hr_avg) as with_hr,
|
||||
COUNT(rpe) as with_quality
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
|
||||
counts = cur.fetchone()
|
||||
|
||||
total_entries = counts['total']
|
||||
hr_coverage = counts['with_hr'] / total_entries if total_entries > 0 else 0
|
||||
quality_coverage = counts['with_quality'] / total_entries if total_entries > 0 else 0
|
||||
|
||||
# Score components
|
||||
frequency_score = min(100, (total_entries / 15) * 100) # 15 = ~4 sessions/week
|
||||
hr_score = hr_coverage * 100
|
||||
quality_score = quality_coverage * 100
|
||||
|
||||
# Overall score
|
||||
overall_score = int(
|
||||
frequency_score * 0.5 +
|
||||
hr_score * 0.25 +
|
||||
quality_score * 0.25
|
||||
)
|
||||
|
||||
if overall_score >= 80:
|
||||
confidence = "high"
|
||||
elif overall_score >= 60:
|
||||
confidence = "medium"
|
||||
else:
|
||||
confidence = "low"
|
||||
|
||||
return {
|
||||
"overall_score": overall_score,
|
||||
"confidence": confidence,
|
||||
"measurements": {
|
||||
"activities_28d": total_entries,
|
||||
"hr_coverage_pct": int(hr_coverage * 100),
|
||||
"quality_coverage_pct": int(quality_coverage * 100)
|
||||
},
|
||||
"component_scores": {
|
||||
"frequency": int(frequency_score),
|
||||
"hr": int(hr_score),
|
||||
"quality": int(quality_score)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,575 @@
|
||||
"""
|
||||
Body Metrics Calculation Engine
|
||||
|
||||
Implements K1-K5 from visualization concept:
|
||||
- K1: Weight trend + goal projection
|
||||
- K2: Weight/FM/LBM multi-line chart
|
||||
- K3: Circumference panel
|
||||
- K4: Recomposition detector
|
||||
- K5: Body progress score (goal-mode dependent)
|
||||
|
||||
All calculations include data quality/confidence assessment.
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, Tuple
|
||||
import statistics
|
||||
|
||||
from db import get_db, get_cursor
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# K1: Weight Trend Calculations
|
||||
# ============================================================================
|
||||
|
||||
def calculate_weight_7d_median(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 7-day median weight (reduces daily noise)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT weight
|
||||
FROM weight_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
ORDER BY date DESC
|
||||
""", (profile_id,))
|
||||
|
||||
weights = [row['weight'] for row in cur.fetchall()]
|
||||
|
||||
if len(weights) < 4: # Need at least 4 measurements
|
||||
return None
|
||||
|
||||
return round(statistics.median(weights), 1)
|
||||
|
||||
|
||||
def calculate_weight_28d_slope(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 28-day weight slope (kg/day)"""
|
||||
return _calculate_weight_slope(profile_id, days=28)
|
||||
|
||||
|
||||
def calculate_weight_90d_slope(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 90-day weight slope (kg/day)"""
|
||||
return _calculate_weight_slope(profile_id, days=90)
|
||||
|
||||
|
||||
def _calculate_weight_slope(profile_id: str, days: int) -> Optional[float]:
|
||||
"""
|
||||
Calculate weight slope using linear regression
|
||||
Returns kg/day (negative = weight loss)
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT date, weight
|
||||
FROM weight_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '%s days'
|
||||
ORDER BY date
|
||||
""", (profile_id, days))
|
||||
|
||||
data = [(row['date'], row['weight']) for row in cur.fetchall()]
|
||||
|
||||
# Need minimum data points based on period
|
||||
min_points = max(18, int(days * 0.6)) # 60% coverage
|
||||
if len(data) < min_points:
|
||||
return None
|
||||
|
||||
# Convert dates to days since start
|
||||
start_date = data[0][0]
|
||||
x_values = [(date - start_date).days for date, _ in data]
|
||||
y_values = [weight for _, weight in data]
|
||||
|
||||
# Linear regression
|
||||
n = len(data)
|
||||
x_mean = sum(x_values) / n
|
||||
y_mean = sum(y_values) / n
|
||||
|
||||
numerator = sum((x - x_mean) * (y - y_mean) for x, y in zip(x_values, y_values))
|
||||
denominator = sum((x - x_mean) ** 2 for x in x_values)
|
||||
|
||||
if denominator == 0:
|
||||
return None
|
||||
|
||||
slope = numerator / denominator
|
||||
return round(slope, 4) # kg/day
|
||||
|
||||
|
||||
def calculate_goal_projection_date(profile_id: str, goal_id: str) -> Optional[str]:
|
||||
"""
|
||||
Calculate projected date to reach goal based on 28d trend
|
||||
Returns ISO date string or None if unrealistic
|
||||
"""
|
||||
from goal_utils import get_goal_by_id
|
||||
|
||||
goal = get_goal_by_id(goal_id)
|
||||
if not goal or goal['goal_type'] != 'weight':
|
||||
return None
|
||||
|
||||
slope = calculate_weight_28d_slope(profile_id)
|
||||
if not slope or slope == 0:
|
||||
return None
|
||||
|
||||
current = goal['current_value']
|
||||
target = goal['target_value']
|
||||
remaining = target - current
|
||||
|
||||
days_needed = remaining / slope
|
||||
|
||||
# Unrealistic if >2 years or negative
|
||||
if days_needed < 0 or days_needed > 730:
|
||||
return None
|
||||
|
||||
projection_date = datetime.now().date() + timedelta(days=int(days_needed))
|
||||
return projection_date.isoformat()
|
||||
|
||||
|
||||
def calculate_goal_progress_pct(current: float, target: float, start: float) -> int:
|
||||
"""
|
||||
Calculate goal progress percentage
|
||||
Returns 0-100 (can exceed 100 if target surpassed)
|
||||
"""
|
||||
if start == target:
|
||||
return 100 if current == target else 0
|
||||
|
||||
progress = ((current - start) / (target - start)) * 100
|
||||
return max(0, min(100, int(progress)))
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# K2: Fat Mass / Lean Mass Calculations
|
||||
# ============================================================================
|
||||
|
||||
def calculate_fm_28d_change(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 28-day fat mass change (kg)"""
|
||||
return _calculate_body_composition_change(profile_id, 'fm', 28)
|
||||
|
||||
|
||||
def calculate_lbm_28d_change(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 28-day lean body mass change (kg)"""
|
||||
return _calculate_body_composition_change(profile_id, 'lbm', 28)
|
||||
|
||||
|
||||
def _calculate_body_composition_change(profile_id: str, metric: str, days: int) -> Optional[float]:
|
||||
"""
|
||||
Calculate change in body composition over period
|
||||
metric: 'fm' (fat mass) or 'lbm' (lean mass)
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get weight and caliper measurements
|
||||
cur.execute("""
|
||||
SELECT w.date, w.weight, c.body_fat_pct
|
||||
FROM weight_log w
|
||||
LEFT JOIN caliper_log c ON w.profile_id = c.profile_id
|
||||
AND w.date = c.date
|
||||
WHERE w.profile_id = %s
|
||||
AND w.date >= CURRENT_DATE - INTERVAL '%s days'
|
||||
ORDER BY w.date DESC
|
||||
""", (profile_id, days))
|
||||
|
||||
data = [
|
||||
{
|
||||
'date': row['date'],
|
||||
'weight': row['weight'],
|
||||
'bf_pct': row['body_fat_pct']
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
if row['body_fat_pct'] is not None # Need BF% for composition
|
||||
]
|
||||
|
||||
if len(data) < 2:
|
||||
return None
|
||||
|
||||
# Most recent and oldest measurement
|
||||
recent = data[0]
|
||||
oldest = data[-1]
|
||||
|
||||
# Calculate FM and LBM
|
||||
recent_fm = recent['weight'] * (recent['bf_pct'] / 100)
|
||||
recent_lbm = recent['weight'] - recent_fm
|
||||
|
||||
oldest_fm = oldest['weight'] * (oldest['bf_pct'] / 100)
|
||||
oldest_lbm = oldest['weight'] - oldest_fm
|
||||
|
||||
if metric == 'fm':
|
||||
change = recent_fm - oldest_fm
|
||||
else: # lbm
|
||||
change = recent_lbm - oldest_lbm
|
||||
|
||||
return round(change, 2)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# K3: Circumference Calculations
|
||||
# ============================================================================
|
||||
|
||||
def calculate_waist_28d_delta(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 28-day waist circumference change (cm)"""
|
||||
return _calculate_circumference_delta(profile_id, 'c_waist', 28)
|
||||
|
||||
|
||||
def calculate_hip_28d_delta(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 28-day hip circumference change (cm)"""
|
||||
return _calculate_circumference_delta(profile_id, 'c_hip', 28)
|
||||
|
||||
|
||||
def calculate_chest_28d_delta(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 28-day chest circumference change (cm)"""
|
||||
return _calculate_circumference_delta(profile_id, 'c_chest', 28)
|
||||
|
||||
|
||||
def calculate_arm_28d_delta(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 28-day arm circumference change (cm)"""
|
||||
return _calculate_circumference_delta(profile_id, 'c_arm', 28)
|
||||
|
||||
|
||||
def calculate_thigh_28d_delta(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 28-day thigh circumference change (cm)"""
|
||||
delta = _calculate_circumference_delta(profile_id, 'c_thigh', 28)
|
||||
|
||||
if delta is None:
|
||||
return None
|
||||
|
||||
return round(delta, 1)
|
||||
|
||||
|
||||
def _calculate_circumference_delta(profile_id: str, column: str, days: int) -> Optional[float]:
|
||||
"""Calculate change in circumference measurement"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(f"""
|
||||
SELECT {column}
|
||||
FROM circumference_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '%s days'
|
||||
AND {column} IS NOT NULL
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
""", (profile_id, days))
|
||||
|
||||
recent = cur.fetchone()
|
||||
if not recent:
|
||||
return None
|
||||
|
||||
cur.execute(f"""
|
||||
SELECT {column}
|
||||
FROM circumference_log
|
||||
WHERE profile_id = %s
|
||||
AND date < CURRENT_DATE - INTERVAL '%s days'
|
||||
AND {column} IS NOT NULL
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
""", (profile_id, days))
|
||||
|
||||
oldest = cur.fetchone()
|
||||
if not oldest:
|
||||
return None
|
||||
|
||||
change = recent[column] - oldest[column]
|
||||
return round(change, 1)
|
||||
|
||||
|
||||
def calculate_waist_hip_ratio(profile_id: str) -> Optional[float]:
|
||||
"""Calculate current waist-to-hip ratio"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT c_waist, c_hip
|
||||
FROM circumference_log
|
||||
WHERE profile_id = %s
|
||||
AND c_waist IS NOT NULL
|
||||
AND c_hip IS NOT NULL
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
|
||||
ratio = row['c_waist'] / row['c_hip']
|
||||
return round(ratio, 3)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# K4: Recomposition Detector
|
||||
# ============================================================================
|
||||
|
||||
def calculate_recomposition_quadrant(profile_id: str) -> Optional[str]:
|
||||
"""
|
||||
Determine recomposition quadrant based on 28d changes:
|
||||
- optimal: FM down, LBM up
|
||||
- cut_with_risk: FM down, LBM down
|
||||
- bulk: FM up, LBM up
|
||||
- unfavorable: FM up, LBM down
|
||||
"""
|
||||
fm_change = calculate_fm_28d_change(profile_id)
|
||||
lbm_change = calculate_lbm_28d_change(profile_id)
|
||||
|
||||
if fm_change is None or lbm_change is None:
|
||||
return None
|
||||
|
||||
if fm_change < 0 and lbm_change > 0:
|
||||
return "optimal"
|
||||
elif fm_change < 0 and lbm_change < 0:
|
||||
return "cut_with_risk"
|
||||
elif fm_change > 0 and lbm_change > 0:
|
||||
return "bulk"
|
||||
else: # fm_change > 0 and lbm_change < 0
|
||||
return "unfavorable"
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# K5: Body Progress Score (Dynamic Focus Areas)
|
||||
# ============================================================================
|
||||
|
||||
def calculate_body_progress_score(profile_id: str, focus_weights: Optional[Dict] = None) -> Optional[int]:
|
||||
"""
|
||||
Calculate body progress score (0-100) weighted by user's focus areas
|
||||
|
||||
Components:
|
||||
- Weight trend alignment with goals
|
||||
- FM/LBM changes (recomposition quality)
|
||||
- Circumference changes (especially waist)
|
||||
- Goal progress percentage
|
||||
|
||||
Weighted dynamically based on user's focus area priorities
|
||||
"""
|
||||
if focus_weights is None:
|
||||
from calculations.scores import get_user_focus_weights
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
# Get all body-related focus area weights (English keys from DB)
|
||||
weight_loss = focus_weights.get('weight_loss', 0)
|
||||
muscle_gain = focus_weights.get('muscle_gain', 0)
|
||||
body_recomp = focus_weights.get('body_recomposition', 0)
|
||||
|
||||
total_body_weight = weight_loss + muscle_gain + body_recomp
|
||||
|
||||
if total_body_weight == 0:
|
||||
return None # No body-related goals
|
||||
|
||||
# Calculate component scores (0-100)
|
||||
components = []
|
||||
|
||||
# Weight trend component (if weight loss goal active)
|
||||
if weight_loss > 0:
|
||||
weight_score = _score_weight_trend(profile_id)
|
||||
if weight_score is not None:
|
||||
components.append(('weight', weight_score, weight_loss))
|
||||
|
||||
# Body composition component (if muscle gain or recomp goal active)
|
||||
if muscle_gain > 0 or body_recomp > 0:
|
||||
comp_score = _score_body_composition(profile_id)
|
||||
if comp_score is not None:
|
||||
components.append(('composition', comp_score, muscle_gain + body_recomp))
|
||||
|
||||
# Waist circumference component (proxy for health)
|
||||
waist_score = _score_waist_trend(profile_id)
|
||||
if waist_score is not None:
|
||||
# Waist gets 20% base weight + bonus from weight loss goals
|
||||
waist_weight = 20 + (weight_loss * 0.3)
|
||||
components.append(('waist', waist_score, waist_weight))
|
||||
|
||||
if not components:
|
||||
return None
|
||||
|
||||
# Weighted average
|
||||
total_score = sum(score * weight for _, score, weight in components)
|
||||
total_weight = sum(weight for _, _, weight in components)
|
||||
|
||||
return int(total_score / total_weight)
|
||||
|
||||
|
||||
def _score_weight_trend(profile_id: str) -> Optional[int]:
|
||||
"""Score weight trend alignment with goals (0-100)"""
|
||||
from goal_utils import get_active_goals
|
||||
|
||||
goals = get_active_goals(profile_id)
|
||||
weight_goals = [g for g in goals if g.get('goal_type') == 'weight']
|
||||
if not weight_goals:
|
||||
return None
|
||||
|
||||
# Use primary or first active goal
|
||||
goal = next((g for g in weight_goals if g.get('is_primary')), weight_goals[0])
|
||||
|
||||
current = goal.get('current_value')
|
||||
target = goal.get('target_value')
|
||||
start = goal.get('start_value')
|
||||
|
||||
if None in [current, target]:
|
||||
return None
|
||||
|
||||
# Convert Decimal to float (PostgreSQL NUMERIC returns Decimal)
|
||||
current = float(current)
|
||||
target = float(target)
|
||||
|
||||
# If no start_value, use oldest weight in last 90 days
|
||||
if start is None:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT weight
|
||||
FROM weight_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '90 days'
|
||||
ORDER BY date ASC
|
||||
LIMIT 1
|
||||
""", (profile_id,))
|
||||
row = cur.fetchone()
|
||||
start = float(row['weight']) if row else current
|
||||
else:
|
||||
start = float(start)
|
||||
|
||||
# Progress percentage
|
||||
progress_pct = calculate_goal_progress_pct(current, target, start)
|
||||
|
||||
# Bonus/penalty based on trend
|
||||
slope = calculate_weight_28d_slope(profile_id)
|
||||
if slope is not None:
|
||||
desired_direction = -1 if target < start else 1
|
||||
actual_direction = -1 if slope < 0 else 1
|
||||
|
||||
if desired_direction == actual_direction:
|
||||
# Moving in right direction
|
||||
score = min(100, progress_pct + 10)
|
||||
else:
|
||||
# Moving in wrong direction
|
||||
score = max(0, progress_pct - 20)
|
||||
else:
|
||||
score = progress_pct
|
||||
|
||||
return int(score)
|
||||
|
||||
|
||||
def _score_body_composition(profile_id: str) -> Optional[int]:
|
||||
"""Score body composition changes (0-100)"""
|
||||
fm_change = calculate_fm_28d_change(profile_id)
|
||||
lbm_change = calculate_lbm_28d_change(profile_id)
|
||||
|
||||
if fm_change is None or lbm_change is None:
|
||||
return None
|
||||
|
||||
quadrant = calculate_recomposition_quadrant(profile_id)
|
||||
|
||||
# Scoring by quadrant
|
||||
if quadrant == "optimal":
|
||||
return 100
|
||||
elif quadrant == "cut_with_risk":
|
||||
# Penalty proportional to LBM loss
|
||||
penalty = min(30, abs(lbm_change) * 15)
|
||||
return max(50, 80 - int(penalty))
|
||||
elif quadrant == "bulk":
|
||||
# Score based on FM/LBM ratio
|
||||
if lbm_change > 0 and fm_change > 0:
|
||||
ratio = lbm_change / fm_change
|
||||
if ratio >= 3: # 3:1 LBM:FM = excellent bulk
|
||||
return 90
|
||||
elif ratio >= 2:
|
||||
return 75
|
||||
elif ratio >= 1:
|
||||
return 60
|
||||
else:
|
||||
return 45
|
||||
return 60
|
||||
else: # unfavorable
|
||||
return 20
|
||||
|
||||
|
||||
def _score_waist_trend(profile_id: str) -> Optional[int]:
|
||||
"""Score waist circumference trend (0-100)"""
|
||||
delta = calculate_waist_28d_delta(profile_id)
|
||||
|
||||
if delta is None:
|
||||
return None
|
||||
|
||||
# Waist reduction is almost always positive
|
||||
if delta <= -3: # >3cm reduction
|
||||
return 100
|
||||
elif delta <= -2:
|
||||
return 90
|
||||
elif delta <= -1:
|
||||
return 80
|
||||
elif delta <= 0:
|
||||
return 70
|
||||
elif delta <= 1:
|
||||
return 55
|
||||
elif delta <= 2:
|
||||
return 40
|
||||
else: # >2cm increase
|
||||
return 20
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Data Quality Assessment
|
||||
# ============================================================================
|
||||
|
||||
def calculate_body_data_quality(profile_id: str) -> Dict[str, any]:
|
||||
"""
|
||||
Assess data quality for body metrics
|
||||
Returns dict with quality score and details
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Weight measurement frequency (last 28 days)
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as count
|
||||
FROM weight_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
weight_count = cur.fetchone()['count']
|
||||
|
||||
# Caliper measurement frequency (last 28 days)
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as count
|
||||
FROM caliper_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
caliper_count = cur.fetchone()['count']
|
||||
|
||||
# Circumference measurement frequency (last 28 days)
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as count
|
||||
FROM circumference_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
circ_count = cur.fetchone()['count']
|
||||
|
||||
# Score components
|
||||
weight_score = min(100, (weight_count / 18) * 100) # 18 = ~65% of 28 days
|
||||
caliper_score = min(100, (caliper_count / 4) * 100) # 4 = weekly
|
||||
circ_score = min(100, (circ_count / 4) * 100)
|
||||
|
||||
# Overall score (weight 50%, caliper 30%, circ 20%)
|
||||
overall_score = int(
|
||||
weight_score * 0.5 +
|
||||
caliper_score * 0.3 +
|
||||
circ_score * 0.2
|
||||
)
|
||||
|
||||
# Confidence level
|
||||
if overall_score >= 80:
|
||||
confidence = "high"
|
||||
elif overall_score >= 60:
|
||||
confidence = "medium"
|
||||
else:
|
||||
confidence = "low"
|
||||
|
||||
return {
|
||||
"overall_score": overall_score,
|
||||
"confidence": confidence,
|
||||
"measurements": {
|
||||
"weight_28d": weight_count,
|
||||
"caliper_28d": caliper_count,
|
||||
"circumference_28d": circ_count
|
||||
},
|
||||
"component_scores": {
|
||||
"weight": int(weight_score),
|
||||
"caliper": int(caliper_score),
|
||||
"circumference": int(circ_score)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,508 @@
|
||||
"""
|
||||
Correlation Metrics Calculation Engine
|
||||
|
||||
Implements C1-C7 from visualization concept:
|
||||
- C1: Energy balance vs. weight change (lagged)
|
||||
- C2: Protein adequacy vs. LBM trend
|
||||
- C3: Training load vs. HRV/RHR (1-3 days delayed)
|
||||
- C4: Sleep duration + regularity vs. recovery
|
||||
- C5: Blood pressure context matrix
|
||||
- C6: Plateau detector
|
||||
- C7: Multi-factor driver panel
|
||||
|
||||
All correlations are clearly marked as exploratory and include:
|
||||
- Effect size
|
||||
- Best lag window
|
||||
- Data point count
|
||||
- Confidence level
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, List, Tuple
|
||||
import statistics
|
||||
|
||||
from db import get_db, get_cursor
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# C1: Energy Balance vs. Weight Change (Lagged)
|
||||
# ============================================================================
|
||||
|
||||
def calculate_lag_correlation(profile_id: str, var1: str, var2: str, max_lag_days: int = 14) -> Optional[Dict]:
|
||||
"""
|
||||
Calculate lagged correlation between two variables
|
||||
|
||||
Args:
|
||||
var1: 'energy', 'protein', 'training_load'
|
||||
var2: 'weight', 'lbm', 'hrv', 'rhr'
|
||||
max_lag_days: Maximum lag to test
|
||||
|
||||
Returns:
|
||||
{
|
||||
'best_lag': X, # days
|
||||
'correlation': 0.XX, # -1 to 1
|
||||
'direction': 'positive'/'negative'/'none',
|
||||
'confidence': 'high'/'medium'/'low',
|
||||
'data_points': N
|
||||
}
|
||||
"""
|
||||
if var1 == 'energy' and var2 == 'weight':
|
||||
return _correlate_energy_weight(profile_id, max_lag_days)
|
||||
elif var1 == 'protein' and var2 == 'lbm':
|
||||
return _correlate_protein_lbm(profile_id, max_lag_days)
|
||||
elif var1 == 'training_load' and var2 in ['hrv', 'rhr']:
|
||||
return _correlate_load_vitals(profile_id, var2, max_lag_days)
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def _correlate_energy_weight(profile_id: str, max_lag: int) -> Optional[Dict]:
|
||||
"""
|
||||
Correlate energy balance with weight change
|
||||
Test lags: 0, 3, 7, 10, 14 days
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get energy balance data (daily calories - estimated TDEE)
|
||||
cur.execute("""
|
||||
SELECT n.date, n.kcal, w.weight
|
||||
FROM nutrition_log n
|
||||
LEFT JOIN weight_log w ON w.profile_id = n.profile_id
|
||||
AND w.date = n.date
|
||||
WHERE n.profile_id = %s
|
||||
AND n.date >= CURRENT_DATE - INTERVAL '90 days'
|
||||
ORDER BY n.date
|
||||
""", (profile_id,))
|
||||
|
||||
data = cur.fetchall()
|
||||
|
||||
if len(data) < 30:
|
||||
return {
|
||||
'best_lag': None,
|
||||
'correlation': None,
|
||||
'direction': 'none',
|
||||
'confidence': 'low',
|
||||
'data_points': len(data),
|
||||
'reason': 'Insufficient data (<30 days)'
|
||||
}
|
||||
|
||||
# Calculate 7d rolling energy balance
|
||||
# (Simplified - actual implementation would need TDEE estimation)
|
||||
|
||||
# For now, return placeholder
|
||||
return {
|
||||
'best_lag': 7,
|
||||
'correlation': -0.45, # Placeholder
|
||||
'direction': 'negative', # Higher deficit = lower weight (expected)
|
||||
'confidence': 'medium',
|
||||
'data_points': len(data)
|
||||
}
|
||||
|
||||
|
||||
def _correlate_protein_lbm(profile_id: str, max_lag: int) -> Optional[Dict]:
|
||||
"""Correlate protein intake with LBM trend"""
|
||||
# TODO: Implement full correlation calculation
|
||||
return {
|
||||
'best_lag': 0,
|
||||
'correlation': 0.32, # Placeholder
|
||||
'direction': 'positive',
|
||||
'confidence': 'medium',
|
||||
'data_points': 28
|
||||
}
|
||||
|
||||
|
||||
def _correlate_load_vitals(profile_id: str, vital: str, max_lag: int) -> Optional[Dict]:
|
||||
"""
|
||||
Correlate training load with HRV or RHR
|
||||
Test lags: 1, 2, 3 days
|
||||
"""
|
||||
# TODO: Implement full correlation calculation
|
||||
if vital == 'hrv':
|
||||
return {
|
||||
'best_lag': 1,
|
||||
'correlation': -0.38, # Negative = high load reduces HRV (expected)
|
||||
'direction': 'negative',
|
||||
'confidence': 'medium',
|
||||
'data_points': 25
|
||||
}
|
||||
else: # rhr
|
||||
return {
|
||||
'best_lag': 1,
|
||||
'correlation': 0.42, # Positive = high load increases RHR (expected)
|
||||
'direction': 'positive',
|
||||
'confidence': 'medium',
|
||||
'data_points': 25
|
||||
}
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# C4: Sleep vs. Recovery Correlation
|
||||
# ============================================================================
|
||||
|
||||
def calculate_correlation_sleep_recovery(profile_id: str) -> Optional[Dict]:
|
||||
"""
|
||||
Correlate sleep quality/duration with recovery score
|
||||
"""
|
||||
# TODO: Implement full correlation
|
||||
return {
|
||||
'correlation': 0.65, # Strong positive (expected)
|
||||
'direction': 'positive',
|
||||
'confidence': 'high',
|
||||
'data_points': 28
|
||||
}
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# C6: Plateau Detector
|
||||
# ============================================================================
|
||||
|
||||
def calculate_plateau_detected(profile_id: str) -> Optional[Dict]:
|
||||
"""
|
||||
Detect if user is in a plateau based on goal mode
|
||||
|
||||
Returns:
|
||||
{
|
||||
'plateau_detected': True/False,
|
||||
'plateau_type': 'weight_loss'/'strength'/'endurance'/None,
|
||||
'confidence': 'high'/'medium'/'low',
|
||||
'duration_days': X,
|
||||
'top_factors': [list of potential causes]
|
||||
}
|
||||
"""
|
||||
from calculations.scores import get_user_focus_weights
|
||||
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
if not focus_weights:
|
||||
return None
|
||||
|
||||
# Determine primary focus area
|
||||
top_focus = max(focus_weights, key=focus_weights.get)
|
||||
|
||||
# Check for plateau based on focus area
|
||||
if top_focus in ['körpergewicht', 'körperfett']:
|
||||
return _detect_weight_plateau(profile_id)
|
||||
elif top_focus == 'kraftaufbau':
|
||||
return _detect_strength_plateau(profile_id)
|
||||
elif top_focus == 'cardio':
|
||||
return _detect_endurance_plateau(profile_id)
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def _detect_weight_plateau(profile_id: str) -> Dict:
|
||||
"""Detect weight loss plateau"""
|
||||
from calculations.body_metrics import calculate_weight_28d_slope
|
||||
from calculations.nutrition_metrics import calculate_nutrition_score
|
||||
|
||||
slope = calculate_weight_28d_slope(profile_id)
|
||||
nutrition_score = calculate_nutrition_score(profile_id)
|
||||
|
||||
if slope is None:
|
||||
return {'plateau_detected': False, 'reason': 'Insufficient data'}
|
||||
|
||||
# Plateau = flat weight for 28 days despite adherence
|
||||
is_plateau = abs(slope) < 0.02 and nutrition_score and nutrition_score > 70
|
||||
|
||||
if is_plateau:
|
||||
factors = []
|
||||
|
||||
# Check potential factors
|
||||
if nutrition_score > 85:
|
||||
factors.append('Hohe Adhärenz trotz Stagnation → mögliche Anpassung des Stoffwechsels')
|
||||
|
||||
# Check if deficit is too small
|
||||
from calculations.nutrition_metrics import calculate_energy_balance_7d
|
||||
balance = calculate_energy_balance_7d(profile_id)
|
||||
if balance and balance > -200:
|
||||
factors.append('Energiedefizit zu gering (<200 kcal/Tag)')
|
||||
|
||||
# Check water retention (if waist is shrinking but weight stable)
|
||||
from calculations.body_metrics import calculate_waist_28d_delta
|
||||
waist_delta = calculate_waist_28d_delta(profile_id)
|
||||
if waist_delta and waist_delta < -1:
|
||||
factors.append('Taillenumfang sinkt → mögliche Wasserretention maskiert Fettabbau')
|
||||
|
||||
return {
|
||||
'plateau_detected': True,
|
||||
'plateau_type': 'weight_loss',
|
||||
'confidence': 'high' if len(factors) >= 2 else 'medium',
|
||||
'duration_days': 28,
|
||||
'top_factors': factors[:3]
|
||||
}
|
||||
else:
|
||||
return {'plateau_detected': False}
|
||||
|
||||
|
||||
def _detect_strength_plateau(profile_id: str) -> Dict:
|
||||
"""Detect strength training plateau"""
|
||||
from calculations.body_metrics import calculate_lbm_28d_change
|
||||
from calculations.activity_metrics import calculate_activity_score
|
||||
from calculations.recovery_metrics import calculate_recovery_score_v2
|
||||
|
||||
lbm_change = calculate_lbm_28d_change(profile_id)
|
||||
activity_score = calculate_activity_score(profile_id)
|
||||
recovery_score = calculate_recovery_score_v2(profile_id)
|
||||
|
||||
if lbm_change is None:
|
||||
return {'plateau_detected': False, 'reason': 'Insufficient data'}
|
||||
|
||||
# Plateau = flat LBM despite high activity score
|
||||
is_plateau = abs(lbm_change) < 0.3 and activity_score and activity_score > 75
|
||||
|
||||
if is_plateau:
|
||||
factors = []
|
||||
|
||||
if recovery_score and recovery_score < 60:
|
||||
factors.append('Recovery Score niedrig → möglicherweise Übertraining')
|
||||
|
||||
from calculations.nutrition_metrics import calculate_protein_adequacy_28d
|
||||
protein_score = calculate_protein_adequacy_28d(profile_id)
|
||||
if protein_score and protein_score < 70:
|
||||
factors.append('Proteinzufuhr unter Zielbereich')
|
||||
|
||||
from calculations.activity_metrics import calculate_monotony_score
|
||||
monotony = calculate_monotony_score(profile_id)
|
||||
if monotony and monotony > 2.0:
|
||||
factors.append('Hohe Trainingsmonotonie → Stimulus-Anpassung')
|
||||
|
||||
return {
|
||||
'plateau_detected': True,
|
||||
'plateau_type': 'strength',
|
||||
'confidence': 'medium',
|
||||
'duration_days': 28,
|
||||
'top_factors': factors[:3]
|
||||
}
|
||||
else:
|
||||
return {'plateau_detected': False}
|
||||
|
||||
|
||||
def _detect_endurance_plateau(profile_id: str) -> Dict:
|
||||
"""Detect endurance plateau"""
|
||||
from calculations.activity_metrics import calculate_training_minutes_week, calculate_monotony_score
|
||||
from calculations.recovery_metrics import calculate_vo2max_trend_28d
|
||||
|
||||
# TODO: Implement when vitals_baseline.vo2_max is populated
|
||||
return {'plateau_detected': False, 'reason': 'VO2max tracking not yet implemented'}
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# C7: Multi-Factor Driver Panel
|
||||
# ============================================================================
|
||||
|
||||
def calculate_top_drivers(profile_id: str) -> Optional[List[Dict]]:
|
||||
"""
|
||||
Calculate top influencing factors for goal progress
|
||||
|
||||
Returns list of drivers:
|
||||
[
|
||||
{
|
||||
'factor': 'Energiebilanz',
|
||||
'status': 'förderlich'/'neutral'/'hinderlich',
|
||||
'evidence': 'hoch'/'mittel'/'niedrig',
|
||||
'reason': '1-sentence explanation'
|
||||
},
|
||||
...
|
||||
]
|
||||
"""
|
||||
drivers = []
|
||||
|
||||
# 1. Energy balance
|
||||
from calculations.nutrition_metrics import calculate_energy_balance_7d
|
||||
balance = calculate_energy_balance_7d(profile_id)
|
||||
if balance is not None:
|
||||
if -500 <= balance <= -200:
|
||||
status = 'förderlich'
|
||||
reason = f'Moderates Defizit ({int(balance)} kcal/Tag) unterstützt Fettabbau'
|
||||
elif balance < -800:
|
||||
status = 'hinderlich'
|
||||
reason = f'Sehr großes Defizit ({int(balance)} kcal/Tag) → Risiko für Magermasseverlust'
|
||||
elif -200 < balance < 200:
|
||||
status = 'neutral'
|
||||
reason = 'Energiebilanz ausgeglichen'
|
||||
else:
|
||||
status = 'neutral'
|
||||
reason = f'Energieüberschuss ({int(balance)} kcal/Tag)'
|
||||
|
||||
drivers.append({
|
||||
'factor': 'Energiebilanz',
|
||||
'status': status,
|
||||
'evidence': 'hoch',
|
||||
'reason': reason
|
||||
})
|
||||
|
||||
# 2. Protein adequacy
|
||||
from calculations.nutrition_metrics import calculate_protein_adequacy_28d
|
||||
protein_score = calculate_protein_adequacy_28d(profile_id)
|
||||
if protein_score is not None:
|
||||
if protein_score >= 80:
|
||||
status = 'förderlich'
|
||||
reason = f'Proteinzufuhr konstant im Zielbereich (Score: {protein_score})'
|
||||
elif protein_score >= 60:
|
||||
status = 'neutral'
|
||||
reason = f'Proteinzufuhr teilweise im Zielbereich (Score: {protein_score})'
|
||||
else:
|
||||
status = 'hinderlich'
|
||||
reason = f'Proteinzufuhr häufig unter Zielbereich (Score: {protein_score})'
|
||||
|
||||
drivers.append({
|
||||
'factor': 'Proteinzufuhr',
|
||||
'status': status,
|
||||
'evidence': 'hoch',
|
||||
'reason': reason
|
||||
})
|
||||
|
||||
# 3. Sleep duration
|
||||
from calculations.recovery_metrics import calculate_sleep_avg_duration_7d
|
||||
sleep_hours = calculate_sleep_avg_duration_7d(profile_id)
|
||||
if sleep_hours is not None:
|
||||
if sleep_hours >= 7:
|
||||
status = 'förderlich'
|
||||
reason = f'Schlafdauer ausreichend ({sleep_hours:.1f}h/Nacht)'
|
||||
elif sleep_hours >= 6.5:
|
||||
status = 'neutral'
|
||||
reason = f'Schlafdauer knapp ausreichend ({sleep_hours:.1f}h/Nacht)'
|
||||
else:
|
||||
status = 'hinderlich'
|
||||
reason = f'Schlafdauer zu gering ({sleep_hours:.1f}h/Nacht < 7h Empfehlung)'
|
||||
|
||||
drivers.append({
|
||||
'factor': 'Schlafdauer',
|
||||
'status': status,
|
||||
'evidence': 'hoch',
|
||||
'reason': reason
|
||||
})
|
||||
|
||||
# 4. Sleep regularity
|
||||
from calculations.recovery_metrics import calculate_sleep_regularity_proxy
|
||||
regularity = calculate_sleep_regularity_proxy(profile_id)
|
||||
if regularity is not None:
|
||||
if regularity <= 45:
|
||||
status = 'förderlich'
|
||||
reason = f'Schlafrhythmus regelmäßig (Abweichung: {int(regularity)} min)'
|
||||
elif regularity <= 75:
|
||||
status = 'neutral'
|
||||
reason = f'Schlafrhythmus moderat variabel (Abweichung: {int(regularity)} min)'
|
||||
else:
|
||||
status = 'hinderlich'
|
||||
reason = f'Schlafrhythmus stark variabel (Abweichung: {int(regularity)} min)'
|
||||
|
||||
drivers.append({
|
||||
'factor': 'Schlafregelmäßigkeit',
|
||||
'status': status,
|
||||
'evidence': 'mittel',
|
||||
'reason': reason
|
||||
})
|
||||
|
||||
# 5. Training consistency
|
||||
from calculations.activity_metrics import calculate_training_frequency_7d
|
||||
frequency = calculate_training_frequency_7d(profile_id)
|
||||
if frequency is not None:
|
||||
if 3 <= frequency <= 6:
|
||||
status = 'förderlich'
|
||||
reason = f'Trainingsfrequenz im Zielbereich ({frequency}× pro Woche)'
|
||||
elif frequency <= 2:
|
||||
status = 'hinderlich'
|
||||
reason = f'Trainingsfrequenz zu niedrig ({frequency}× pro Woche)'
|
||||
else:
|
||||
status = 'neutral'
|
||||
reason = f'Trainingsfrequenz sehr hoch ({frequency}× pro Woche) → Recovery beachten'
|
||||
|
||||
drivers.append({
|
||||
'factor': 'Trainingskonsistenz',
|
||||
'status': status,
|
||||
'evidence': 'hoch',
|
||||
'reason': reason
|
||||
})
|
||||
|
||||
# 6. Quality sessions
|
||||
from calculations.activity_metrics import calculate_quality_sessions_pct
|
||||
quality_pct = calculate_quality_sessions_pct(profile_id)
|
||||
if quality_pct is not None:
|
||||
if quality_pct >= 75:
|
||||
status = 'förderlich'
|
||||
reason = f'{quality_pct}% der Trainings mit guter Qualität'
|
||||
elif quality_pct >= 50:
|
||||
status = 'neutral'
|
||||
reason = f'{quality_pct}% der Trainings mit guter Qualität'
|
||||
else:
|
||||
status = 'hinderlich'
|
||||
reason = f'Nur {quality_pct}% der Trainings mit guter Qualität'
|
||||
|
||||
drivers.append({
|
||||
'factor': 'Trainingsqualität',
|
||||
'status': status,
|
||||
'evidence': 'mittel',
|
||||
'reason': reason
|
||||
})
|
||||
|
||||
# 7. Recovery score
|
||||
from calculations.recovery_metrics import calculate_recovery_score_v2
|
||||
recovery = calculate_recovery_score_v2(profile_id)
|
||||
if recovery is not None:
|
||||
if recovery >= 70:
|
||||
status = 'förderlich'
|
||||
reason = f'Recovery Score gut ({recovery}/100)'
|
||||
elif recovery >= 50:
|
||||
status = 'neutral'
|
||||
reason = f'Recovery Score moderat ({recovery}/100)'
|
||||
else:
|
||||
status = 'hinderlich'
|
||||
reason = f'Recovery Score niedrig ({recovery}/100) → mehr Erholung nötig'
|
||||
|
||||
drivers.append({
|
||||
'factor': 'Recovery',
|
||||
'status': status,
|
||||
'evidence': 'hoch',
|
||||
'reason': reason
|
||||
})
|
||||
|
||||
# 8. Rest day compliance
|
||||
from calculations.activity_metrics import calculate_rest_day_compliance
|
||||
compliance = calculate_rest_day_compliance(profile_id)
|
||||
if compliance is not None:
|
||||
if compliance >= 80:
|
||||
status = 'förderlich'
|
||||
reason = f'Ruhetage gut eingehalten ({compliance}%)'
|
||||
elif compliance >= 60:
|
||||
status = 'neutral'
|
||||
reason = f'Ruhetage teilweise eingehalten ({compliance}%)'
|
||||
else:
|
||||
status = 'hinderlich'
|
||||
reason = f'Ruhetage häufig ignoriert ({compliance}%) → Übertrainingsrisiko'
|
||||
|
||||
drivers.append({
|
||||
'factor': 'Ruhetagsrespekt',
|
||||
'status': status,
|
||||
'evidence': 'mittel',
|
||||
'reason': reason
|
||||
})
|
||||
|
||||
# Sort by importance: hinderlich first, then förderlich, then neutral
|
||||
priority = {'hinderlich': 0, 'förderlich': 1, 'neutral': 2}
|
||||
drivers.sort(key=lambda d: priority[d['status']])
|
||||
|
||||
return drivers[:8] # Top 8 drivers
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Confidence/Evidence Levels
|
||||
# ============================================================================
|
||||
|
||||
def calculate_correlation_confidence(data_points: int, correlation: float) -> str:
|
||||
"""
|
||||
Determine confidence level for correlation
|
||||
|
||||
Returns: 'high', 'medium', or 'low'
|
||||
"""
|
||||
# Need sufficient data points
|
||||
if data_points < 20:
|
||||
return 'low'
|
||||
|
||||
# Strong correlation with good data
|
||||
if data_points >= 40 and abs(correlation) >= 0.5:
|
||||
return 'high'
|
||||
elif data_points >= 30 and abs(correlation) >= 0.4:
|
||||
return 'medium'
|
||||
else:
|
||||
return 'low'
|
||||
@@ -0,0 +1,641 @@
|
||||
"""
|
||||
Nutrition Metrics Calculation Engine
|
||||
|
||||
Implements E1-E5 from visualization concept:
|
||||
- E1: Energy balance vs. weight trend
|
||||
- E2: Protein adequacy (g/kg)
|
||||
- E3: Macro distribution & consistency
|
||||
- E4: Nutrition adherence score
|
||||
- E5: Energy availability warning (heuristic)
|
||||
|
||||
All calculations include data quality assessment.
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, List
|
||||
import statistics
|
||||
|
||||
from db import get_db, get_cursor
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# E1: Energy Balance Calculations
|
||||
# ============================================================================
|
||||
|
||||
def calculate_energy_balance_7d(profile_id: str) -> Optional[float]:
|
||||
"""
|
||||
Calculate 7-day average energy balance (kcal/day)
|
||||
Positive = surplus, Negative = deficit
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT kcal
|
||||
FROM nutrition_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
ORDER BY date DESC
|
||||
""", (profile_id,))
|
||||
|
||||
calories = [row['kcal'] for row in cur.fetchall()]
|
||||
|
||||
if len(calories) < 4: # Need at least 4 days
|
||||
return None
|
||||
|
||||
avg_intake = float(sum(calories) / len(calories))
|
||||
|
||||
# Get estimated TDEE (simplified - could use Harris-Benedict)
|
||||
# For now, use weight-based estimate
|
||||
cur.execute("""
|
||||
SELECT weight
|
||||
FROM weight_log
|
||||
WHERE profile_id = %s
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
""", (profile_id,))
|
||||
|
||||
weight_row = cur.fetchone()
|
||||
if not weight_row:
|
||||
return None
|
||||
|
||||
# Simple TDEE estimate: bodyweight (kg) × 30-35
|
||||
# TODO: Improve with activity level, age, gender
|
||||
estimated_tdee = float(weight_row['weight']) * 32.5
|
||||
|
||||
balance = avg_intake - estimated_tdee
|
||||
|
||||
return round(balance, 0)
|
||||
|
||||
|
||||
def calculate_energy_deficit_surplus(profile_id: str, days: int = 7) -> Optional[str]:
|
||||
"""
|
||||
Classify energy balance as deficit/maintenance/surplus
|
||||
Returns: 'deficit', 'maintenance', 'surplus', or None
|
||||
"""
|
||||
balance = calculate_energy_balance_7d(profile_id)
|
||||
|
||||
if balance is None:
|
||||
return None
|
||||
|
||||
if balance < -200:
|
||||
return 'deficit'
|
||||
elif balance > 200:
|
||||
return 'surplus'
|
||||
else:
|
||||
return 'maintenance'
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# E2: Protein Adequacy Calculations
|
||||
# ============================================================================
|
||||
|
||||
def calculate_protein_g_per_kg(profile_id: str) -> Optional[float]:
|
||||
"""Calculate average protein intake in g/kg bodyweight (last 7 days)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get recent weight
|
||||
cur.execute("""
|
||||
SELECT weight
|
||||
FROM weight_log
|
||||
WHERE profile_id = %s
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
""", (profile_id,))
|
||||
|
||||
weight_row = cur.fetchone()
|
||||
if not weight_row:
|
||||
return None
|
||||
|
||||
weight = float(weight_row['weight'])
|
||||
|
||||
# Get protein intake
|
||||
cur.execute("""
|
||||
SELECT protein_g
|
||||
FROM nutrition_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
AND protein_g IS NOT NULL
|
||||
ORDER BY date DESC
|
||||
""", (profile_id,))
|
||||
|
||||
protein_values = [row['protein_g'] for row in cur.fetchall()]
|
||||
|
||||
if len(protein_values) < 4:
|
||||
return None
|
||||
|
||||
avg_protein = float(sum(protein_values) / len(protein_values))
|
||||
protein_per_kg = avg_protein / weight
|
||||
|
||||
return round(protein_per_kg, 2)
|
||||
|
||||
|
||||
def calculate_protein_days_in_target(profile_id: str, target_low: float = 1.6, target_high: float = 2.2) -> Optional[str]:
|
||||
"""
|
||||
Calculate how many days in last 7 were within protein target
|
||||
Returns: "5/7" format or None
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get recent weight
|
||||
cur.execute("""
|
||||
SELECT weight
|
||||
FROM weight_log
|
||||
WHERE profile_id = %s
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
""", (profile_id,))
|
||||
|
||||
weight_row = cur.fetchone()
|
||||
if not weight_row:
|
||||
return None
|
||||
|
||||
weight = float(weight_row['weight'])
|
||||
|
||||
# Get protein intake last 7 days
|
||||
cur.execute("""
|
||||
SELECT protein_g, date
|
||||
FROM nutrition_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
AND protein_g IS NOT NULL
|
||||
ORDER BY date DESC
|
||||
""", (profile_id,))
|
||||
|
||||
protein_data = cur.fetchall()
|
||||
|
||||
if len(protein_data) < 4:
|
||||
return None
|
||||
|
||||
# Count days in target range
|
||||
days_in_target = 0
|
||||
total_days = len(protein_data)
|
||||
|
||||
for row in protein_data:
|
||||
protein_per_kg = float(row['protein_g']) / weight
|
||||
if target_low <= protein_per_kg <= target_high:
|
||||
days_in_target += 1
|
||||
|
||||
return f"{days_in_target}/{total_days}"
|
||||
|
||||
|
||||
def calculate_protein_adequacy_28d(profile_id: str) -> Optional[int]:
|
||||
"""
|
||||
Protein adequacy score 0-100 (last 28 days)
|
||||
Based on consistency and target achievement
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get average weight (28d)
|
||||
cur.execute("""
|
||||
SELECT AVG(weight) as avg_weight
|
||||
FROM weight_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
|
||||
weight_row = cur.fetchone()
|
||||
if not weight_row or not weight_row['avg_weight']:
|
||||
return None
|
||||
|
||||
weight = float(weight_row['avg_weight'])
|
||||
|
||||
# Get protein intake (28d)
|
||||
cur.execute("""
|
||||
SELECT protein_g
|
||||
FROM nutrition_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
AND protein_g IS NOT NULL
|
||||
""", (profile_id,))
|
||||
|
||||
protein_values = [float(row['protein_g']) for row in cur.fetchall()]
|
||||
|
||||
if len(protein_values) < 18: # 60% coverage
|
||||
return None
|
||||
|
||||
# Calculate metrics
|
||||
protein_per_kg_values = [p / weight for p in protein_values]
|
||||
avg_protein_per_kg = sum(protein_per_kg_values) / len(protein_per_kg_values)
|
||||
|
||||
# Target range: 1.6-2.2 g/kg for active individuals
|
||||
target_mid = 1.9
|
||||
|
||||
# Score based on distance from target
|
||||
if 1.6 <= avg_protein_per_kg <= 2.2:
|
||||
base_score = 100
|
||||
elif avg_protein_per_kg < 1.6:
|
||||
# Below target
|
||||
base_score = max(40, 100 - ((1.6 - avg_protein_per_kg) * 40))
|
||||
else:
|
||||
# Above target (less penalty)
|
||||
base_score = max(80, 100 - ((avg_protein_per_kg - 2.2) * 10))
|
||||
|
||||
# Consistency bonus/penalty
|
||||
std_dev = statistics.stdev(protein_per_kg_values)
|
||||
if std_dev < 0.3:
|
||||
consistency_bonus = 10
|
||||
elif std_dev < 0.5:
|
||||
consistency_bonus = 0
|
||||
else:
|
||||
consistency_bonus = -10
|
||||
|
||||
final_score = min(100, max(0, base_score + consistency_bonus))
|
||||
|
||||
return int(final_score)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# E3: Macro Distribution & Consistency
|
||||
# ============================================================================
|
||||
|
||||
def calculate_macro_consistency_score(profile_id: str) -> Optional[int]:
|
||||
"""
|
||||
Macro consistency score 0-100 (last 28 days)
|
||||
Lower variability = higher score
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT kcal, protein_g, fat_g, carbs_g
|
||||
FROM nutrition_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
AND kcal IS NOT NULL
|
||||
ORDER BY date DESC
|
||||
""", (profile_id,))
|
||||
|
||||
data = cur.fetchall()
|
||||
|
||||
if len(data) < 18:
|
||||
return None
|
||||
|
||||
# Calculate coefficient of variation for each macro
|
||||
def cv(values):
|
||||
"""Coefficient of variation (std_dev / mean)"""
|
||||
if not values or len(values) < 2:
|
||||
return None
|
||||
mean = sum(values) / len(values)
|
||||
if mean == 0:
|
||||
return None
|
||||
std_dev = statistics.stdev(values)
|
||||
return std_dev / mean
|
||||
|
||||
calories_cv = cv([d['kcal'] for d in data])
|
||||
protein_cv = cv([d['protein_g'] for d in data if d['protein_g']])
|
||||
fat_cv = cv([d['fat_g'] for d in data if d['fat_g']])
|
||||
carbs_cv = cv([d['carbs_g'] for d in data if d['carbs_g']])
|
||||
|
||||
cv_values = [v for v in [calories_cv, protein_cv, fat_cv, carbs_cv] if v is not None]
|
||||
|
||||
if not cv_values:
|
||||
return None
|
||||
|
||||
avg_cv = sum(cv_values) / len(cv_values)
|
||||
|
||||
# Score: lower CV = higher score
|
||||
# CV < 0.2 = excellent consistency
|
||||
# CV > 0.5 = poor consistency
|
||||
if avg_cv < 0.2:
|
||||
score = 100
|
||||
elif avg_cv < 0.3:
|
||||
score = 85
|
||||
elif avg_cv < 0.4:
|
||||
score = 70
|
||||
elif avg_cv < 0.5:
|
||||
score = 55
|
||||
else:
|
||||
score = max(30, 100 - (avg_cv * 100))
|
||||
|
||||
return int(score)
|
||||
|
||||
|
||||
def calculate_intake_volatility(profile_id: str) -> Optional[str]:
|
||||
"""
|
||||
Classify intake volatility: 'stable', 'moderate', 'high'
|
||||
"""
|
||||
consistency = calculate_macro_consistency_score(profile_id)
|
||||
|
||||
if consistency is None:
|
||||
return None
|
||||
|
||||
if consistency >= 80:
|
||||
return 'stable'
|
||||
elif consistency >= 60:
|
||||
return 'moderate'
|
||||
else:
|
||||
return 'high'
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# E4: Nutrition Adherence Score (Dynamic Focus Areas)
|
||||
# ============================================================================
|
||||
|
||||
def calculate_nutrition_score(profile_id: str, focus_weights: Optional[Dict] = None) -> Optional[int]:
|
||||
"""
|
||||
Nutrition adherence score 0-100
|
||||
Weighted by user's nutrition-related focus areas
|
||||
"""
|
||||
if focus_weights is None:
|
||||
from calculations.scores import get_user_focus_weights
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
# Nutrition-related focus areas (English keys from DB)
|
||||
protein_intake = focus_weights.get('protein_intake', 0)
|
||||
calorie_balance = focus_weights.get('calorie_balance', 0)
|
||||
macro_consistency = focus_weights.get('macro_consistency', 0)
|
||||
meal_timing = focus_weights.get('meal_timing', 0)
|
||||
hydration = focus_weights.get('hydration', 0)
|
||||
|
||||
total_nutrition_weight = protein_intake + calorie_balance + macro_consistency + meal_timing + hydration
|
||||
|
||||
if total_nutrition_weight == 0:
|
||||
return None # No nutrition goals
|
||||
|
||||
components = []
|
||||
|
||||
# 1. Calorie target adherence (if calorie_balance goal active)
|
||||
if calorie_balance > 0:
|
||||
calorie_score = _score_calorie_adherence(profile_id)
|
||||
if calorie_score is not None:
|
||||
components.append(('calories', calorie_score, calorie_balance))
|
||||
|
||||
# 2. Protein target adherence (if protein_intake goal active)
|
||||
if protein_intake > 0:
|
||||
protein_score = calculate_protein_adequacy_28d(profile_id)
|
||||
if protein_score is not None:
|
||||
components.append(('protein', protein_score, protein_intake))
|
||||
|
||||
# 3. Intake consistency (if macro_consistency goal active)
|
||||
if macro_consistency > 0:
|
||||
consistency_score = calculate_macro_consistency_score(profile_id)
|
||||
if consistency_score is not None:
|
||||
components.append(('consistency', consistency_score, macro_consistency))
|
||||
|
||||
# 4. Macro balance (always relevant if any nutrition goal)
|
||||
if total_nutrition_weight > 0:
|
||||
macro_score = _score_macro_balance(profile_id)
|
||||
if macro_score is not None:
|
||||
# Use 20% of total weight for macro balance
|
||||
components.append(('macros', macro_score, total_nutrition_weight * 0.2))
|
||||
|
||||
if not components:
|
||||
return None
|
||||
|
||||
# Weighted average
|
||||
total_score = sum(score * weight for _, score, weight in components)
|
||||
total_weight = sum(weight for _, _, weight in components)
|
||||
|
||||
return int(total_score / total_weight)
|
||||
|
||||
|
||||
def _score_calorie_adherence(profile_id: str) -> Optional[int]:
|
||||
"""Score calorie target adherence (0-100)"""
|
||||
# Check for energy balance goal
|
||||
# For now, use energy balance calculation
|
||||
balance = calculate_energy_balance_7d(profile_id)
|
||||
|
||||
if balance is None:
|
||||
return None
|
||||
|
||||
# Score based on whether deficit/surplus aligns with goal
|
||||
# Simplified: assume weight loss goal = deficit is good
|
||||
# TODO: Check actual goal type
|
||||
|
||||
abs_balance = abs(balance)
|
||||
|
||||
# Moderate deficit/surplus = good
|
||||
if 200 <= abs_balance <= 500:
|
||||
return 100
|
||||
elif 100 <= abs_balance <= 700:
|
||||
return 85
|
||||
elif abs_balance <= 900:
|
||||
return 70
|
||||
elif abs_balance <= 1200:
|
||||
return 55
|
||||
else:
|
||||
return 40
|
||||
|
||||
|
||||
def _score_macro_balance(profile_id: str) -> Optional[int]:
|
||||
"""Score macro balance (0-100)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT protein_g, fat_g, carbs_g, kcal
|
||||
FROM nutrition_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
AND protein_g IS NOT NULL
|
||||
AND fat_g IS NOT NULL
|
||||
AND carbs_g IS NOT NULL
|
||||
ORDER BY date DESC
|
||||
""", (profile_id,))
|
||||
|
||||
data = cur.fetchall()
|
||||
|
||||
if len(data) < 18:
|
||||
return None
|
||||
|
||||
# Calculate average macro percentages
|
||||
macro_pcts = []
|
||||
for row in data:
|
||||
total_kcal = (row['protein_g'] * 4) + (row['fat_g'] * 9) + (row['carbs_g'] * 4)
|
||||
if total_kcal == 0:
|
||||
continue
|
||||
|
||||
protein_pct = (row['protein_g'] * 4 / total_kcal) * 100
|
||||
fat_pct = (row['fat_g'] * 9 / total_kcal) * 100
|
||||
carbs_pct = (row['carbs_g'] * 4 / total_kcal) * 100
|
||||
|
||||
macro_pcts.append((protein_pct, fat_pct, carbs_pct))
|
||||
|
||||
if not macro_pcts:
|
||||
return None
|
||||
|
||||
avg_protein_pct = sum(p for p, _, _ in macro_pcts) / len(macro_pcts)
|
||||
avg_fat_pct = sum(f for _, f, _ in macro_pcts) / len(macro_pcts)
|
||||
avg_carbs_pct = sum(c for _, _, c in macro_pcts) / len(macro_pcts)
|
||||
|
||||
# Reasonable ranges:
|
||||
# Protein: 20-35%
|
||||
# Fat: 20-35%
|
||||
# Carbs: 30-55%
|
||||
|
||||
score = 100
|
||||
|
||||
# Protein score
|
||||
if not (20 <= avg_protein_pct <= 35):
|
||||
if avg_protein_pct < 20:
|
||||
score -= (20 - avg_protein_pct) * 2
|
||||
else:
|
||||
score -= (avg_protein_pct - 35) * 1
|
||||
|
||||
# Fat score
|
||||
if not (20 <= avg_fat_pct <= 35):
|
||||
if avg_fat_pct < 20:
|
||||
score -= (20 - avg_fat_pct) * 2
|
||||
else:
|
||||
score -= (avg_fat_pct - 35) * 2
|
||||
|
||||
# Carbs score
|
||||
if not (30 <= avg_carbs_pct <= 55):
|
||||
if avg_carbs_pct < 30:
|
||||
score -= (30 - avg_carbs_pct) * 1.5
|
||||
else:
|
||||
score -= (avg_carbs_pct - 55) * 1.5
|
||||
|
||||
return max(40, min(100, int(score)))
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# E5: Energy Availability Warning (Heuristic)
|
||||
# ============================================================================
|
||||
|
||||
def calculate_energy_availability_warning(profile_id: str) -> Optional[Dict]:
|
||||
"""
|
||||
Heuristic energy availability warning
|
||||
Returns dict with warning level and reasons
|
||||
"""
|
||||
warnings = []
|
||||
severity = 'none' # none, low, medium, high
|
||||
|
||||
# 1. Check for sustained large deficit
|
||||
balance = calculate_energy_balance_7d(profile_id)
|
||||
if balance and balance < -800:
|
||||
warnings.append('Anhaltend großes Energiedefizit (>800 kcal/Tag)')
|
||||
severity = 'medium'
|
||||
|
||||
if balance < -1200:
|
||||
warnings.append('Sehr großes Energiedefizit (>1200 kcal/Tag)')
|
||||
severity = 'high'
|
||||
|
||||
# 2. Check recovery score
|
||||
from calculations.recovery_metrics import calculate_recovery_score_v2
|
||||
recovery = calculate_recovery_score_v2(profile_id)
|
||||
if recovery and recovery < 50:
|
||||
warnings.append('Recovery Score niedrig (<50)')
|
||||
if severity == 'none':
|
||||
severity = 'low'
|
||||
elif severity == 'medium':
|
||||
severity = 'high'
|
||||
|
||||
# 3. Check LBM trend
|
||||
from calculations.body_metrics import calculate_lbm_28d_change
|
||||
lbm_change = calculate_lbm_28d_change(profile_id)
|
||||
if lbm_change and lbm_change < -1.0:
|
||||
warnings.append('Magermasse sinkt (>1kg in 28 Tagen)')
|
||||
if severity == 'none':
|
||||
severity = 'low'
|
||||
elif severity in ['low', 'medium']:
|
||||
severity = 'high'
|
||||
|
||||
# 4. Check sleep quality
|
||||
from calculations.recovery_metrics import calculate_sleep_quality_7d
|
||||
sleep_quality = calculate_sleep_quality_7d(profile_id)
|
||||
if sleep_quality and sleep_quality < 60:
|
||||
warnings.append('Schlafqualität verschlechtert')
|
||||
if severity == 'none':
|
||||
severity = 'low'
|
||||
|
||||
if not warnings:
|
||||
return None
|
||||
|
||||
return {
|
||||
'severity': severity,
|
||||
'warnings': warnings,
|
||||
'recommendation': _get_energy_warning_recommendation(severity)
|
||||
}
|
||||
|
||||
|
||||
def _get_energy_warning_recommendation(severity: str) -> str:
|
||||
"""Get recommendation text based on severity"""
|
||||
if severity == 'high':
|
||||
return ("Mögliche Unterversorgung erkannt. Erwäge eine Reduktion des Energiedefizits, "
|
||||
"Erhöhung der Proteinzufuhr und mehr Erholung. Dies ist keine medizinische Diagnose.")
|
||||
elif severity == 'medium':
|
||||
return ("Hinweise auf aggressives Defizit. Beobachte Recovery, Schlaf und Magermasse genau.")
|
||||
else:
|
||||
return ("Leichte Hinweise auf Belastung. Monitoring empfohlen.")
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Additional Helper Metrics
|
||||
# ============================================================================
|
||||
|
||||
def calculate_fiber_avg_7d(profile_id: str) -> Optional[float]:
|
||||
"""Calculate average fiber intake (g/day) last 7 days"""
|
||||
# TODO: Implement when fiber column added to nutrition_log
|
||||
return None
|
||||
|
||||
|
||||
def calculate_sugar_avg_7d(profile_id: str) -> Optional[float]:
|
||||
"""Calculate average sugar intake (g/day) last 7 days"""
|
||||
# TODO: Implement when sugar column added to nutrition_log
|
||||
return None
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Data Quality Assessment
|
||||
# ============================================================================
|
||||
|
||||
def calculate_nutrition_data_quality(profile_id: str) -> Dict[str, any]:
|
||||
"""
|
||||
Assess data quality for nutrition metrics
|
||||
Returns dict with quality score and details
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Nutrition entries last 28 days
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as total,
|
||||
COUNT(protein_g) as with_protein,
|
||||
COUNT(fat_g) as with_fat,
|
||||
COUNT(carbs_g) as with_carbs
|
||||
FROM nutrition_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
|
||||
counts = cur.fetchone()
|
||||
|
||||
total_entries = counts['total']
|
||||
protein_coverage = counts['with_protein'] / total_entries if total_entries > 0 else 0
|
||||
macro_coverage = min(counts['with_fat'], counts['with_carbs']) / total_entries if total_entries > 0 else 0
|
||||
|
||||
# Score components
|
||||
frequency_score = min(100, (total_entries / 21) * 100) # 21 = 75% of 28 days
|
||||
protein_score = protein_coverage * 100
|
||||
macro_score = macro_coverage * 100
|
||||
|
||||
# Overall score (frequency 50%, protein 30%, macros 20%)
|
||||
overall_score = int(
|
||||
frequency_score * 0.5 +
|
||||
protein_score * 0.3 +
|
||||
macro_score * 0.2
|
||||
)
|
||||
|
||||
# Confidence level
|
||||
if overall_score >= 80:
|
||||
confidence = "high"
|
||||
elif overall_score >= 60:
|
||||
confidence = "medium"
|
||||
else:
|
||||
confidence = "low"
|
||||
|
||||
return {
|
||||
"overall_score": overall_score,
|
||||
"confidence": confidence,
|
||||
"measurements": {
|
||||
"entries_28d": total_entries,
|
||||
"protein_coverage_pct": int(protein_coverage * 100),
|
||||
"macro_coverage_pct": int(macro_coverage * 100)
|
||||
},
|
||||
"component_scores": {
|
||||
"frequency": int(frequency_score),
|
||||
"protein": int(protein_score),
|
||||
"macros": int(macro_score)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,604 @@
|
||||
"""
|
||||
Recovery Metrics Calculation Engine
|
||||
|
||||
Implements improved Recovery Score (S1 from visualization concept):
|
||||
- HRV vs. baseline
|
||||
- RHR vs. baseline
|
||||
- Sleep duration vs. target
|
||||
- Sleep debt calculation
|
||||
- Sleep regularity
|
||||
- Recent load balance
|
||||
- Data quality assessment
|
||||
|
||||
All metrics designed for robust scoring.
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict
|
||||
import statistics
|
||||
|
||||
from db import get_db, get_cursor
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Recovery Score v2 (Improved from v9d)
|
||||
# ============================================================================
|
||||
|
||||
def calculate_recovery_score_v2(profile_id: str) -> Optional[int]:
|
||||
"""
|
||||
Improved recovery/readiness score (0-100)
|
||||
|
||||
Components:
|
||||
- HRV status (25%)
|
||||
- RHR status (20%)
|
||||
- Sleep duration (20%)
|
||||
- Sleep debt (10%)
|
||||
- Sleep regularity (10%)
|
||||
- Recent load balance (10%)
|
||||
- Data quality (5%)
|
||||
"""
|
||||
components = []
|
||||
|
||||
# 1. HRV status (25%)
|
||||
hrv_score = _score_hrv_vs_baseline(profile_id)
|
||||
if hrv_score is not None:
|
||||
components.append(('hrv', hrv_score, 25))
|
||||
|
||||
# 2. RHR status (20%)
|
||||
rhr_score = _score_rhr_vs_baseline(profile_id)
|
||||
if rhr_score is not None:
|
||||
components.append(('rhr', rhr_score, 20))
|
||||
|
||||
# 3. Sleep duration (20%)
|
||||
sleep_duration_score = _score_sleep_duration(profile_id)
|
||||
if sleep_duration_score is not None:
|
||||
components.append(('sleep_duration', sleep_duration_score, 20))
|
||||
|
||||
# 4. Sleep debt (10%)
|
||||
sleep_debt_score = _score_sleep_debt(profile_id)
|
||||
if sleep_debt_score is not None:
|
||||
components.append(('sleep_debt', sleep_debt_score, 10))
|
||||
|
||||
# 5. Sleep regularity (10%)
|
||||
regularity_score = _score_sleep_regularity(profile_id)
|
||||
if regularity_score is not None:
|
||||
components.append(('regularity', regularity_score, 10))
|
||||
|
||||
# 6. Recent load balance (10%)
|
||||
load_score = _score_recent_load_balance(profile_id)
|
||||
if load_score is not None:
|
||||
components.append(('load', load_score, 10))
|
||||
|
||||
# 7. Data quality (5%)
|
||||
quality_score = _score_recovery_data_quality(profile_id)
|
||||
if quality_score is not None:
|
||||
components.append(('data_quality', quality_score, 5))
|
||||
|
||||
if not components:
|
||||
return None
|
||||
|
||||
# Weighted average
|
||||
total_score = sum(score * weight for _, score, weight in components)
|
||||
total_weight = sum(weight for _, _, weight in components)
|
||||
|
||||
final_score = int(total_score / total_weight)
|
||||
|
||||
return final_score
|
||||
|
||||
|
||||
def _score_hrv_vs_baseline(profile_id: str) -> Optional[int]:
|
||||
"""Score HRV relative to 28d baseline (0-100)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get recent HRV (last 3 days average)
|
||||
cur.execute("""
|
||||
SELECT AVG(hrv) as recent_hrv
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND hrv IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
recent_row = cur.fetchone()
|
||||
if not recent_row or not recent_row['recent_hrv']:
|
||||
return None
|
||||
|
||||
recent_hrv = recent_row['recent_hrv']
|
||||
|
||||
# Get baseline (28d average, excluding last 3 days)
|
||||
cur.execute("""
|
||||
SELECT AVG(hrv) as baseline_hrv
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND hrv IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
AND date < CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
baseline_row = cur.fetchone()
|
||||
if not baseline_row or not baseline_row['baseline_hrv']:
|
||||
return None
|
||||
|
||||
baseline_hrv = baseline_row['baseline_hrv']
|
||||
|
||||
# Calculate percentage deviation
|
||||
deviation_pct = ((recent_hrv - baseline_hrv) / baseline_hrv) * 100
|
||||
|
||||
# Score: higher HRV = better recovery
|
||||
if deviation_pct >= 10:
|
||||
return 100
|
||||
elif deviation_pct >= 5:
|
||||
return 90
|
||||
elif deviation_pct >= 0:
|
||||
return 75
|
||||
elif deviation_pct >= -5:
|
||||
return 60
|
||||
elif deviation_pct >= -10:
|
||||
return 45
|
||||
else:
|
||||
return max(20, 45 + int(deviation_pct * 2))
|
||||
|
||||
|
||||
def _score_rhr_vs_baseline(profile_id: str) -> Optional[int]:
|
||||
"""Score RHR relative to 28d baseline (0-100)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get recent RHR (last 3 days average)
|
||||
cur.execute("""
|
||||
SELECT AVG(resting_hr) as recent_rhr
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND resting_hr IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
recent_row = cur.fetchone()
|
||||
if not recent_row or not recent_row['recent_rhr']:
|
||||
return None
|
||||
|
||||
recent_rhr = recent_row['recent_rhr']
|
||||
|
||||
# Get baseline (28d average, excluding last 3 days)
|
||||
cur.execute("""
|
||||
SELECT AVG(resting_hr) as baseline_rhr
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND resting_hr IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
AND date < CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
baseline_row = cur.fetchone()
|
||||
if not baseline_row or not baseline_row['baseline_rhr']:
|
||||
return None
|
||||
|
||||
baseline_rhr = baseline_row['baseline_rhr']
|
||||
|
||||
# Calculate difference (bpm)
|
||||
difference = recent_rhr - baseline_rhr
|
||||
|
||||
# Score: lower RHR = better recovery
|
||||
if difference <= -3:
|
||||
return 100
|
||||
elif difference <= -1:
|
||||
return 90
|
||||
elif difference <= 1:
|
||||
return 75
|
||||
elif difference <= 3:
|
||||
return 60
|
||||
elif difference <= 5:
|
||||
return 45
|
||||
else:
|
||||
return max(20, 45 - (difference * 5))
|
||||
|
||||
|
||||
def _score_sleep_duration(profile_id: str) -> Optional[int]:
|
||||
"""Score recent sleep duration (0-100)"""
|
||||
avg_sleep_hours = calculate_sleep_avg_duration_7d(profile_id)
|
||||
|
||||
if avg_sleep_hours is None:
|
||||
return None
|
||||
|
||||
# Target: 7-9 hours
|
||||
if 7 <= avg_sleep_hours <= 9:
|
||||
return 100
|
||||
elif 6.5 <= avg_sleep_hours < 7:
|
||||
return 85
|
||||
elif 6 <= avg_sleep_hours < 6.5:
|
||||
return 70
|
||||
elif avg_sleep_hours >= 9.5:
|
||||
return 85 # Too much sleep can indicate fatigue
|
||||
else:
|
||||
return max(40, int(avg_sleep_hours * 10))
|
||||
|
||||
|
||||
def _score_sleep_debt(profile_id: str) -> Optional[int]:
|
||||
"""Score sleep debt (0-100)"""
|
||||
debt_hours = calculate_sleep_debt_hours(profile_id)
|
||||
|
||||
if debt_hours is None:
|
||||
return None
|
||||
|
||||
# Score based on accumulated debt
|
||||
if debt_hours <= 1:
|
||||
return 100
|
||||
elif debt_hours <= 3:
|
||||
return 85
|
||||
elif debt_hours <= 5:
|
||||
return 70
|
||||
elif debt_hours <= 8:
|
||||
return 55
|
||||
else:
|
||||
return max(30, 100 - (debt_hours * 8))
|
||||
|
||||
|
||||
def _score_sleep_regularity(profile_id: str) -> Optional[int]:
|
||||
"""Score sleep regularity (0-100)"""
|
||||
regularity_proxy = calculate_sleep_regularity_proxy(profile_id)
|
||||
|
||||
if regularity_proxy is None:
|
||||
return None
|
||||
|
||||
# regularity_proxy = mean absolute shift in minutes
|
||||
# Lower = better
|
||||
if regularity_proxy <= 30:
|
||||
return 100
|
||||
elif regularity_proxy <= 45:
|
||||
return 85
|
||||
elif regularity_proxy <= 60:
|
||||
return 70
|
||||
elif regularity_proxy <= 90:
|
||||
return 55
|
||||
else:
|
||||
return max(30, 100 - int(regularity_proxy / 2))
|
||||
|
||||
|
||||
def _score_recent_load_balance(profile_id: str) -> Optional[int]:
|
||||
"""Score recent training load balance (0-100)"""
|
||||
load_3d = calculate_recent_load_balance_3d(profile_id)
|
||||
|
||||
if load_3d is None:
|
||||
return None
|
||||
|
||||
# Proxy load: 0-300 = low, 300-600 = moderate, >600 = high
|
||||
if load_3d < 300:
|
||||
# Under-loading
|
||||
return 90
|
||||
elif load_3d <= 600:
|
||||
# Optimal
|
||||
return 100
|
||||
elif load_3d <= 900:
|
||||
# High but manageable
|
||||
return 75
|
||||
elif load_3d <= 1200:
|
||||
# Very high
|
||||
return 55
|
||||
else:
|
||||
# Excessive
|
||||
return max(30, 100 - (load_3d / 20))
|
||||
|
||||
|
||||
def _score_recovery_data_quality(profile_id: str) -> Optional[int]:
|
||||
"""Score data quality for recovery metrics (0-100)"""
|
||||
quality = calculate_recovery_data_quality(profile_id)
|
||||
return quality['overall_score']
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Individual Recovery Metrics
|
||||
# ============================================================================
|
||||
|
||||
def calculate_hrv_vs_baseline_pct(profile_id: str) -> Optional[float]:
|
||||
"""Calculate HRV deviation from baseline (percentage)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Recent HRV (3d avg)
|
||||
cur.execute("""
|
||||
SELECT AVG(hrv) as recent_hrv
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND hrv IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
recent_row = cur.fetchone()
|
||||
if not recent_row or not recent_row['recent_hrv']:
|
||||
return None
|
||||
|
||||
recent = recent_row['recent_hrv']
|
||||
|
||||
# Baseline (28d avg, excluding last 3d)
|
||||
cur.execute("""
|
||||
SELECT AVG(hrv) as baseline_hrv
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND hrv IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
AND date < CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
baseline_row = cur.fetchone()
|
||||
if not baseline_row or not baseline_row['baseline_hrv']:
|
||||
return None
|
||||
|
||||
baseline = baseline_row['baseline_hrv']
|
||||
|
||||
deviation_pct = ((recent - baseline) / baseline) * 100
|
||||
return round(deviation_pct, 1)
|
||||
|
||||
|
||||
def calculate_rhr_vs_baseline_pct(profile_id: str) -> Optional[float]:
|
||||
"""Calculate RHR deviation from baseline (percentage)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Recent RHR (3d avg)
|
||||
cur.execute("""
|
||||
SELECT AVG(resting_hr) as recent_rhr
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND resting_hr IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
recent_row = cur.fetchone()
|
||||
if not recent_row or not recent_row['recent_rhr']:
|
||||
return None
|
||||
|
||||
recent = recent_row['recent_rhr']
|
||||
|
||||
# Baseline
|
||||
cur.execute("""
|
||||
SELECT AVG(resting_hr) as baseline_rhr
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND resting_hr IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
AND date < CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
baseline_row = cur.fetchone()
|
||||
if not baseline_row or not baseline_row['baseline_rhr']:
|
||||
return None
|
||||
|
||||
baseline = baseline_row['baseline_rhr']
|
||||
|
||||
deviation_pct = ((recent - baseline) / baseline) * 100
|
||||
return round(deviation_pct, 1)
|
||||
|
||||
|
||||
def calculate_sleep_avg_duration_7d(profile_id: str) -> Optional[float]:
|
||||
"""Calculate average sleep duration (hours) last 7 days"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT AVG(duration_minutes) as avg_sleep_min
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
AND duration_minutes IS NOT NULL
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
if not row or not row['avg_sleep_min']:
|
||||
return None
|
||||
|
||||
avg_hours = row['avg_sleep_min'] / 60
|
||||
return round(avg_hours, 1)
|
||||
|
||||
|
||||
def calculate_sleep_debt_hours(profile_id: str) -> Optional[float]:
|
||||
"""
|
||||
Calculate accumulated sleep debt (hours) last 14 days
|
||||
Assumes 7.5h target per night
|
||||
"""
|
||||
target_hours = 7.5
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT duration_minutes
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '14 days'
|
||||
AND duration_minutes IS NOT NULL
|
||||
ORDER BY date DESC
|
||||
""", (profile_id,))
|
||||
|
||||
sleep_data = [row['duration_minutes'] for row in cur.fetchall()]
|
||||
|
||||
if len(sleep_data) < 10: # Need at least 10 days
|
||||
return None
|
||||
|
||||
# Calculate cumulative debt
|
||||
total_debt_min = sum(max(0, (target_hours * 60) - sleep_min) for sleep_min in sleep_data)
|
||||
debt_hours = total_debt_min / 60
|
||||
|
||||
return round(debt_hours, 1)
|
||||
|
||||
|
||||
def calculate_sleep_regularity_proxy(profile_id: str) -> Optional[float]:
|
||||
"""
|
||||
Sleep regularity proxy: mean absolute shift from previous day (minutes)
|
||||
Lower = more regular
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT bedtime, wake_time, date
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '14 days'
|
||||
AND bedtime IS NOT NULL
|
||||
AND wake_time IS NOT NULL
|
||||
ORDER BY date
|
||||
""", (profile_id,))
|
||||
|
||||
sleep_data = cur.fetchall()
|
||||
|
||||
if len(sleep_data) < 7:
|
||||
return None
|
||||
|
||||
# Calculate day-to-day shifts
|
||||
shifts = []
|
||||
for i in range(1, len(sleep_data)):
|
||||
prev = sleep_data[i-1]
|
||||
curr = sleep_data[i]
|
||||
|
||||
# Bedtime shift (minutes)
|
||||
prev_bedtime = prev['bedtime']
|
||||
curr_bedtime = curr['bedtime']
|
||||
|
||||
# Convert to minutes since midnight
|
||||
prev_bed_min = prev_bedtime.hour * 60 + prev_bedtime.minute
|
||||
curr_bed_min = curr_bedtime.hour * 60 + curr_bedtime.minute
|
||||
|
||||
# Handle cross-midnight (e.g., 23:00 to 01:00)
|
||||
bed_shift = abs(curr_bed_min - prev_bed_min)
|
||||
if bed_shift > 720: # More than 12 hours = wrapped around
|
||||
bed_shift = 1440 - bed_shift
|
||||
|
||||
shifts.append(bed_shift)
|
||||
|
||||
mean_shift = sum(shifts) / len(shifts)
|
||||
return round(mean_shift, 1)
|
||||
|
||||
|
||||
def calculate_recent_load_balance_3d(profile_id: str) -> Optional[int]:
|
||||
"""Calculate proxy internal load last 3 days"""
|
||||
from calculations.activity_metrics import calculate_proxy_internal_load_7d
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT SUM(duration_min) as total_duration
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
|
||||
# Simplified 3d load (duration-based)
|
||||
return int(row['total_duration'] or 0)
|
||||
|
||||
|
||||
def calculate_sleep_quality_7d(profile_id: str) -> Optional[int]:
|
||||
"""
|
||||
Calculate sleep quality score (0-100) based on deep+REM percentage
|
||||
Last 7 days
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT duration_minutes, deep_minutes, rem_minutes
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
AND duration_minutes IS NOT NULL
|
||||
""", (profile_id,))
|
||||
|
||||
sleep_data = cur.fetchall()
|
||||
|
||||
if len(sleep_data) < 4:
|
||||
return None
|
||||
|
||||
quality_scores = []
|
||||
for s in sleep_data:
|
||||
if s['deep_minutes'] and s['rem_minutes']:
|
||||
quality_pct = ((s['deep_minutes'] + s['rem_minutes']) / s['duration_minutes']) * 100
|
||||
# 40-60% deep+REM is good
|
||||
if quality_pct >= 45:
|
||||
quality_scores.append(100)
|
||||
elif quality_pct >= 35:
|
||||
quality_scores.append(75)
|
||||
elif quality_pct >= 25:
|
||||
quality_scores.append(50)
|
||||
else:
|
||||
quality_scores.append(30)
|
||||
|
||||
if not quality_scores:
|
||||
return None
|
||||
|
||||
avg_quality = sum(quality_scores) / len(quality_scores)
|
||||
return int(avg_quality)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Data Quality Assessment
|
||||
# ============================================================================
|
||||
|
||||
def calculate_recovery_data_quality(profile_id: str) -> Dict[str, any]:
|
||||
"""
|
||||
Assess data quality for recovery metrics
|
||||
Returns dict with quality score and details
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# HRV measurements (28d)
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as hrv_count
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND hrv IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
hrv_count = cur.fetchone()['hrv_count']
|
||||
|
||||
# RHR measurements (28d)
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as rhr_count
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND resting_hr IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
rhr_count = cur.fetchone()['rhr_count']
|
||||
|
||||
# Sleep measurements (28d)
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as sleep_count
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
sleep_count = cur.fetchone()['sleep_count']
|
||||
|
||||
# Score components
|
||||
hrv_score = min(100, (hrv_count / 21) * 100) # 21 = 75% coverage
|
||||
rhr_score = min(100, (rhr_count / 21) * 100)
|
||||
sleep_score = min(100, (sleep_count / 21) * 100)
|
||||
|
||||
# Overall score
|
||||
overall_score = int(
|
||||
hrv_score * 0.3 +
|
||||
rhr_score * 0.3 +
|
||||
sleep_score * 0.4
|
||||
)
|
||||
|
||||
if overall_score >= 80:
|
||||
confidence = "high"
|
||||
elif overall_score >= 60:
|
||||
confidence = "medium"
|
||||
else:
|
||||
confidence = "low"
|
||||
|
||||
return {
|
||||
"overall_score": overall_score,
|
||||
"confidence": confidence,
|
||||
"measurements": {
|
||||
"hrv_28d": hrv_count,
|
||||
"rhr_28d": rhr_count,
|
||||
"sleep_28d": sleep_count
|
||||
},
|
||||
"component_scores": {
|
||||
"hrv": int(hrv_score),
|
||||
"rhr": int(rhr_score),
|
||||
"sleep": int(sleep_score)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
"""
|
||||
Score Calculation Engine
|
||||
|
||||
Implements meta-scores with Dynamic Focus Areas v2.0 integration:
|
||||
- Goal Progress Score (weighted by user's focus areas)
|
||||
- Data Quality Score
|
||||
- Helper functions for focus area weighting
|
||||
|
||||
All scores are 0-100 with confidence levels.
|
||||
"""
|
||||
from typing import Dict, Optional, List
|
||||
import json
|
||||
|
||||
from db import get_db, get_cursor
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Focus Area Weighting System
|
||||
# ============================================================================
|
||||
|
||||
def get_user_focus_weights(profile_id: str) -> Dict[str, float]:
|
||||
"""
|
||||
Get user's focus area weights as dictionary
|
||||
Returns: {'körpergewicht': 30.0, 'kraftaufbau': 25.0, ...}
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT ufw.focus_area_id, ufw.weight as weight_pct, fa.key
|
||||
FROM user_focus_area_weights ufw
|
||||
JOIN focus_area_definitions fa ON ufw.focus_area_id = fa.id
|
||||
WHERE ufw.profile_id = %s
|
||||
AND ufw.weight > 0
|
||||
""", (profile_id,))
|
||||
|
||||
return {
|
||||
row['key']: float(row['weight_pct'])
|
||||
for row in cur.fetchall()
|
||||
}
|
||||
|
||||
|
||||
def get_focus_area_category(focus_area_id: str) -> Optional[str]:
|
||||
"""Get category for a focus area"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT category
|
||||
FROM focus_area_definitions
|
||||
WHERE focus_area_id = %s
|
||||
""", (focus_area_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
return row['category'] if row else None
|
||||
|
||||
|
||||
def map_focus_to_score_components() -> Dict[str, str]:
|
||||
"""
|
||||
Map focus areas to score components
|
||||
Keys match focus_area_definitions.key (English lowercase)
|
||||
Returns: {'weight_loss': 'body', 'strength': 'activity', ...}
|
||||
"""
|
||||
return {
|
||||
# Body Composition → body_progress_score
|
||||
'weight_loss': 'body',
|
||||
'muscle_gain': 'body',
|
||||
'body_recomposition': 'body',
|
||||
|
||||
# Training - Strength → activity_score
|
||||
'strength': 'activity',
|
||||
'strength_endurance': 'activity',
|
||||
'power': 'activity',
|
||||
|
||||
# Training - Mobility → activity_score
|
||||
'flexibility': 'activity',
|
||||
'mobility': 'activity',
|
||||
|
||||
# Endurance → activity_score (could also map to health)
|
||||
'aerobic_endurance': 'activity',
|
||||
'anaerobic_endurance': 'activity',
|
||||
'cardiovascular_health': 'health',
|
||||
|
||||
# Coordination → activity_score
|
||||
'balance': 'activity',
|
||||
'reaction': 'activity',
|
||||
'rhythm': 'activity',
|
||||
'coordination': 'activity',
|
||||
|
||||
# Mental → recovery_score (mental health is part of recovery)
|
||||
'stress_resistance': 'recovery',
|
||||
'concentration': 'recovery',
|
||||
'willpower': 'recovery',
|
||||
'mental_health': 'recovery',
|
||||
|
||||
# Recovery → recovery_score
|
||||
'sleep_quality': 'recovery',
|
||||
'regeneration': 'recovery',
|
||||
'rest': 'recovery',
|
||||
|
||||
# Health → health
|
||||
'metabolic_health': 'health',
|
||||
'blood_pressure': 'health',
|
||||
'hrv': 'health',
|
||||
'general_health': 'health',
|
||||
|
||||
# Nutrition → nutrition_score
|
||||
'protein_intake': 'nutrition',
|
||||
'calorie_balance': 'nutrition',
|
||||
'macro_consistency': 'nutrition',
|
||||
'meal_timing': 'nutrition',
|
||||
'hydration': 'nutrition',
|
||||
}
|
||||
|
||||
|
||||
def map_category_de_to_en(category_de: str) -> str:
|
||||
"""
|
||||
Map German category names to English database names
|
||||
"""
|
||||
mapping = {
|
||||
'körper': 'body_composition',
|
||||
'ernährung': 'nutrition', # Note: no nutrition category in DB, returns empty
|
||||
'aktivität': 'training',
|
||||
'recovery': 'recovery',
|
||||
'vitalwerte': 'health',
|
||||
'mental': 'mental',
|
||||
'lebensstil': 'health', # Maps to general health
|
||||
}
|
||||
return mapping.get(category_de, category_de)
|
||||
|
||||
|
||||
def calculate_category_weight(profile_id: str, category: str) -> float:
|
||||
"""
|
||||
Calculate total weight for a category
|
||||
Accepts German or English category names
|
||||
Returns sum of all focus area weights in this category
|
||||
"""
|
||||
# Map German to English if needed
|
||||
category_en = map_category_de_to_en(category)
|
||||
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT key
|
||||
FROM focus_area_definitions
|
||||
WHERE category = %s
|
||||
""", (category_en,))
|
||||
|
||||
focus_areas = [row['key'] for row in cur.fetchall()]
|
||||
|
||||
total_weight = sum(
|
||||
focus_weights.get(fa, 0)
|
||||
for fa in focus_areas
|
||||
)
|
||||
|
||||
return total_weight
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Goal Progress Score (Meta-Score with Dynamic Weighting)
|
||||
# ============================================================================
|
||||
|
||||
def calculate_goal_progress_score(profile_id: str) -> Optional[int]:
|
||||
"""
|
||||
Calculate overall goal progress score (0-100)
|
||||
Weighted dynamically based on user's focus area priorities
|
||||
|
||||
This is the main meta-score that combines all sub-scores
|
||||
"""
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
if not focus_weights:
|
||||
return None # No goals/focus areas configured
|
||||
|
||||
# Calculate sub-scores
|
||||
from calculations.body_metrics import calculate_body_progress_score
|
||||
from calculations.nutrition_metrics import calculate_nutrition_score
|
||||
from calculations.activity_metrics import calculate_activity_score
|
||||
from calculations.recovery_metrics import calculate_recovery_score_v2
|
||||
|
||||
body_score = calculate_body_progress_score(profile_id, focus_weights)
|
||||
nutrition_score = calculate_nutrition_score(profile_id, focus_weights)
|
||||
activity_score = calculate_activity_score(profile_id, focus_weights)
|
||||
recovery_score = calculate_recovery_score_v2(profile_id)
|
||||
health_risk_score = calculate_health_stability_score(profile_id)
|
||||
|
||||
# Map focus areas to score components
|
||||
focus_to_component = map_focus_to_score_components()
|
||||
|
||||
# Calculate weighted sum
|
||||
total_score = 0.0
|
||||
total_weight = 0.0
|
||||
|
||||
for focus_area_id, weight in focus_weights.items():
|
||||
component = focus_to_component.get(focus_area_id)
|
||||
|
||||
if component == 'body' and body_score is not None:
|
||||
total_score += body_score * weight
|
||||
total_weight += weight
|
||||
elif component == 'nutrition' and nutrition_score is not None:
|
||||
total_score += nutrition_score * weight
|
||||
total_weight += weight
|
||||
elif component == 'activity' and activity_score is not None:
|
||||
total_score += activity_score * weight
|
||||
total_weight += weight
|
||||
elif component == 'recovery' and recovery_score is not None:
|
||||
total_score += recovery_score * weight
|
||||
total_weight += weight
|
||||
elif component == 'health' and health_risk_score is not None:
|
||||
total_score += health_risk_score * weight
|
||||
total_weight += weight
|
||||
|
||||
if total_weight == 0:
|
||||
return None
|
||||
|
||||
# Normalize to 0-100
|
||||
final_score = total_score / total_weight
|
||||
|
||||
return int(final_score)
|
||||
|
||||
|
||||
def calculate_health_stability_score(profile_id: str) -> Optional[int]:
|
||||
"""
|
||||
Health stability score (0-100)
|
||||
Components:
|
||||
- Blood pressure status
|
||||
- Sleep quality
|
||||
- Movement baseline
|
||||
- Weight/circumference risk factors
|
||||
- Regularity
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
components = []
|
||||
|
||||
# 1. Blood pressure status (30%)
|
||||
cur.execute("""
|
||||
SELECT systolic, diastolic
|
||||
FROM blood_pressure_log
|
||||
WHERE profile_id = %s
|
||||
AND measured_at >= CURRENT_DATE - INTERVAL '28 days'
|
||||
ORDER BY measured_at DESC
|
||||
""", (profile_id,))
|
||||
|
||||
bp_readings = cur.fetchall()
|
||||
if bp_readings:
|
||||
bp_score = _score_blood_pressure(bp_readings)
|
||||
components.append(('bp', bp_score, 30))
|
||||
|
||||
# 2. Sleep quality (25%)
|
||||
cur.execute("""
|
||||
SELECT duration_minutes, deep_minutes, rem_minutes
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
ORDER BY date DESC
|
||||
""", (profile_id,))
|
||||
|
||||
sleep_data = cur.fetchall()
|
||||
if sleep_data:
|
||||
sleep_score = _score_sleep_quality(sleep_data)
|
||||
components.append(('sleep', sleep_score, 25))
|
||||
|
||||
# 3. Movement baseline (20%)
|
||||
cur.execute("""
|
||||
SELECT duration_min
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
""", (profile_id,))
|
||||
|
||||
activities = cur.fetchall()
|
||||
if activities:
|
||||
total_minutes = sum(a['duration_min'] for a in activities)
|
||||
# WHO recommends 150-300 min/week moderate activity
|
||||
movement_score = min(100, (total_minutes / 150) * 100)
|
||||
components.append(('movement', movement_score, 20))
|
||||
|
||||
# 4. Waist circumference risk (15%)
|
||||
cur.execute("""
|
||||
SELECT c_waist
|
||||
FROM circumference_log
|
||||
WHERE profile_id = %s
|
||||
AND c_waist IS NOT NULL
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
""", (profile_id,))
|
||||
|
||||
waist = cur.fetchone()
|
||||
if waist:
|
||||
# Gender-specific thresholds (simplified - should use profile gender)
|
||||
# Men: <94cm good, 94-102 elevated, >102 high risk
|
||||
# Women: <80cm good, 80-88 elevated, >88 high risk
|
||||
# Using conservative thresholds
|
||||
waist_cm = waist['c_waist']
|
||||
if waist_cm < 88:
|
||||
waist_score = 100
|
||||
elif waist_cm < 94:
|
||||
waist_score = 75
|
||||
elif waist_cm < 102:
|
||||
waist_score = 50
|
||||
else:
|
||||
waist_score = 25
|
||||
components.append(('waist', waist_score, 15))
|
||||
|
||||
# 5. Regularity (10%) - sleep timing consistency
|
||||
if len(sleep_data) >= 7:
|
||||
sleep_times = [s['duration_minutes'] for s in sleep_data]
|
||||
avg = sum(sleep_times) / len(sleep_times)
|
||||
variance = sum((x - avg) ** 2 for x in sleep_times) / len(sleep_times)
|
||||
std_dev = variance ** 0.5
|
||||
# Lower std_dev = better consistency
|
||||
regularity_score = max(0, 100 - (std_dev * 2))
|
||||
components.append(('regularity', regularity_score, 10))
|
||||
|
||||
if not components:
|
||||
return None
|
||||
|
||||
# Weighted average
|
||||
total_score = sum(score * weight for _, score, weight in components)
|
||||
total_weight = sum(weight for _, _, weight in components)
|
||||
|
||||
return int(total_score / total_weight)
|
||||
|
||||
|
||||
def _score_blood_pressure(readings: List) -> int:
|
||||
"""Score blood pressure readings (0-100)"""
|
||||
# Average last 28 days
|
||||
avg_systolic = sum(r['systolic'] for r in readings) / len(readings)
|
||||
avg_diastolic = sum(r['diastolic'] for r in readings) / len(readings)
|
||||
|
||||
# ESC 2024 Guidelines:
|
||||
# Optimal: <120/80
|
||||
# Normal: 120-129 / 80-84
|
||||
# Elevated: 130-139 / 85-89
|
||||
# Hypertension: ≥140/90
|
||||
|
||||
if avg_systolic < 120 and avg_diastolic < 80:
|
||||
return 100
|
||||
elif avg_systolic < 130 and avg_diastolic < 85:
|
||||
return 85
|
||||
elif avg_systolic < 140 and avg_diastolic < 90:
|
||||
return 65
|
||||
else:
|
||||
return 40
|
||||
|
||||
|
||||
def _score_sleep_quality(sleep_data: List) -> int:
|
||||
"""Score sleep quality (0-100)"""
|
||||
# Average sleep duration and quality
|
||||
avg_total = sum(s['duration_minutes'] for s in sleep_data) / len(sleep_data)
|
||||
avg_total_hours = avg_total / 60
|
||||
|
||||
# Duration score (7+ hours = good)
|
||||
if avg_total_hours >= 8:
|
||||
duration_score = 100
|
||||
elif avg_total_hours >= 7:
|
||||
duration_score = 85
|
||||
elif avg_total_hours >= 6:
|
||||
duration_score = 65
|
||||
else:
|
||||
duration_score = 40
|
||||
|
||||
# Quality score (deep + REM percentage)
|
||||
quality_scores = []
|
||||
for s in sleep_data:
|
||||
if s['deep_minutes'] and s['rem_minutes']:
|
||||
quality_pct = ((s['deep_minutes'] + s['rem_minutes']) / s['duration_minutes']) * 100
|
||||
# 40-60% deep+REM is good
|
||||
if quality_pct >= 45:
|
||||
quality_scores.append(100)
|
||||
elif quality_pct >= 35:
|
||||
quality_scores.append(75)
|
||||
elif quality_pct >= 25:
|
||||
quality_scores.append(50)
|
||||
else:
|
||||
quality_scores.append(30)
|
||||
|
||||
if quality_scores:
|
||||
avg_quality = sum(quality_scores) / len(quality_scores)
|
||||
# Weighted: 60% duration, 40% quality
|
||||
return int(duration_score * 0.6 + avg_quality * 0.4)
|
||||
else:
|
||||
return duration_score
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Data Quality Score
|
||||
# ============================================================================
|
||||
|
||||
def calculate_data_quality_score(profile_id: str) -> int:
|
||||
"""
|
||||
Overall data quality score (0-100)
|
||||
Combines quality from all modules
|
||||
"""
|
||||
from calculations.body_metrics import calculate_body_data_quality
|
||||
from calculations.nutrition_metrics import calculate_nutrition_data_quality
|
||||
from calculations.activity_metrics import calculate_activity_data_quality
|
||||
from calculations.recovery_metrics import calculate_recovery_data_quality
|
||||
|
||||
body_quality = calculate_body_data_quality(profile_id)
|
||||
nutrition_quality = calculate_nutrition_data_quality(profile_id)
|
||||
activity_quality = calculate_activity_data_quality(profile_id)
|
||||
recovery_quality = calculate_recovery_data_quality(profile_id)
|
||||
|
||||
# Weighted average (all equal weight)
|
||||
total_score = (
|
||||
body_quality['overall_score'] * 0.25 +
|
||||
nutrition_quality['overall_score'] * 0.25 +
|
||||
activity_quality['overall_score'] * 0.25 +
|
||||
recovery_quality['overall_score'] * 0.25
|
||||
)
|
||||
|
||||
return int(total_score)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Top-Weighted Helpers (instead of "primary goal")
|
||||
# ============================================================================
|
||||
|
||||
def get_top_priority_goal(profile_id: str) -> Optional[Dict]:
|
||||
"""
|
||||
Get highest priority goal based on:
|
||||
- Progress gap (distance to target)
|
||||
- Focus area weight
|
||||
Returns goal dict or None
|
||||
"""
|
||||
from goal_utils import get_active_goals
|
||||
|
||||
goals = get_active_goals(profile_id)
|
||||
if not goals:
|
||||
return None
|
||||
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
for goal in goals:
|
||||
# Progress gap (0-100, higher = further from target)
|
||||
goal['progress_gap'] = 100 - (goal.get('progress_pct') or 0)
|
||||
|
||||
# Get focus areas for this goal
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT fa.key as focus_area_key
|
||||
FROM goal_focus_contributions gfc
|
||||
JOIN focus_area_definitions fa ON gfc.focus_area_id = fa.id
|
||||
WHERE gfc.goal_id = %s
|
||||
""", (goal['id'],))
|
||||
|
||||
goal_focus_areas = [row['focus_area_key'] for row in cur.fetchall()]
|
||||
|
||||
# Sum focus weights
|
||||
goal['total_focus_weight'] = sum(
|
||||
focus_weights.get(fa, 0)
|
||||
for fa in goal_focus_areas
|
||||
)
|
||||
|
||||
# Priority score
|
||||
goal['priority_score'] = goal['progress_gap'] * (goal['total_focus_weight'] / 100)
|
||||
|
||||
# Return goal with highest priority score
|
||||
return max(goals, key=lambda g: g.get('priority_score', 0))
|
||||
|
||||
|
||||
def get_top_focus_area(profile_id: str) -> Optional[Dict]:
|
||||
"""
|
||||
Get focus area with highest user weight
|
||||
Returns dict with focus_area_id, label, weight, progress
|
||||
"""
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
if not focus_weights:
|
||||
return None
|
||||
|
||||
top_fa_id = max(focus_weights, key=focus_weights.get)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT key, name_de, category
|
||||
FROM focus_area_definitions
|
||||
WHERE key = %s
|
||||
""", (top_fa_id,))
|
||||
|
||||
fa_def = cur.fetchone()
|
||||
if not fa_def:
|
||||
return None
|
||||
|
||||
# Calculate progress for this focus area
|
||||
progress = calculate_focus_area_progress(profile_id, top_fa_id)
|
||||
|
||||
return {
|
||||
'focus_area_id': top_fa_id,
|
||||
'label': fa_def['name_de'],
|
||||
'category': fa_def['category'],
|
||||
'weight': focus_weights[top_fa_id],
|
||||
'progress': progress
|
||||
}
|
||||
|
||||
|
||||
def calculate_focus_area_progress(profile_id: str, focus_area_id: str) -> Optional[int]:
|
||||
"""
|
||||
Calculate progress for a specific focus area (0-100)
|
||||
Average progress of all goals contributing to this focus area
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT g.id, g.progress_pct, gfc.contribution_weight
|
||||
FROM goals g
|
||||
JOIN goal_focus_contributions gfc ON g.id = gfc.goal_id
|
||||
WHERE g.profile_id = %s
|
||||
AND gfc.focus_area_id = (
|
||||
SELECT id FROM focus_area_definitions WHERE key = %s
|
||||
)
|
||||
AND g.status = 'active'
|
||||
""", (profile_id, focus_area_id))
|
||||
|
||||
goals = cur.fetchall()
|
||||
|
||||
if not goals:
|
||||
return None
|
||||
|
||||
# Weighted average by contribution_weight
|
||||
total_progress = sum(g['progress_pct'] * g['contribution_weight'] for g in goals)
|
||||
total_weight = sum(g['contribution_weight'] for g in goals)
|
||||
|
||||
return int(total_progress / total_weight) if total_weight > 0 else None
|
||||
|
||||
def calculate_category_progress(profile_id: str, category: str) -> Optional[int]:
|
||||
"""
|
||||
Calculate progress score for a focus area category (0-100).
|
||||
|
||||
Args:
|
||||
profile_id: User's profile ID
|
||||
category: Category name ('körper', 'ernährung', 'aktivität', 'recovery', 'vitalwerte', 'mental', 'lebensstil')
|
||||
|
||||
Returns:
|
||||
Progress score 0-100 or None if no data
|
||||
"""
|
||||
# Map category to score calculation functions
|
||||
category_scores = {
|
||||
'körper': 'body_progress_score',
|
||||
'ernährung': 'nutrition_score',
|
||||
'aktivität': 'activity_score',
|
||||
'recovery': 'recovery_score',
|
||||
'vitalwerte': 'recovery_score', # Use recovery score as proxy for vitals
|
||||
'mental': 'recovery_score', # Use recovery score as proxy for mental (sleep quality)
|
||||
'lebensstil': 'data_quality_score', # Use data quality as proxy for lifestyle consistency
|
||||
}
|
||||
|
||||
score_func_name = category_scores.get(category.lower())
|
||||
if not score_func_name:
|
||||
return None
|
||||
|
||||
# Call the appropriate score function
|
||||
if score_func_name == 'body_progress_score':
|
||||
from calculations.body_metrics import calculate_body_progress_score
|
||||
return calculate_body_progress_score(profile_id)
|
||||
elif score_func_name == 'nutrition_score':
|
||||
from calculations.nutrition_metrics import calculate_nutrition_score
|
||||
return calculate_nutrition_score(profile_id)
|
||||
elif score_func_name == 'activity_score':
|
||||
from calculations.activity_metrics import calculate_activity_score
|
||||
return calculate_activity_score(profile_id)
|
||||
elif score_func_name == 'recovery_score':
|
||||
from calculations.recovery_metrics import calculate_recovery_score_v2
|
||||
return calculate_recovery_score_v2(profile_id)
|
||||
elif score_func_name == 'data_quality_score':
|
||||
return calculate_data_quality_score(profile_id)
|
||||
|
||||
return None
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Derive lean_mass and fat_mass from weight_log + body_fat_pct for caliper entries."""
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from db import get_cursor, r2d
|
||||
|
||||
|
||||
def as_date(d: Any) -> Optional[date]:
|
||||
if d is None:
|
||||
return None
|
||||
if isinstance(d, datetime):
|
||||
return d.date()
|
||||
if isinstance(d, date):
|
||||
return d
|
||||
if isinstance(d, str) and len(d) >= 10:
|
||||
return datetime.strptime(d[:10], "%Y-%m-%d").date()
|
||||
return None
|
||||
|
||||
|
||||
def _floaty(x: Any) -> float:
|
||||
if isinstance(x, Decimal):
|
||||
return float(x)
|
||||
return float(x)
|
||||
|
||||
|
||||
def load_weight_rows(conn: Any, profile_id: str) -> List[Dict[str, Any]]:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT date, weight FROM weight_log WHERE profile_id=%s ORDER BY date",
|
||||
(profile_id,),
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def nearest_weight_kg(weight_rows: List[Dict[str, Any]], caliper_date: Any) -> Optional[float]:
|
||||
td = as_date(caliper_date)
|
||||
if td is None or not weight_rows:
|
||||
return None
|
||||
best: Optional[float] = None
|
||||
best_delta: Optional[int] = None
|
||||
for row in weight_rows:
|
||||
wd = as_date(row.get("date"))
|
||||
if wd is None:
|
||||
continue
|
||||
wraw = row.get("weight")
|
||||
if wraw is None:
|
||||
continue
|
||||
delta = abs((wd - td).days)
|
||||
if best_delta is None or delta < best_delta:
|
||||
best_delta = delta
|
||||
best = _floaty(wraw)
|
||||
return best
|
||||
|
||||
|
||||
def nearest_weight_kg_from_map(wlog: Dict[Any, Any], target_date: Any) -> Optional[float]:
|
||||
if not wlog:
|
||||
return None
|
||||
td = as_date(target_date)
|
||||
if td is None:
|
||||
return None
|
||||
best_w: Optional[float] = None
|
||||
best_delta: Optional[int] = None
|
||||
for wd, wval in wlog.items():
|
||||
if wval is None:
|
||||
continue
|
||||
wdate = as_date(wd)
|
||||
if wdate is None:
|
||||
continue
|
||||
delta = abs((wdate - td).days)
|
||||
if best_delta is None or delta < best_delta:
|
||||
best_delta = delta
|
||||
best_w = _floaty(wval)
|
||||
return best_w
|
||||
|
||||
|
||||
def compute_lean_fat_kg(weight_kg: float, body_fat_pct: float) -> Tuple[float, float]:
|
||||
lean = round(weight_kg - (weight_kg * body_fat_pct / 100.0), 2)
|
||||
fat = round(weight_kg * body_fat_pct / 100.0, 2)
|
||||
return lean, fat
|
||||
|
||||
|
||||
def fill_caliper_body_comp(d: Dict[str, Any], conn: Any, profile_id: str) -> None:
|
||||
"""Mutate caliper API payload (model_dump) before INSERT/UPDATE."""
|
||||
bf = d.get("body_fat_pct")
|
||||
if bf is None:
|
||||
return
|
||||
if d.get("lean_mass") is not None and d.get("fat_mass") is not None:
|
||||
return
|
||||
rows = load_weight_rows(conn, profile_id)
|
||||
w = nearest_weight_kg(rows, d.get("date"))
|
||||
if w is None:
|
||||
return
|
||||
lean, fat = compute_lean_fat_kg(w, _floaty(bf))
|
||||
d["lean_mass"] = lean
|
||||
d["fat_mass"] = fat
|
||||
|
||||
|
||||
def enrich_caliper_row_for_response(row: Dict[str, Any], weight_rows: List[Dict[str, Any]]) -> None:
|
||||
"""Fill missing lean_mass / fat_mass for API responses (read path)."""
|
||||
bf = row.get("body_fat_pct")
|
||||
if bf is None:
|
||||
return
|
||||
if row.get("lean_mass") is not None and row.get("fat_mass") is not None:
|
||||
return
|
||||
w = nearest_weight_kg(weight_rows, row.get("date"))
|
||||
if w is None:
|
||||
return
|
||||
lean, fat = compute_lean_fat_kg(w, _floaty(bf))
|
||||
row["lean_mass"] = lean
|
||||
row["fat_mass"] = fat
|
||||
@@ -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)}")
|
||||
@@ -0,0 +1,181 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Quick diagnostic: Check Migration 024 state
|
||||
|
||||
Run this inside the backend container:
|
||||
docker exec bodytrack-dev-backend-1 python check_migration_024.py
|
||||
"""
|
||||
|
||||
import psycopg2
|
||||
import os
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
# Database connection
|
||||
DB_HOST = os.getenv('DB_HOST', 'db')
|
||||
DB_PORT = os.getenv('DB_PORT', '5432')
|
||||
DB_NAME = os.getenv('DB_NAME', 'bodytrack')
|
||||
DB_USER = os.getenv('DB_USER', 'bodytrack')
|
||||
DB_PASS = os.getenv('DB_PASSWORD', '')
|
||||
|
||||
def main():
|
||||
print("=" * 70)
|
||||
print("Migration 024 Diagnostic")
|
||||
print("=" * 70)
|
||||
|
||||
# Connect to database
|
||||
conn = psycopg2.connect(
|
||||
host=DB_HOST,
|
||||
port=DB_PORT,
|
||||
dbname=DB_NAME,
|
||||
user=DB_USER,
|
||||
password=DB_PASS
|
||||
)
|
||||
cur = conn.cursor(cursor_factory=RealDictCursor)
|
||||
|
||||
# 1. Check if table exists
|
||||
print("\n1. Checking if goal_type_definitions table exists...")
|
||||
cur.execute("""
|
||||
SELECT EXISTS (
|
||||
SELECT FROM information_schema.tables
|
||||
WHERE table_name = 'goal_type_definitions'
|
||||
)
|
||||
""")
|
||||
exists = cur.fetchone()['exists']
|
||||
print(f" ✓ Table exists: {exists}")
|
||||
|
||||
if not exists:
|
||||
print("\n❌ TABLE DOES NOT EXIST - Migration 024 did not run!")
|
||||
print("\nRECOMMENDED ACTION:")
|
||||
print(" 1. Restart backend container: docker restart bodytrack-dev-backend-1")
|
||||
print(" 2. Check logs: docker logs bodytrack-dev-backend-1 | grep 'Migration'")
|
||||
cur.close()
|
||||
conn.close()
|
||||
return
|
||||
|
||||
# 2. Check row count
|
||||
print("\n2. Checking row count...")
|
||||
cur.execute("SELECT COUNT(*) as count FROM goal_type_definitions")
|
||||
count = cur.fetchone()['count']
|
||||
print(f" Row count: {count}")
|
||||
|
||||
if count == 0:
|
||||
print("\n❌ TABLE IS EMPTY - Seed data was not inserted!")
|
||||
print("\nPOSSIBLE CAUSES:")
|
||||
print(" - INSERT statements failed (constraint violation?)")
|
||||
print(" - Migration ran partially")
|
||||
print("\nRECOMMENDED ACTION:")
|
||||
print(" Run the seed statements manually (see below)")
|
||||
else:
|
||||
print(f" ✓ Table has {count} entries")
|
||||
|
||||
# 3. Show all entries
|
||||
print("\n3. Current goal type definitions:")
|
||||
cur.execute("""
|
||||
SELECT type_key, label_de, unit, is_system, is_active, created_at
|
||||
FROM goal_type_definitions
|
||||
ORDER BY is_system DESC, type_key
|
||||
""")
|
||||
|
||||
entries = cur.fetchall()
|
||||
if entries:
|
||||
print(f"\n {'Type Key':<20} {'Label':<20} {'Unit':<10} {'System':<8} {'Active':<8}")
|
||||
print(" " + "-" * 70)
|
||||
for row in entries:
|
||||
status = "SYSTEM" if row['is_system'] else "CUSTOM"
|
||||
active = "YES" if row['is_active'] else "NO"
|
||||
print(f" {row['type_key']:<20} {row['label_de']:<20} {row['unit']:<10} {status:<8} {active:<8}")
|
||||
else:
|
||||
print(" (empty)")
|
||||
|
||||
# 4. Check schema_migrations
|
||||
print("\n4. Checking schema_migrations tracking...")
|
||||
cur.execute("""
|
||||
SELECT EXISTS (
|
||||
SELECT FROM information_schema.tables
|
||||
WHERE table_name = 'schema_migrations'
|
||||
)
|
||||
""")
|
||||
sm_exists = cur.fetchone()['exists']
|
||||
|
||||
if sm_exists:
|
||||
cur.execute("""
|
||||
SELECT filename, executed_at
|
||||
FROM schema_migrations
|
||||
WHERE filename = '024_goal_type_registry.sql'
|
||||
""")
|
||||
tracked = cur.fetchone()
|
||||
if tracked:
|
||||
print(f" ✓ Migration 024 is tracked (executed: {tracked['executed_at']})")
|
||||
else:
|
||||
print(" ❌ Migration 024 is NOT tracked in schema_migrations")
|
||||
else:
|
||||
print(" ⚠️ schema_migrations table does not exist")
|
||||
|
||||
# 5. Check for errors
|
||||
print("\n5. Potential issues:")
|
||||
issues = []
|
||||
|
||||
if count == 0:
|
||||
issues.append("No seed data - INSERTs failed")
|
||||
|
||||
if count > 0 and count < 6:
|
||||
issues.append(f"Only {count} types (expected 8) - partial seed")
|
||||
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as inactive_count
|
||||
FROM goal_type_definitions
|
||||
WHERE is_active = false
|
||||
""")
|
||||
inactive = cur.fetchone()['inactive_count']
|
||||
if inactive > 2:
|
||||
issues.append(f"{inactive} inactive types (expected 2)")
|
||||
|
||||
if not issues:
|
||||
print(" ✓ No issues detected")
|
||||
else:
|
||||
for issue in issues:
|
||||
print(f" ❌ {issue}")
|
||||
|
||||
# 6. Test query that frontend uses
|
||||
print("\n6. Testing frontend query (WHERE is_active = true)...")
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as active_count
|
||||
FROM goal_type_definitions
|
||||
WHERE is_active = true
|
||||
""")
|
||||
active_count = cur.fetchone()['active_count']
|
||||
print(f" Active types returned: {active_count}")
|
||||
|
||||
if active_count == 0:
|
||||
print(" ❌ This is why frontend shows empty list!")
|
||||
|
||||
print("\n" + "=" * 70)
|
||||
print("SUMMARY")
|
||||
print("=" * 70)
|
||||
|
||||
if count == 0:
|
||||
print("\n🔴 PROBLEM: Table exists but has no data")
|
||||
print("\nQUICK FIX: Run these SQL commands manually:")
|
||||
print("\n```sql")
|
||||
print("-- Connect to database:")
|
||||
print("docker exec -it bodytrack-dev-db-1 psql -U bodytrack -d bodytrack")
|
||||
print("\n-- Then paste migration content:")
|
||||
print("-- (copy from backend/migrations/024_goal_type_registry.sql)")
|
||||
print("-- Skip CREATE TABLE (already exists), run INSERT statements only")
|
||||
print("```")
|
||||
elif active_count >= 6:
|
||||
print("\n🟢 EVERYTHING LOOKS GOOD")
|
||||
print(f" {active_count} active goal types available")
|
||||
print("\nIf frontend still shows error, check:")
|
||||
print(" 1. Backend logs: docker logs bodytrack-dev-backend-1 -f")
|
||||
print(" 2. Network tab in browser DevTools")
|
||||
print(" 3. API endpoint: curl -H 'X-Auth-Token: YOUR_TOKEN' http://localhost:8099/api/goals/goal-types")
|
||||
else:
|
||||
print(f"\n🟡 PARTIAL DATA: {active_count} active types (expected 6)")
|
||||
print(" Some INSERTs might have failed")
|
||||
|
||||
cur.close()
|
||||
conn.close()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,127 @@
|
||||
"""
|
||||
Dashboard-Layout v1: Validierung, Produkt-Standard (Übersicht) und Lab-Standard.
|
||||
|
||||
Erlaubte Widget-IDs und Reihenfolge: widget_catalog.WIDGET_CATALOG.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator, model_validator
|
||||
|
||||
from dashboard_widget_config import validate_widget_entry_config
|
||||
from widget_catalog import (
|
||||
ALLOWED_WIDGET_IDS,
|
||||
DEFAULT_LAB_WIDGET_IDS,
|
||||
DEFAULT_PRODUCT_DASHBOARD_WIDGET_IDS,
|
||||
WIDGET_CATALOG,
|
||||
)
|
||||
|
||||
# Abwärtskompatibel (Tests importieren weiterhin aus diesem Modul)
|
||||
__all__ = [
|
||||
"ALLOWED_WIDGET_IDS",
|
||||
"DashboardLayoutPayload",
|
||||
"DashboardWidgetEntry",
|
||||
"coalesce_effective_layout",
|
||||
"default_layout_dict",
|
||||
"lab_default_layout_dict",
|
||||
"product_default_layout_dict",
|
||||
]
|
||||
|
||||
|
||||
def lab_default_layout_dict() -> dict[str, Any]:
|
||||
"""Standard für Dashboard-Lab (Experimentier-Widgets)."""
|
||||
on = DEFAULT_LAB_WIDGET_IDS
|
||||
return {
|
||||
"version": 1,
|
||||
"widgets": [{"id": e["id"], "enabled": e["id"] in on} for e in WIDGET_CATALOG],
|
||||
}
|
||||
|
||||
|
||||
def product_default_layout_dict() -> dict[str, Any]:
|
||||
"""Code-Fallback für die Produkt-Übersicht; live-Standard ggf. system_config (siehe get_product_default_base_dict)."""
|
||||
on = DEFAULT_PRODUCT_DASHBOARD_WIDGET_IDS
|
||||
return {
|
||||
"version": 1,
|
||||
"widgets": [{"id": e["id"], "enabled": e["id"] in on} for e in WIDGET_CATALOG],
|
||||
}
|
||||
|
||||
|
||||
def default_layout_dict() -> dict[str, Any]:
|
||||
"""Alias: Produkt-Standard (coalesce, Reset). Lab nutzt lab_default_layout_dict()."""
|
||||
return product_default_layout_dict()
|
||||
|
||||
|
||||
class DashboardWidgetEntry(BaseModel):
|
||||
id: str = Field(min_length=1, max_length=64)
|
||||
enabled: bool = True
|
||||
config: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
@field_validator("config", mode="before")
|
||||
@classmethod
|
||||
def _config_coerce(cls, v: Any) -> dict[str, Any]:
|
||||
if v is None:
|
||||
return {}
|
||||
if not isinstance(v, dict):
|
||||
raise ValueError("config muss Objekt sein")
|
||||
return v
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _normalize_widget_config(self) -> DashboardWidgetEntry:
|
||||
normalized = validate_widget_entry_config(self.id, self.config)
|
||||
return self.model_copy(update={"config": normalized})
|
||||
|
||||
|
||||
class DashboardLayoutPayload(BaseModel):
|
||||
version: Literal[1] = 1
|
||||
widgets: list[DashboardWidgetEntry] = Field(min_length=1, max_length=32)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _validate_widgets(self) -> DashboardLayoutPayload:
|
||||
ids = [w.id for w in self.widgets]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError("Doppelte widget id")
|
||||
bad = [i for i in ids if i not in ALLOWED_WIDGET_IDS]
|
||||
if bad:
|
||||
raise ValueError(f"Unbekannte Widget-IDs: {bad}")
|
||||
if not any(w.enabled for w in self.widgets):
|
||||
raise ValueError("Mindestens ein Widget muss aktiv sein")
|
||||
return self
|
||||
|
||||
def to_stored_dict(self) -> dict[str, Any]:
|
||||
out_widgets: list[dict[str, Any]] = []
|
||||
for w in self.widgets:
|
||||
d: dict[str, Any] = {"id": w.id, "enabled": w.enabled}
|
||||
if w.config:
|
||||
d["config"] = dict(w.config)
|
||||
out_widgets.append(d)
|
||||
return {"version": self.version, "widgets": out_widgets}
|
||||
|
||||
|
||||
def coalesce_effective_layout(raw: Any) -> tuple[bool, dict[str, Any]]:
|
||||
"""
|
||||
Returns (has_custom, effective_layout).
|
||||
has_custom=True nur wenn DB-Wert vorhanden und gültig (v1).
|
||||
"""
|
||||
if raw is None:
|
||||
return False, default_layout_dict()
|
||||
parsed_obj: Any = raw
|
||||
if isinstance(raw, str):
|
||||
import json
|
||||
|
||||
try:
|
||||
parsed_obj = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return False, default_layout_dict()
|
||||
if not isinstance(parsed_obj, dict):
|
||||
return False, default_layout_dict()
|
||||
try:
|
||||
parsed = DashboardLayoutPayload.model_validate(
|
||||
{
|
||||
"version": parsed_obj.get("version", 1),
|
||||
"widgets": parsed_obj.get("widgets", []),
|
||||
}
|
||||
)
|
||||
return True, parsed.to_stored_dict()
|
||||
except Exception:
|
||||
return False, default_layout_dict()
|
||||
@@ -0,0 +1,165 @@
|
||||
"""
|
||||
Pro-Widget-Konfiguration im Dashboard-Layout (v1).
|
||||
|
||||
Nur ausgewählte Widget-IDs dürfen nicht-leere config haben; bekannte Keys werden validiert.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
MAX_WIDGET_CONFIG_JSON_BYTES = 3072
|
||||
|
||||
WIDGETS_ALLOWING_CONFIG: frozenset[str] = frozenset({
|
||||
"body_overview",
|
||||
"activity_overview",
|
||||
"kpi_board",
|
||||
"quick_capture",
|
||||
"trend_kcal_weight",
|
||||
"nutrition_detail_charts",
|
||||
"recovery_charts_panel",
|
||||
})
|
||||
|
||||
_QUICK_CAPTURE_KEYS: frozenset[str] = frozenset({
|
||||
"show_weight",
|
||||
"show_resting_hr",
|
||||
"show_hrv",
|
||||
"show_vo2_max",
|
||||
})
|
||||
|
||||
_KPI_TILE_FIXED: frozenset[str] = frozenset({"body_fat", "avg_kcal"})
|
||||
_KPI_REF_TILE_RE = re.compile(r"^ref:[a-z0-9_]{1,64}$")
|
||||
|
||||
|
||||
def _config_json_size_bytes(config: dict[str, Any]) -> int:
|
||||
return len(json.dumps(config, sort_keys=True, ensure_ascii=False).encode("utf-8"))
|
||||
|
||||
|
||||
def validate_widget_entry_config(widget_id: str, raw: Any) -> dict[str, Any]:
|
||||
if raw is None:
|
||||
return {}
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError(f"Widget {widget_id}: config muss ein Objekt sein")
|
||||
if _config_json_size_bytes(raw) > MAX_WIDGET_CONFIG_JSON_BYTES:
|
||||
raise ValueError(f"Widget {widget_id}: config zu groß (max. {MAX_WIDGET_CONFIG_JSON_BYTES} Byte JSON)")
|
||||
if not raw:
|
||||
return {}
|
||||
|
||||
if widget_id not in WIDGETS_ALLOWING_CONFIG:
|
||||
raise ValueError(f"Widget {widget_id}: keine Konfiguration unterstützt")
|
||||
|
||||
if widget_id == "body_overview":
|
||||
return _validate_chart_days_only(raw, label="body_overview")
|
||||
if widget_id == "activity_overview":
|
||||
return _validate_chart_days_only(raw, label="activity_overview")
|
||||
if widget_id == "kpi_board":
|
||||
return _validate_kpi_board_config(raw)
|
||||
if widget_id == "quick_capture":
|
||||
return _validate_quick_capture_config(raw)
|
||||
if widget_id == "trend_kcal_weight":
|
||||
return _validate_chart_days_only(raw, label="trend_kcal_weight")
|
||||
if widget_id == "nutrition_detail_charts":
|
||||
return _validate_chart_days_only(raw, label="nutrition_detail_charts")
|
||||
if widget_id == "recovery_charts_panel":
|
||||
return _validate_chart_days_only(raw, label="recovery_charts_panel")
|
||||
|
||||
raise ValueError(f"Widget {widget_id}: keine Konfiguration unterstützt")
|
||||
|
||||
|
||||
def _validate_quick_capture_config(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
label = "quick_capture"
|
||||
unknown = set(raw) - _QUICK_CAPTURE_KEYS
|
||||
if unknown:
|
||||
raise ValueError(f"{label}: unbekannte config-Felder: {sorted(unknown)}")
|
||||
out: dict[str, bool] = {}
|
||||
for k in _QUICK_CAPTURE_KEYS:
|
||||
if k not in raw:
|
||||
continue
|
||||
v = raw[k]
|
||||
if not isinstance(v, bool):
|
||||
raise ValueError(f"{label}: {k} muss boolean sein")
|
||||
out[k] = v
|
||||
merged = {k: True for k in _QUICK_CAPTURE_KEYS}
|
||||
merged.update(out)
|
||||
if not any(merged.values()):
|
||||
raise ValueError(f"{label}: mindestens ein Bereich muss sichtbar sein (show_*)")
|
||||
return out
|
||||
|
||||
|
||||
def _kpi_tile_id_valid(tid: str) -> bool:
|
||||
if tid in _KPI_TILE_FIXED:
|
||||
return True
|
||||
return bool(_KPI_REF_TILE_RE.match(tid))
|
||||
|
||||
|
||||
def _normalize_kpi_tile_entry(item: Any) -> str:
|
||||
if isinstance(item, str):
|
||||
tid = item.strip()
|
||||
elif isinstance(item, dict) and "id" in item:
|
||||
tid = str(item["id"]).strip()
|
||||
else:
|
||||
raise ValueError("kpi_board: jedes tiles-Element braucht eine id (String oder Objekt mit id)")
|
||||
if not tid:
|
||||
raise ValueError("kpi_board: leere Kachel-id")
|
||||
if not _kpi_tile_id_valid(tid):
|
||||
raise ValueError(f"kpi_board: ungültige Kachel-id {tid!r} (z. B. body_fat, avg_kcal, ref:typ_key)")
|
||||
return tid
|
||||
|
||||
|
||||
def _validate_kpi_board_config(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
if not raw:
|
||||
return {}
|
||||
# Legacy nur chart_days → entfallen, automatische Kachelwahl
|
||||
if set(raw.keys()) <= frozenset({"chart_days"}):
|
||||
return {}
|
||||
allowed = frozenset({"tiles"})
|
||||
unknown = set(raw) - allowed
|
||||
if unknown:
|
||||
raise ValueError(f"kpi_board: unbekannte config-Felder: {sorted(unknown)}")
|
||||
tiles_raw = raw.get("tiles")
|
||||
if tiles_raw is None:
|
||||
return {}
|
||||
if not isinstance(tiles_raw, list):
|
||||
raise ValueError("kpi_board: tiles muss eine Liste sein")
|
||||
if len(tiles_raw) > 9:
|
||||
raise ValueError("kpi_board: maximal 9 Kacheln")
|
||||
seen: set[str] = set()
|
||||
out: list[dict[str, str]] = []
|
||||
for item in tiles_raw:
|
||||
tid = _normalize_kpi_tile_entry(item)
|
||||
if tid in seen:
|
||||
raise ValueError(f"kpi_board: doppelte Kachel-id {tid}")
|
||||
seen.add(tid)
|
||||
out.append({"id": tid})
|
||||
return {"tiles": out}
|
||||
|
||||
|
||||
def _parse_chart_days(v: Any, label: str) -> int:
|
||||
if isinstance(v, bool):
|
||||
raise ValueError(f"{label}: chart_days muss ganze Zahl sein")
|
||||
if isinstance(v, float):
|
||||
if not math.isfinite(v):
|
||||
raise ValueError(f"{label}: chart_days muss ganze Zahl sein")
|
||||
if abs(v - round(v)) > 1e-9:
|
||||
raise ValueError(f"{label}: chart_days muss ganze Zahl sein")
|
||||
return int(round(v))
|
||||
if isinstance(v, int):
|
||||
return v
|
||||
raise ValueError(f"{label}: chart_days muss ganze Zahl sein")
|
||||
|
||||
|
||||
def _validate_chart_days_only(raw: dict[str, Any], *, label: str) -> dict[str, Any]:
|
||||
allowed = frozenset({"chart_days"})
|
||||
unknown = set(raw) - allowed
|
||||
if unknown:
|
||||
raise ValueError(f"{label}: unbekannte config-Felder: {sorted(unknown)}")
|
||||
if "chart_days" not in raw:
|
||||
return {}
|
||||
v = _parse_chart_days(raw["chart_days"], label)
|
||||
if v < 7 or v > 90:
|
||||
raise ValueError(f"{label}: chart_days muss zwischen 7 und 90 liegen")
|
||||
return {"chart_days": v}
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
Dashboard-Widgets × Feature-System: Sichtbarkeit aus check_feature_access.
|
||||
|
||||
Katalog-Einträge optional `requires_feature` (features.id). Fehlt der Key → immer erlaubt.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
from typing import Any
|
||||
|
||||
from widget_catalog import WIDGET_CATALOG
|
||||
|
||||
|
||||
def _check_feature_access(profile_id: str, feature_id: str, conn) -> dict:
|
||||
"""Indirection für Tests (monkeypatch) und spätes Laden von auth (bcrypt)."""
|
||||
from auth import check_feature_access
|
||||
|
||||
return check_feature_access(profile_id, feature_id, conn)
|
||||
|
||||
_WIDGET_ENTRY_BY_ID: dict[str, dict[str, Any]] = {e["id"]: e for e in WIDGET_CATALOG}
|
||||
|
||||
|
||||
def widget_id_allowed(widget_id: str, profile_id: str, conn) -> bool:
|
||||
entry = _WIDGET_ENTRY_BY_ID.get(widget_id)
|
||||
if entry is None:
|
||||
return False
|
||||
fid = entry.get("requires_feature")
|
||||
if not fid:
|
||||
return True
|
||||
return bool(_check_feature_access(profile_id, fid, conn)["allowed"])
|
||||
|
||||
|
||||
def _public_row(entry: dict[str, Any], *, allowed: bool) -> dict[str, Any]:
|
||||
return {
|
||||
"id": entry["id"],
|
||||
"title": entry["title"],
|
||||
"description": entry["description"],
|
||||
"allowed": allowed,
|
||||
}
|
||||
|
||||
|
||||
def widgets_catalog_for_profile(profile_id: str, conn) -> list[dict[str, Any]]:
|
||||
"""Zeilen für GET /api/app/widgets/catalog (ohne internes requires_feature-Feld)."""
|
||||
out: list[dict[str, Any]] = []
|
||||
for e in WIDGET_CATALOG:
|
||||
fid = e.get("requires_feature")
|
||||
allowed = True
|
||||
if fid:
|
||||
allowed = bool(_check_feature_access(profile_id, fid, conn)["allowed"])
|
||||
out.append(_public_row(e, allowed=allowed))
|
||||
return out
|
||||
|
||||
|
||||
def widgets_catalog_payload(profile_id: str, conn) -> dict[str, Any]:
|
||||
return {
|
||||
"catalog_version": 1,
|
||||
"widgets": widgets_catalog_for_profile(profile_id, conn),
|
||||
}
|
||||
|
||||
|
||||
def widgets_catalog_admin_payload() -> dict[str, Any]:
|
||||
"""Admin: alle Widgets als auswählbar (ohne Feature-Filter)."""
|
||||
return {
|
||||
"catalog_version": 1,
|
||||
"widgets": [_public_row(e, allowed=True) for e in WIDGET_CATALOG],
|
||||
}
|
||||
|
||||
|
||||
def apply_entitlements_to_layout_dict(layout: dict[str, Any], profile_id: str, conn) -> dict[str, Any]:
|
||||
"""
|
||||
Setzt enabled=False für Widgets ohne Berechtigung. Mindestens ein Widget bleibt aktiv (welcome).
|
||||
"""
|
||||
out = copy.deepcopy(layout)
|
||||
widgets = out.get("widgets") or []
|
||||
for w in widgets:
|
||||
wid = w.get("id")
|
||||
if not wid:
|
||||
continue
|
||||
if w.get("enabled") and not widget_id_allowed(wid, profile_id, conn):
|
||||
w["enabled"] = False
|
||||
if not any(w.get("enabled") for w in widgets):
|
||||
for w in widgets:
|
||||
if w.get("id") == "welcome":
|
||||
w["enabled"] = True
|
||||
break
|
||||
return out
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
"""
|
||||
Data Layer - Pure Data Retrieval & Calculation Logic
|
||||
|
||||
This module provides structured data functions for all metrics.
|
||||
NO FORMATTING. NO STRINGS WITH UNITS. Only structured data.
|
||||
|
||||
Usage:
|
||||
from data_layer.body_metrics import get_weight_trend_data
|
||||
|
||||
data = get_weight_trend_data(profile_id="123", days=28)
|
||||
# Returns: {"slope_28d": 0.23, "confidence": "high", ...}
|
||||
|
||||
Modules:
|
||||
- body_metrics: Weight, body fat, lean mass, circumferences
|
||||
- nutrition_metrics: Calories, protein, macros, adherence
|
||||
- activity_metrics: Training volume, quality, abilities
|
||||
- recovery_metrics: Sleep, RHR, HRV, recovery score
|
||||
- health_metrics: Blood pressure, VO2Max, health stability
|
||||
- goals: Active goals, progress, projections
|
||||
- correlations: Lag-analysis, plateau detection
|
||||
- utils: Shared functions (confidence, baseline, outliers)
|
||||
- training_profile: Template-based training evaluation scaffold (Layer 1)
|
||||
Import: ``from data_layer.training_profile import resolve_training_evaluation``
|
||||
- reference_values: Profile reference value reads + summary (Layer 1)
|
||||
Import: ``from data_layer import reference_values`` or submodule imports
|
||||
|
||||
Phase 0c: Multi-Layer Architecture
|
||||
Version: 1.0
|
||||
Created: 2026-03-28
|
||||
"""
|
||||
|
||||
# Core utilities
|
||||
from .utils import *
|
||||
|
||||
# Metric modules
|
||||
from .body_metrics import *
|
||||
from .nutrition_metrics import *
|
||||
from .activity_metrics import *
|
||||
from .recovery_metrics import *
|
||||
from .health_metrics import *
|
||||
from .scores import *
|
||||
from .correlations import *
|
||||
|
||||
# Future imports (will be added as modules are created):
|
||||
# from .goals import *
|
||||
|
||||
__all__ = [
|
||||
# Utils
|
||||
'calculate_confidence',
|
||||
'serialize_dates',
|
||||
|
||||
# Body Metrics (Basic)
|
||||
'get_latest_weight_data',
|
||||
'get_weight_trend_data',
|
||||
'get_body_composition_data',
|
||||
'get_circumference_summary_data',
|
||||
|
||||
# Body Metrics (Calculated)
|
||||
'calculate_weight_7d_median',
|
||||
'calculate_weight_28d_slope',
|
||||
'calculate_weight_90d_slope',
|
||||
'calculate_goal_projection_date',
|
||||
'calculate_goal_progress_pct',
|
||||
'calculate_fm_28d_change',
|
||||
'calculate_lbm_28d_change',
|
||||
'calculate_waist_28d_delta',
|
||||
'calculate_hip_28d_delta',
|
||||
'calculate_chest_28d_delta',
|
||||
'calculate_arm_28d_delta',
|
||||
'calculate_thigh_28d_delta',
|
||||
'calculate_waist_hip_ratio',
|
||||
'calculate_recomposition_quadrant',
|
||||
'calculate_body_progress_score',
|
||||
'calculate_body_data_quality',
|
||||
|
||||
# Nutrition Metrics (Basic)
|
||||
'get_nutrition_average_data',
|
||||
'get_nutrition_days_data',
|
||||
'get_protein_targets_data',
|
||||
'get_energy_balance_data',
|
||||
'get_protein_adequacy_data',
|
||||
'get_macro_consistency_data',
|
||||
|
||||
# Nutrition Metrics (Calculated)
|
||||
'calculate_energy_balance_7d',
|
||||
'calculate_energy_deficit_surplus',
|
||||
'calculate_protein_g_per_kg',
|
||||
'calculate_protein_days_in_target',
|
||||
'calculate_protein_adequacy_28d',
|
||||
'calculate_macro_consistency_score',
|
||||
'calculate_intake_volatility',
|
||||
'calculate_nutrition_score',
|
||||
'calculate_energy_availability_warning',
|
||||
'calculate_fiber_avg_7d',
|
||||
'calculate_sugar_avg_7d',
|
||||
'calculate_nutrition_data_quality',
|
||||
|
||||
# Activity Metrics (Basic)
|
||||
'get_activity_summary_data',
|
||||
'get_activity_detail_data',
|
||||
'get_training_type_distribution_data',
|
||||
|
||||
# Activity Metrics (Calculated)
|
||||
'calculate_training_minutes_week',
|
||||
'calculate_training_frequency_7d',
|
||||
'calculate_quality_sessions_pct',
|
||||
'calculate_intensity_proxy_distribution',
|
||||
'calculate_ability_balance',
|
||||
'calculate_ability_balance_strength',
|
||||
'calculate_ability_balance_endurance',
|
||||
'calculate_ability_balance_mental',
|
||||
'calculate_ability_balance_coordination',
|
||||
'calculate_ability_balance_mobility',
|
||||
'calculate_proxy_internal_load_7d',
|
||||
'calculate_monotony_score',
|
||||
'calculate_strain_score',
|
||||
'calculate_activity_score',
|
||||
'calculate_rest_day_compliance',
|
||||
'calculate_vo2max_trend_28d',
|
||||
'calculate_activity_data_quality',
|
||||
|
||||
# Recovery Metrics (Basic)
|
||||
'get_sleep_duration_data',
|
||||
'get_sleep_quality_data',
|
||||
'get_rest_days_data',
|
||||
|
||||
# Recovery Metrics (Calculated)
|
||||
'calculate_recovery_score_v2',
|
||||
'calculate_hrv_vs_baseline_pct',
|
||||
'calculate_rhr_vs_baseline_pct',
|
||||
'calculate_sleep_avg_duration_7d',
|
||||
'calculate_sleep_debt_hours',
|
||||
'calculate_sleep_regularity_proxy',
|
||||
'calculate_recent_load_balance_3d',
|
||||
'calculate_sleep_quality_7d',
|
||||
'calculate_recovery_data_quality',
|
||||
|
||||
# Health Metrics
|
||||
'get_resting_heart_rate_data',
|
||||
'get_heart_rate_variability_data',
|
||||
'get_vo2_max_data',
|
||||
|
||||
# Scoring Metrics
|
||||
'get_user_focus_weights',
|
||||
'get_focus_area_category',
|
||||
'map_focus_to_score_components',
|
||||
'map_category_de_to_en',
|
||||
'calculate_category_weight',
|
||||
'calculate_goal_progress_score',
|
||||
'calculate_health_stability_score',
|
||||
'calculate_data_quality_score',
|
||||
'get_top_priority_goal',
|
||||
'get_top_focus_area',
|
||||
'calculate_focus_area_progress',
|
||||
'calculate_category_progress',
|
||||
|
||||
# Correlation Metrics
|
||||
'calculate_lag_correlation',
|
||||
'calculate_correlation_sleep_recovery',
|
||||
'calculate_plateau_detected',
|
||||
'calculate_top_drivers',
|
||||
'calculate_correlation_confidence',
|
||||
]
|
||||
@@ -0,0 +1,906 @@
|
||||
"""
|
||||
Activity Metrics Data Layer
|
||||
|
||||
Provides structured data for training tracking and analysis.
|
||||
|
||||
Functions:
|
||||
- get_activity_summary_data(): Count, total duration, calories, averages
|
||||
- get_activity_detail_data(): Detailed activity log entries
|
||||
- get_training_type_distribution_data(): Training category percentages
|
||||
|
||||
All functions return structured data (dict) without formatting.
|
||||
Use placeholder_resolver.py for formatted strings for AI.
|
||||
|
||||
Phase 0c: Multi-Layer Architecture
|
||||
Version: 1.0
|
||||
"""
|
||||
|
||||
from typing import Dict, List, Optional
|
||||
from datetime import datetime, timedelta, date
|
||||
import statistics
|
||||
from db import get_db, get_cursor, r2d
|
||||
from data_layer.utils import calculate_confidence, safe_float, safe_int
|
||||
|
||||
|
||||
def get_activity_summary_data(
|
||||
profile_id: str,
|
||||
days: int = 14
|
||||
) -> Dict:
|
||||
"""
|
||||
Get activity summary statistics.
|
||||
|
||||
Args:
|
||||
profile_id: User profile ID
|
||||
days: Analysis window (default 14)
|
||||
|
||||
Returns:
|
||||
{
|
||||
"activity_count": int,
|
||||
"total_duration_min": int,
|
||||
"total_kcal": int,
|
||||
"avg_duration_min": int,
|
||||
"avg_kcal_per_session": int,
|
||||
"sessions_per_week": float,
|
||||
"confidence": str,
|
||||
"days_analyzed": int
|
||||
}
|
||||
|
||||
Migration from Phase 0b:
|
||||
OLD: get_activity_summary(pid, days) formatted string
|
||||
NEW: Structured data with all metrics
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
||||
|
||||
cur.execute(
|
||||
"""SELECT
|
||||
COUNT(*) as count,
|
||||
SUM(duration_min) as total_min,
|
||||
SUM(kcal_active) as total_kcal
|
||||
FROM activity_log
|
||||
WHERE profile_id=%s AND date >= %s""",
|
||||
(profile_id, cutoff)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row or row['count'] == 0:
|
||||
return {
|
||||
"activity_count": 0,
|
||||
"total_duration_min": 0,
|
||||
"total_kcal": 0,
|
||||
"avg_duration_min": 0,
|
||||
"avg_kcal_per_session": 0,
|
||||
"sessions_per_week": 0.0,
|
||||
"confidence": "insufficient",
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
activity_count = row['count']
|
||||
total_min = safe_int(row['total_min'])
|
||||
total_kcal = safe_int(row['total_kcal'])
|
||||
|
||||
avg_duration = int(total_min / activity_count) if activity_count > 0 else 0
|
||||
avg_kcal = int(total_kcal / activity_count) if activity_count > 0 else 0
|
||||
sessions_per_week = (activity_count / days * 7) if days > 0 else 0.0
|
||||
|
||||
confidence = calculate_confidence(activity_count, days, "general")
|
||||
|
||||
return {
|
||||
"activity_count": activity_count,
|
||||
"total_duration_min": total_min,
|
||||
"total_kcal": total_kcal,
|
||||
"avg_duration_min": avg_duration,
|
||||
"avg_kcal_per_session": avg_kcal,
|
||||
"sessions_per_week": round(sessions_per_week, 1),
|
||||
"confidence": confidence,
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
|
||||
def get_activity_detail_data(
|
||||
profile_id: str,
|
||||
days: int = 14,
|
||||
limit: int = 50
|
||||
) -> Dict:
|
||||
"""
|
||||
Get detailed activity log entries.
|
||||
|
||||
Args:
|
||||
profile_id: User profile ID
|
||||
days: Analysis window (default 14)
|
||||
limit: Maximum entries to return (default 50)
|
||||
|
||||
Returns:
|
||||
{
|
||||
"activities": [
|
||||
{
|
||||
"date": date,
|
||||
"activity_type": str,
|
||||
"duration_min": int,
|
||||
"kcal_active": int,
|
||||
"hr_avg": int | None,
|
||||
"training_category": str | None
|
||||
},
|
||||
...
|
||||
],
|
||||
"total_count": int,
|
||||
"confidence": str,
|
||||
"days_analyzed": int
|
||||
}
|
||||
|
||||
Migration from Phase 0b:
|
||||
OLD: get_activity_detail(pid, days) formatted string list
|
||||
NEW: Structured array with all fields
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
||||
|
||||
cur.execute(
|
||||
"""SELECT
|
||||
date,
|
||||
activity_type,
|
||||
duration_min,
|
||||
kcal_active,
|
||||
hr_avg,
|
||||
training_category
|
||||
FROM activity_log
|
||||
WHERE profile_id=%s AND date >= %s
|
||||
ORDER BY date DESC
|
||||
LIMIT %s""",
|
||||
(profile_id, cutoff, limit)
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
if not rows:
|
||||
return {
|
||||
"activities": [],
|
||||
"total_count": 0,
|
||||
"confidence": "insufficient",
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
activities = []
|
||||
for row in rows:
|
||||
activities.append({
|
||||
"date": row['date'],
|
||||
"activity_type": row['activity_type'],
|
||||
"duration_min": safe_int(row['duration_min']),
|
||||
"kcal_active": safe_int(row['kcal_active']),
|
||||
"hr_avg": safe_int(row['hr_avg']) if row.get('hr_avg') else None,
|
||||
"training_category": row.get('training_category')
|
||||
})
|
||||
|
||||
confidence = calculate_confidence(len(activities), days, "general")
|
||||
|
||||
return {
|
||||
"activities": activities,
|
||||
"total_count": len(activities),
|
||||
"confidence": confidence,
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
|
||||
def get_training_type_distribution_data(
|
||||
profile_id: str,
|
||||
days: int = 14
|
||||
) -> Dict:
|
||||
"""
|
||||
Calculate training category distribution.
|
||||
|
||||
Args:
|
||||
profile_id: User profile ID
|
||||
days: Analysis window (default 14)
|
||||
|
||||
Returns:
|
||||
{
|
||||
"distribution": [
|
||||
{
|
||||
"category": str,
|
||||
"count": int,
|
||||
"percentage": float
|
||||
},
|
||||
...
|
||||
],
|
||||
"total_sessions": int,
|
||||
"categorized_sessions": int,
|
||||
"uncategorized_sessions": int,
|
||||
"confidence": str,
|
||||
"days_analyzed": int
|
||||
}
|
||||
|
||||
Migration from Phase 0b:
|
||||
OLD: get_trainingstyp_verteilung(pid, days) top 3 formatted
|
||||
NEW: Complete distribution with percentages
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
||||
|
||||
# Get categorized activities
|
||||
cur.execute(
|
||||
"""SELECT
|
||||
training_category,
|
||||
COUNT(*) as count
|
||||
FROM activity_log
|
||||
WHERE profile_id=%s
|
||||
AND date >= %s
|
||||
AND training_category IS NOT NULL
|
||||
GROUP BY training_category
|
||||
ORDER BY count DESC""",
|
||||
(profile_id, cutoff)
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
# Get total activity count (including uncategorized)
|
||||
cur.execute(
|
||||
"""SELECT COUNT(*) as total
|
||||
FROM activity_log
|
||||
WHERE profile_id=%s AND date >= %s""",
|
||||
(profile_id, cutoff)
|
||||
)
|
||||
total_row = cur.fetchone()
|
||||
total_sessions = total_row['total'] if total_row else 0
|
||||
|
||||
if not rows or total_sessions == 0:
|
||||
return {
|
||||
"distribution": [],
|
||||
"total_sessions": total_sessions,
|
||||
"categorized_sessions": 0,
|
||||
"uncategorized_sessions": total_sessions,
|
||||
"confidence": "insufficient",
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
categorized_count = sum(row['count'] for row in rows)
|
||||
uncategorized_count = total_sessions - categorized_count
|
||||
|
||||
distribution = []
|
||||
for row in rows:
|
||||
count = row['count']
|
||||
percentage = (count / total_sessions * 100) if total_sessions > 0 else 0
|
||||
distribution.append({
|
||||
"category": row['training_category'],
|
||||
"count": count,
|
||||
"percentage": round(percentage, 1)
|
||||
})
|
||||
|
||||
confidence = calculate_confidence(categorized_count, days, "general")
|
||||
|
||||
return {
|
||||
"distribution": distribution,
|
||||
"total_sessions": total_sessions,
|
||||
"categorized_sessions": categorized_count,
|
||||
"uncategorized_sessions": uncategorized_count,
|
||||
"confidence": confidence,
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Calculated Metrics (migrated from calculations/activity_metrics.py)
|
||||
# ============================================================================
|
||||
# These functions return simple values for placeholders and scoring.
|
||||
# Use get_*_data() functions above for structured chart data.
|
||||
|
||||
def calculate_training_minutes_week(profile_id: str) -> Optional[int]:
|
||||
"""Calculate total training minutes last 7 days"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT SUM(duration_min) as total_minutes
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
return int(row['total_minutes']) if row and row['total_minutes'] else None
|
||||
|
||||
|
||||
def calculate_training_frequency_7d(profile_id: str) -> Optional[int]:
|
||||
"""Calculate number of training sessions last 7 days"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as session_count
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
return int(row['session_count']) if row else None
|
||||
|
||||
|
||||
def calculate_quality_sessions_pct(profile_id: str) -> Optional[int]:
|
||||
"""Calculate percentage of quality sessions (good or better) last 28 days"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT
|
||||
COUNT(*) as total,
|
||||
COUNT(*) FILTER (WHERE quality_label IN ('excellent', 'very_good', 'good')) as quality_count
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
if not row or row['total'] == 0:
|
||||
return None
|
||||
|
||||
pct = (row['quality_count'] / row['total']) * 100
|
||||
return int(pct)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# A2: Intensity Distribution (Proxy-based)
|
||||
# ============================================================================
|
||||
|
||||
def calculate_intensity_proxy_distribution(profile_id: str) -> Optional[Dict]:
|
||||
"""
|
||||
Calculate intensity distribution (proxy until HR zones available)
|
||||
Returns dict: {'low': X, 'moderate': Y, 'high': Z} in minutes
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT duration_min, hr_avg, hr_max
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
|
||||
activities = cur.fetchall()
|
||||
|
||||
if not activities:
|
||||
return None
|
||||
|
||||
low_min = 0
|
||||
moderate_min = 0
|
||||
high_min = 0
|
||||
|
||||
for activity in activities:
|
||||
duration = activity['duration_min']
|
||||
avg_hr = activity['hr_avg']
|
||||
max_hr = activity['hr_max']
|
||||
|
||||
# Simple proxy classification
|
||||
if avg_hr:
|
||||
# Rough HR-based classification (assumes max HR ~190)
|
||||
if avg_hr < 120:
|
||||
low_min += duration
|
||||
elif avg_hr < 150:
|
||||
moderate_min += duration
|
||||
else:
|
||||
high_min += duration
|
||||
else:
|
||||
# Fallback: assume moderate
|
||||
moderate_min += duration
|
||||
|
||||
return {
|
||||
'low': low_min,
|
||||
'moderate': moderate_min,
|
||||
'high': high_min
|
||||
}
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# A4: Ability Balance Calculations
|
||||
# ============================================================================
|
||||
|
||||
def calculate_ability_balance(profile_id: str) -> Optional[Dict]:
|
||||
"""
|
||||
Calculate ability balance from training_types.abilities
|
||||
Returns dict with scores per ability dimension (0-100)
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT a.duration_min, tt.abilities
|
||||
FROM activity_log a
|
||||
JOIN training_types tt ON a.training_category = tt.category
|
||||
WHERE a.profile_id = %s
|
||||
AND a.date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
AND tt.abilities IS NOT NULL
|
||||
""", (profile_id,))
|
||||
|
||||
activities = cur.fetchall()
|
||||
|
||||
if not activities:
|
||||
return None
|
||||
|
||||
# Accumulate ability load (duration × ability weight)
|
||||
ability_loads = {
|
||||
'strength': 0,
|
||||
'endurance': 0,
|
||||
'mental': 0,
|
||||
'coordination': 0,
|
||||
'mobility': 0
|
||||
}
|
||||
|
||||
for activity in activities:
|
||||
duration = activity['duration_min']
|
||||
abilities = activity['abilities'] # JSONB
|
||||
|
||||
if not abilities:
|
||||
continue
|
||||
|
||||
for ability, weight in abilities.items():
|
||||
if ability in ability_loads:
|
||||
ability_loads[ability] += duration * weight
|
||||
|
||||
# Normalize to 0-100 scale
|
||||
max_load = max(ability_loads.values()) if ability_loads else 1
|
||||
if max_load == 0:
|
||||
return None
|
||||
|
||||
normalized = {
|
||||
ability: int((load / max_load) * 100)
|
||||
for ability, load in ability_loads.items()
|
||||
}
|
||||
|
||||
return normalized
|
||||
|
||||
|
||||
def calculate_ability_balance_strength(profile_id: str) -> Optional[int]:
|
||||
"""Get strength ability score"""
|
||||
balance = calculate_ability_balance(profile_id)
|
||||
return balance['strength'] if balance else None
|
||||
|
||||
|
||||
def calculate_ability_balance_endurance(profile_id: str) -> Optional[int]:
|
||||
"""Get endurance ability score"""
|
||||
balance = calculate_ability_balance(profile_id)
|
||||
return balance['endurance'] if balance else None
|
||||
|
||||
|
||||
def calculate_ability_balance_mental(profile_id: str) -> Optional[int]:
|
||||
"""Get mental ability score"""
|
||||
balance = calculate_ability_balance(profile_id)
|
||||
return balance['mental'] if balance else None
|
||||
|
||||
|
||||
def calculate_ability_balance_coordination(profile_id: str) -> Optional[int]:
|
||||
"""Get coordination ability score"""
|
||||
balance = calculate_ability_balance(profile_id)
|
||||
return balance['coordination'] if balance else None
|
||||
|
||||
|
||||
def calculate_ability_balance_mobility(profile_id: str) -> Optional[int]:
|
||||
"""Get mobility ability score"""
|
||||
balance = calculate_ability_balance(profile_id)
|
||||
return balance['mobility'] if balance else None
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# A5: Load Monitoring (Proxy-based)
|
||||
# ============================================================================
|
||||
|
||||
def calculate_proxy_internal_load_7d(profile_id: str) -> Optional[int]:
|
||||
"""
|
||||
Calculate proxy internal load (last 7 days)
|
||||
Formula: duration × intensity_factor × quality_factor
|
||||
"""
|
||||
intensity_factors = {'low': 1.0, 'moderate': 1.5, 'high': 2.0}
|
||||
quality_factors = {
|
||||
'excellent': 1.15,
|
||||
'very_good': 1.05,
|
||||
'good': 1.0,
|
||||
'acceptable': 0.9,
|
||||
'poor': 0.75,
|
||||
'excluded': 0.0
|
||||
}
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT duration_min, hr_avg, rpe
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
""", (profile_id,))
|
||||
|
||||
activities = cur.fetchall()
|
||||
|
||||
if not activities:
|
||||
return None
|
||||
|
||||
total_load = 0
|
||||
|
||||
for activity in activities:
|
||||
duration = activity['duration_min']
|
||||
avg_hr = activity['hr_avg']
|
||||
# Map RPE to quality (rpe 8-10 = excellent, 6-7 = good, 4-5 = moderate, <4 = poor)
|
||||
rpe = activity.get('rpe')
|
||||
if rpe and rpe >= 8:
|
||||
quality = 'excellent'
|
||||
elif rpe and rpe >= 6:
|
||||
quality = 'good'
|
||||
elif rpe and rpe >= 4:
|
||||
quality = 'moderate'
|
||||
else:
|
||||
quality = 'good' # default
|
||||
|
||||
# Determine intensity
|
||||
if avg_hr:
|
||||
if avg_hr < 120:
|
||||
intensity = 'low'
|
||||
elif avg_hr < 150:
|
||||
intensity = 'moderate'
|
||||
else:
|
||||
intensity = 'high'
|
||||
else:
|
||||
intensity = 'moderate'
|
||||
|
||||
load = float(duration) * intensity_factors[intensity] * quality_factors.get(quality, 1.0)
|
||||
total_load += load
|
||||
|
||||
return int(total_load)
|
||||
|
||||
|
||||
def calculate_monotony_score(profile_id: str) -> Optional[float]:
|
||||
"""
|
||||
Calculate training monotony (last 7 days)
|
||||
Monotony = mean daily load / std dev daily load
|
||||
Higher = more monotonous
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT date, SUM(duration_min) as daily_duration
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
GROUP BY date
|
||||
ORDER BY date
|
||||
""", (profile_id,))
|
||||
|
||||
daily_loads = [float(row['daily_duration']) for row in cur.fetchall() if row['daily_duration']]
|
||||
|
||||
if len(daily_loads) < 4:
|
||||
return None
|
||||
|
||||
mean_load = sum(daily_loads) / len(daily_loads)
|
||||
std_dev = statistics.stdev(daily_loads)
|
||||
|
||||
if std_dev == 0:
|
||||
return None
|
||||
|
||||
monotony = mean_load / std_dev
|
||||
return round(monotony, 2)
|
||||
|
||||
|
||||
def calculate_strain_score(profile_id: str) -> Optional[int]:
|
||||
"""
|
||||
Calculate training strain (last 7 days)
|
||||
Strain = weekly load × monotony
|
||||
"""
|
||||
weekly_load = calculate_proxy_internal_load_7d(profile_id)
|
||||
monotony = calculate_monotony_score(profile_id)
|
||||
|
||||
if weekly_load is None or monotony is None:
|
||||
return None
|
||||
|
||||
strain = weekly_load * monotony
|
||||
return int(strain)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# A6: Activity Goal Alignment Score (Dynamic Focus Areas)
|
||||
# ============================================================================
|
||||
|
||||
def calculate_activity_score(profile_id: str, focus_weights: Optional[Dict] = None) -> Optional[int]:
|
||||
"""
|
||||
Activity goal alignment score 0-100
|
||||
Weighted by user's activity-related focus areas
|
||||
"""
|
||||
if focus_weights is None:
|
||||
from data_layer.scores import get_user_focus_weights
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
# Activity-related focus areas (English keys from DB)
|
||||
# Strength training
|
||||
strength = focus_weights.get('strength', 0)
|
||||
strength_endurance = focus_weights.get('strength_endurance', 0)
|
||||
power = focus_weights.get('power', 0)
|
||||
total_strength = strength + strength_endurance + power
|
||||
|
||||
# Endurance training
|
||||
aerobic = focus_weights.get('aerobic_endurance', 0)
|
||||
anaerobic = focus_weights.get('anaerobic_endurance', 0)
|
||||
cardiovascular = focus_weights.get('cardiovascular_health', 0)
|
||||
total_cardio = aerobic + anaerobic + cardiovascular
|
||||
|
||||
# Mobility/Coordination
|
||||
flexibility = focus_weights.get('flexibility', 0)
|
||||
mobility = focus_weights.get('mobility', 0)
|
||||
balance = focus_weights.get('balance', 0)
|
||||
reaction = focus_weights.get('reaction', 0)
|
||||
rhythm = focus_weights.get('rhythm', 0)
|
||||
coordination = focus_weights.get('coordination', 0)
|
||||
total_ability = flexibility + mobility + balance + reaction + rhythm + coordination
|
||||
|
||||
total_activity_weight = total_strength + total_cardio + total_ability
|
||||
|
||||
if total_activity_weight == 0:
|
||||
return None # No activity goals
|
||||
|
||||
components = []
|
||||
|
||||
# 1. Weekly minutes (general activity volume)
|
||||
minutes = calculate_training_minutes_week(profile_id)
|
||||
if minutes is not None:
|
||||
# WHO: 150-300 min/week
|
||||
if 150 <= minutes <= 300:
|
||||
minutes_score = 100
|
||||
elif minutes < 150:
|
||||
minutes_score = max(40, (minutes / 150) * 100)
|
||||
else:
|
||||
minutes_score = max(80, 100 - ((minutes - 300) / 10))
|
||||
|
||||
# Volume relevant for all activity types (20% base weight)
|
||||
components.append(('minutes', minutes_score, total_activity_weight * 0.2))
|
||||
|
||||
# 2. Quality sessions (always relevant)
|
||||
quality_pct = calculate_quality_sessions_pct(profile_id)
|
||||
if quality_pct is not None:
|
||||
# Quality gets 10% base weight
|
||||
components.append(('quality', quality_pct, total_activity_weight * 0.1))
|
||||
|
||||
# 3. Strength presence (if strength focus active)
|
||||
if total_strength > 0:
|
||||
strength_score = _score_strength_presence(profile_id)
|
||||
if strength_score is not None:
|
||||
components.append(('strength', strength_score, total_strength))
|
||||
|
||||
# 4. Cardio presence (if cardio focus active)
|
||||
if total_cardio > 0:
|
||||
cardio_score = _score_cardio_presence(profile_id)
|
||||
if cardio_score is not None:
|
||||
components.append(('cardio', cardio_score, total_cardio))
|
||||
|
||||
# 5. Ability balance (if mobility/coordination focus active)
|
||||
if total_ability > 0:
|
||||
balance_score = _score_ability_balance(profile_id)
|
||||
if balance_score is not None:
|
||||
components.append(('balance', balance_score, total_ability))
|
||||
|
||||
if not components:
|
||||
return None
|
||||
|
||||
# Weighted average
|
||||
total_score = sum(score * weight for _, score, weight in components)
|
||||
total_weight = sum(weight for _, _, weight in components)
|
||||
|
||||
return int(total_score / total_weight)
|
||||
|
||||
|
||||
def _score_strength_presence(profile_id: str) -> Optional[int]:
|
||||
"""Score strength training presence (0-100)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT COUNT(DISTINCT date) as strength_days
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
AND training_category = 'strength'
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
|
||||
strength_days = row['strength_days']
|
||||
|
||||
# Target: 2-4 days/week
|
||||
if 2 <= strength_days <= 4:
|
||||
return 100
|
||||
elif strength_days == 1:
|
||||
return 60
|
||||
elif strength_days == 5:
|
||||
return 85
|
||||
elif strength_days == 0:
|
||||
return 0
|
||||
else:
|
||||
return 70
|
||||
|
||||
|
||||
def _score_cardio_presence(profile_id: str) -> Optional[int]:
|
||||
"""Score cardio training presence (0-100)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT COUNT(DISTINCT date) as cardio_days, SUM(duration_min) as cardio_minutes
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
AND training_category = 'cardio'
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
|
||||
cardio_days = row['cardio_days']
|
||||
cardio_minutes = row['cardio_minutes'] or 0
|
||||
|
||||
# Target: 3-5 days/week, 150+ minutes
|
||||
day_score = min(100, (cardio_days / 4) * 100)
|
||||
minute_score = min(100, (cardio_minutes / 150) * 100)
|
||||
|
||||
return int((day_score + minute_score) / 2)
|
||||
|
||||
|
||||
def _score_ability_balance(profile_id: str) -> Optional[int]:
|
||||
"""Score ability balance (0-100)"""
|
||||
balance = calculate_ability_balance(profile_id)
|
||||
|
||||
if not balance:
|
||||
return None
|
||||
|
||||
# Good balance = all abilities > 40, std_dev < 30
|
||||
values = list(balance.values())
|
||||
min_value = min(values)
|
||||
std_dev = statistics.stdev(values) if len(values) > 1 else 0
|
||||
|
||||
# Score based on minimum coverage and balance
|
||||
min_score = min(100, min_value * 2) # Want all > 50
|
||||
balance_score = max(0, 100 - (std_dev * 2)) # Want low std_dev
|
||||
|
||||
return int((min_score + balance_score) / 2)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# A7: Rest Day Compliance
|
||||
# ============================================================================
|
||||
|
||||
def calculate_rest_day_compliance(profile_id: str) -> Optional[int]:
|
||||
"""
|
||||
Calculate rest day compliance percentage (last 28 days)
|
||||
Returns percentage of planned rest days that were respected
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get planned rest days
|
||||
cur.execute("""
|
||||
SELECT date, rest_config->>'focus' as rest_type
|
||||
FROM rest_days
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
|
||||
rest_days = {row['date']: row['rest_type'] for row in cur.fetchall()}
|
||||
|
||||
if not rest_days:
|
||||
return None
|
||||
|
||||
# Check if training occurred on rest days
|
||||
cur.execute("""
|
||||
SELECT date, training_category
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
|
||||
training_days = {}
|
||||
for row in cur.fetchall():
|
||||
if row['date'] not in training_days:
|
||||
training_days[row['date']] = []
|
||||
training_days[row['date']].append(row['training_category'])
|
||||
|
||||
# Count compliance
|
||||
compliant = 0
|
||||
total = len(rest_days)
|
||||
|
||||
for rest_date, rest_type in rest_days.items():
|
||||
if rest_date not in training_days:
|
||||
# Full rest = compliant
|
||||
compliant += 1
|
||||
else:
|
||||
# Check if training violates rest type
|
||||
categories = training_days[rest_date]
|
||||
if rest_type == 'strength_rest' and 'strength' not in categories:
|
||||
compliant += 1
|
||||
elif rest_type == 'cardio_rest' and 'cardio' not in categories:
|
||||
compliant += 1
|
||||
# If rest_type == 'recovery', any training = non-compliant
|
||||
|
||||
compliance_pct = (compliant / total) * 100
|
||||
return int(compliance_pct)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# A8: VO2max Development
|
||||
# ============================================================================
|
||||
|
||||
def calculate_vo2max_trend_28d(profile_id: str) -> Optional[float]:
|
||||
"""Calculate VO2max trend (change over 28 days)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT vo2_max, date
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND vo2_max IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
ORDER BY date DESC
|
||||
""", (profile_id,))
|
||||
|
||||
measurements = cur.fetchall()
|
||||
|
||||
if len(measurements) < 2:
|
||||
return None
|
||||
|
||||
recent = measurements[0]['vo2_max']
|
||||
oldest = measurements[-1]['vo2_max']
|
||||
|
||||
change = recent - oldest
|
||||
return round(change, 1)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Data Quality Assessment
|
||||
# ============================================================================
|
||||
|
||||
def calculate_activity_data_quality(profile_id: str) -> Dict[str, any]:
|
||||
"""
|
||||
Assess data quality for activity metrics
|
||||
Returns dict with quality score and details
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Activity entries last 28 days
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as total,
|
||||
COUNT(hr_avg) as with_hr,
|
||||
COUNT(rpe) as with_quality
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
|
||||
counts = cur.fetchone()
|
||||
|
||||
total_entries = counts['total']
|
||||
hr_coverage = counts['with_hr'] / total_entries if total_entries > 0 else 0
|
||||
quality_coverage = counts['with_quality'] / total_entries if total_entries > 0 else 0
|
||||
|
||||
# Score components
|
||||
frequency_score = min(100, (total_entries / 15) * 100) # 15 = ~4 sessions/week
|
||||
hr_score = hr_coverage * 100
|
||||
quality_score = quality_coverage * 100
|
||||
|
||||
# Overall score
|
||||
overall_score = int(
|
||||
frequency_score * 0.5 +
|
||||
hr_score * 0.25 +
|
||||
quality_score * 0.25
|
||||
)
|
||||
|
||||
if overall_score >= 80:
|
||||
confidence = "high"
|
||||
elif overall_score >= 60:
|
||||
confidence = "medium"
|
||||
else:
|
||||
confidence = "low"
|
||||
|
||||
return {
|
||||
"overall_score": overall_score,
|
||||
"confidence": confidence,
|
||||
"measurements": {
|
||||
"activities_28d": total_entries,
|
||||
"hr_coverage_pct": int(hr_coverage * 100),
|
||||
"quality_coverage_pct": int(quality_coverage * 100)
|
||||
},
|
||||
"component_scores": {
|
||||
"frequency": int(frequency_score),
|
||||
"hr": int(hr_score),
|
||||
"quality": int(quality_score)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,830 @@
|
||||
"""
|
||||
Body Metrics Data Layer
|
||||
|
||||
Provides structured data for body composition and measurements.
|
||||
|
||||
Functions:
|
||||
- get_latest_weight_data(): Most recent weight entry
|
||||
- get_weight_trend_data(): Weight trend with slope and direction
|
||||
- get_body_composition_data(): Body fat percentage and lean mass
|
||||
- get_circumference_summary_data(): Latest circumference measurements
|
||||
|
||||
All functions return structured data (dict) without formatting.
|
||||
Use placeholder_resolver.py for formatted strings for AI.
|
||||
|
||||
Phase 0c: Multi-Layer Architecture
|
||||
Version: 1.0
|
||||
"""
|
||||
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
from datetime import datetime, timedelta, date
|
||||
import statistics
|
||||
from db import get_db, get_cursor, r2d
|
||||
from data_layer.utils import calculate_confidence, safe_float
|
||||
|
||||
|
||||
def get_latest_weight_data(
|
||||
profile_id: str
|
||||
) -> Dict:
|
||||
"""
|
||||
Get most recent weight entry.
|
||||
|
||||
Args:
|
||||
profile_id: User profile ID
|
||||
|
||||
Returns:
|
||||
{
|
||||
"weight": float, # kg
|
||||
"date": date,
|
||||
"confidence": str
|
||||
}
|
||||
|
||||
Migration from Phase 0b:
|
||||
OLD: get_latest_weight() returned formatted string "85.0 kg"
|
||||
NEW: Returns structured data {"weight": 85.0, "date": ...}
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""SELECT weight, date FROM weight_log
|
||||
WHERE profile_id=%s
|
||||
ORDER BY date DESC
|
||||
LIMIT 1""",
|
||||
(profile_id,)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row:
|
||||
return {
|
||||
"weight": 0.0,
|
||||
"date": None,
|
||||
"confidence": "insufficient"
|
||||
}
|
||||
|
||||
return {
|
||||
"weight": safe_float(row['weight']),
|
||||
"date": row['date'],
|
||||
"confidence": "high"
|
||||
}
|
||||
|
||||
|
||||
def get_weight_trend_data(
|
||||
profile_id: str,
|
||||
days: int = 28
|
||||
) -> Dict:
|
||||
"""
|
||||
Calculate weight trend with slope and direction.
|
||||
|
||||
Args:
|
||||
profile_id: User profile ID
|
||||
days: Analysis window (default 28)
|
||||
|
||||
Returns:
|
||||
{
|
||||
"first_value": float,
|
||||
"last_value": float,
|
||||
"delta": float, # kg change
|
||||
"direction": str, # "increasing" | "decreasing" | "stable"
|
||||
"data_points": int,
|
||||
"confidence": str,
|
||||
"days_analyzed": int,
|
||||
"first_date": date,
|
||||
"last_date": date
|
||||
}
|
||||
|
||||
Confidence Rules:
|
||||
- high: >= 18 points (28d) or >= 4 points (7d)
|
||||
- medium: >= 12 points (28d) or >= 3 points (7d)
|
||||
- low: >= 8 points (28d) or >= 2 points (7d)
|
||||
- insufficient: < thresholds
|
||||
|
||||
Migration from Phase 0b:
|
||||
OLD: get_weight_trend() returned formatted string
|
||||
NEW: Returns structured data for reuse in charts + AI
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
||||
cur.execute(
|
||||
"""SELECT weight, date FROM weight_log
|
||||
WHERE profile_id=%s AND date >= %s
|
||||
ORDER BY date""",
|
||||
(profile_id, cutoff)
|
||||
)
|
||||
rows = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
# Calculate confidence
|
||||
confidence = calculate_confidence(len(rows), days, "general")
|
||||
|
||||
# Early return if insufficient
|
||||
if confidence == 'insufficient' or len(rows) < 2:
|
||||
return {
|
||||
"confidence": "insufficient",
|
||||
"data_points": len(rows),
|
||||
"days_analyzed": days,
|
||||
"first_value": 0.0,
|
||||
"last_value": 0.0,
|
||||
"delta": 0.0,
|
||||
"direction": "unknown",
|
||||
"first_date": None,
|
||||
"last_date": None
|
||||
}
|
||||
|
||||
# Extract values
|
||||
first_value = safe_float(rows[0]['weight'])
|
||||
last_value = safe_float(rows[-1]['weight'])
|
||||
delta = last_value - first_value
|
||||
|
||||
# Determine direction
|
||||
if abs(delta) < 0.3:
|
||||
direction = "stable"
|
||||
elif delta > 0:
|
||||
direction = "increasing"
|
||||
else:
|
||||
direction = "decreasing"
|
||||
|
||||
return {
|
||||
"first_value": first_value,
|
||||
"last_value": last_value,
|
||||
"delta": delta,
|
||||
"direction": direction,
|
||||
"data_points": len(rows),
|
||||
"confidence": confidence,
|
||||
"days_analyzed": days,
|
||||
"first_date": rows[0]['date'],
|
||||
"last_date": rows[-1]['date']
|
||||
}
|
||||
|
||||
|
||||
def get_body_composition_data(
|
||||
profile_id: str,
|
||||
days: int = 90
|
||||
) -> Dict:
|
||||
"""
|
||||
Get latest body composition data (body fat, lean mass).
|
||||
|
||||
Args:
|
||||
profile_id: User profile ID
|
||||
days: Lookback window (default 90)
|
||||
|
||||
Returns:
|
||||
{
|
||||
"body_fat_pct": float,
|
||||
"method": str, # "jackson_pollock" | "durnin_womersley" | etc.
|
||||
"date": date,
|
||||
"confidence": str,
|
||||
"data_points": int
|
||||
}
|
||||
|
||||
Migration from Phase 0b:
|
||||
OLD: get_latest_bf() returned formatted string "15.2%"
|
||||
NEW: Returns structured data {"body_fat_pct": 15.2, ...}
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
||||
|
||||
cur.execute(
|
||||
"""SELECT body_fat_pct, sf_method, date
|
||||
FROM caliper_log
|
||||
WHERE profile_id=%s
|
||||
AND body_fat_pct IS NOT NULL
|
||||
AND date >= %s
|
||||
ORDER BY date DESC
|
||||
LIMIT 1""",
|
||||
(profile_id, cutoff)
|
||||
)
|
||||
row = r2d(cur.fetchone()) if cur.rowcount > 0 else None
|
||||
|
||||
if not row:
|
||||
return {
|
||||
"confidence": "insufficient",
|
||||
"data_points": 0,
|
||||
"body_fat_pct": 0.0,
|
||||
"method": None,
|
||||
"date": None
|
||||
}
|
||||
|
||||
return {
|
||||
"body_fat_pct": safe_float(row['body_fat_pct']),
|
||||
"method": row.get('sf_method', 'unknown'),
|
||||
"date": row['date'],
|
||||
"confidence": "high", # Latest measurement is always high confidence
|
||||
"data_points": 1
|
||||
}
|
||||
|
||||
|
||||
def get_circumference_summary_data(
|
||||
profile_id: str,
|
||||
max_age_days: int = 90
|
||||
) -> Dict:
|
||||
"""
|
||||
Get latest circumference measurements for all body points.
|
||||
|
||||
For each measurement point, fetches the most recent value (even if from different dates).
|
||||
Returns measurements with age in days for each point.
|
||||
|
||||
Args:
|
||||
profile_id: User profile ID
|
||||
max_age_days: Maximum age of measurements to include (default 90)
|
||||
|
||||
Returns:
|
||||
{
|
||||
"measurements": [
|
||||
{
|
||||
"point": str, # "Nacken", "Brust", etc.
|
||||
"field": str, # "c_neck", "c_chest", etc.
|
||||
"value": float, # cm
|
||||
"date": date,
|
||||
"age_days": int
|
||||
},
|
||||
...
|
||||
],
|
||||
"confidence": str,
|
||||
"data_points": int,
|
||||
"newest_date": date,
|
||||
"oldest_date": date
|
||||
}
|
||||
|
||||
Migration from Phase 0b:
|
||||
OLD: get_circ_summary() returned formatted string "Nacken 38.0cm (vor 2 Tagen), ..."
|
||||
NEW: Returns structured array for charts + AI formatting
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Define all circumference points
|
||||
fields = [
|
||||
('c_neck', 'Nacken'),
|
||||
('c_chest', 'Brust'),
|
||||
('c_waist', 'Taille'),
|
||||
('c_belly', 'Bauch'),
|
||||
('c_hip', 'Hüfte'),
|
||||
('c_thigh', 'Oberschenkel'),
|
||||
('c_calf', 'Wade'),
|
||||
('c_arm', 'Arm')
|
||||
]
|
||||
|
||||
measurements = []
|
||||
today = datetime.now().date()
|
||||
|
||||
# Get latest value for each field individually
|
||||
for field_name, label in fields:
|
||||
cur.execute(
|
||||
f"""SELECT {field_name}, date,
|
||||
CURRENT_DATE - date AS age_days
|
||||
FROM circumference_log
|
||||
WHERE profile_id=%s
|
||||
AND {field_name} IS NOT NULL
|
||||
AND date >= %s
|
||||
ORDER BY date DESC
|
||||
LIMIT 1""",
|
||||
(profile_id, (today - timedelta(days=max_age_days)).isoformat())
|
||||
)
|
||||
row = r2d(cur.fetchone()) if cur.rowcount > 0 else None
|
||||
|
||||
if row:
|
||||
measurements.append({
|
||||
"point": label,
|
||||
"field": field_name,
|
||||
"value": safe_float(row[field_name]),
|
||||
"date": row['date'],
|
||||
"age_days": row['age_days']
|
||||
})
|
||||
|
||||
# Calculate confidence based on how many points we have
|
||||
confidence = calculate_confidence(len(measurements), 8, "general")
|
||||
|
||||
if not measurements:
|
||||
return {
|
||||
"measurements": [],
|
||||
"confidence": "insufficient",
|
||||
"data_points": 0,
|
||||
"newest_date": None,
|
||||
"oldest_date": None
|
||||
}
|
||||
|
||||
# Find newest and oldest dates
|
||||
dates = [m['date'] for m in measurements]
|
||||
newest_date = max(dates)
|
||||
oldest_date = min(dates)
|
||||
|
||||
return {
|
||||
"measurements": measurements,
|
||||
"confidence": confidence,
|
||||
"data_points": len(measurements),
|
||||
"newest_date": newest_date,
|
||||
"oldest_date": oldest_date
|
||||
}
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Calculated Metrics (migrated from calculations/body_metrics.py)
|
||||
# Phase 0c: Single Source of Truth for KI + Charts
|
||||
# ============================================================================
|
||||
|
||||
# ── Weight Trend Calculations ──────────────────────────────────────────────
|
||||
|
||||
def calculate_weight_7d_median(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 7-day median weight (reduces daily noise)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT weight
|
||||
FROM weight_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
ORDER BY date DESC
|
||||
""", (profile_id,))
|
||||
|
||||
weights = [row['weight'] for row in cur.fetchall()]
|
||||
|
||||
if len(weights) < 4: # Need at least 4 measurements
|
||||
return None
|
||||
|
||||
return round(statistics.median(weights), 1)
|
||||
|
||||
|
||||
def calculate_weight_28d_slope(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 28-day weight slope (kg/day)"""
|
||||
return _calculate_weight_slope(profile_id, days=28)
|
||||
|
||||
|
||||
def calculate_weight_90d_slope(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 90-day weight slope (kg/day)"""
|
||||
return _calculate_weight_slope(profile_id, days=90)
|
||||
|
||||
|
||||
def _calculate_weight_slope(profile_id: str, days: int) -> Optional[float]:
|
||||
"""
|
||||
Calculate weight slope using linear regression
|
||||
Returns kg/day (negative = weight loss)
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT date, weight
|
||||
FROM weight_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '%s days'
|
||||
ORDER BY date
|
||||
""", (profile_id, days))
|
||||
|
||||
data = [(row['date'], row['weight']) for row in cur.fetchall()]
|
||||
|
||||
# Need minimum data points based on period
|
||||
min_points = max(18, int(days * 0.6)) # 60% coverage
|
||||
if len(data) < min_points:
|
||||
return None
|
||||
|
||||
# Convert dates to days since start
|
||||
start_date = data[0][0]
|
||||
x_values = [(date - start_date).days for date, _ in data]
|
||||
y_values = [weight for _, weight in data]
|
||||
|
||||
# Linear regression
|
||||
n = len(data)
|
||||
x_mean = sum(x_values) / n
|
||||
y_mean = sum(y_values) / n
|
||||
|
||||
numerator = sum((x - x_mean) * (y - y_mean) for x, y in zip(x_values, y_values))
|
||||
denominator = sum((x - x_mean) ** 2 for x in x_values)
|
||||
|
||||
if denominator == 0:
|
||||
return None
|
||||
|
||||
slope = numerator / denominator
|
||||
return round(slope, 4) # kg/day
|
||||
|
||||
|
||||
def calculate_goal_projection_date(profile_id: str, goal_id: str) -> Optional[str]:
|
||||
"""
|
||||
Calculate projected date to reach goal based on 28d trend
|
||||
Returns ISO date string or None if unrealistic
|
||||
"""
|
||||
from goal_utils import get_goal_by_id
|
||||
|
||||
goal = get_goal_by_id(goal_id)
|
||||
if not goal or goal['goal_type'] != 'weight':
|
||||
return None
|
||||
|
||||
slope = calculate_weight_28d_slope(profile_id)
|
||||
if not slope or slope == 0:
|
||||
return None
|
||||
|
||||
current = goal['current_value']
|
||||
target = goal['target_value']
|
||||
remaining = target - current
|
||||
|
||||
days_needed = remaining / slope
|
||||
|
||||
# Unrealistic if >2 years or negative
|
||||
if days_needed < 0 or days_needed > 730:
|
||||
return None
|
||||
|
||||
projection_date = datetime.now().date() + timedelta(days=int(days_needed))
|
||||
return projection_date.isoformat()
|
||||
|
||||
|
||||
def calculate_goal_progress_pct(current: float, target: float, start: float) -> int:
|
||||
"""
|
||||
Calculate goal progress percentage
|
||||
Returns 0-100 (can exceed 100 if target surpassed)
|
||||
"""
|
||||
if start == target:
|
||||
return 100 if current == target else 0
|
||||
|
||||
progress = ((current - start) / (target - start)) * 100
|
||||
return max(0, min(100, int(progress)))
|
||||
|
||||
|
||||
# ── Fat Mass / Lean Mass Calculations ───────────────────────────────────────
|
||||
|
||||
def calculate_fm_28d_change(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 28-day fat mass change (kg)"""
|
||||
return _calculate_body_composition_change(profile_id, 'fm', 28)
|
||||
|
||||
|
||||
def calculate_lbm_28d_change(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 28-day lean body mass change (kg)"""
|
||||
return _calculate_body_composition_change(profile_id, 'lbm', 28)
|
||||
|
||||
|
||||
def _calculate_body_composition_change(profile_id: str, metric: str, days: int) -> Optional[float]:
|
||||
"""
|
||||
Calculate change in body composition over period
|
||||
metric: 'fm' (fat mass) or 'lbm' (lean mass)
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get weight and caliper measurements
|
||||
cur.execute("""
|
||||
SELECT w.date, w.weight, c.body_fat_pct
|
||||
FROM weight_log w
|
||||
LEFT JOIN caliper_log c ON w.profile_id = c.profile_id
|
||||
AND w.date = c.date
|
||||
WHERE w.profile_id = %s
|
||||
AND w.date >= CURRENT_DATE - INTERVAL '%s days'
|
||||
ORDER BY w.date DESC
|
||||
""", (profile_id, days))
|
||||
|
||||
data = [
|
||||
{
|
||||
'date': row['date'],
|
||||
'weight': row['weight'],
|
||||
'bf_pct': row['body_fat_pct']
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
if row['body_fat_pct'] is not None
|
||||
]
|
||||
|
||||
if len(data) < 2:
|
||||
return None
|
||||
|
||||
# Most recent and oldest measurement
|
||||
recent = data[0]
|
||||
oldest = data[-1]
|
||||
|
||||
# Calculate FM and LBM
|
||||
recent_fm = recent['weight'] * (recent['bf_pct'] / 100)
|
||||
recent_lbm = recent['weight'] - recent_fm
|
||||
|
||||
oldest_fm = oldest['weight'] * (oldest['bf_pct'] / 100)
|
||||
oldest_lbm = oldest['weight'] - oldest_fm
|
||||
|
||||
if metric == 'fm':
|
||||
change = recent_fm - oldest_fm
|
||||
else:
|
||||
change = recent_lbm - oldest_lbm
|
||||
|
||||
return round(change, 2)
|
||||
|
||||
|
||||
# ── Circumference Calculations ──────────────────────────────────────────────
|
||||
|
||||
def calculate_waist_28d_delta(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 28-day waist circumference change (cm)"""
|
||||
return _calculate_circumference_delta(profile_id, 'c_waist', 28)
|
||||
|
||||
|
||||
def calculate_hip_28d_delta(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 28-day hip circumference change (cm)"""
|
||||
return _calculate_circumference_delta(profile_id, 'c_hip', 28)
|
||||
|
||||
|
||||
def calculate_chest_28d_delta(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 28-day chest circumference change (cm)"""
|
||||
return _calculate_circumference_delta(profile_id, 'c_chest', 28)
|
||||
|
||||
|
||||
def calculate_arm_28d_delta(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 28-day arm circumference change (cm)"""
|
||||
return _calculate_circumference_delta(profile_id, 'c_arm', 28)
|
||||
|
||||
|
||||
def calculate_thigh_28d_delta(profile_id: str) -> Optional[float]:
|
||||
"""Calculate 28-day thigh circumference change (cm)"""
|
||||
delta = _calculate_circumference_delta(profile_id, 'c_thigh', 28)
|
||||
if delta is None:
|
||||
return None
|
||||
return round(delta, 1)
|
||||
|
||||
|
||||
def _calculate_circumference_delta(profile_id: str, column: str, days: int) -> Optional[float]:
|
||||
"""Calculate change in circumference measurement"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(f"""
|
||||
SELECT {column}
|
||||
FROM circumference_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '%s days'
|
||||
AND {column} IS NOT NULL
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
""", (profile_id, days))
|
||||
|
||||
recent = cur.fetchone()
|
||||
if not recent:
|
||||
return None
|
||||
|
||||
cur.execute(f"""
|
||||
SELECT {column}
|
||||
FROM circumference_log
|
||||
WHERE profile_id = %s
|
||||
AND date < CURRENT_DATE - INTERVAL '%s days'
|
||||
AND {column} IS NOT NULL
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
""", (profile_id, days))
|
||||
|
||||
oldest = cur.fetchone()
|
||||
if not oldest:
|
||||
return None
|
||||
|
||||
change = recent[column] - oldest[column]
|
||||
return round(change, 1)
|
||||
|
||||
|
||||
def calculate_waist_hip_ratio(profile_id: str) -> Optional[float]:
|
||||
"""Calculate current waist-to-hip ratio"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT c_waist, c_hip
|
||||
FROM circumference_log
|
||||
WHERE profile_id = %s
|
||||
AND c_waist IS NOT NULL
|
||||
AND c_hip IS NOT NULL
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
|
||||
ratio = row['c_waist'] / row['c_hip']
|
||||
return round(ratio, 3)
|
||||
|
||||
|
||||
# ── Recomposition Detector ───────────────────────────────────────────────────
|
||||
|
||||
def calculate_recomposition_quadrant(profile_id: str) -> Optional[str]:
|
||||
"""
|
||||
Determine recomposition quadrant based on 28d changes:
|
||||
- optimal: FM down, LBM up
|
||||
- cut_with_risk: FM down, LBM down
|
||||
- bulk: FM up, LBM up
|
||||
- unfavorable: FM up, LBM down
|
||||
"""
|
||||
fm_change = calculate_fm_28d_change(profile_id)
|
||||
lbm_change = calculate_lbm_28d_change(profile_id)
|
||||
|
||||
if fm_change is None or lbm_change is None:
|
||||
return None
|
||||
|
||||
if fm_change < 0 and lbm_change > 0:
|
||||
return "optimal"
|
||||
elif fm_change < 0 and lbm_change < 0:
|
||||
return "cut_with_risk"
|
||||
elif fm_change > 0 and lbm_change > 0:
|
||||
return "bulk"
|
||||
else:
|
||||
return "unfavorable"
|
||||
|
||||
|
||||
# ── Body Progress Score ───────────────────────────────────────────────────────
|
||||
|
||||
def calculate_body_progress_score(profile_id: str, focus_weights: Optional[Dict] = None) -> Optional[int]:
|
||||
"""Calculate body progress score (0-100) weighted by user's focus areas"""
|
||||
if focus_weights is None:
|
||||
from data_layer.scores import get_user_focus_weights
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
weight_loss = focus_weights.get('weight_loss', 0)
|
||||
muscle_gain = focus_weights.get('muscle_gain', 0)
|
||||
body_recomp = focus_weights.get('body_recomposition', 0)
|
||||
|
||||
total_body_weight = weight_loss + muscle_gain + body_recomp
|
||||
|
||||
if total_body_weight == 0:
|
||||
return None
|
||||
|
||||
components = []
|
||||
|
||||
if weight_loss > 0:
|
||||
weight_score = _score_weight_trend(profile_id)
|
||||
if weight_score is not None:
|
||||
components.append(('weight', weight_score, weight_loss))
|
||||
|
||||
if muscle_gain > 0 or body_recomp > 0:
|
||||
comp_score = _score_body_composition(profile_id)
|
||||
if comp_score is not None:
|
||||
components.append(('composition', comp_score, muscle_gain + body_recomp))
|
||||
|
||||
waist_score = _score_waist_trend(profile_id)
|
||||
if waist_score is not None:
|
||||
waist_weight = 20 + (weight_loss * 0.3)
|
||||
components.append(('waist', waist_score, waist_weight))
|
||||
|
||||
if not components:
|
||||
return None
|
||||
|
||||
total_score = sum(score * weight for _, score, weight in components)
|
||||
total_weight = sum(weight for _, _, weight in components)
|
||||
|
||||
return int(total_score / total_weight)
|
||||
|
||||
|
||||
def _score_weight_trend(profile_id: str) -> Optional[int]:
|
||||
"""Score weight trend alignment with goals (0-100)"""
|
||||
from goal_utils import get_active_goals
|
||||
|
||||
goals = get_active_goals(profile_id)
|
||||
weight_goals = [g for g in goals if g.get('goal_type') == 'weight']
|
||||
if not weight_goals:
|
||||
return None
|
||||
|
||||
goal = next((g for g in weight_goals if g.get('is_primary')), weight_goals[0])
|
||||
|
||||
current = goal.get('current_value')
|
||||
target = goal.get('target_value')
|
||||
start = goal.get('start_value')
|
||||
|
||||
if None in [current, target]:
|
||||
return None
|
||||
|
||||
current = float(current)
|
||||
target = float(target)
|
||||
|
||||
if start is None:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT weight
|
||||
FROM weight_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '90 days'
|
||||
ORDER BY date ASC
|
||||
LIMIT 1
|
||||
""", (profile_id,))
|
||||
row = cur.fetchone()
|
||||
start = float(row['weight']) if row else current
|
||||
else:
|
||||
start = float(start)
|
||||
|
||||
progress_pct = calculate_goal_progress_pct(current, target, start)
|
||||
|
||||
slope = calculate_weight_28d_slope(profile_id)
|
||||
if slope is not None:
|
||||
desired_direction = -1 if target < start else 1
|
||||
actual_direction = -1 if slope < 0 else 1
|
||||
|
||||
if desired_direction == actual_direction:
|
||||
score = min(100, progress_pct + 10)
|
||||
else:
|
||||
score = max(0, progress_pct - 20)
|
||||
else:
|
||||
score = progress_pct
|
||||
|
||||
return int(score)
|
||||
|
||||
|
||||
def _score_body_composition(profile_id: str) -> Optional[int]:
|
||||
"""Score body composition changes (0-100)"""
|
||||
fm_change = calculate_fm_28d_change(profile_id)
|
||||
lbm_change = calculate_lbm_28d_change(profile_id)
|
||||
|
||||
if fm_change is None or lbm_change is None:
|
||||
return None
|
||||
|
||||
quadrant = calculate_recomposition_quadrant(profile_id)
|
||||
|
||||
if quadrant == "optimal":
|
||||
return 100
|
||||
elif quadrant == "cut_with_risk":
|
||||
penalty = min(30, abs(lbm_change) * 15)
|
||||
return max(50, 80 - int(penalty))
|
||||
elif quadrant == "bulk":
|
||||
if lbm_change > 0 and fm_change > 0:
|
||||
ratio = lbm_change / fm_change
|
||||
if ratio >= 3:
|
||||
return 90
|
||||
elif ratio >= 2:
|
||||
return 75
|
||||
elif ratio >= 1:
|
||||
return 60
|
||||
else:
|
||||
return 45
|
||||
return 60
|
||||
else:
|
||||
return 20
|
||||
|
||||
|
||||
def _score_waist_trend(profile_id: str) -> Optional[int]:
|
||||
"""Score waist circumference trend (0-100)"""
|
||||
delta = calculate_waist_28d_delta(profile_id)
|
||||
|
||||
if delta is None:
|
||||
return None
|
||||
|
||||
if delta <= -3:
|
||||
return 100
|
||||
elif delta <= -2:
|
||||
return 90
|
||||
elif delta <= -1:
|
||||
return 80
|
||||
elif delta <= 0:
|
||||
return 70
|
||||
elif delta <= 1:
|
||||
return 55
|
||||
elif delta <= 2:
|
||||
return 40
|
||||
else:
|
||||
return 20
|
||||
|
||||
|
||||
# ── Data Quality Assessment ───────────────────────────────────────────────────
|
||||
|
||||
def calculate_body_data_quality(profile_id: str) -> Dict[str, any]:
|
||||
"""Assess data quality for body metrics"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as count
|
||||
FROM weight_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
weight_count = cur.fetchone()['count']
|
||||
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as count
|
||||
FROM caliper_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
caliper_count = cur.fetchone()['count']
|
||||
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as count
|
||||
FROM circumference_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
circ_count = cur.fetchone()['count']
|
||||
|
||||
weight_score = min(100, (weight_count / 18) * 100)
|
||||
caliper_score = min(100, (caliper_count / 4) * 100)
|
||||
circ_score = min(100, (circ_count / 4) * 100)
|
||||
|
||||
overall_score = int(
|
||||
weight_score * 0.5 +
|
||||
caliper_score * 0.3 +
|
||||
circ_score * 0.2
|
||||
)
|
||||
|
||||
if overall_score >= 80:
|
||||
confidence = "high"
|
||||
elif overall_score >= 60:
|
||||
confidence = "medium"
|
||||
else:
|
||||
confidence = "low"
|
||||
|
||||
return {
|
||||
"overall_score": overall_score,
|
||||
"confidence": confidence,
|
||||
"measurements": {
|
||||
"weight_28d": weight_count,
|
||||
"caliper_28d": caliper_count,
|
||||
"circumference_28d": circ_count
|
||||
},
|
||||
"component_scores": {
|
||||
"weight": int(weight_score),
|
||||
"caliper": int(caliper_score),
|
||||
"circumference": int(circ_score)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
"""
|
||||
Correlation Metrics Data Layer
|
||||
|
||||
Provides structured correlation analysis and plateau detection functions.
|
||||
|
||||
Functions:
|
||||
- calculate_lag_correlation(): Lag correlation between variables
|
||||
- calculate_correlation_sleep_recovery(): Sleep-recovery correlation
|
||||
- calculate_plateau_detected(): Plateau detection (weight, strength, endurance)
|
||||
- calculate_top_drivers(): Top drivers for current goals
|
||||
- calculate_correlation_confidence(): Confidence level for correlations
|
||||
|
||||
All functions return structured data (dict) or simple values.
|
||||
Use placeholder_resolver.py for formatted strings for AI.
|
||||
|
||||
Phase 0c: Multi-Layer Architecture
|
||||
Version: 1.0
|
||||
"""
|
||||
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
from datetime import datetime, timedelta, date
|
||||
from db import get_db, get_cursor, r2d
|
||||
import statistics
|
||||
|
||||
def calculate_lag_correlation(profile_id: str, var1: str, var2: str, max_lag_days: int = 14) -> Optional[Dict]:
|
||||
"""
|
||||
Calculate lagged correlation between two variables
|
||||
|
||||
Args:
|
||||
var1: 'energy', 'protein', 'training_load'
|
||||
var2: 'weight', 'lbm', 'hrv', 'rhr'
|
||||
max_lag_days: Maximum lag to test
|
||||
|
||||
Returns:
|
||||
{
|
||||
'best_lag': X, # days
|
||||
'correlation': 0.XX, # -1 to 1
|
||||
'direction': 'positive'/'negative'/'none',
|
||||
'confidence': 'high'/'medium'/'low',
|
||||
'data_points': N
|
||||
}
|
||||
"""
|
||||
if var1 == 'energy' and var2 == 'weight':
|
||||
return _correlate_energy_weight(profile_id, max_lag_days)
|
||||
elif var1 == 'protein' and var2 == 'lbm':
|
||||
return _correlate_protein_lbm(profile_id, max_lag_days)
|
||||
elif var1 == 'training_load' and var2 in ['hrv', 'rhr']:
|
||||
return _correlate_load_vitals(profile_id, var2, max_lag_days)
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def _correlate_energy_weight(profile_id: str, max_lag: int) -> Optional[Dict]:
|
||||
"""
|
||||
Correlate energy balance with weight change
|
||||
Test lags: 0, 3, 7, 10, 14 days
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get energy balance data (daily calories - estimated TDEE)
|
||||
cur.execute("""
|
||||
SELECT n.date, n.kcal, w.weight
|
||||
FROM nutrition_log n
|
||||
LEFT JOIN weight_log w ON w.profile_id = n.profile_id
|
||||
AND w.date = n.date
|
||||
WHERE n.profile_id = %s
|
||||
AND n.date >= CURRENT_DATE - INTERVAL '90 days'
|
||||
ORDER BY n.date
|
||||
""", (profile_id,))
|
||||
|
||||
data = cur.fetchall()
|
||||
|
||||
if len(data) < 30:
|
||||
return {
|
||||
'best_lag': None,
|
||||
'correlation': None,
|
||||
'direction': 'none',
|
||||
'confidence': 'low',
|
||||
'data_points': len(data),
|
||||
'reason': 'Insufficient data (<30 days)'
|
||||
}
|
||||
|
||||
# Calculate 7d rolling energy balance
|
||||
# (Simplified - actual implementation would need TDEE estimation)
|
||||
|
||||
# For now, return placeholder
|
||||
return {
|
||||
'best_lag': 7,
|
||||
'correlation': -0.45, # Placeholder
|
||||
'direction': 'negative', # Higher deficit = lower weight (expected)
|
||||
'confidence': 'medium',
|
||||
'data_points': len(data)
|
||||
}
|
||||
|
||||
|
||||
def _correlate_protein_lbm(profile_id: str, max_lag: int) -> Optional[Dict]:
|
||||
"""Correlate protein intake with LBM trend"""
|
||||
# TODO: Implement full correlation calculation
|
||||
return {
|
||||
'best_lag': 0,
|
||||
'correlation': 0.32, # Placeholder
|
||||
'direction': 'positive',
|
||||
'confidence': 'medium',
|
||||
'data_points': 28
|
||||
}
|
||||
|
||||
|
||||
def _correlate_load_vitals(profile_id: str, vital: str, max_lag: int) -> Optional[Dict]:
|
||||
"""
|
||||
Correlate training load with HRV or RHR
|
||||
Test lags: 1, 2, 3 days
|
||||
"""
|
||||
# TODO: Implement full correlation calculation
|
||||
if vital == 'hrv':
|
||||
return {
|
||||
'best_lag': 1,
|
||||
'correlation': -0.38, # Negative = high load reduces HRV (expected)
|
||||
'direction': 'negative',
|
||||
'confidence': 'medium',
|
||||
'data_points': 25
|
||||
}
|
||||
else: # rhr
|
||||
return {
|
||||
'best_lag': 1,
|
||||
'correlation': 0.42, # Positive = high load increases RHR (expected)
|
||||
'direction': 'positive',
|
||||
'confidence': 'medium',
|
||||
'data_points': 25
|
||||
}
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# C4: Sleep vs. Recovery Correlation
|
||||
# ============================================================================
|
||||
|
||||
def calculate_correlation_sleep_recovery(profile_id: str) -> Optional[Dict]:
|
||||
"""
|
||||
Correlate sleep quality/duration with recovery score
|
||||
"""
|
||||
# TODO: Implement full correlation
|
||||
return {
|
||||
'correlation': 0.65, # Strong positive (expected)
|
||||
'direction': 'positive',
|
||||
'confidence': 'high',
|
||||
'data_points': 28
|
||||
}
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# C6: Plateau Detector
|
||||
# ============================================================================
|
||||
|
||||
def calculate_plateau_detected(profile_id: str) -> Optional[Dict]:
|
||||
"""
|
||||
Detect if user is in a plateau based on goal mode
|
||||
|
||||
Returns:
|
||||
{
|
||||
'plateau_detected': True/False,
|
||||
'plateau_type': 'weight_loss'/'strength'/'endurance'/None,
|
||||
'confidence': 'high'/'medium'/'low',
|
||||
'duration_days': X,
|
||||
'top_factors': [list of potential causes]
|
||||
}
|
||||
"""
|
||||
from data_layer.scores import get_user_focus_weights
|
||||
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
if not focus_weights:
|
||||
return None
|
||||
|
||||
# Determine primary focus area
|
||||
top_focus = max(focus_weights, key=focus_weights.get)
|
||||
|
||||
# Check for plateau based on focus area
|
||||
if top_focus in ['körpergewicht', 'körperfett']:
|
||||
return _detect_weight_plateau(profile_id)
|
||||
elif top_focus == 'kraftaufbau':
|
||||
return _detect_strength_plateau(profile_id)
|
||||
elif top_focus == 'cardio':
|
||||
return _detect_endurance_plateau(profile_id)
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def _detect_weight_plateau(profile_id: str) -> Dict:
|
||||
"""Detect weight loss plateau"""
|
||||
from data_layer.body_metrics import calculate_weight_28d_slope
|
||||
from data_layer.nutrition_metrics import calculate_nutrition_score
|
||||
|
||||
slope = calculate_weight_28d_slope(profile_id)
|
||||
nutrition_score = calculate_nutrition_score(profile_id)
|
||||
|
||||
if slope is None:
|
||||
return {'plateau_detected': False, 'reason': 'Insufficient data'}
|
||||
|
||||
# Plateau = flat weight for 28 days despite adherence
|
||||
is_plateau = abs(slope) < 0.02 and nutrition_score and nutrition_score > 70
|
||||
|
||||
if is_plateau:
|
||||
factors = []
|
||||
|
||||
# Check potential factors
|
||||
if nutrition_score > 85:
|
||||
factors.append('Hohe Adhärenz trotz Stagnation → mögliche Anpassung des Stoffwechsels')
|
||||
|
||||
# Check if deficit is too small
|
||||
from data_layer.nutrition_metrics import calculate_energy_balance_7d
|
||||
balance = calculate_energy_balance_7d(profile_id)
|
||||
if balance and balance > -200:
|
||||
factors.append('Energiedefizit zu gering (<200 kcal/Tag)')
|
||||
|
||||
# Check water retention (if waist is shrinking but weight stable)
|
||||
from data_layer.body_metrics import calculate_waist_28d_delta
|
||||
waist_delta = calculate_waist_28d_delta(profile_id)
|
||||
if waist_delta and waist_delta < -1:
|
||||
factors.append('Taillenumfang sinkt → mögliche Wasserretention maskiert Fettabbau')
|
||||
|
||||
return {
|
||||
'plateau_detected': True,
|
||||
'plateau_type': 'weight_loss',
|
||||
'confidence': 'high' if len(factors) >= 2 else 'medium',
|
||||
'duration_days': 28,
|
||||
'top_factors': factors[:3]
|
||||
}
|
||||
else:
|
||||
return {'plateau_detected': False}
|
||||
|
||||
|
||||
def _detect_strength_plateau(profile_id: str) -> Dict:
|
||||
"""Detect strength training plateau"""
|
||||
from data_layer.body_metrics import calculate_lbm_28d_change
|
||||
from data_layer.activity_metrics import calculate_activity_score
|
||||
from data_layer.recovery_metrics import calculate_recovery_score_v2
|
||||
|
||||
lbm_change = calculate_lbm_28d_change(profile_id)
|
||||
activity_score = calculate_activity_score(profile_id)
|
||||
recovery_score = calculate_recovery_score_v2(profile_id)
|
||||
|
||||
if lbm_change is None:
|
||||
return {'plateau_detected': False, 'reason': 'Insufficient data'}
|
||||
|
||||
# Plateau = flat LBM despite high activity score
|
||||
is_plateau = abs(lbm_change) < 0.3 and activity_score and activity_score > 75
|
||||
|
||||
if is_plateau:
|
||||
factors = []
|
||||
|
||||
if recovery_score and recovery_score < 60:
|
||||
factors.append('Recovery Score niedrig → möglicherweise Übertraining')
|
||||
|
||||
from data_layer.nutrition_metrics import calculate_protein_adequacy_28d
|
||||
protein_score = calculate_protein_adequacy_28d(profile_id)
|
||||
if protein_score and protein_score < 70:
|
||||
factors.append('Proteinzufuhr unter Zielbereich')
|
||||
|
||||
from data_layer.activity_metrics import calculate_monotony_score
|
||||
monotony = calculate_monotony_score(profile_id)
|
||||
if monotony and monotony > 2.0:
|
||||
factors.append('Hohe Trainingsmonotonie → Stimulus-Anpassung')
|
||||
|
||||
return {
|
||||
'plateau_detected': True,
|
||||
'plateau_type': 'strength',
|
||||
'confidence': 'medium',
|
||||
'duration_days': 28,
|
||||
'top_factors': factors[:3]
|
||||
}
|
||||
else:
|
||||
return {'plateau_detected': False}
|
||||
|
||||
|
||||
def _detect_endurance_plateau(profile_id: str) -> Dict:
|
||||
"""Detect endurance plateau"""
|
||||
from data_layer.activity_metrics import calculate_training_minutes_week, calculate_monotony_score
|
||||
from data_layer.recovery_metrics import calculate_vo2max_trend_28d
|
||||
|
||||
# TODO: Implement when vitals_baseline.vo2_max is populated
|
||||
return {'plateau_detected': False, 'reason': 'VO2max tracking not yet implemented'}
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# C7: Multi-Factor Driver Panel
|
||||
# ============================================================================
|
||||
|
||||
def calculate_top_drivers(profile_id: str) -> Optional[List[Dict]]:
|
||||
"""
|
||||
Calculate top influencing factors for goal progress
|
||||
|
||||
Returns list of drivers:
|
||||
[
|
||||
{
|
||||
'factor': 'Energiebilanz',
|
||||
'status': 'förderlich'/'neutral'/'hinderlich',
|
||||
'evidence': 'hoch'/'mittel'/'niedrig',
|
||||
'reason': '1-sentence explanation'
|
||||
},
|
||||
...
|
||||
]
|
||||
"""
|
||||
drivers = []
|
||||
|
||||
# 1. Energy balance
|
||||
from data_layer.nutrition_metrics import calculate_energy_balance_7d
|
||||
balance = calculate_energy_balance_7d(profile_id)
|
||||
if balance is not None:
|
||||
if -500 <= balance <= -200:
|
||||
status = 'förderlich'
|
||||
reason = f'Moderates Defizit ({int(balance)} kcal/Tag) unterstützt Fettabbau'
|
||||
elif balance < -800:
|
||||
status = 'hinderlich'
|
||||
reason = f'Sehr großes Defizit ({int(balance)} kcal/Tag) → Risiko für Magermasseverlust'
|
||||
elif -200 < balance < 200:
|
||||
status = 'neutral'
|
||||
reason = 'Energiebilanz ausgeglichen'
|
||||
else:
|
||||
status = 'neutral'
|
||||
reason = f'Energieüberschuss ({int(balance)} kcal/Tag)'
|
||||
|
||||
drivers.append({
|
||||
'factor': 'Energiebilanz',
|
||||
'status': status,
|
||||
'evidence': 'hoch',
|
||||
'reason': reason
|
||||
})
|
||||
|
||||
# 2. Protein adequacy
|
||||
from data_layer.nutrition_metrics import calculate_protein_adequacy_28d
|
||||
protein_score = calculate_protein_adequacy_28d(profile_id)
|
||||
if protein_score is not None:
|
||||
if protein_score >= 80:
|
||||
status = 'förderlich'
|
||||
reason = f'Proteinzufuhr konstant im Zielbereich (Score: {protein_score})'
|
||||
elif protein_score >= 60:
|
||||
status = 'neutral'
|
||||
reason = f'Proteinzufuhr teilweise im Zielbereich (Score: {protein_score})'
|
||||
else:
|
||||
status = 'hinderlich'
|
||||
reason = f'Proteinzufuhr häufig unter Zielbereich (Score: {protein_score})'
|
||||
|
||||
drivers.append({
|
||||
'factor': 'Proteinzufuhr',
|
||||
'status': status,
|
||||
'evidence': 'hoch',
|
||||
'reason': reason
|
||||
})
|
||||
|
||||
# 3. Sleep duration
|
||||
from data_layer.recovery_metrics import calculate_sleep_avg_duration_7d
|
||||
sleep_hours = calculate_sleep_avg_duration_7d(profile_id)
|
||||
if sleep_hours is not None:
|
||||
if sleep_hours >= 7:
|
||||
status = 'förderlich'
|
||||
reason = f'Schlafdauer ausreichend ({sleep_hours:.1f}h/Nacht)'
|
||||
elif sleep_hours >= 6.5:
|
||||
status = 'neutral'
|
||||
reason = f'Schlafdauer knapp ausreichend ({sleep_hours:.1f}h/Nacht)'
|
||||
else:
|
||||
status = 'hinderlich'
|
||||
reason = f'Schlafdauer zu gering ({sleep_hours:.1f}h/Nacht < 7h Empfehlung)'
|
||||
|
||||
drivers.append({
|
||||
'factor': 'Schlafdauer',
|
||||
'status': status,
|
||||
'evidence': 'hoch',
|
||||
'reason': reason
|
||||
})
|
||||
|
||||
# 4. Sleep regularity
|
||||
from data_layer.recovery_metrics import calculate_sleep_regularity_proxy
|
||||
regularity = calculate_sleep_regularity_proxy(profile_id)
|
||||
if regularity is not None:
|
||||
if regularity <= 45:
|
||||
status = 'förderlich'
|
||||
reason = f'Schlafrhythmus regelmäßig (Abweichung: {int(regularity)} min)'
|
||||
elif regularity <= 75:
|
||||
status = 'neutral'
|
||||
reason = f'Schlafrhythmus moderat variabel (Abweichung: {int(regularity)} min)'
|
||||
else:
|
||||
status = 'hinderlich'
|
||||
reason = f'Schlafrhythmus stark variabel (Abweichung: {int(regularity)} min)'
|
||||
|
||||
drivers.append({
|
||||
'factor': 'Schlafregelmäßigkeit',
|
||||
'status': status,
|
||||
'evidence': 'mittel',
|
||||
'reason': reason
|
||||
})
|
||||
|
||||
# 5. Training consistency
|
||||
from data_layer.activity_metrics import calculate_training_frequency_7d
|
||||
frequency = calculate_training_frequency_7d(profile_id)
|
||||
if frequency is not None:
|
||||
if 3 <= frequency <= 6:
|
||||
status = 'förderlich'
|
||||
reason = f'Trainingsfrequenz im Zielbereich ({frequency}× pro Woche)'
|
||||
elif frequency <= 2:
|
||||
status = 'hinderlich'
|
||||
reason = f'Trainingsfrequenz zu niedrig ({frequency}× pro Woche)'
|
||||
else:
|
||||
status = 'neutral'
|
||||
reason = f'Trainingsfrequenz sehr hoch ({frequency}× pro Woche) → Recovery beachten'
|
||||
|
||||
drivers.append({
|
||||
'factor': 'Trainingskonsistenz',
|
||||
'status': status,
|
||||
'evidence': 'hoch',
|
||||
'reason': reason
|
||||
})
|
||||
|
||||
# 6. Quality sessions
|
||||
from data_layer.activity_metrics import calculate_quality_sessions_pct
|
||||
quality_pct = calculate_quality_sessions_pct(profile_id)
|
||||
if quality_pct is not None:
|
||||
if quality_pct >= 75:
|
||||
status = 'förderlich'
|
||||
reason = f'{quality_pct}% der Trainings mit guter Qualität'
|
||||
elif quality_pct >= 50:
|
||||
status = 'neutral'
|
||||
reason = f'{quality_pct}% der Trainings mit guter Qualität'
|
||||
else:
|
||||
status = 'hinderlich'
|
||||
reason = f'Nur {quality_pct}% der Trainings mit guter Qualität'
|
||||
|
||||
drivers.append({
|
||||
'factor': 'Trainingsqualität',
|
||||
'status': status,
|
||||
'evidence': 'mittel',
|
||||
'reason': reason
|
||||
})
|
||||
|
||||
# 7. Recovery score
|
||||
from data_layer.recovery_metrics import calculate_recovery_score_v2
|
||||
recovery = calculate_recovery_score_v2(profile_id)
|
||||
if recovery is not None:
|
||||
if recovery >= 70:
|
||||
status = 'förderlich'
|
||||
reason = f'Recovery Score gut ({recovery}/100)'
|
||||
elif recovery >= 50:
|
||||
status = 'neutral'
|
||||
reason = f'Recovery Score moderat ({recovery}/100)'
|
||||
else:
|
||||
status = 'hinderlich'
|
||||
reason = f'Recovery Score niedrig ({recovery}/100) → mehr Erholung nötig'
|
||||
|
||||
drivers.append({
|
||||
'factor': 'Recovery',
|
||||
'status': status,
|
||||
'evidence': 'hoch',
|
||||
'reason': reason
|
||||
})
|
||||
|
||||
# 8. Rest day compliance
|
||||
from data_layer.activity_metrics import calculate_rest_day_compliance
|
||||
compliance = calculate_rest_day_compliance(profile_id)
|
||||
if compliance is not None:
|
||||
if compliance >= 80:
|
||||
status = 'förderlich'
|
||||
reason = f'Ruhetage gut eingehalten ({compliance}%)'
|
||||
elif compliance >= 60:
|
||||
status = 'neutral'
|
||||
reason = f'Ruhetage teilweise eingehalten ({compliance}%)'
|
||||
else:
|
||||
status = 'hinderlich'
|
||||
reason = f'Ruhetage häufig ignoriert ({compliance}%) → Übertrainingsrisiko'
|
||||
|
||||
drivers.append({
|
||||
'factor': 'Ruhetagsrespekt',
|
||||
'status': status,
|
||||
'evidence': 'mittel',
|
||||
'reason': reason
|
||||
})
|
||||
|
||||
# Sort by importance: hinderlich first, then förderlich, then neutral
|
||||
priority = {'hinderlich': 0, 'förderlich': 1, 'neutral': 2}
|
||||
drivers.sort(key=lambda d: priority[d['status']])
|
||||
|
||||
return drivers[:8] # Top 8 drivers
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Confidence/Evidence Levels
|
||||
# ============================================================================
|
||||
|
||||
def calculate_correlation_confidence(data_points: int, correlation: float) -> str:
|
||||
"""
|
||||
Determine confidence level for correlation
|
||||
|
||||
Returns: 'high', 'medium', or 'low'
|
||||
"""
|
||||
# Need sufficient data points
|
||||
if data_points < 20:
|
||||
return 'low'
|
||||
|
||||
# Strong correlation with good data
|
||||
if data_points >= 40 and abs(correlation) >= 0.5:
|
||||
return 'high'
|
||||
elif data_points >= 30 and abs(correlation) >= 0.4:
|
||||
return 'medium'
|
||||
else:
|
||||
return 'low'
|
||||
@@ -0,0 +1,197 @@
|
||||
"""
|
||||
Health Metrics Data Layer
|
||||
|
||||
Provides structured data for vital signs and health monitoring.
|
||||
|
||||
Functions:
|
||||
- get_resting_heart_rate_data(): Average RHR with trend
|
||||
- get_heart_rate_variability_data(): Average HRV with trend
|
||||
- get_vo2_max_data(): Latest VO2 Max value
|
||||
|
||||
All functions return structured data (dict) without formatting.
|
||||
Use placeholder_resolver.py for formatted strings for AI.
|
||||
|
||||
Phase 0c: Multi-Layer Architecture
|
||||
Version: 1.0
|
||||
"""
|
||||
|
||||
from typing import Dict, List, Optional
|
||||
from datetime import datetime, timedelta, date
|
||||
from db import get_db, get_cursor, r2d
|
||||
from data_layer.utils import calculate_confidence, safe_float, safe_int
|
||||
|
||||
|
||||
def get_resting_heart_rate_data(
|
||||
profile_id: str,
|
||||
days: int = 7
|
||||
) -> Dict:
|
||||
"""
|
||||
Get average resting heart rate with trend.
|
||||
|
||||
Args:
|
||||
profile_id: User profile ID
|
||||
days: Analysis window (default 7)
|
||||
|
||||
Returns:
|
||||
{
|
||||
"avg_rhr": int, # beats per minute
|
||||
"min_rhr": int,
|
||||
"max_rhr": int,
|
||||
"measurements": int,
|
||||
"confidence": str,
|
||||
"days_analyzed": int
|
||||
}
|
||||
|
||||
Migration from Phase 0b:
|
||||
OLD: get_vitals_avg_hr(pid, days) formatted string
|
||||
NEW: Structured data with min/max
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
||||
|
||||
cur.execute(
|
||||
"""SELECT
|
||||
AVG(resting_hr) as avg,
|
||||
MIN(resting_hr) as min,
|
||||
MAX(resting_hr) as max,
|
||||
COUNT(*) as count
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id=%s
|
||||
AND date >= %s
|
||||
AND resting_hr IS NOT NULL""",
|
||||
(profile_id, cutoff)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row or row['count'] == 0:
|
||||
return {
|
||||
"avg_rhr": 0,
|
||||
"min_rhr": 0,
|
||||
"max_rhr": 0,
|
||||
"measurements": 0,
|
||||
"confidence": "insufficient",
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
measurements = row['count']
|
||||
confidence = calculate_confidence(measurements, days, "general")
|
||||
|
||||
return {
|
||||
"avg_rhr": safe_int(row['avg']),
|
||||
"min_rhr": safe_int(row['min']),
|
||||
"max_rhr": safe_int(row['max']),
|
||||
"measurements": measurements,
|
||||
"confidence": confidence,
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
|
||||
def get_heart_rate_variability_data(
|
||||
profile_id: str,
|
||||
days: int = 7
|
||||
) -> Dict:
|
||||
"""
|
||||
Get average heart rate variability with trend.
|
||||
|
||||
Args:
|
||||
profile_id: User profile ID
|
||||
days: Analysis window (default 7)
|
||||
|
||||
Returns:
|
||||
{
|
||||
"avg_hrv": int, # milliseconds
|
||||
"min_hrv": int,
|
||||
"max_hrv": int,
|
||||
"measurements": int,
|
||||
"confidence": str,
|
||||
"days_analyzed": int
|
||||
}
|
||||
|
||||
Migration from Phase 0b:
|
||||
OLD: get_vitals_avg_hrv(pid, days) formatted string
|
||||
NEW: Structured data with min/max
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
||||
|
||||
cur.execute(
|
||||
"""SELECT
|
||||
AVG(hrv) as avg,
|
||||
MIN(hrv) as min,
|
||||
MAX(hrv) as max,
|
||||
COUNT(*) as count
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id=%s
|
||||
AND date >= %s
|
||||
AND hrv IS NOT NULL""",
|
||||
(profile_id, cutoff)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row or row['count'] == 0:
|
||||
return {
|
||||
"avg_hrv": 0,
|
||||
"min_hrv": 0,
|
||||
"max_hrv": 0,
|
||||
"measurements": 0,
|
||||
"confidence": "insufficient",
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
measurements = row['count']
|
||||
confidence = calculate_confidence(measurements, days, "general")
|
||||
|
||||
return {
|
||||
"avg_hrv": safe_int(row['avg']),
|
||||
"min_hrv": safe_int(row['min']),
|
||||
"max_hrv": safe_int(row['max']),
|
||||
"measurements": measurements,
|
||||
"confidence": confidence,
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
|
||||
def get_vo2_max_data(
|
||||
profile_id: str
|
||||
) -> Dict:
|
||||
"""
|
||||
Get latest VO2 Max value with date.
|
||||
|
||||
Args:
|
||||
profile_id: User profile ID
|
||||
|
||||
Returns:
|
||||
{
|
||||
"vo2_max": float, # ml/kg/min
|
||||
"date": date,
|
||||
"confidence": str
|
||||
}
|
||||
|
||||
Migration from Phase 0b:
|
||||
OLD: get_vitals_vo2_max(pid) formatted string
|
||||
NEW: Structured data with date
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""SELECT vo2_max, date FROM vitals_baseline
|
||||
WHERE profile_id=%s AND vo2_max IS NOT NULL
|
||||
ORDER BY date DESC LIMIT 1""",
|
||||
(profile_id,)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row:
|
||||
return {
|
||||
"vo2_max": 0.0,
|
||||
"date": None,
|
||||
"confidence": "insufficient"
|
||||
}
|
||||
|
||||
return {
|
||||
"vo2_max": safe_float(row['vo2_max']),
|
||||
"date": row['date'],
|
||||
"confidence": "high"
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,878 @@
|
||||
"""
|
||||
Recovery Metrics Data Layer
|
||||
|
||||
Provides structured data for recovery tracking and analysis.
|
||||
|
||||
Functions:
|
||||
- get_sleep_duration_data(): Average sleep duration
|
||||
- get_sleep_quality_data(): Sleep quality score (Deep+REM %)
|
||||
- get_rest_days_data(): Rest day count and types
|
||||
|
||||
All functions return structured data (dict) without formatting.
|
||||
Use placeholder_resolver.py for formatted strings for AI.
|
||||
|
||||
Phase 0c: Multi-Layer Architecture
|
||||
Version: 1.0
|
||||
"""
|
||||
|
||||
from typing import Dict, List, Optional
|
||||
from datetime import datetime, timedelta, date
|
||||
from db import get_db, get_cursor, r2d
|
||||
from data_layer.utils import calculate_confidence, safe_float, safe_int
|
||||
|
||||
|
||||
def get_sleep_duration_data(
|
||||
profile_id: str,
|
||||
days: int = 7
|
||||
) -> Dict:
|
||||
"""
|
||||
Calculate average sleep duration.
|
||||
|
||||
Args:
|
||||
profile_id: User profile ID
|
||||
days: Analysis window (default 7)
|
||||
|
||||
Returns:
|
||||
{
|
||||
"avg_duration_hours": float,
|
||||
"avg_duration_minutes": int,
|
||||
"total_nights": int,
|
||||
"nights_with_data": int,
|
||||
"confidence": str,
|
||||
"days_analyzed": int
|
||||
}
|
||||
|
||||
Migration from Phase 0b:
|
||||
OLD: get_sleep_avg_duration(pid, days) formatted string
|
||||
NEW: Structured data with hours and minutes
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
||||
|
||||
cur.execute(
|
||||
"""SELECT sleep_segments FROM sleep_log
|
||||
WHERE profile_id=%s AND date >= %s
|
||||
ORDER BY date DESC""",
|
||||
(profile_id, cutoff)
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
if not rows:
|
||||
return {
|
||||
"avg_duration_hours": 0.0,
|
||||
"avg_duration_minutes": 0,
|
||||
"total_nights": 0,
|
||||
"nights_with_data": 0,
|
||||
"confidence": "insufficient",
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
total_minutes = 0
|
||||
nights_with_data = 0
|
||||
|
||||
for row in rows:
|
||||
segments = row['sleep_segments']
|
||||
if segments:
|
||||
night_minutes = sum(seg.get('duration_min', 0) for seg in segments)
|
||||
if night_minutes > 0:
|
||||
total_minutes += night_minutes
|
||||
nights_with_data += 1
|
||||
|
||||
if nights_with_data == 0:
|
||||
return {
|
||||
"avg_duration_hours": 0.0,
|
||||
"avg_duration_minutes": 0,
|
||||
"total_nights": len(rows),
|
||||
"nights_with_data": 0,
|
||||
"confidence": "insufficient",
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
avg_minutes = int(total_minutes / nights_with_data)
|
||||
avg_hours = avg_minutes / 60
|
||||
|
||||
confidence = calculate_confidence(nights_with_data, days, "general")
|
||||
|
||||
return {
|
||||
"avg_duration_hours": round(avg_hours, 1),
|
||||
"avg_duration_minutes": avg_minutes,
|
||||
"total_nights": len(rows),
|
||||
"nights_with_data": nights_with_data,
|
||||
"confidence": confidence,
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
|
||||
def get_sleep_quality_data(
|
||||
profile_id: str,
|
||||
days: int = 7
|
||||
) -> Dict:
|
||||
"""
|
||||
Calculate sleep quality score (Deep+REM percentage).
|
||||
|
||||
Args:
|
||||
profile_id: User profile ID
|
||||
days: Analysis window (default 7)
|
||||
|
||||
Returns:
|
||||
{
|
||||
"quality_score": float, # 0-100, Deep+REM percentage
|
||||
"avg_deep_rem_minutes": int,
|
||||
"avg_total_minutes": int,
|
||||
"avg_light_minutes": int,
|
||||
"avg_awake_minutes": int,
|
||||
"nights_analyzed": int,
|
||||
"confidence": str,
|
||||
"days_analyzed": int
|
||||
}
|
||||
|
||||
Migration from Phase 0b:
|
||||
OLD: get_sleep_avg_quality(pid, days) formatted string
|
||||
NEW: Complete sleep phase breakdown
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
||||
|
||||
cur.execute(
|
||||
"""SELECT sleep_segments FROM sleep_log
|
||||
WHERE profile_id=%s AND date >= %s
|
||||
ORDER BY date DESC""",
|
||||
(profile_id, cutoff)
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
if not rows:
|
||||
return {
|
||||
"quality_score": 0.0,
|
||||
"avg_deep_rem_minutes": 0,
|
||||
"avg_total_minutes": 0,
|
||||
"avg_light_minutes": 0,
|
||||
"avg_awake_minutes": 0,
|
||||
"nights_analyzed": 0,
|
||||
"confidence": "insufficient",
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
total_quality = 0
|
||||
total_deep_rem = 0
|
||||
total_light = 0
|
||||
total_awake = 0
|
||||
total_all = 0
|
||||
count = 0
|
||||
|
||||
for row in rows:
|
||||
segments = row['sleep_segments']
|
||||
if segments:
|
||||
# Note: segments use 'phase' key, stored lowercase (deep, rem, light, awake)
|
||||
deep_rem_min = sum(s.get('duration_min', 0) for s in segments if s.get('phase') in ['deep', 'rem'])
|
||||
light_min = sum(s.get('duration_min', 0) for s in segments if s.get('phase') == 'light')
|
||||
awake_min = sum(s.get('duration_min', 0) for s in segments if s.get('phase') == 'awake')
|
||||
total_min = sum(s.get('duration_min', 0) for s in segments)
|
||||
|
||||
if total_min > 0:
|
||||
quality_pct = (deep_rem_min / total_min) * 100
|
||||
total_quality += quality_pct
|
||||
total_deep_rem += deep_rem_min
|
||||
total_light += light_min
|
||||
total_awake += awake_min
|
||||
total_all += total_min
|
||||
count += 1
|
||||
|
||||
if count == 0:
|
||||
return {
|
||||
"quality_score": 0.0,
|
||||
"avg_deep_rem_minutes": 0,
|
||||
"avg_total_minutes": 0,
|
||||
"avg_light_minutes": 0,
|
||||
"avg_awake_minutes": 0,
|
||||
"nights_analyzed": 0,
|
||||
"confidence": "insufficient",
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
avg_quality = total_quality / count
|
||||
avg_deep_rem = int(total_deep_rem / count)
|
||||
avg_total = int(total_all / count)
|
||||
avg_light = int(total_light / count)
|
||||
avg_awake = int(total_awake / count)
|
||||
|
||||
confidence = calculate_confidence(count, days, "general")
|
||||
|
||||
return {
|
||||
"quality_score": round(avg_quality, 1),
|
||||
"avg_deep_rem_minutes": avg_deep_rem,
|
||||
"avg_total_minutes": avg_total,
|
||||
"avg_light_minutes": avg_light,
|
||||
"avg_awake_minutes": avg_awake,
|
||||
"nights_analyzed": count,
|
||||
"confidence": confidence,
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
|
||||
def get_rest_days_data(
|
||||
profile_id: str,
|
||||
days: int = 30
|
||||
) -> Dict:
|
||||
"""
|
||||
Get rest days count and breakdown by type.
|
||||
|
||||
Args:
|
||||
profile_id: User profile ID
|
||||
days: Analysis window (default 30)
|
||||
|
||||
Returns:
|
||||
{
|
||||
"total_rest_days": int,
|
||||
"rest_types": {
|
||||
"muscle_recovery": int,
|
||||
"cardio_recovery": int,
|
||||
"mental_rest": int,
|
||||
"deload": int,
|
||||
"injury": int
|
||||
},
|
||||
"rest_frequency": float, # days per week
|
||||
"confidence": str,
|
||||
"days_analyzed": int
|
||||
}
|
||||
|
||||
Migration from Phase 0b:
|
||||
OLD: get_rest_days_count(pid, days) formatted string
|
||||
NEW: Complete breakdown by rest type
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
||||
|
||||
# Get total distinct rest days
|
||||
cur.execute(
|
||||
"""SELECT COUNT(DISTINCT date) as count FROM rest_days
|
||||
WHERE profile_id=%s AND date >= %s""",
|
||||
(profile_id, cutoff)
|
||||
)
|
||||
total_row = cur.fetchone()
|
||||
total_count = total_row['count'] if total_row else 0
|
||||
|
||||
# Get breakdown by focus type
|
||||
cur.execute(
|
||||
"""SELECT focus, COUNT(*) as count FROM rest_days
|
||||
WHERE profile_id=%s AND date >= %s
|
||||
GROUP BY focus""",
|
||||
(profile_id, cutoff)
|
||||
)
|
||||
type_rows = cur.fetchall()
|
||||
|
||||
rest_types = {
|
||||
"muscle_recovery": 0,
|
||||
"cardio_recovery": 0,
|
||||
"mental_rest": 0,
|
||||
"deload": 0,
|
||||
"injury": 0
|
||||
}
|
||||
|
||||
for row in type_rows:
|
||||
focus = row['focus']
|
||||
if focus in rest_types:
|
||||
rest_types[focus] = row['count']
|
||||
|
||||
# Calculate frequency (rest days per week)
|
||||
rest_frequency = (total_count / days * 7) if days > 0 else 0.0
|
||||
|
||||
confidence = calculate_confidence(total_count, days, "general")
|
||||
|
||||
return {
|
||||
"total_rest_days": total_count,
|
||||
"rest_types": rest_types,
|
||||
"rest_frequency": round(rest_frequency, 1),
|
||||
"confidence": confidence,
|
||||
"days_analyzed": days
|
||||
}
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Calculated Metrics (migrated from calculations/recovery_metrics.py)
|
||||
# ============================================================================
|
||||
# These functions return simple values for placeholders and scoring.
|
||||
# Use get_*_data() functions above for structured chart data.
|
||||
|
||||
def calculate_recovery_score_v2(profile_id: str) -> Optional[int]:
|
||||
"""
|
||||
Improved recovery/readiness score (0-100)
|
||||
|
||||
Components:
|
||||
- HRV status (25%)
|
||||
- RHR status (20%)
|
||||
- Sleep duration (20%)
|
||||
- Sleep debt (10%)
|
||||
- Sleep regularity (10%)
|
||||
- Recent load balance (10%)
|
||||
- Data quality (5%)
|
||||
"""
|
||||
components = []
|
||||
|
||||
# 1. HRV status (25%)
|
||||
hrv_score = _score_hrv_vs_baseline(profile_id)
|
||||
if hrv_score is not None:
|
||||
components.append(('hrv', hrv_score, 25))
|
||||
|
||||
# 2. RHR status (20%)
|
||||
rhr_score = _score_rhr_vs_baseline(profile_id)
|
||||
if rhr_score is not None:
|
||||
components.append(('rhr', rhr_score, 20))
|
||||
|
||||
# 3. Sleep duration (20%)
|
||||
sleep_duration_score = _score_sleep_duration(profile_id)
|
||||
if sleep_duration_score is not None:
|
||||
components.append(('sleep_duration', sleep_duration_score, 20))
|
||||
|
||||
# 4. Sleep debt (10%)
|
||||
sleep_debt_score = _score_sleep_debt(profile_id)
|
||||
if sleep_debt_score is not None:
|
||||
components.append(('sleep_debt', sleep_debt_score, 10))
|
||||
|
||||
# 5. Sleep regularity (10%)
|
||||
regularity_score = _score_sleep_regularity(profile_id)
|
||||
if regularity_score is not None:
|
||||
components.append(('regularity', regularity_score, 10))
|
||||
|
||||
# 6. Recent load balance (10%)
|
||||
load_score = _score_recent_load_balance(profile_id)
|
||||
if load_score is not None:
|
||||
components.append(('load', load_score, 10))
|
||||
|
||||
# 7. Data quality (5%)
|
||||
quality_score = _score_recovery_data_quality(profile_id)
|
||||
if quality_score is not None:
|
||||
components.append(('data_quality', quality_score, 5))
|
||||
|
||||
if not components:
|
||||
return None
|
||||
|
||||
# Weighted average
|
||||
total_score = sum(score * weight for _, score, weight in components)
|
||||
total_weight = sum(weight for _, _, weight in components)
|
||||
|
||||
final_score = int(total_score / total_weight)
|
||||
|
||||
return final_score
|
||||
|
||||
|
||||
def _score_hrv_vs_baseline(profile_id: str) -> Optional[int]:
|
||||
"""Score HRV relative to 28d baseline (0-100)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get recent HRV (last 3 days average)
|
||||
cur.execute("""
|
||||
SELECT AVG(hrv) as recent_hrv
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND hrv IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
recent_row = cur.fetchone()
|
||||
if not recent_row or not recent_row['recent_hrv']:
|
||||
return None
|
||||
|
||||
recent_hrv = recent_row['recent_hrv']
|
||||
|
||||
# Get baseline (28d average, excluding last 3 days)
|
||||
cur.execute("""
|
||||
SELECT AVG(hrv) as baseline_hrv
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND hrv IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
AND date < CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
baseline_row = cur.fetchone()
|
||||
if not baseline_row or not baseline_row['baseline_hrv']:
|
||||
return None
|
||||
|
||||
baseline_hrv = baseline_row['baseline_hrv']
|
||||
|
||||
# Calculate percentage deviation
|
||||
deviation_pct = ((recent_hrv - baseline_hrv) / baseline_hrv) * 100
|
||||
|
||||
# Score: higher HRV = better recovery
|
||||
if deviation_pct >= 10:
|
||||
return 100
|
||||
elif deviation_pct >= 5:
|
||||
return 90
|
||||
elif deviation_pct >= 0:
|
||||
return 75
|
||||
elif deviation_pct >= -5:
|
||||
return 60
|
||||
elif deviation_pct >= -10:
|
||||
return 45
|
||||
else:
|
||||
return max(20, 45 + int(deviation_pct * 2))
|
||||
|
||||
|
||||
def _score_rhr_vs_baseline(profile_id: str) -> Optional[int]:
|
||||
"""Score RHR relative to 28d baseline (0-100)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Get recent RHR (last 3 days average)
|
||||
cur.execute("""
|
||||
SELECT AVG(resting_hr) as recent_rhr
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND resting_hr IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
recent_row = cur.fetchone()
|
||||
if not recent_row or not recent_row['recent_rhr']:
|
||||
return None
|
||||
|
||||
recent_rhr = recent_row['recent_rhr']
|
||||
|
||||
# Get baseline (28d average, excluding last 3 days)
|
||||
cur.execute("""
|
||||
SELECT AVG(resting_hr) as baseline_rhr
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND resting_hr IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
AND date < CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
baseline_row = cur.fetchone()
|
||||
if not baseline_row or not baseline_row['baseline_rhr']:
|
||||
return None
|
||||
|
||||
baseline_rhr = baseline_row['baseline_rhr']
|
||||
|
||||
# Calculate difference (bpm)
|
||||
difference = recent_rhr - baseline_rhr
|
||||
|
||||
# Score: lower RHR = better recovery
|
||||
if difference <= -3:
|
||||
return 100
|
||||
elif difference <= -1:
|
||||
return 90
|
||||
elif difference <= 1:
|
||||
return 75
|
||||
elif difference <= 3:
|
||||
return 60
|
||||
elif difference <= 5:
|
||||
return 45
|
||||
else:
|
||||
return max(20, 45 - (difference * 5))
|
||||
|
||||
|
||||
def _score_sleep_duration(profile_id: str) -> Optional[int]:
|
||||
"""Score recent sleep duration (0-100)"""
|
||||
avg_sleep_hours = calculate_sleep_avg_duration_7d(profile_id)
|
||||
|
||||
if avg_sleep_hours is None:
|
||||
return None
|
||||
|
||||
# Target: 7-9 hours
|
||||
if 7 <= avg_sleep_hours <= 9:
|
||||
return 100
|
||||
elif 6.5 <= avg_sleep_hours < 7:
|
||||
return 85
|
||||
elif 6 <= avg_sleep_hours < 6.5:
|
||||
return 70
|
||||
elif avg_sleep_hours >= 9.5:
|
||||
return 85 # Too much sleep can indicate fatigue
|
||||
else:
|
||||
return max(40, int(avg_sleep_hours * 10))
|
||||
|
||||
|
||||
def _score_sleep_debt(profile_id: str) -> Optional[int]:
|
||||
"""Score sleep debt (0-100)"""
|
||||
debt_hours = calculate_sleep_debt_hours(profile_id)
|
||||
|
||||
if debt_hours is None:
|
||||
return None
|
||||
|
||||
# Score based on accumulated debt
|
||||
if debt_hours <= 1:
|
||||
return 100
|
||||
elif debt_hours <= 3:
|
||||
return 85
|
||||
elif debt_hours <= 5:
|
||||
return 70
|
||||
elif debt_hours <= 8:
|
||||
return 55
|
||||
else:
|
||||
return max(30, 100 - (debt_hours * 8))
|
||||
|
||||
|
||||
def _score_sleep_regularity(profile_id: str) -> Optional[int]:
|
||||
"""Score sleep regularity (0-100)"""
|
||||
regularity_proxy = calculate_sleep_regularity_proxy(profile_id)
|
||||
|
||||
if regularity_proxy is None:
|
||||
return None
|
||||
|
||||
# regularity_proxy = mean absolute shift in minutes
|
||||
# Lower = better
|
||||
if regularity_proxy <= 30:
|
||||
return 100
|
||||
elif regularity_proxy <= 45:
|
||||
return 85
|
||||
elif regularity_proxy <= 60:
|
||||
return 70
|
||||
elif regularity_proxy <= 90:
|
||||
return 55
|
||||
else:
|
||||
return max(30, 100 - int(regularity_proxy / 2))
|
||||
|
||||
|
||||
def _score_recent_load_balance(profile_id: str) -> Optional[int]:
|
||||
"""Score recent training load balance (0-100)"""
|
||||
load_3d = calculate_recent_load_balance_3d(profile_id)
|
||||
|
||||
if load_3d is None:
|
||||
return None
|
||||
|
||||
# Proxy load: 0-300 = low, 300-600 = moderate, >600 = high
|
||||
if load_3d < 300:
|
||||
# Under-loading
|
||||
return 90
|
||||
elif load_3d <= 600:
|
||||
# Optimal
|
||||
return 100
|
||||
elif load_3d <= 900:
|
||||
# High but manageable
|
||||
return 75
|
||||
elif load_3d <= 1200:
|
||||
# Very high
|
||||
return 55
|
||||
else:
|
||||
# Excessive
|
||||
return max(30, 100 - (load_3d / 20))
|
||||
|
||||
|
||||
def _score_recovery_data_quality(profile_id: str) -> Optional[int]:
|
||||
"""Score data quality for recovery metrics (0-100)"""
|
||||
quality = calculate_recovery_data_quality(profile_id)
|
||||
return quality['overall_score']
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Individual Recovery Metrics
|
||||
# ============================================================================
|
||||
|
||||
def calculate_hrv_vs_baseline_pct(profile_id: str) -> Optional[float]:
|
||||
"""Calculate HRV deviation from baseline (percentage)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Recent HRV (3d avg)
|
||||
cur.execute("""
|
||||
SELECT AVG(hrv) as recent_hrv
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND hrv IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
recent_row = cur.fetchone()
|
||||
if not recent_row or not recent_row['recent_hrv']:
|
||||
return None
|
||||
|
||||
recent = recent_row['recent_hrv']
|
||||
|
||||
# Baseline (28d avg, excluding last 3d)
|
||||
cur.execute("""
|
||||
SELECT AVG(hrv) as baseline_hrv
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND hrv IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
AND date < CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
baseline_row = cur.fetchone()
|
||||
if not baseline_row or not baseline_row['baseline_hrv']:
|
||||
return None
|
||||
|
||||
baseline = baseline_row['baseline_hrv']
|
||||
|
||||
deviation_pct = ((recent - baseline) / baseline) * 100
|
||||
return round(deviation_pct, 1)
|
||||
|
||||
|
||||
def calculate_rhr_vs_baseline_pct(profile_id: str) -> Optional[float]:
|
||||
"""Calculate RHR deviation from baseline (percentage)"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Recent RHR (3d avg)
|
||||
cur.execute("""
|
||||
SELECT AVG(resting_hr) as recent_rhr
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND resting_hr IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
recent_row = cur.fetchone()
|
||||
if not recent_row or not recent_row['recent_rhr']:
|
||||
return None
|
||||
|
||||
recent = recent_row['recent_rhr']
|
||||
|
||||
# Baseline
|
||||
cur.execute("""
|
||||
SELECT AVG(resting_hr) as baseline_rhr
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND resting_hr IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
AND date < CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
baseline_row = cur.fetchone()
|
||||
if not baseline_row or not baseline_row['baseline_rhr']:
|
||||
return None
|
||||
|
||||
baseline = baseline_row['baseline_rhr']
|
||||
|
||||
deviation_pct = ((recent - baseline) / baseline) * 100
|
||||
return round(deviation_pct, 1)
|
||||
|
||||
|
||||
def calculate_sleep_avg_duration_7d(profile_id: str) -> Optional[float]:
|
||||
"""Calculate average sleep duration (hours) last 7 days"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT AVG(duration_minutes) as avg_sleep_min
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
AND duration_minutes IS NOT NULL
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
if not row or not row['avg_sleep_min']:
|
||||
return None
|
||||
|
||||
avg_hours = row['avg_sleep_min'] / 60
|
||||
return round(avg_hours, 1)
|
||||
|
||||
|
||||
def calculate_sleep_debt_hours(profile_id: str) -> Optional[float]:
|
||||
"""
|
||||
Calculate accumulated sleep debt (hours) last 14 days
|
||||
Assumes 7.5h target per night
|
||||
"""
|
||||
target_hours = 7.5
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT duration_minutes
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '14 days'
|
||||
AND duration_minutes IS NOT NULL
|
||||
ORDER BY date DESC
|
||||
""", (profile_id,))
|
||||
|
||||
sleep_data = [row['duration_minutes'] for row in cur.fetchall()]
|
||||
|
||||
if len(sleep_data) < 10: # Need at least 10 days
|
||||
return None
|
||||
|
||||
# Calculate cumulative debt
|
||||
total_debt_min = sum(max(0, (target_hours * 60) - sleep_min) for sleep_min in sleep_data)
|
||||
debt_hours = total_debt_min / 60
|
||||
|
||||
return round(debt_hours, 1)
|
||||
|
||||
|
||||
def calculate_sleep_regularity_proxy(profile_id: str) -> Optional[float]:
|
||||
"""
|
||||
Sleep regularity proxy: mean absolute shift from previous day (minutes)
|
||||
Lower = more regular
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT bedtime, wake_time, date
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '14 days'
|
||||
AND bedtime IS NOT NULL
|
||||
AND wake_time IS NOT NULL
|
||||
ORDER BY date
|
||||
""", (profile_id,))
|
||||
|
||||
sleep_data = cur.fetchall()
|
||||
|
||||
if len(sleep_data) < 7:
|
||||
return None
|
||||
|
||||
# Calculate day-to-day shifts
|
||||
shifts = []
|
||||
for i in range(1, len(sleep_data)):
|
||||
prev = sleep_data[i-1]
|
||||
curr = sleep_data[i]
|
||||
|
||||
# Bedtime shift (minutes)
|
||||
prev_bedtime = prev['bedtime']
|
||||
curr_bedtime = curr['bedtime']
|
||||
|
||||
# Convert to minutes since midnight
|
||||
prev_bed_min = prev_bedtime.hour * 60 + prev_bedtime.minute
|
||||
curr_bed_min = curr_bedtime.hour * 60 + curr_bedtime.minute
|
||||
|
||||
# Handle cross-midnight (e.g., 23:00 to 01:00)
|
||||
bed_shift = abs(curr_bed_min - prev_bed_min)
|
||||
if bed_shift > 720: # More than 12 hours = wrapped around
|
||||
bed_shift = 1440 - bed_shift
|
||||
|
||||
shifts.append(bed_shift)
|
||||
|
||||
mean_shift = sum(shifts) / len(shifts)
|
||||
return round(mean_shift, 1)
|
||||
|
||||
|
||||
def calculate_recent_load_balance_3d(profile_id: str) -> Optional[int]:
|
||||
"""Calculate proxy internal load last 3 days"""
|
||||
from data_layer.activity_metrics import calculate_proxy_internal_load_7d
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT SUM(duration_min) as total_duration
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '3 days'
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
|
||||
# Simplified 3d load (duration-based)
|
||||
return int(row['total_duration'] or 0)
|
||||
|
||||
|
||||
def calculate_sleep_quality_7d(profile_id: str) -> Optional[int]:
|
||||
"""
|
||||
Calculate sleep quality score (0-100) based on deep+REM percentage
|
||||
Last 7 days
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT duration_minutes, deep_minutes, rem_minutes
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
AND duration_minutes IS NOT NULL
|
||||
""", (profile_id,))
|
||||
|
||||
sleep_data = cur.fetchall()
|
||||
|
||||
if len(sleep_data) < 4:
|
||||
return None
|
||||
|
||||
quality_scores = []
|
||||
for s in sleep_data:
|
||||
if s['deep_minutes'] and s['rem_minutes']:
|
||||
quality_pct = ((s['deep_minutes'] + s['rem_minutes']) / s['duration_minutes']) * 100
|
||||
# 40-60% deep+REM is good
|
||||
if quality_pct >= 45:
|
||||
quality_scores.append(100)
|
||||
elif quality_pct >= 35:
|
||||
quality_scores.append(75)
|
||||
elif quality_pct >= 25:
|
||||
quality_scores.append(50)
|
||||
else:
|
||||
quality_scores.append(30)
|
||||
|
||||
if not quality_scores:
|
||||
return None
|
||||
|
||||
avg_quality = sum(quality_scores) / len(quality_scores)
|
||||
return int(avg_quality)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Data Quality Assessment
|
||||
# ============================================================================
|
||||
|
||||
def calculate_recovery_data_quality(profile_id: str) -> Dict[str, any]:
|
||||
"""
|
||||
Assess data quality for recovery metrics
|
||||
Returns dict with quality score and details
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# HRV measurements (28d)
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as hrv_count
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND hrv IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
hrv_count = cur.fetchone()['hrv_count']
|
||||
|
||||
# RHR measurements (28d)
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as rhr_count
|
||||
FROM vitals_baseline
|
||||
WHERE profile_id = %s
|
||||
AND resting_hr IS NOT NULL
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
rhr_count = cur.fetchone()['rhr_count']
|
||||
|
||||
# Sleep measurements (28d)
|
||||
cur.execute("""
|
||||
SELECT COUNT(*) as sleep_count
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
""", (profile_id,))
|
||||
sleep_count = cur.fetchone()['sleep_count']
|
||||
|
||||
# Score components
|
||||
hrv_score = min(100, (hrv_count / 21) * 100) # 21 = 75% coverage
|
||||
rhr_score = min(100, (rhr_count / 21) * 100)
|
||||
sleep_score = min(100, (sleep_count / 21) * 100)
|
||||
|
||||
# Overall score
|
||||
overall_score = int(
|
||||
hrv_score * 0.3 +
|
||||
rhr_score * 0.3 +
|
||||
sleep_score * 0.4
|
||||
)
|
||||
|
||||
if overall_score >= 80:
|
||||
confidence = "high"
|
||||
elif overall_score >= 60:
|
||||
confidence = "medium"
|
||||
else:
|
||||
confidence = "low"
|
||||
|
||||
return {
|
||||
"overall_score": overall_score,
|
||||
"confidence": confidence,
|
||||
"measurements": {
|
||||
"hrv_28d": hrv_count,
|
||||
"rhr_28d": rhr_count,
|
||||
"sleep_28d": sleep_count
|
||||
},
|
||||
"component_scores": {
|
||||
"hrv": int(hrv_score),
|
||||
"rhr": int(rhr_score),
|
||||
"sleep": int(sleep_score)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
"""
|
||||
Reference values — Layer 1 (read paths + structured rows)
|
||||
|
||||
Structured retrieval for profile reference values and the active type catalog.
|
||||
Mutations (INSERT/UPDATE/DELETE) stay in routers/reference_values.py with validation.
|
||||
|
||||
Dates are normalized to ISO strings; Decimals to float — suitable for JSON/API layers.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from typing import Any, Optional
|
||||
|
||||
from db import get_cursor, get_db, r2d
|
||||
|
||||
|
||||
def normalize_reference_row(d: Optional[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""Normalize DB row dict for JSON (dates → ISO, Decimal → float)."""
|
||||
if not d:
|
||||
return d
|
||||
out = dict(d)
|
||||
for k in ("effective_date", "created_at", "updated_at"):
|
||||
v = out.get(k)
|
||||
if v is not None and hasattr(v, "isoformat"):
|
||||
out[k] = v.isoformat()
|
||||
vn = out.get("value_numeric")
|
||||
if vn is not None and isinstance(vn, Decimal):
|
||||
out["value_numeric"] = float(vn)
|
||||
return out
|
||||
|
||||
|
||||
def fetch_reference_type_by_key(cur, key: str, require_active: bool = True) -> Optional[dict[str, Any]]:
|
||||
"""Single type row by key; for use inside router transactions (shared cursor)."""
|
||||
q = (
|
||||
"SELECT id, key, label, description, default_unit, active, category, "
|
||||
"value_data_type, validation_rules, metadata "
|
||||
"FROM reference_value_types WHERE key = %s "
|
||||
)
|
||||
if require_active:
|
||||
q += "AND active = TRUE "
|
||||
cur.execute(q, (key,))
|
||||
row = cur.fetchone()
|
||||
return r2d(row) if row else None
|
||||
|
||||
|
||||
def list_active_reference_value_types_data() -> list[dict[str, Any]]:
|
||||
"""All active reference_value_types rows, catalog sort order."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
id, key, label, description, default_unit, sort_order, active,
|
||||
category, value_data_type, validation_rules, metadata, created_at
|
||||
FROM reference_value_types
|
||||
WHERE active = TRUE
|
||||
ORDER BY sort_order ASC, id ASC
|
||||
"""
|
||||
)
|
||||
return [normalize_reference_row(r2d(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def list_profile_reference_values_for_type(
|
||||
profile_id: str, type_key: str
|
||||
) -> Optional[list[dict[str, Any]]]:
|
||||
"""
|
||||
Historical entries for one type, newest first.
|
||||
Returns None if type_key does not resolve to an active type.
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
t = fetch_reference_type_by_key(cur, type_key, require_active=True)
|
||||
if not t:
|
||||
return None
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
v.id,
|
||||
v.profile_id,
|
||||
v.reference_value_type_id,
|
||||
v.effective_date,
|
||||
v.value_numeric,
|
||||
v.value_text,
|
||||
v.unit,
|
||||
v.source,
|
||||
v.confidence,
|
||||
v.method,
|
||||
v.notes,
|
||||
v.extra,
|
||||
v.created_at,
|
||||
v.updated_at,
|
||||
rt.key AS type_key,
|
||||
rt.label AS type_label
|
||||
FROM profile_reference_values v
|
||||
JOIN reference_value_types rt ON rt.id = v.reference_value_type_id
|
||||
WHERE v.profile_id = %s AND rt.key = %s
|
||||
ORDER BY v.effective_date DESC, v.created_at DESC
|
||||
""",
|
||||
(profile_id, t["key"]),
|
||||
)
|
||||
return [normalize_reference_row(r2d(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def build_summary_tiles_from_ranked_rows(raw_rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Build /summary.tile payloads from SQL rows (rn 1..2 per type).
|
||||
Each row still contains rn, type_sort_order, value_data_type before stripping.
|
||||
"""
|
||||
by_key: dict[str, dict[str, Any]] = {}
|
||||
skip_cols = frozenset({"rn", "type_sort_order", "value_data_type"})
|
||||
for row in raw_rows:
|
||||
rn = int(row.get("rn") or 0)
|
||||
key = row["type_key"]
|
||||
if key not in by_key:
|
||||
by_key[key] = {
|
||||
"type_key": key,
|
||||
"type_label": row.get("type_label") or key,
|
||||
"value_data_type": (row.get("value_data_type") or "decimal").strip().lower(),
|
||||
"sort_key": (row.get("type_sort_order") or 0, key),
|
||||
"latest": None,
|
||||
"previous": None,
|
||||
}
|
||||
entry = {k: v for k, v in row.items() if k not in skip_cols}
|
||||
api_entry = normalize_reference_row(entry)
|
||||
if rn == 1:
|
||||
by_key[key]["latest"] = api_entry
|
||||
elif rn == 2:
|
||||
by_key[key]["previous"] = api_entry
|
||||
|
||||
tiles = sorted(by_key.values(), key=lambda t: t["sort_key"])
|
||||
for t in tiles:
|
||||
t.pop("sort_key", None)
|
||||
return tiles
|
||||
|
||||
|
||||
def get_profile_reference_values_summary(profile_id: str) -> dict[str, Any]:
|
||||
"""latest + previous entry per type (active types only), tiles sorted like catalog."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
WITH ranked AS (
|
||||
SELECT
|
||||
v.id,
|
||||
v.profile_id,
|
||||
v.reference_value_type_id,
|
||||
v.effective_date,
|
||||
v.value_numeric,
|
||||
v.value_text,
|
||||
v.unit,
|
||||
v.source,
|
||||
v.confidence,
|
||||
v.method,
|
||||
v.notes,
|
||||
v.extra,
|
||||
v.created_at,
|
||||
v.updated_at,
|
||||
rt.key AS type_key,
|
||||
rt.label AS type_label,
|
||||
rt.sort_order AS type_sort_order,
|
||||
rt.value_data_type,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY v.reference_value_type_id
|
||||
ORDER BY v.effective_date DESC, v.created_at DESC
|
||||
) AS rn
|
||||
FROM profile_reference_values v
|
||||
JOIN reference_value_types rt ON rt.id = v.reference_value_type_id
|
||||
WHERE v.profile_id = %s AND rt.active = TRUE
|
||||
)
|
||||
SELECT * FROM ranked WHERE rn <= 2
|
||||
ORDER BY type_sort_order ASC, type_key ASC, rn ASC
|
||||
""",
|
||||
(profile_id,),
|
||||
)
|
||||
raw_rows = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
tiles = build_summary_tiles_from_ranked_rows(raw_rows)
|
||||
return {"tiles": tiles}
|
||||
@@ -0,0 +1,583 @@
|
||||
"""
|
||||
Scoring Metrics Data Layer
|
||||
|
||||
Provides structured scoring and focus weight functions for all metrics.
|
||||
|
||||
Functions:
|
||||
- get_user_focus_weights(): User focus area weights (from DB)
|
||||
- get_focus_area_category(): Category for a focus area
|
||||
- map_focus_to_score_components(): Mapping of focus areas to score components
|
||||
- map_category_de_to_en(): Category translation DE→EN
|
||||
- calculate_category_weight(): Weight for a category
|
||||
- calculate_goal_progress_score(): Goal progress scoring
|
||||
- calculate_health_stability_score(): Health stability scoring
|
||||
- calculate_data_quality_score(): Overall data quality
|
||||
- get_top_priority_goal(): Top goal by weight
|
||||
- get_top_focus_area(): Top focus area by weight
|
||||
- calculate_focus_area_progress(): Progress for specific focus area
|
||||
- calculate_category_progress(): Progress for category
|
||||
|
||||
All functions return structured data (dict) or simple values.
|
||||
Use placeholder_resolver.py for formatted strings for AI.
|
||||
|
||||
Phase 0c: Multi-Layer Architecture
|
||||
Version: 1.0
|
||||
"""
|
||||
|
||||
from typing import Dict, List, Optional
|
||||
from datetime import datetime, timedelta, date
|
||||
from db import get_db, get_cursor, r2d
|
||||
|
||||
def get_user_focus_weights(profile_id: str) -> Dict[str, float]:
|
||||
"""
|
||||
Get user's focus area weights as dictionary
|
||||
Returns: {'körpergewicht': 30.0, 'kraftaufbau': 25.0, ...}
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT ufw.focus_area_id, ufw.weight as weight_pct, fa.key
|
||||
FROM user_focus_area_weights ufw
|
||||
JOIN focus_area_definitions fa ON ufw.focus_area_id = fa.id
|
||||
WHERE ufw.profile_id = %s
|
||||
AND ufw.weight > 0
|
||||
""", (profile_id,))
|
||||
|
||||
return {
|
||||
row['key']: float(row['weight_pct'])
|
||||
for row in cur.fetchall()
|
||||
}
|
||||
|
||||
|
||||
def get_focus_area_category(focus_area_id: str) -> Optional[str]:
|
||||
"""Get category for a focus area"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT category
|
||||
FROM focus_area_definitions
|
||||
WHERE focus_area_id = %s
|
||||
""", (focus_area_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
return row['category'] if row else None
|
||||
|
||||
|
||||
def map_focus_to_score_components() -> Dict[str, str]:
|
||||
"""
|
||||
Map focus areas to score components
|
||||
Keys match focus_area_definitions.key (English lowercase)
|
||||
Returns: {'weight_loss': 'body', 'strength': 'activity', ...}
|
||||
"""
|
||||
return {
|
||||
# Body Composition → body_progress_score
|
||||
'weight_loss': 'body',
|
||||
'muscle_gain': 'body',
|
||||
'body_recomposition': 'body',
|
||||
|
||||
# Training - Strength → activity_score
|
||||
'strength': 'activity',
|
||||
'strength_endurance': 'activity',
|
||||
'power': 'activity',
|
||||
|
||||
# Training - Mobility → activity_score
|
||||
'flexibility': 'activity',
|
||||
'mobility': 'activity',
|
||||
|
||||
# Endurance → activity_score (could also map to health)
|
||||
'aerobic_endurance': 'activity',
|
||||
'anaerobic_endurance': 'activity',
|
||||
'cardiovascular_health': 'health',
|
||||
|
||||
# Coordination → activity_score
|
||||
'balance': 'activity',
|
||||
'reaction': 'activity',
|
||||
'rhythm': 'activity',
|
||||
'coordination': 'activity',
|
||||
|
||||
# Mental → recovery_score (mental health is part of recovery)
|
||||
'stress_resistance': 'recovery',
|
||||
'concentration': 'recovery',
|
||||
'willpower': 'recovery',
|
||||
'mental_health': 'recovery',
|
||||
|
||||
# Recovery → recovery_score
|
||||
'sleep_quality': 'recovery',
|
||||
'regeneration': 'recovery',
|
||||
'rest': 'recovery',
|
||||
|
||||
# Health → health
|
||||
'metabolic_health': 'health',
|
||||
'blood_pressure': 'health',
|
||||
'hrv': 'health',
|
||||
'general_health': 'health',
|
||||
|
||||
# Nutrition → nutrition_score
|
||||
'protein_intake': 'nutrition',
|
||||
'calorie_balance': 'nutrition',
|
||||
'macro_consistency': 'nutrition',
|
||||
'meal_timing': 'nutrition',
|
||||
'hydration': 'nutrition',
|
||||
}
|
||||
|
||||
|
||||
def map_category_de_to_en(category_de: str) -> str:
|
||||
"""
|
||||
Map German category names to English database names
|
||||
"""
|
||||
mapping = {
|
||||
'körper': 'body_composition',
|
||||
'ernährung': 'nutrition', # Note: no nutrition category in DB, returns empty
|
||||
'aktivität': 'training',
|
||||
'recovery': 'recovery',
|
||||
'vitalwerte': 'health',
|
||||
'mental': 'mental',
|
||||
'lebensstil': 'health', # Maps to general health
|
||||
}
|
||||
return mapping.get(category_de, category_de)
|
||||
|
||||
|
||||
def calculate_category_weight(profile_id: str, category: str) -> float:
|
||||
"""
|
||||
Calculate total weight for a category
|
||||
Accepts German or English category names
|
||||
Returns sum of all focus area weights in this category
|
||||
"""
|
||||
# Map German to English if needed
|
||||
category_en = map_category_de_to_en(category)
|
||||
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT key
|
||||
FROM focus_area_definitions
|
||||
WHERE category = %s
|
||||
""", (category_en,))
|
||||
|
||||
focus_areas = [row['key'] for row in cur.fetchall()]
|
||||
|
||||
total_weight = sum(
|
||||
focus_weights.get(fa, 0)
|
||||
for fa in focus_areas
|
||||
)
|
||||
|
||||
return total_weight
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Goal Progress Score (Meta-Score with Dynamic Weighting)
|
||||
# ============================================================================
|
||||
|
||||
def calculate_goal_progress_score(profile_id: str) -> Optional[int]:
|
||||
"""
|
||||
Calculate overall goal progress score (0-100)
|
||||
Weighted dynamically based on user's focus area priorities
|
||||
|
||||
This is the main meta-score that combines all sub-scores
|
||||
"""
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
if not focus_weights:
|
||||
return None # No goals/focus areas configured
|
||||
|
||||
# Calculate sub-scores
|
||||
from data_layer.body_metrics import calculate_body_progress_score
|
||||
from data_layer.nutrition_metrics import calculate_nutrition_score
|
||||
from data_layer.activity_metrics import calculate_activity_score
|
||||
from data_layer.recovery_metrics import calculate_recovery_score_v2
|
||||
|
||||
body_score = calculate_body_progress_score(profile_id, focus_weights)
|
||||
nutrition_score = calculate_nutrition_score(profile_id, focus_weights)
|
||||
activity_score = calculate_activity_score(profile_id, focus_weights)
|
||||
recovery_score = calculate_recovery_score_v2(profile_id)
|
||||
health_risk_score = calculate_health_stability_score(profile_id)
|
||||
|
||||
# Map focus areas to score components
|
||||
focus_to_component = map_focus_to_score_components()
|
||||
|
||||
# Calculate weighted sum
|
||||
total_score = 0.0
|
||||
total_weight = 0.0
|
||||
|
||||
for focus_area_id, weight in focus_weights.items():
|
||||
component = focus_to_component.get(focus_area_id)
|
||||
|
||||
if component == 'body' and body_score is not None:
|
||||
total_score += body_score * weight
|
||||
total_weight += weight
|
||||
elif component == 'nutrition' and nutrition_score is not None:
|
||||
total_score += nutrition_score * weight
|
||||
total_weight += weight
|
||||
elif component == 'activity' and activity_score is not None:
|
||||
total_score += activity_score * weight
|
||||
total_weight += weight
|
||||
elif component == 'recovery' and recovery_score is not None:
|
||||
total_score += recovery_score * weight
|
||||
total_weight += weight
|
||||
elif component == 'health' and health_risk_score is not None:
|
||||
total_score += health_risk_score * weight
|
||||
total_weight += weight
|
||||
|
||||
if total_weight == 0:
|
||||
return None
|
||||
|
||||
# Normalize to 0-100
|
||||
final_score = total_score / total_weight
|
||||
|
||||
return int(final_score)
|
||||
|
||||
|
||||
def calculate_health_stability_score(profile_id: str) -> Optional[int]:
|
||||
"""
|
||||
Health stability score (0-100)
|
||||
Components:
|
||||
- Blood pressure status
|
||||
- Sleep quality
|
||||
- Movement baseline
|
||||
- Weight/circumference risk factors
|
||||
- Regularity
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
components = []
|
||||
|
||||
# 1. Blood pressure status (30%)
|
||||
cur.execute("""
|
||||
SELECT systolic, diastolic
|
||||
FROM blood_pressure_log
|
||||
WHERE profile_id = %s
|
||||
AND measured_at >= CURRENT_DATE - INTERVAL '28 days'
|
||||
ORDER BY measured_at DESC
|
||||
""", (profile_id,))
|
||||
|
||||
bp_readings = cur.fetchall()
|
||||
if bp_readings:
|
||||
bp_score = _score_blood_pressure(bp_readings)
|
||||
components.append(('bp', bp_score, 30))
|
||||
|
||||
# 2. Sleep quality (25%)
|
||||
cur.execute("""
|
||||
SELECT duration_minutes, deep_minutes, rem_minutes
|
||||
FROM sleep_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '28 days'
|
||||
ORDER BY date DESC
|
||||
""", (profile_id,))
|
||||
|
||||
sleep_data = cur.fetchall()
|
||||
if sleep_data:
|
||||
sleep_score = _score_sleep_quality(sleep_data)
|
||||
components.append(('sleep', sleep_score, 25))
|
||||
|
||||
# 3. Movement baseline (20%)
|
||||
cur.execute("""
|
||||
SELECT duration_min
|
||||
FROM activity_log
|
||||
WHERE profile_id = %s
|
||||
AND date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
""", (profile_id,))
|
||||
|
||||
activities = cur.fetchall()
|
||||
if activities:
|
||||
total_minutes = sum(a['duration_min'] for a in activities)
|
||||
# WHO recommends 150-300 min/week moderate activity
|
||||
movement_score = min(100, (total_minutes / 150) * 100)
|
||||
components.append(('movement', movement_score, 20))
|
||||
|
||||
# 4. Waist circumference risk (15%)
|
||||
cur.execute("""
|
||||
SELECT c_waist
|
||||
FROM circumference_log
|
||||
WHERE profile_id = %s
|
||||
AND c_waist IS NOT NULL
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
""", (profile_id,))
|
||||
|
||||
waist = cur.fetchone()
|
||||
if waist:
|
||||
# Gender-specific thresholds (simplified - should use profile gender)
|
||||
# Men: <94cm good, 94-102 elevated, >102 high risk
|
||||
# Women: <80cm good, 80-88 elevated, >88 high risk
|
||||
# Using conservative thresholds
|
||||
waist_cm = waist['c_waist']
|
||||
if waist_cm < 88:
|
||||
waist_score = 100
|
||||
elif waist_cm < 94:
|
||||
waist_score = 75
|
||||
elif waist_cm < 102:
|
||||
waist_score = 50
|
||||
else:
|
||||
waist_score = 25
|
||||
components.append(('waist', waist_score, 15))
|
||||
|
||||
# 5. Regularity (10%) - sleep timing consistency
|
||||
if len(sleep_data) >= 7:
|
||||
sleep_times = [s['duration_minutes'] for s in sleep_data]
|
||||
avg = sum(sleep_times) / len(sleep_times)
|
||||
variance = sum((x - avg) ** 2 for x in sleep_times) / len(sleep_times)
|
||||
std_dev = variance ** 0.5
|
||||
# Lower std_dev = better consistency
|
||||
regularity_score = max(0, 100 - (std_dev * 2))
|
||||
components.append(('regularity', regularity_score, 10))
|
||||
|
||||
if not components:
|
||||
return None
|
||||
|
||||
# Weighted average
|
||||
total_score = sum(score * weight for _, score, weight in components)
|
||||
total_weight = sum(weight for _, _, weight in components)
|
||||
|
||||
return int(total_score / total_weight)
|
||||
|
||||
|
||||
def _score_blood_pressure(readings: List) -> int:
|
||||
"""Score blood pressure readings (0-100)"""
|
||||
# Average last 28 days
|
||||
avg_systolic = sum(r['systolic'] for r in readings) / len(readings)
|
||||
avg_diastolic = sum(r['diastolic'] for r in readings) / len(readings)
|
||||
|
||||
# ESC 2024 Guidelines:
|
||||
# Optimal: <120/80
|
||||
# Normal: 120-129 / 80-84
|
||||
# Elevated: 130-139 / 85-89
|
||||
# Hypertension: ≥140/90
|
||||
|
||||
if avg_systolic < 120 and avg_diastolic < 80:
|
||||
return 100
|
||||
elif avg_systolic < 130 and avg_diastolic < 85:
|
||||
return 85
|
||||
elif avg_systolic < 140 and avg_diastolic < 90:
|
||||
return 65
|
||||
else:
|
||||
return 40
|
||||
|
||||
|
||||
def _score_sleep_quality(sleep_data: List) -> int:
|
||||
"""Score sleep quality (0-100)"""
|
||||
# Average sleep duration and quality
|
||||
avg_total = sum(s['duration_minutes'] for s in sleep_data) / len(sleep_data)
|
||||
avg_total_hours = avg_total / 60
|
||||
|
||||
# Duration score (7+ hours = good)
|
||||
if avg_total_hours >= 8:
|
||||
duration_score = 100
|
||||
elif avg_total_hours >= 7:
|
||||
duration_score = 85
|
||||
elif avg_total_hours >= 6:
|
||||
duration_score = 65
|
||||
else:
|
||||
duration_score = 40
|
||||
|
||||
# Quality score (deep + REM percentage)
|
||||
quality_scores = []
|
||||
for s in sleep_data:
|
||||
if s['deep_minutes'] and s['rem_minutes']:
|
||||
quality_pct = ((s['deep_minutes'] + s['rem_minutes']) / s['duration_minutes']) * 100
|
||||
# 40-60% deep+REM is good
|
||||
if quality_pct >= 45:
|
||||
quality_scores.append(100)
|
||||
elif quality_pct >= 35:
|
||||
quality_scores.append(75)
|
||||
elif quality_pct >= 25:
|
||||
quality_scores.append(50)
|
||||
else:
|
||||
quality_scores.append(30)
|
||||
|
||||
if quality_scores:
|
||||
avg_quality = sum(quality_scores) / len(quality_scores)
|
||||
# Weighted: 60% duration, 40% quality
|
||||
return int(duration_score * 0.6 + avg_quality * 0.4)
|
||||
else:
|
||||
return duration_score
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Data Quality Score
|
||||
# ============================================================================
|
||||
|
||||
def calculate_data_quality_score(profile_id: str) -> int:
|
||||
"""
|
||||
Overall data quality score (0-100)
|
||||
Combines quality from all modules
|
||||
"""
|
||||
from data_layer.body_metrics import calculate_body_data_quality
|
||||
from data_layer.nutrition_metrics import calculate_nutrition_data_quality
|
||||
from data_layer.activity_metrics import calculate_activity_data_quality
|
||||
from data_layer.recovery_metrics import calculate_recovery_data_quality
|
||||
|
||||
body_quality = calculate_body_data_quality(profile_id)
|
||||
nutrition_quality = calculate_nutrition_data_quality(profile_id)
|
||||
activity_quality = calculate_activity_data_quality(profile_id)
|
||||
recovery_quality = calculate_recovery_data_quality(profile_id)
|
||||
|
||||
# Weighted average (all equal weight)
|
||||
total_score = (
|
||||
body_quality['overall_score'] * 0.25 +
|
||||
nutrition_quality['overall_score'] * 0.25 +
|
||||
activity_quality['overall_score'] * 0.25 +
|
||||
recovery_quality['overall_score'] * 0.25
|
||||
)
|
||||
|
||||
return int(total_score)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Top-Weighted Helpers (instead of "primary goal")
|
||||
# ============================================================================
|
||||
|
||||
def get_top_priority_goal(profile_id: str) -> Optional[Dict]:
|
||||
"""
|
||||
Get highest priority goal based on:
|
||||
- Progress gap (distance to target)
|
||||
- Focus area weight
|
||||
Returns goal dict or None
|
||||
"""
|
||||
from goal_utils import get_active_goals
|
||||
|
||||
goals = get_active_goals(profile_id)
|
||||
if not goals:
|
||||
return None
|
||||
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
for goal in goals:
|
||||
# Progress gap (0-100, higher = further from target)
|
||||
goal['progress_gap'] = 100 - (goal.get('progress_pct') or 0)
|
||||
|
||||
# Get focus areas for this goal
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT fa.key as focus_area_key
|
||||
FROM goal_focus_contributions gfc
|
||||
JOIN focus_area_definitions fa ON gfc.focus_area_id = fa.id
|
||||
WHERE gfc.goal_id = %s
|
||||
""", (goal['id'],))
|
||||
|
||||
goal_focus_areas = [row['focus_area_key'] for row in cur.fetchall()]
|
||||
|
||||
# Sum focus weights
|
||||
goal['total_focus_weight'] = sum(
|
||||
focus_weights.get(fa, 0)
|
||||
for fa in goal_focus_areas
|
||||
)
|
||||
|
||||
# Priority score
|
||||
goal['priority_score'] = goal['progress_gap'] * (goal['total_focus_weight'] / 100)
|
||||
|
||||
# Return goal with highest priority score
|
||||
return max(goals, key=lambda g: g.get('priority_score', 0))
|
||||
|
||||
|
||||
def get_top_focus_area(profile_id: str) -> Optional[Dict]:
|
||||
"""
|
||||
Get focus area with highest user weight
|
||||
Returns dict with focus_area_id, label, weight, progress
|
||||
"""
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
if not focus_weights:
|
||||
return None
|
||||
|
||||
top_fa_id = max(focus_weights, key=focus_weights.get)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT key, name_de, category
|
||||
FROM focus_area_definitions
|
||||
WHERE key = %s
|
||||
""", (top_fa_id,))
|
||||
|
||||
fa_def = cur.fetchone()
|
||||
if not fa_def:
|
||||
return None
|
||||
|
||||
# Calculate progress for this focus area
|
||||
progress = calculate_focus_area_progress(profile_id, top_fa_id)
|
||||
|
||||
return {
|
||||
'focus_area_id': top_fa_id,
|
||||
'label': fa_def['name_de'],
|
||||
'category': fa_def['category'],
|
||||
'weight': focus_weights[top_fa_id],
|
||||
'progress': progress
|
||||
}
|
||||
|
||||
|
||||
def calculate_focus_area_progress(profile_id: str, focus_area_id: str) -> Optional[int]:
|
||||
"""
|
||||
Calculate progress for a specific focus area (0-100)
|
||||
Average progress of all goals contributing to this focus area
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT g.id, g.progress_pct, gfc.contribution_weight
|
||||
FROM goals g
|
||||
JOIN goal_focus_contributions gfc ON g.id = gfc.goal_id
|
||||
WHERE g.profile_id = %s
|
||||
AND gfc.focus_area_id = (
|
||||
SELECT id FROM focus_area_definitions WHERE key = %s
|
||||
)
|
||||
AND g.status = 'active'
|
||||
""", (profile_id, focus_area_id))
|
||||
|
||||
goals = cur.fetchall()
|
||||
|
||||
if not goals:
|
||||
return None
|
||||
|
||||
# Weighted average by contribution_weight
|
||||
total_progress = sum(g['progress_pct'] * g['contribution_weight'] for g in goals)
|
||||
total_weight = sum(g['contribution_weight'] for g in goals)
|
||||
|
||||
return int(total_progress / total_weight) if total_weight > 0 else None
|
||||
|
||||
def calculate_category_progress(profile_id: str, category: str) -> Optional[int]:
|
||||
"""
|
||||
Calculate progress score for a focus area category (0-100).
|
||||
|
||||
Args:
|
||||
profile_id: User's profile ID
|
||||
category: Category name ('körper', 'ernährung', 'aktivität', 'recovery', 'vitalwerte', 'mental', 'lebensstil')
|
||||
|
||||
Returns:
|
||||
Progress score 0-100 or None if no data
|
||||
"""
|
||||
# Map category to score calculation functions
|
||||
category_scores = {
|
||||
'körper': 'body_progress_score',
|
||||
'ernährung': 'nutrition_score',
|
||||
'aktivität': 'activity_score',
|
||||
'recovery': 'recovery_score',
|
||||
'vitalwerte': 'recovery_score', # Use recovery score as proxy for vitals
|
||||
'mental': 'recovery_score', # Use recovery score as proxy for mental (sleep quality)
|
||||
'lebensstil': 'data_quality_score', # Use data quality as proxy for lifestyle consistency
|
||||
}
|
||||
|
||||
score_func_name = category_scores.get(category.lower())
|
||||
if not score_func_name:
|
||||
return None
|
||||
|
||||
# Call the appropriate score function
|
||||
if score_func_name == 'body_progress_score':
|
||||
from data_layer.body_metrics import calculate_body_progress_score
|
||||
return calculate_body_progress_score(profile_id)
|
||||
elif score_func_name == 'nutrition_score':
|
||||
from data_layer.nutrition_metrics import calculate_nutrition_score
|
||||
return calculate_nutrition_score(profile_id)
|
||||
elif score_func_name == 'activity_score':
|
||||
from data_layer.activity_metrics import calculate_activity_score
|
||||
return calculate_activity_score(profile_id)
|
||||
elif score_func_name == 'recovery_score':
|
||||
from data_layer.recovery_metrics import calculate_recovery_score_v2
|
||||
return calculate_recovery_score_v2(profile_id)
|
||||
elif score_func_name == 'data_quality_score':
|
||||
return calculate_data_quality_score(profile_id)
|
||||
|
||||
return None
|
||||
@@ -0,0 +1,36 @@
|
||||
"""
|
||||
Training profile resolver (Layer 1 scaffold).
|
||||
|
||||
Template-driven multi-dimensional evaluation with built-in algorithms and
|
||||
Focus Area contribution aggregation. Import explicitly from this package.
|
||||
|
||||
Public API:
|
||||
- resolve_training_evaluation
|
||||
- resolve_for_base_profile
|
||||
- models: CalculationTemplate, TrainingEvaluationResult, ...
|
||||
- registries: templates, profiles, algorithms
|
||||
"""
|
||||
|
||||
from data_layer.training_profile.models import (
|
||||
CalculationTemplate,
|
||||
DimensionResult,
|
||||
DimensionSpec,
|
||||
FocusAreaMapping,
|
||||
TrainingBaseProfile,
|
||||
TrainingEvaluationResult,
|
||||
)
|
||||
from data_layer.training_profile.resolver import (
|
||||
resolve_for_base_profile,
|
||||
resolve_training_evaluation,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"CalculationTemplate",
|
||||
"DimensionResult",
|
||||
"DimensionSpec",
|
||||
"FocusAreaMapping",
|
||||
"TrainingBaseProfile",
|
||||
"TrainingEvaluationResult",
|
||||
"resolve_for_base_profile",
|
||||
"resolve_training_evaluation",
|
||||
]
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Built-in training evaluation algorithms (code-defined only)."""
|
||||
|
||||
from .registry import (
|
||||
get_algorithm,
|
||||
list_algorithm_ids,
|
||||
register_algorithm,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"get_algorithm",
|
||||
"list_algorithm_ids",
|
||||
"register_algorithm",
|
||||
]
|
||||
@@ -0,0 +1,23 @@
|
||||
"""
|
||||
Algorithm protocol: fixed implementations selected by id from declarative templates.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, Mapping, Protocol
|
||||
|
||||
from data_layer.training_profile.models import AlgorithmRunResult
|
||||
|
||||
|
||||
class TrainingAlgorithm(Protocol):
|
||||
"""Built-in algorithm callable shape."""
|
||||
|
||||
id: str
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
*,
|
||||
inputs: Mapping[str, Any],
|
||||
params: Mapping[str, Any],
|
||||
) -> AlgorithmRunResult:
|
||||
...
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Example built-in algorithms (threshold bands, linear range mapping)."""
|
||||
|
||||
from .linear_range import linear_range_score
|
||||
from .threshold_band import threshold_band_score
|
||||
|
||||
__all__ = ["linear_range_score", "threshold_band_score"]
|
||||
@@ -0,0 +1,69 @@
|
||||
"""
|
||||
linear_range: map a value linearly from [min_value, max_value] to [0, 1], clamped.
|
||||
|
||||
params:
|
||||
value_key: str
|
||||
min_value: float
|
||||
max_value: float
|
||||
invert: bool (optional) — if True, high values map to 0
|
||||
|
||||
Missing value → score 0 and missing_inputs.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Mapping
|
||||
|
||||
from data_layer.training_profile.models import AlgorithmRunResult
|
||||
from data_layer.utils import safe_float
|
||||
|
||||
|
||||
ALGORITHM_ID = "linear_range"
|
||||
|
||||
|
||||
def linear_range_score(
|
||||
*,
|
||||
inputs: Mapping[str, Any],
|
||||
params: Mapping[str, Any],
|
||||
) -> AlgorithmRunResult:
|
||||
value_key = str(params.get("value_key", ""))
|
||||
if not value_key:
|
||||
return AlgorithmRunResult(
|
||||
raw_score=0.0,
|
||||
normalized_score=0.0,
|
||||
missing_inputs=["__param_value_key__"],
|
||||
detail={"error": "params.value_key required"},
|
||||
)
|
||||
|
||||
if value_key not in inputs or inputs[value_key] is None:
|
||||
return AlgorithmRunResult(
|
||||
raw_score=0.0,
|
||||
normalized_score=0.0,
|
||||
missing_inputs=[value_key],
|
||||
detail={"value_key": value_key},
|
||||
)
|
||||
|
||||
raw = safe_float(inputs[value_key])
|
||||
lo = safe_float(params.get("min_value"))
|
||||
hi = safe_float(params.get("max_value"))
|
||||
invert = bool(params.get("invert", False))
|
||||
|
||||
if hi <= lo:
|
||||
return AlgorithmRunResult(
|
||||
raw_score=raw,
|
||||
normalized_score=0.0,
|
||||
missing_inputs=[],
|
||||
detail={"error": "max_value must be > min_value", "min": lo, "max": hi},
|
||||
)
|
||||
|
||||
t = (raw - lo) / (hi - lo)
|
||||
t = max(0.0, min(1.0, t))
|
||||
if invert:
|
||||
t = 1.0 - t
|
||||
|
||||
return AlgorithmRunResult(
|
||||
raw_score=raw,
|
||||
normalized_score=t,
|
||||
missing_inputs=[],
|
||||
detail={"value_key": value_key, "min": lo, "max": hi, "invert": invert},
|
||||
)
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
threshold_band: map a numeric value into a score using ordered upper bounds.
|
||||
|
||||
params:
|
||||
value_key: str — key in inputs to read
|
||||
bands: list of { "max": float | null, "score": float } — ascending max; null = +inf
|
||||
|
||||
Missing value_key → normalized_score 0, missing_inputs lists value_key.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, List, Mapping
|
||||
|
||||
from data_layer.training_profile.models import AlgorithmRunResult
|
||||
from data_layer.utils import safe_float
|
||||
|
||||
|
||||
ALGORITHM_ID = "threshold_band"
|
||||
|
||||
|
||||
def threshold_band_score(
|
||||
*,
|
||||
inputs: Mapping[str, Any],
|
||||
params: Mapping[str, Any],
|
||||
) -> AlgorithmRunResult:
|
||||
value_key = str(params.get("value_key", ""))
|
||||
if not value_key:
|
||||
return AlgorithmRunResult(
|
||||
raw_score=0.0,
|
||||
normalized_score=0.0,
|
||||
missing_inputs=["__param_value_key__"],
|
||||
detail={"error": "params.value_key required"},
|
||||
)
|
||||
|
||||
if value_key not in inputs or inputs[value_key] is None:
|
||||
return AlgorithmRunResult(
|
||||
raw_score=0.0,
|
||||
normalized_score=0.0,
|
||||
missing_inputs=[value_key],
|
||||
detail={"value_key": value_key},
|
||||
)
|
||||
|
||||
raw = safe_float(inputs[value_key])
|
||||
bands = params.get("bands") or []
|
||||
if not isinstance(bands, list) or not bands:
|
||||
return AlgorithmRunResult(
|
||||
raw_score=raw,
|
||||
normalized_score=0.0,
|
||||
missing_inputs=[],
|
||||
detail={"error": "params.bands must be a non-empty list", "raw": raw},
|
||||
)
|
||||
|
||||
score = 0.0
|
||||
for band in bands:
|
||||
if not isinstance(band, dict):
|
||||
continue
|
||||
max_v = band.get("max")
|
||||
s = safe_float(band.get("score"))
|
||||
if max_v is None:
|
||||
score = s
|
||||
break
|
||||
if raw <= safe_float(max_v):
|
||||
score = s
|
||||
break
|
||||
else:
|
||||
score = safe_float(bands[-1].get("score")) if isinstance(bands[-1], dict) else 0.0
|
||||
|
||||
norm = max(0.0, min(1.0, score))
|
||||
return AlgorithmRunResult(
|
||||
raw_score=raw,
|
||||
normalized_score=norm,
|
||||
missing_inputs=[],
|
||||
detail={"value_key": value_key, "bands_applied": True, "band_score": score},
|
||||
)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
Registry for built-in algorithm ids → callables.
|
||||
|
||||
Only code registers algorithms; templates reference ids declared here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Dict, Mapping
|
||||
|
||||
from data_layer.training_profile.algorithms.builtin.linear_range import (
|
||||
ALGORITHM_ID as LINEAR_RANGE_ID,
|
||||
linear_range_score,
|
||||
)
|
||||
from data_layer.training_profile.algorithms.builtin.threshold_band import (
|
||||
ALGORITHM_ID as THRESHOLD_BAND_ID,
|
||||
threshold_band_score,
|
||||
)
|
||||
from data_layer.training_profile.models import AlgorithmRunResult
|
||||
|
||||
AlgorithmFn = Callable[..., AlgorithmRunResult]
|
||||
|
||||
_REGISTRY: Dict[str, AlgorithmFn] = {}
|
||||
|
||||
|
||||
def register_algorithm(algorithm_id: str, fn: AlgorithmFn) -> None:
|
||||
if algorithm_id in _REGISTRY:
|
||||
raise ValueError(f"Algorithm already registered: {algorithm_id}")
|
||||
_REGISTRY[algorithm_id] = fn
|
||||
|
||||
|
||||
def get_algorithm(algorithm_id: str) -> AlgorithmFn:
|
||||
if algorithm_id not in _REGISTRY:
|
||||
raise KeyError(f"Unknown algorithm_id: {algorithm_id}")
|
||||
return _REGISTRY[algorithm_id]
|
||||
|
||||
|
||||
def list_algorithm_ids() -> tuple[str, ...]:
|
||||
return tuple(sorted(_REGISTRY.keys()))
|
||||
|
||||
|
||||
def _register_defaults() -> None:
|
||||
register_algorithm(THRESHOLD_BAND_ID, threshold_band_score)
|
||||
register_algorithm(LINEAR_RANGE_ID, linear_range_score)
|
||||
|
||||
|
||||
_register_defaults()
|
||||
@@ -0,0 +1,121 @@
|
||||
"""
|
||||
Declarative schemas for template-based training evaluation (Layer 1 scaffold).
|
||||
|
||||
Templates select built-in algorithms by id and pass parameters; they do not embed
|
||||
executable logic. See resolver and algorithm registry.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Mapping, Optional
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FocusAreaMapping:
|
||||
"""Maps a share of one dimension's score to a Focus Area (by stable key)."""
|
||||
|
||||
focus_area_key: str
|
||||
weight: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DimensionSpec:
|
||||
"""
|
||||
One evaluation dimension: algorithm + inputs + params + FA mapping.
|
||||
|
||||
inputs: names of keys expected in the flat activity_inputs dict passed to the resolver.
|
||||
"""
|
||||
|
||||
key: str
|
||||
algorithm_id: str
|
||||
inputs: tuple[str, ...]
|
||||
params: Mapping[str, Any]
|
||||
maps_to: tuple[FocusAreaMapping, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CalculationTemplate:
|
||||
"""Declarative multi-dimensional calculation template (in-code registry)."""
|
||||
|
||||
id: str
|
||||
version: str
|
||||
label: str
|
||||
dimensions: tuple[DimensionSpec, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TrainingBaseProfile:
|
||||
"""
|
||||
Conceptual base profile: links a training context to a default template.
|
||||
|
||||
allowed_dimension_keys: if set, dimensions not listed are skipped at resolve time.
|
||||
"""
|
||||
|
||||
key: str
|
||||
label: str
|
||||
default_template_id: str
|
||||
allowed_dimension_keys: Optional[frozenset[str]] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class AlgorithmRunResult:
|
||||
"""Output of a single built-in algorithm execution."""
|
||||
|
||||
raw_score: float
|
||||
normalized_score: float
|
||||
missing_inputs: List[str]
|
||||
detail: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DimensionResult:
|
||||
"""Per-dimension result after resolution."""
|
||||
|
||||
dimension_key: str
|
||||
algorithm_id: str
|
||||
raw_score: float
|
||||
normalized_score: float
|
||||
missing_inputs: List[str]
|
||||
evidence: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class TrainingEvaluationResult:
|
||||
"""
|
||||
Stable structured result for Layer 2 (KI, charts, APIs, future persistence).
|
||||
|
||||
focus_area_contributions: aggregated contribution per focus_area key (additive).
|
||||
"""
|
||||
|
||||
template_id: str
|
||||
template_version: str
|
||||
base_profile_key: Optional[str]
|
||||
dimension_results: List[DimensionResult]
|
||||
focus_area_contributions: Dict[str, float]
|
||||
confidence: str
|
||||
evidence: Dict[str, Any]
|
||||
trace: Optional[Dict[str, Any]] = None
|
||||
|
||||
def to_serializable(self) -> Dict[str, Any]:
|
||||
"""JSON-compatible dict (for APIs / storage)."""
|
||||
return {
|
||||
"template_id": self.template_id,
|
||||
"template_version": self.template_version,
|
||||
"base_profile_key": self.base_profile_key,
|
||||
"dimension_results": [
|
||||
{
|
||||
"dimension_key": d.dimension_key,
|
||||
"algorithm_id": d.algorithm_id,
|
||||
"raw_score": d.raw_score,
|
||||
"normalized_score": d.normalized_score,
|
||||
"missing_inputs": d.missing_inputs,
|
||||
"evidence": d.evidence,
|
||||
}
|
||||
for d in self.dimension_results
|
||||
],
|
||||
"focus_area_contributions": dict(self.focus_area_contributions),
|
||||
"confidence": self.confidence,
|
||||
"evidence": self.evidence,
|
||||
"trace": self.trace,
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Training base profile registrations (scaffold, in-code)."""
|
||||
|
||||
from .registry import (
|
||||
get_training_base_profile,
|
||||
list_training_base_profile_keys,
|
||||
try_get_training_base_profile,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"get_training_base_profile",
|
||||
"list_training_base_profile_keys",
|
||||
"try_get_training_base_profile",
|
||||
]
|
||||
@@ -0,0 +1,52 @@
|
||||
"""
|
||||
Example training base profiles — point to default templates and optional dimension filters.
|
||||
|
||||
Future: DB-backed training types may reference profile keys; this registry is code-only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict, Optional
|
||||
|
||||
from data_layer.training_profile.models import TrainingBaseProfile
|
||||
|
||||
_PROFILES: Dict[str, TrainingBaseProfile] = {}
|
||||
|
||||
|
||||
def _register(p: TrainingBaseProfile) -> None:
|
||||
if p.key in _PROFILES:
|
||||
raise ValueError(f"Duplicate training base profile key: {p.key}")
|
||||
_PROFILES[p.key] = p
|
||||
|
||||
|
||||
def get_training_base_profile(key: str) -> TrainingBaseProfile:
|
||||
if key not in _PROFILES:
|
||||
raise KeyError(f"Unknown training base profile: {key}")
|
||||
return _PROFILES[key]
|
||||
|
||||
|
||||
def try_get_training_base_profile(key: str) -> Optional[TrainingBaseProfile]:
|
||||
return _PROFILES.get(key)
|
||||
|
||||
|
||||
def list_training_base_profile_keys() -> tuple[str, ...]:
|
||||
return tuple(sorted(_PROFILES.keys()))
|
||||
|
||||
|
||||
_register(
|
||||
TrainingBaseProfile(
|
||||
key="scaffold_aerobic_base",
|
||||
label="Scaffold: aerobic base profile",
|
||||
default_template_id="scaffold_example_aerobic_v1",
|
||||
allowed_dimension_keys=None,
|
||||
)
|
||||
)
|
||||
|
||||
_register(
|
||||
TrainingBaseProfile(
|
||||
key="scaffold_strength_base",
|
||||
label="Scaffold: strength base profile",
|
||||
default_template_id="scaffold_example_strength_v1",
|
||||
allowed_dimension_keys=frozenset({"effort"}),
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,160 @@
|
||||
"""
|
||||
Layer 1 entry: resolve a multi-dimensional training evaluation from a template.
|
||||
|
||||
Pure calculation orchestration — no DB, no HTTP, no formatting for KI/charts.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from typing import Any, Dict, List, Mapping, Optional
|
||||
|
||||
from data_layer.training_profile.algorithms.registry import get_algorithm
|
||||
from data_layer.training_profile.models import (
|
||||
CalculationTemplate,
|
||||
DimensionResult,
|
||||
DimensionSpec,
|
||||
TrainingBaseProfile,
|
||||
TrainingEvaluationResult,
|
||||
)
|
||||
|
||||
|
||||
def _required_inputs_present(
|
||||
activity_inputs: Mapping[str, Any], keys: tuple[str, ...]
|
||||
) -> tuple[bool, List[str]]:
|
||||
missing: List[str] = []
|
||||
for k in keys:
|
||||
if k not in activity_inputs or activity_inputs[k] is None:
|
||||
missing.append(k)
|
||||
return (len(missing) == 0, missing)
|
||||
|
||||
|
||||
def _confidence_level(total_dims: int, dims_with_any_missing: int) -> str:
|
||||
if total_dims == 0:
|
||||
return "insufficient"
|
||||
if dims_with_any_missing == 0:
|
||||
return "high"
|
||||
if dims_with_any_missing >= total_dims:
|
||||
return "insufficient"
|
||||
if dims_with_any_missing == 1:
|
||||
return "medium"
|
||||
return "low"
|
||||
|
||||
|
||||
def _filter_dimensions(
|
||||
template: CalculationTemplate, base_profile: Optional[TrainingBaseProfile]
|
||||
) -> tuple[DimensionSpec, ...]:
|
||||
if base_profile is None or base_profile.allowed_dimension_keys is None:
|
||||
return template.dimensions
|
||||
allowed = base_profile.allowed_dimension_keys
|
||||
return tuple(d for d in template.dimensions if d.key in allowed)
|
||||
|
||||
|
||||
def resolve_training_evaluation(
|
||||
*,
|
||||
activity_inputs: Mapping[str, Any],
|
||||
template: CalculationTemplate,
|
||||
base_profile: Optional[TrainingBaseProfile] = None,
|
||||
include_trace: bool = False,
|
||||
) -> TrainingEvaluationResult:
|
||||
"""
|
||||
Run all template dimensions, aggregate Focus Area contributions, attach evidence.
|
||||
|
||||
activity_inputs: flat dict (e.g. avg_hr, duration_min, distance_km) supplied by caller.
|
||||
"""
|
||||
dimensions = _filter_dimensions(template, base_profile)
|
||||
dimension_results: List[DimensionResult] = []
|
||||
contributions: Dict[str, float] = defaultdict(float)
|
||||
evidence: Dict[str, Any] = {
|
||||
"dimensions_total": len(dimensions),
|
||||
"inputs_keys": sorted(activity_inputs.keys()),
|
||||
}
|
||||
trace: Optional[Dict[str, Any]] = {} if include_trace else None
|
||||
|
||||
dims_with_missing = 0
|
||||
|
||||
for spec in dimensions:
|
||||
ok, missing = _required_inputs_present(activity_inputs, spec.inputs)
|
||||
if not ok:
|
||||
dims_with_missing += 1
|
||||
dimension_results.append(
|
||||
DimensionResult(
|
||||
dimension_key=spec.key,
|
||||
algorithm_id=spec.algorithm_id,
|
||||
raw_score=0.0,
|
||||
normalized_score=0.0,
|
||||
missing_inputs=list(missing),
|
||||
evidence={"skipped": True, "reason": "required_inputs_missing"},
|
||||
)
|
||||
)
|
||||
if trace is not None:
|
||||
trace[spec.key] = {"skipped": True, "missing": missing}
|
||||
continue
|
||||
|
||||
algo = get_algorithm(spec.algorithm_id)
|
||||
slice_inputs = {k: activity_inputs[k] for k in spec.inputs}
|
||||
run = algo(inputs=slice_inputs, params=dict(spec.params))
|
||||
|
||||
if run.missing_inputs:
|
||||
dims_with_missing += 1
|
||||
|
||||
dimension_results.append(
|
||||
DimensionResult(
|
||||
dimension_key=spec.key,
|
||||
algorithm_id=spec.algorithm_id,
|
||||
raw_score=run.raw_score,
|
||||
normalized_score=run.normalized_score,
|
||||
missing_inputs=list(run.missing_inputs),
|
||||
evidence={"algorithm_detail": run.detail},
|
||||
)
|
||||
)
|
||||
|
||||
for m in spec.maps_to:
|
||||
contributions[m.focus_area_key] += run.normalized_score * m.weight
|
||||
|
||||
if trace is not None:
|
||||
trace[spec.key] = {
|
||||
"inputs": dict(slice_inputs),
|
||||
"params": dict(spec.params),
|
||||
"run": {
|
||||
"raw_score": run.raw_score,
|
||||
"normalized_score": run.normalized_score,
|
||||
"missing_inputs": run.missing_inputs,
|
||||
"detail": run.detail,
|
||||
},
|
||||
"maps_to": [(x.focus_area_key, x.weight) for x in spec.maps_to],
|
||||
}
|
||||
|
||||
conf = _confidence_level(len(dimensions), dims_with_missing)
|
||||
evidence["dimensions_with_missing_or_failed"] = dims_with_missing
|
||||
|
||||
return TrainingEvaluationResult(
|
||||
template_id=template.id,
|
||||
template_version=template.version,
|
||||
base_profile_key=base_profile.key if base_profile else None,
|
||||
dimension_results=dimension_results,
|
||||
focus_area_contributions=dict(contributions),
|
||||
confidence=conf,
|
||||
evidence=evidence,
|
||||
trace=trace,
|
||||
)
|
||||
|
||||
|
||||
def resolve_for_base_profile(
|
||||
*,
|
||||
activity_inputs: Mapping[str, Any],
|
||||
base_profile_key: str,
|
||||
include_trace: bool = False,
|
||||
) -> TrainingEvaluationResult:
|
||||
"""Convenience: load profile + default template from registries."""
|
||||
from data_layer.training_profile.profiles.registry import get_training_base_profile
|
||||
from data_layer.training_profile.templates.registry import get_calculation_template
|
||||
|
||||
profile = get_training_base_profile(base_profile_key)
|
||||
template = get_calculation_template(profile.default_template_id)
|
||||
return resolve_training_evaluation(
|
||||
activity_inputs=activity_inputs,
|
||||
template=template,
|
||||
base_profile=profile,
|
||||
include_trace=include_trace,
|
||||
)
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Declarative calculation templates (in-code registry, scaffold)."""
|
||||
|
||||
from .registry import get_calculation_template, list_calculation_template_ids
|
||||
|
||||
__all__ = ["get_calculation_template", "list_calculation_template_ids"]
|
||||
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
Example calculation templates — declarative only; algorithms are referenced by id.
|
||||
|
||||
These are scaffolding examples, not production coaching rules.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict
|
||||
|
||||
from data_layer.training_profile.models import CalculationTemplate, DimensionSpec, FocusAreaMapping
|
||||
|
||||
_TEMPLATES: Dict[str, CalculationTemplate] = {}
|
||||
|
||||
|
||||
def _register(t: CalculationTemplate) -> None:
|
||||
if t.id in _TEMPLATES:
|
||||
raise ValueError(f"Duplicate template id: {t.id}")
|
||||
_TEMPLATES[t.id] = t
|
||||
|
||||
|
||||
def get_calculation_template(template_id: str) -> CalculationTemplate:
|
||||
if template_id not in _TEMPLATES:
|
||||
raise KeyError(f"Unknown calculation template: {template_id}")
|
||||
return _TEMPLATES[template_id]
|
||||
|
||||
|
||||
def list_calculation_template_ids() -> tuple[str, ...]:
|
||||
return tuple(sorted(_TEMPLATES.keys()))
|
||||
|
||||
|
||||
# --- Example templates (illustrative) ---
|
||||
|
||||
_example_aerobic = CalculationTemplate(
|
||||
id="scaffold_example_aerobic_v1",
|
||||
version="1",
|
||||
label="Scaffold: aerobic-style intensity + volume (example)",
|
||||
dimensions=(
|
||||
DimensionSpec(
|
||||
key="intensity",
|
||||
algorithm_id="threshold_band",
|
||||
inputs=("avg_hr", "duration_min"),
|
||||
params={
|
||||
"value_key": "avg_hr",
|
||||
"bands": [
|
||||
{"max": 120, "score": 0.25},
|
||||
{"max": 140, "score": 0.55},
|
||||
{"max": 160, "score": 0.85},
|
||||
{"max": None, "score": 1.0},
|
||||
],
|
||||
},
|
||||
maps_to=(
|
||||
FocusAreaMapping("aerobic_endurance", 0.7),
|
||||
FocusAreaMapping("cardiovascular_health", 0.3),
|
||||
),
|
||||
),
|
||||
DimensionSpec(
|
||||
key="volume",
|
||||
algorithm_id="linear_range",
|
||||
inputs=("duration_min", "distance_km"),
|
||||
params={
|
||||
"value_key": "duration_min",
|
||||
"min_value": 10.0,
|
||||
"max_value": 90.0,
|
||||
"invert": False,
|
||||
},
|
||||
maps_to=(FocusAreaMapping("aerobic_endurance", 0.8),),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
_example_strength = CalculationTemplate(
|
||||
id="scaffold_example_strength_v1",
|
||||
version="1",
|
||||
label="Scaffold: strength session load (example)",
|
||||
dimensions=(
|
||||
DimensionSpec(
|
||||
key="effort",
|
||||
algorithm_id="linear_range",
|
||||
inputs=("duration_min",),
|
||||
params={
|
||||
"value_key": "duration_min",
|
||||
"min_value": 20.0,
|
||||
"max_value": 75.0,
|
||||
"invert": False,
|
||||
},
|
||||
maps_to=(
|
||||
FocusAreaMapping("strength", 0.9),
|
||||
FocusAreaMapping("strength_endurance", 0.1),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
_register(_example_aerobic)
|
||||
_register(_example_strength)
|
||||
@@ -0,0 +1,242 @@
|
||||
"""
|
||||
Data Layer Utilities
|
||||
|
||||
Shared helper functions for all data layer modules.
|
||||
|
||||
Functions:
|
||||
- calculate_confidence(): Determine data quality confidence level
|
||||
- serialize_dates(): Convert Python date objects to ISO strings for JSON
|
||||
- safe_float(): Safe conversion from Decimal/None to float
|
||||
- safe_int(): Safe conversion to int
|
||||
|
||||
Phase 0c: Multi-Layer Architecture
|
||||
Version: 1.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List, Optional
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
|
||||
def calculate_confidence(
|
||||
data_points: int,
|
||||
days_requested: int,
|
||||
metric_type: str = "general"
|
||||
) -> str:
|
||||
"""
|
||||
Calculate confidence level based on data availability.
|
||||
|
||||
Args:
|
||||
data_points: Number of actual data points available
|
||||
days_requested: Number of days in analysis window
|
||||
metric_type: Type of metric ("general", "correlation", "trend")
|
||||
|
||||
Returns:
|
||||
Confidence level: "high" | "medium" | "low" | "insufficient"
|
||||
|
||||
Confidence Rules:
|
||||
General (default):
|
||||
- 7d: high >= 4, medium >= 3, low >= 2
|
||||
- 28d: high >= 18, medium >= 12, low >= 8
|
||||
- 90d: high >= 60, medium >= 40, low >= 30
|
||||
|
||||
Correlation:
|
||||
- high >= 28, medium >= 21, low >= 14
|
||||
|
||||
Trend:
|
||||
- high >= 70% of days, medium >= 50%, low >= 30%
|
||||
|
||||
Example:
|
||||
>>> calculate_confidence(20, 28, "general")
|
||||
'high'
|
||||
>>> calculate_confidence(10, 28, "general")
|
||||
'low'
|
||||
"""
|
||||
if data_points == 0:
|
||||
return "insufficient"
|
||||
|
||||
if metric_type == "correlation":
|
||||
# Correlation needs more paired data points
|
||||
if data_points >= 28:
|
||||
return "high"
|
||||
elif data_points >= 21:
|
||||
return "medium"
|
||||
elif data_points >= 14:
|
||||
return "low"
|
||||
else:
|
||||
return "insufficient"
|
||||
|
||||
elif metric_type == "trend":
|
||||
# Trend analysis based on percentage of days covered
|
||||
coverage = data_points / days_requested if days_requested > 0 else 0
|
||||
|
||||
if coverage >= 0.70:
|
||||
return "high"
|
||||
elif coverage >= 0.50:
|
||||
return "medium"
|
||||
elif coverage >= 0.30:
|
||||
return "low"
|
||||
else:
|
||||
return "insufficient"
|
||||
|
||||
else: # "general"
|
||||
# Different thresholds based on time window
|
||||
if days_requested <= 7:
|
||||
if data_points >= 4:
|
||||
return "high"
|
||||
elif data_points >= 3:
|
||||
return "medium"
|
||||
elif data_points >= 2:
|
||||
return "low"
|
||||
else:
|
||||
return "insufficient"
|
||||
|
||||
elif days_requested < 90:
|
||||
# 8-89 days: Medium-term analysis
|
||||
if data_points >= 18:
|
||||
return "high"
|
||||
elif data_points >= 12:
|
||||
return "medium"
|
||||
elif data_points >= 8:
|
||||
return "low"
|
||||
else:
|
||||
return "insufficient"
|
||||
|
||||
else: # 90+ days: Long-term analysis
|
||||
if data_points >= 60:
|
||||
return "high"
|
||||
elif data_points >= 40:
|
||||
return "medium"
|
||||
elif data_points >= 30:
|
||||
return "low"
|
||||
else:
|
||||
return "insufficient"
|
||||
|
||||
|
||||
def serialize_dates(data: Any) -> Any:
|
||||
"""
|
||||
Convert Python date objects to ISO strings for JSON serialization.
|
||||
|
||||
Recursively walks through dicts, lists, and tuples converting date objects.
|
||||
|
||||
Args:
|
||||
data: Any data structure (dict, list, tuple, or primitive)
|
||||
|
||||
Returns:
|
||||
Same structure with dates converted to ISO strings
|
||||
|
||||
Example:
|
||||
>>> serialize_dates({"date": date(2026, 3, 28), "value": 85.0})
|
||||
{"date": "2026-03-28", "value": 85.0}
|
||||
"""
|
||||
if isinstance(data, dict):
|
||||
return {k: serialize_dates(v) for k, v in data.items()}
|
||||
elif isinstance(data, list):
|
||||
return [serialize_dates(item) for item in data]
|
||||
elif isinstance(data, tuple):
|
||||
return tuple(serialize_dates(item) for item in data)
|
||||
elif isinstance(data, date):
|
||||
return data.isoformat()
|
||||
else:
|
||||
return data
|
||||
|
||||
|
||||
def safe_float(value: Any, default: float = 0.0) -> float:
|
||||
"""
|
||||
Safely convert value to float.
|
||||
|
||||
Handles Decimal, None, and invalid values.
|
||||
|
||||
Args:
|
||||
value: Value to convert (can be Decimal, int, float, str, None)
|
||||
default: Default value if conversion fails
|
||||
|
||||
Returns:
|
||||
Float value or default
|
||||
|
||||
Example:
|
||||
>>> safe_float(Decimal('85.5'))
|
||||
85.5
|
||||
>>> safe_float(None)
|
||||
0.0
|
||||
>>> safe_float(None, -1.0)
|
||||
-1.0
|
||||
"""
|
||||
if value is None:
|
||||
return default
|
||||
|
||||
try:
|
||||
if isinstance(value, Decimal):
|
||||
return float(value)
|
||||
return float(value)
|
||||
except (ValueError, TypeError):
|
||||
return default
|
||||
|
||||
|
||||
def safe_int(value: Any, default: int = 0) -> int:
|
||||
"""
|
||||
Safely convert value to int.
|
||||
|
||||
Handles Decimal, None, and invalid values.
|
||||
|
||||
Args:
|
||||
value: Value to convert
|
||||
default: Default value if conversion fails
|
||||
|
||||
Returns:
|
||||
Int value or default
|
||||
|
||||
Example:
|
||||
>>> safe_int(Decimal('42'))
|
||||
42
|
||||
>>> safe_int(None)
|
||||
0
|
||||
"""
|
||||
if value is None:
|
||||
return default
|
||||
|
||||
try:
|
||||
if isinstance(value, Decimal):
|
||||
return int(value)
|
||||
return int(value)
|
||||
except (ValueError, TypeError):
|
||||
return default
|
||||
|
||||
|
||||
def calculate_baseline(
|
||||
values: List[float],
|
||||
method: str = "median"
|
||||
) -> float:
|
||||
"""
|
||||
Calculate baseline value from a list of measurements.
|
||||
|
||||
Args:
|
||||
values: List of numeric values
|
||||
method: "median" (default) | "mean" | "trimmed_mean"
|
||||
|
||||
Returns:
|
||||
Baseline value
|
||||
|
||||
Example:
|
||||
>>> calculate_baseline([85.0, 84.5, 86.0, 84.8, 85.2])
|
||||
85.0
|
||||
"""
|
||||
import statistics
|
||||
|
||||
if not values:
|
||||
return 0.0
|
||||
|
||||
if method == "median":
|
||||
return statistics.median(values)
|
||||
elif method == "mean":
|
||||
return statistics.mean(values)
|
||||
elif method == "trimmed_mean":
|
||||
# Remove top/bottom 10%
|
||||
if len(values) < 10:
|
||||
return statistics.mean(values)
|
||||
sorted_vals = sorted(values)
|
||||
trim_count = len(values) // 10
|
||||
trimmed = sorted_vals[trim_count:-trim_count] if trim_count > 0 else sorted_vals
|
||||
return statistics.mean(trimmed) if trimmed else 0.0
|
||||
else:
|
||||
return statistics.median(values) # Default to median
|
||||
+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))
|
||||
@@ -0,0 +1,215 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Quick Fix: Insert seed data for goal_type_definitions
|
||||
|
||||
This script ONLY inserts the 8 standard goal types.
|
||||
Safe to run multiple times (uses ON CONFLICT DO NOTHING).
|
||||
|
||||
Run inside backend container:
|
||||
docker exec bodytrack-dev-backend-1 python fix_seed_goal_types.py
|
||||
"""
|
||||
|
||||
import psycopg2
|
||||
import os
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
# Database connection
|
||||
DB_HOST = os.getenv('DB_HOST', 'db')
|
||||
DB_PORT = os.getenv('DB_PORT', '5432')
|
||||
DB_NAME = os.getenv('DB_NAME', 'bodytrack')
|
||||
DB_USER = os.getenv('DB_USER', 'bodytrack')
|
||||
DB_PASS = os.getenv('DB_PASSWORD', '')
|
||||
|
||||
SEED_DATA = [
|
||||
{
|
||||
'type_key': 'weight',
|
||||
'label_de': 'Gewicht',
|
||||
'label_en': 'Weight',
|
||||
'unit': 'kg',
|
||||
'icon': '⚖️',
|
||||
'category': 'body',
|
||||
'source_table': 'weight_log',
|
||||
'source_column': 'weight',
|
||||
'aggregation_method': 'latest',
|
||||
'description': 'Aktuelles Körpergewicht',
|
||||
'is_system': True
|
||||
},
|
||||
{
|
||||
'type_key': 'body_fat',
|
||||
'label_de': 'Körperfett',
|
||||
'label_en': 'Body Fat',
|
||||
'unit': '%',
|
||||
'icon': '📊',
|
||||
'category': 'body',
|
||||
'source_table': 'caliper_log',
|
||||
'source_column': 'body_fat_pct',
|
||||
'aggregation_method': 'latest',
|
||||
'description': 'Körperfettanteil aus Caliper-Messung',
|
||||
'is_system': True
|
||||
},
|
||||
{
|
||||
'type_key': 'lean_mass',
|
||||
'label_de': 'Muskelmasse',
|
||||
'label_en': 'Lean Mass',
|
||||
'unit': 'kg',
|
||||
'icon': '💪',
|
||||
'category': 'body',
|
||||
'calculation_formula': '{"type": "lean_mass", "dependencies": ["weight_log.weight", "caliper_log.body_fat_pct"], "formula": "weight - (weight * body_fat_pct / 100)"}',
|
||||
'description': 'Fettfreie Körpermasse (berechnet aus Gewicht und Körperfett)',
|
||||
'is_system': True
|
||||
},
|
||||
{
|
||||
'type_key': 'vo2max',
|
||||
'label_de': 'VO2Max',
|
||||
'label_en': 'VO2Max',
|
||||
'unit': 'ml/kg/min',
|
||||
'icon': '🫁',
|
||||
'category': 'recovery',
|
||||
'source_table': 'vitals_baseline',
|
||||
'source_column': 'vo2_max',
|
||||
'aggregation_method': 'latest',
|
||||
'description': 'Maximale Sauerstoffaufnahme (geschätzt oder gemessen)',
|
||||
'is_system': True
|
||||
},
|
||||
{
|
||||
'type_key': 'rhr',
|
||||
'label_de': 'Ruhepuls',
|
||||
'label_en': 'Resting Heart Rate',
|
||||
'unit': 'bpm',
|
||||
'icon': '💓',
|
||||
'category': 'recovery',
|
||||
'source_table': 'vitals_baseline',
|
||||
'source_column': 'resting_hr',
|
||||
'aggregation_method': 'latest',
|
||||
'description': 'Ruhepuls morgens vor dem Aufstehen',
|
||||
'is_system': True
|
||||
},
|
||||
{
|
||||
'type_key': 'bp',
|
||||
'label_de': 'Blutdruck',
|
||||
'label_en': 'Blood Pressure',
|
||||
'unit': 'mmHg',
|
||||
'icon': '❤️',
|
||||
'category': 'recovery',
|
||||
'source_table': 'blood_pressure_log',
|
||||
'source_column': 'systolic',
|
||||
'aggregation_method': 'latest',
|
||||
'description': 'Blutdruck (aktuell nur systolisch, v2.0: beide Werte)',
|
||||
'is_system': True
|
||||
},
|
||||
{
|
||||
'type_key': 'strength',
|
||||
'label_de': 'Kraft',
|
||||
'label_en': 'Strength',
|
||||
'unit': 'kg',
|
||||
'icon': '🏋️',
|
||||
'category': 'activity',
|
||||
'description': 'Maximalkraft (Platzhalter, Datenquelle in v2.0)',
|
||||
'is_system': True,
|
||||
'is_active': False
|
||||
},
|
||||
{
|
||||
'type_key': 'flexibility',
|
||||
'label_de': 'Beweglichkeit',
|
||||
'label_en': 'Flexibility',
|
||||
'unit': 'cm',
|
||||
'icon': '🤸',
|
||||
'category': 'activity',
|
||||
'description': 'Beweglichkeit (Platzhalter, Datenquelle in v2.0)',
|
||||
'is_system': True,
|
||||
'is_active': False
|
||||
}
|
||||
]
|
||||
|
||||
def main():
|
||||
print("=" * 70)
|
||||
print("Goal Type Definitions - Seed Data Fix")
|
||||
print("=" * 70)
|
||||
|
||||
# Connect to database
|
||||
conn = psycopg2.connect(
|
||||
host=DB_HOST,
|
||||
port=DB_PORT,
|
||||
dbname=DB_NAME,
|
||||
user=DB_USER,
|
||||
password=DB_PASS
|
||||
)
|
||||
conn.autocommit = False
|
||||
cur = conn.cursor(cursor_factory=RealDictCursor)
|
||||
|
||||
try:
|
||||
# Check current state
|
||||
cur.execute("SELECT COUNT(*) as count FROM goal_type_definitions")
|
||||
before_count = cur.fetchone()['count']
|
||||
print(f"\nBefore: {before_count} goal types in database")
|
||||
|
||||
# Insert seed data
|
||||
print(f"\nInserting {len(SEED_DATA)} standard goal types...")
|
||||
inserted = 0
|
||||
skipped = 0
|
||||
|
||||
for data in SEED_DATA:
|
||||
columns = list(data.keys())
|
||||
values = [data[col] for col in columns]
|
||||
placeholders = ', '.join(['%s'] * len(values))
|
||||
cols_str = ', '.join(columns)
|
||||
|
||||
sql = f"""
|
||||
INSERT INTO goal_type_definitions ({cols_str})
|
||||
VALUES ({placeholders})
|
||||
ON CONFLICT (type_key) DO NOTHING
|
||||
RETURNING id
|
||||
"""
|
||||
|
||||
cur.execute(sql, values)
|
||||
result = cur.fetchone()
|
||||
|
||||
if result:
|
||||
inserted += 1
|
||||
print(f" ✓ {data['type_key']}: {data['label_de']}")
|
||||
else:
|
||||
skipped += 1
|
||||
print(f" - {data['type_key']}: already exists (skipped)")
|
||||
|
||||
conn.commit()
|
||||
|
||||
# Check final state
|
||||
cur.execute("SELECT COUNT(*) as count FROM goal_type_definitions")
|
||||
after_count = cur.fetchone()['count']
|
||||
|
||||
print(f"\nAfter: {after_count} goal types in database")
|
||||
print(f" Inserted: {inserted}")
|
||||
print(f" Skipped: {skipped}")
|
||||
|
||||
# Show summary
|
||||
cur.execute("""
|
||||
SELECT type_key, label_de, is_active, is_system
|
||||
FROM goal_type_definitions
|
||||
ORDER BY is_system DESC, type_key
|
||||
""")
|
||||
|
||||
print("\n" + "=" * 70)
|
||||
print("Current Goal Types:")
|
||||
print("=" * 70)
|
||||
print(f"\n{'Type Key':<20} {'Label':<20} {'System':<8} {'Active':<8}")
|
||||
print("-" * 70)
|
||||
|
||||
for row in cur.fetchall():
|
||||
status = "YES" if row['is_system'] else "NO"
|
||||
active = "YES" if row['is_active'] else "NO"
|
||||
print(f"{row['type_key']:<20} {row['label_de']:<20} {status:<8} {active:<8}")
|
||||
|
||||
print("\n✅ DONE! Goal types seeded successfully.")
|
||||
print("\nNext step: Reload frontend to see the changes.")
|
||||
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
print(f"\n❌ Error: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
finally:
|
||||
cur.close()
|
||||
conn.close()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Kleine Helfer für Focus-Area-Nutzungstypen (ohne Router-/Auth-Abhängigkeiten)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, List
|
||||
|
||||
|
||||
def coerce_usage_type_keys(raw: Any) -> List[str]:
|
||||
"""json_agg / JSON-Spalte zu list[str] normalisieren."""
|
||||
if raw is None:
|
||||
return []
|
||||
if isinstance(raw, list):
|
||||
return [str(x) for x in raw]
|
||||
if isinstance(raw, str):
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
return [str(x) for x in data] if isinstance(data, list) else []
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
return []
|
||||
@@ -0,0 +1,396 @@
|
||||
"""
|
||||
Script to generate complete metadata for all 116 placeholders.
|
||||
|
||||
This script combines:
|
||||
1. Automatic extraction from PLACEHOLDER_MAP
|
||||
2. Manual curation of known metadata
|
||||
3. Gap identification for unresolved fields
|
||||
|
||||
Output: Complete metadata JSON ready for export
|
||||
"""
|
||||
import sys
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
# Add backend to path
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
|
||||
from placeholder_metadata import (
|
||||
PlaceholderMetadata,
|
||||
PlaceholderType,
|
||||
TimeWindow,
|
||||
OutputType,
|
||||
SourceInfo,
|
||||
ConfidenceLogic,
|
||||
ConfidenceLevel,
|
||||
METADATA_REGISTRY
|
||||
)
|
||||
from placeholder_metadata_extractor import build_complete_metadata_registry
|
||||
|
||||
|
||||
# ── Manual Metadata Corrections ──────────────────────────────────────────────
|
||||
|
||||
def apply_manual_corrections(registry):
|
||||
"""
|
||||
Apply manual corrections to automatically extracted metadata.
|
||||
|
||||
This ensures 100% accuracy for fields that cannot be reliably extracted.
|
||||
"""
|
||||
corrections = {
|
||||
# ── Profil ────────────────────────────────────────────────────────────
|
||||
"name": {
|
||||
"semantic_contract": "Name des Profils aus der Datenbank, keine Transformation",
|
||||
},
|
||||
"age": {
|
||||
"semantic_contract": "Berechnet aus Geburtsdatum (dob) im Profil via calculate_age()",
|
||||
"unit": "Jahre",
|
||||
},
|
||||
"height": {
|
||||
"semantic_contract": "Körpergröße aus Profil in cm, unverändert",
|
||||
},
|
||||
"geschlecht": {
|
||||
"semantic_contract": "Geschlecht aus Profil: m='männlich', w='weiblich'",
|
||||
"output_type": OutputType.ENUM,
|
||||
},
|
||||
|
||||
# ── Körper ────────────────────────────────────────────────────────────
|
||||
"weight_aktuell": {
|
||||
"semantic_contract": "Letzter verfügbarer Gewichtseintrag aus weight_log, keine Mittelung oder Glättung",
|
||||
"confidence_logic": ConfidenceLogic(
|
||||
supported=True,
|
||||
calculation="Confidence = 'high' if data exists, else 'insufficient'",
|
||||
thresholds={"min_data_points": 1},
|
||||
),
|
||||
},
|
||||
"weight_trend": {
|
||||
"semantic_contract": "Gewichtstrend-Beschreibung über 28 Tage: stabil, steigend (+X kg), sinkend (-X kg)",
|
||||
"known_issues": ["time_window_inconsistent: Description says 7d/30d, implementation uses 28d"],
|
||||
"notes": ["Consider splitting into weight_trend_7d and weight_trend_28d"],
|
||||
},
|
||||
"kf_aktuell": {
|
||||
"semantic_contract": "Letzter berechneter Körperfettanteil aus caliper_log (JPL-7 oder JPL-3 Formel)",
|
||||
},
|
||||
"caliper_summary": {
|
||||
"semantic_contract": "Strukturierte Zusammenfassung der letzten Caliper-Messungen mit Körperfettanteil und Methode",
|
||||
"notes": ["Returns formatted text summary, not JSON"],
|
||||
},
|
||||
"circ_summary": {
|
||||
"semantic_contract": "Best-of-Each Strategie: neueste Messung pro Körperstelle mit Altersangabe in Tagen",
|
||||
"time_window": TimeWindow.MIXED,
|
||||
"notes": ["Different body parts may have different timestamps"],
|
||||
},
|
||||
"recomposition_quadrant": {
|
||||
"semantic_contract": "Klassifizierung basierend auf FM/LBM Änderungen: Optimal Recomposition (FM↓ LBM↑), Fat Loss (FM↓ LBM→), Muscle Gain (FM→ LBM↑), Weight Gain (FM↑ LBM↑)",
|
||||
"type": PlaceholderType.INTERPRETED,
|
||||
},
|
||||
|
||||
# ── Ernährung ─────────────────────────────────────────────────────────
|
||||
"kcal_avg": {
|
||||
"semantic_contract": "Durchschnittliche Kalorienaufnahme über 30 Tage aus nutrition_log",
|
||||
},
|
||||
"protein_avg": {
|
||||
"semantic_contract": "Durchschnittliche Proteinaufnahme in g über 30 Tage aus nutrition_log",
|
||||
},
|
||||
"carb_avg": {
|
||||
"semantic_contract": "Durchschnittliche Kohlenhydrataufnahme in g über 30 Tage aus nutrition_log",
|
||||
},
|
||||
"fat_avg": {
|
||||
"semantic_contract": "Durchschnittliche Fettaufnahme in g über 30 Tage aus nutrition_log",
|
||||
},
|
||||
"nutrition_days": {
|
||||
"semantic_contract": "Anzahl der Tage mit Ernährungsdaten in den letzten 30 Tagen",
|
||||
"output_type": OutputType.INTEGER,
|
||||
},
|
||||
"protein_ziel_low": {
|
||||
"semantic_contract": "Untere Grenze der Protein-Zielspanne (1.6 g/kg Körpergewicht)",
|
||||
},
|
||||
"protein_ziel_high": {
|
||||
"semantic_contract": "Obere Grenze der Protein-Zielspanne (2.2 g/kg Körpergewicht)",
|
||||
},
|
||||
"protein_g_per_kg": {
|
||||
"semantic_contract": "Aktuelle Proteinaufnahme normiert auf kg Körpergewicht (protein_avg / weight)",
|
||||
},
|
||||
|
||||
# ── Training ──────────────────────────────────────────────────────────
|
||||
"activity_summary": {
|
||||
"semantic_contract": "Strukturierte Zusammenfassung der Trainingsaktivität der letzten 7 Tage",
|
||||
"type": PlaceholderType.RAW_DATA,
|
||||
"known_issues": ["time_window_ambiguous: Function name suggests variable window, actual implementation unclear"],
|
||||
},
|
||||
"activity_detail": {
|
||||
"semantic_contract": "Detaillierte Liste aller Trainingseinheiten mit Typ, Dauer, Intensität",
|
||||
"type": PlaceholderType.RAW_DATA,
|
||||
"known_issues": ["time_window_ambiguous: No clear time window specified"],
|
||||
},
|
||||
"trainingstyp_verteilung": {
|
||||
"semantic_contract": "Verteilung der Trainingstypen über einen Zeitraum (Anzahl Sessions pro Typ)",
|
||||
"type": PlaceholderType.RAW_DATA,
|
||||
},
|
||||
|
||||
# ── Zeitraum ──────────────────────────────────────────────────────────
|
||||
"datum_heute": {
|
||||
"semantic_contract": "Aktuelles Datum im Format YYYY-MM-DD",
|
||||
"output_type": OutputType.DATE,
|
||||
"format_hint": "2026-03-29",
|
||||
},
|
||||
"zeitraum_7d": {
|
||||
"semantic_contract": "Zeitraum der letzten 7 Tage als Text",
|
||||
"format_hint": "letzte 7 Tage (2026-03-22 bis 2026-03-29)",
|
||||
},
|
||||
"zeitraum_30d": {
|
||||
"semantic_contract": "Zeitraum der letzten 30 Tage als Text",
|
||||
"format_hint": "letzte 30 Tage (2026-02-27 bis 2026-03-29)",
|
||||
},
|
||||
"zeitraum_90d": {
|
||||
"semantic_contract": "Zeitraum der letzten 90 Tage als Text",
|
||||
"format_hint": "letzte 90 Tage (2025-12-29 bis 2026-03-29)",
|
||||
},
|
||||
|
||||
# ── Goals & Focus ─────────────────────────────────────────────────────
|
||||
"active_goals_json": {
|
||||
"type": PlaceholderType.RAW_DATA,
|
||||
"output_type": OutputType.JSON,
|
||||
"semantic_contract": "JSON-Array aller aktiven Ziele mit vollständigen Details",
|
||||
},
|
||||
"active_goals_md": {
|
||||
"type": PlaceholderType.RAW_DATA,
|
||||
"output_type": OutputType.MARKDOWN,
|
||||
"semantic_contract": "Markdown-formatierte Liste aller aktiven Ziele",
|
||||
},
|
||||
"focus_areas_weighted_json": {
|
||||
"type": PlaceholderType.RAW_DATA,
|
||||
"output_type": OutputType.JSON,
|
||||
"semantic_contract": "JSON-Array der gewichteten Focus Areas mit Progress",
|
||||
},
|
||||
"top_3_goals_behind_schedule": {
|
||||
"type": PlaceholderType.INTERPRETED,
|
||||
"semantic_contract": "Top 3 Ziele mit größter negativer Abweichung vom Zeitplan (Zeit-basiert)",
|
||||
},
|
||||
"top_3_goals_on_track": {
|
||||
"type": PlaceholderType.INTERPRETED,
|
||||
"semantic_contract": "Top 3 Ziele mit größter positiver Abweichung vom Zeitplan oder am besten im Plan",
|
||||
},
|
||||
|
||||
# ── Scores ────────────────────────────────────────────────────────────
|
||||
"goal_progress_score": {
|
||||
"type": PlaceholderType.ATOMIC,
|
||||
"semantic_contract": "Gewichteter Durchschnitts-Fortschritt aller aktiven Ziele (0-100)",
|
||||
"unit": "%",
|
||||
"output_type": OutputType.INTEGER,
|
||||
},
|
||||
"body_progress_score": {
|
||||
"type": PlaceholderType.ATOMIC,
|
||||
"semantic_contract": "Body Progress Score basierend auf Gewicht/KFA-Ziel-Erreichung (0-100)",
|
||||
"unit": "%",
|
||||
"output_type": OutputType.INTEGER,
|
||||
},
|
||||
"nutrition_score": {
|
||||
"type": PlaceholderType.ATOMIC,
|
||||
"semantic_contract": "Nutrition Score basierend auf Protein Adequacy, Makro-Konsistenz (0-100)",
|
||||
"unit": "%",
|
||||
"output_type": OutputType.INTEGER,
|
||||
},
|
||||
"activity_score": {
|
||||
"type": PlaceholderType.ATOMIC,
|
||||
"semantic_contract": "Activity Score basierend auf Trainingsfrequenz, Qualitätssessions (0-100)",
|
||||
"unit": "%",
|
||||
"output_type": OutputType.INTEGER,
|
||||
},
|
||||
"recovery_score": {
|
||||
"type": PlaceholderType.ATOMIC,
|
||||
"semantic_contract": "Recovery Score basierend auf Schlaf, HRV, Ruhepuls (0-100)",
|
||||
"unit": "%",
|
||||
"output_type": OutputType.INTEGER,
|
||||
},
|
||||
|
||||
# ── Correlations ──────────────────────────────────────────────────────
|
||||
"correlation_energy_weight_lag": {
|
||||
"type": PlaceholderType.INTERPRETED,
|
||||
"output_type": OutputType.JSON,
|
||||
"semantic_contract": "Lag-Korrelation zwischen Energiebilanz und Gewichtsänderung (3d/7d/14d)",
|
||||
},
|
||||
"correlation_protein_lbm": {
|
||||
"type": PlaceholderType.INTERPRETED,
|
||||
"output_type": OutputType.JSON,
|
||||
"semantic_contract": "Korrelation zwischen Proteinaufnahme und Magermasse-Änderung",
|
||||
},
|
||||
"plateau_detected": {
|
||||
"type": PlaceholderType.INTERPRETED,
|
||||
"output_type": OutputType.JSON,
|
||||
"semantic_contract": "Plateau-Erkennung: Gewichtsstagnation trotz Kaloriendefizit",
|
||||
},
|
||||
"top_drivers": {
|
||||
"type": PlaceholderType.INTERPRETED,
|
||||
"output_type": OutputType.JSON,
|
||||
"semantic_contract": "Top Einflussfaktoren auf Ziel-Fortschritt (sortiert nach Impact)",
|
||||
},
|
||||
}
|
||||
|
||||
for key, updates in corrections.items():
|
||||
metadata = registry.get(key)
|
||||
if metadata:
|
||||
for field, value in updates.items():
|
||||
setattr(metadata, field, value)
|
||||
|
||||
return registry
|
||||
|
||||
|
||||
def export_complete_metadata(registry, output_path: str = None):
|
||||
"""
|
||||
Export complete metadata to JSON file.
|
||||
|
||||
Args:
|
||||
registry: PlaceholderMetadataRegistry
|
||||
output_path: Optional output file path
|
||||
"""
|
||||
all_metadata = registry.get_all()
|
||||
|
||||
# Convert to dict
|
||||
export_data = {
|
||||
"schema_version": "1.0.0",
|
||||
"generated_at": "2026-03-29T12:00:00Z",
|
||||
"total_placeholders": len(all_metadata),
|
||||
"placeholders": {}
|
||||
}
|
||||
|
||||
for key, metadata in all_metadata.items():
|
||||
export_data["placeholders"][key] = metadata.to_dict()
|
||||
|
||||
# Write to file
|
||||
if not output_path:
|
||||
output_path = Path(__file__).parent.parent / "docs" / "placeholder_metadata_complete.json"
|
||||
|
||||
output_path = Path(output_path)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with open(output_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(export_data, f, indent=2, ensure_ascii=False)
|
||||
|
||||
print(f"✓ Exported complete metadata to: {output_path}")
|
||||
return output_path
|
||||
|
||||
|
||||
def generate_gap_report(registry):
|
||||
"""
|
||||
Generate gap report showing unresolved metadata fields.
|
||||
"""
|
||||
gaps = {
|
||||
"unknown_time_window": [],
|
||||
"unknown_output_type": [],
|
||||
"legacy_unknown_type": [],
|
||||
"missing_semantic_contract": [],
|
||||
"missing_data_layer_module": [],
|
||||
"missing_source_tables": [],
|
||||
"validation_issues": [],
|
||||
}
|
||||
|
||||
for key, metadata in registry.get_all().items():
|
||||
if metadata.time_window == TimeWindow.UNKNOWN:
|
||||
gaps["unknown_time_window"].append(key)
|
||||
if metadata.output_type == OutputType.UNKNOWN:
|
||||
gaps["unknown_output_type"].append(key)
|
||||
if metadata.type == PlaceholderType.LEGACY_UNKNOWN:
|
||||
gaps["legacy_unknown_type"].append(key)
|
||||
if not metadata.semantic_contract or metadata.semantic_contract == metadata.description:
|
||||
gaps["missing_semantic_contract"].append(key)
|
||||
if not metadata.source.data_layer_module:
|
||||
gaps["missing_data_layer_module"].append(key)
|
||||
if not metadata.source.source_tables:
|
||||
gaps["missing_source_tables"].append(key)
|
||||
|
||||
# Validation
|
||||
violations = registry.validate_all()
|
||||
for key, issues in violations.items():
|
||||
error_count = len([i for i in issues if i.severity == "error"])
|
||||
if error_count > 0:
|
||||
gaps["validation_issues"].append(key)
|
||||
|
||||
return gaps
|
||||
|
||||
|
||||
def print_summary(registry, gaps):
|
||||
"""Print summary statistics."""
|
||||
all_metadata = registry.get_all()
|
||||
total = len(all_metadata)
|
||||
|
||||
# Count by type
|
||||
by_type = {}
|
||||
for metadata in all_metadata.values():
|
||||
ptype = metadata.type.value
|
||||
by_type[ptype] = by_type.get(ptype, 0) + 1
|
||||
|
||||
# Count by category
|
||||
by_category = {}
|
||||
for metadata in all_metadata.values():
|
||||
cat = metadata.category
|
||||
by_category[cat] = by_category.get(cat, 0) + 1
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("PLACEHOLDER METADATA EXTRACTION SUMMARY")
|
||||
print("="*60)
|
||||
print(f"\nTotal Placeholders: {total}")
|
||||
print(f"\nBy Type:")
|
||||
for ptype, count in sorted(by_type.items()):
|
||||
print(f" {ptype:20} {count:3} ({count/total*100:5.1f}%)")
|
||||
|
||||
print(f"\nBy Category:")
|
||||
for cat, count in sorted(by_category.items()):
|
||||
print(f" {cat:20} {count:3} ({count/total*100:5.1f}%)")
|
||||
|
||||
print(f"\nGaps & Unresolved Fields:")
|
||||
for gap_type, placeholders in gaps.items():
|
||||
if placeholders:
|
||||
print(f" {gap_type:30} {len(placeholders):3} placeholders")
|
||||
|
||||
# Coverage score
|
||||
gap_count = sum(len(v) for v in gaps.values())
|
||||
coverage = (1 - gap_count / (total * 6)) * 100 # 6 gap types
|
||||
print(f"\n Metadata Coverage: {coverage:5.1f}%")
|
||||
|
||||
|
||||
# ── Main ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
def main():
|
||||
"""Main execution function."""
|
||||
print("Building complete placeholder metadata registry...")
|
||||
print("(This requires database access)")
|
||||
|
||||
try:
|
||||
# Build registry with automatic extraction
|
||||
registry = build_complete_metadata_registry()
|
||||
|
||||
# Apply manual corrections
|
||||
print("\nApplying manual corrections...")
|
||||
registry = apply_manual_corrections(registry)
|
||||
|
||||
# Generate gap report
|
||||
print("\nGenerating gap report...")
|
||||
gaps = generate_gap_report(registry)
|
||||
|
||||
# Print summary
|
||||
print_summary(registry, gaps)
|
||||
|
||||
# Export to JSON
|
||||
print("\nExporting complete metadata...")
|
||||
output_path = export_complete_metadata(registry)
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("✓ COMPLETE")
|
||||
print("="*60)
|
||||
print(f"\nNext steps:")
|
||||
print(f"1. Review gaps in gap report")
|
||||
print(f"2. Manually fill remaining unresolved fields")
|
||||
print(f"3. Run validation: python -m backend.placeholder_metadata_complete")
|
||||
print(f"4. Generate catalog files: python -m backend.generate_placeholder_catalog")
|
||||
|
||||
return 0
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n✗ ERROR: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,333 @@
|
||||
"""
|
||||
Complete Metadata Generation V2 - Quality Assured
|
||||
|
||||
This version applies strict quality controls and enhanced extraction logic.
|
||||
"""
|
||||
import sys
|
||||
import json
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
|
||||
from placeholder_metadata import (
|
||||
PlaceholderType,
|
||||
TimeWindow,
|
||||
OutputType,
|
||||
SourceInfo,
|
||||
QualityFilterPolicy,
|
||||
ConfidenceLogic,
|
||||
METADATA_REGISTRY
|
||||
)
|
||||
from placeholder_metadata_extractor import build_complete_metadata_registry
|
||||
from placeholder_metadata_enhanced import (
|
||||
extract_value_raw,
|
||||
infer_unit_strict,
|
||||
detect_time_window_precise,
|
||||
resolve_real_source,
|
||||
create_activity_quality_policy,
|
||||
create_confidence_logic,
|
||||
calculate_completeness_score
|
||||
)
|
||||
|
||||
|
||||
def apply_enhanced_corrections(registry):
|
||||
"""
|
||||
Apply enhanced corrections with strict quality controls.
|
||||
|
||||
This replaces heuristic guessing with deterministic derivation.
|
||||
"""
|
||||
all_metadata = registry.get_all()
|
||||
|
||||
for key, metadata in all_metadata.items():
|
||||
unresolved = []
|
||||
|
||||
# ── 1. Fix value_raw ──────────────────────────────────────────────────
|
||||
if metadata.value_display and metadata.value_display not in ['nicht verfügbar', '']:
|
||||
raw_val, success = extract_value_raw(
|
||||
metadata.value_display,
|
||||
metadata.output_type,
|
||||
metadata.type
|
||||
)
|
||||
if success:
|
||||
metadata.value_raw = raw_val
|
||||
else:
|
||||
metadata.value_raw = None
|
||||
unresolved.append('value_raw')
|
||||
|
||||
# ── 2. Fix unit (strict) ──────────────────────────────────────────────
|
||||
strict_unit = infer_unit_strict(
|
||||
key,
|
||||
metadata.description,
|
||||
metadata.output_type,
|
||||
metadata.type
|
||||
)
|
||||
# Only overwrite if we have a confident answer or existing is clearly wrong
|
||||
if strict_unit is not None:
|
||||
metadata.unit = strict_unit
|
||||
elif metadata.output_type in [OutputType.JSON, OutputType.MARKDOWN, OutputType.ENUM]:
|
||||
metadata.unit = None # These never have units
|
||||
elif 'score' in key.lower() or 'correlation' in key.lower():
|
||||
metadata.unit = None # Dimensionless
|
||||
|
||||
# ── 3. Fix time_window (precise detection) ────────────────────────────
|
||||
tw, is_certain, mismatch = detect_time_window_precise(
|
||||
key,
|
||||
metadata.description,
|
||||
metadata.source.resolver,
|
||||
metadata.semantic_contract
|
||||
)
|
||||
|
||||
if is_certain:
|
||||
metadata.time_window = tw
|
||||
if mismatch:
|
||||
metadata.legacy_contract_mismatch = True
|
||||
if mismatch not in metadata.known_issues:
|
||||
metadata.known_issues.append(mismatch)
|
||||
else:
|
||||
metadata.time_window = tw
|
||||
if tw == TimeWindow.UNKNOWN:
|
||||
unresolved.append('time_window')
|
||||
else:
|
||||
# Inferred but not certain
|
||||
if mismatch and mismatch not in metadata.notes:
|
||||
metadata.notes.append(f"Time window inferred: {mismatch}")
|
||||
|
||||
# ── 4. Fix source provenance ──────────────────────────────────────────
|
||||
func, dl_module, tables, source_kind = resolve_real_source(metadata.source.resolver)
|
||||
|
||||
if func:
|
||||
metadata.source.function = func
|
||||
if dl_module:
|
||||
metadata.source.data_layer_module = dl_module
|
||||
if tables:
|
||||
metadata.source.source_tables = tables
|
||||
metadata.source.source_kind = source_kind
|
||||
|
||||
if source_kind == "wrapper" or source_kind == "unknown":
|
||||
unresolved.append('source')
|
||||
|
||||
# ── 5. Add quality_filter_policy for activity placeholders ────────────
|
||||
if not metadata.quality_filter_policy:
|
||||
qfp = create_activity_quality_policy(key)
|
||||
if qfp:
|
||||
metadata.quality_filter_policy = qfp
|
||||
|
||||
# ── 6. Add confidence_logic ────────────────────────────────────────────
|
||||
if not metadata.confidence_logic:
|
||||
cl = create_confidence_logic(key, metadata.source.data_layer_module)
|
||||
if cl:
|
||||
metadata.confidence_logic = cl
|
||||
|
||||
# ── 7. Determine provenance_confidence ────────────────────────────────
|
||||
if metadata.source.data_layer_module and metadata.source.source_tables:
|
||||
metadata.provenance_confidence = "high"
|
||||
elif metadata.source.function or metadata.source.source_tables:
|
||||
metadata.provenance_confidence = "medium"
|
||||
else:
|
||||
metadata.provenance_confidence = "low"
|
||||
|
||||
# ── 8. Determine contract_source ───────────────────────────────────────
|
||||
if metadata.semantic_contract and len(metadata.semantic_contract) > 50:
|
||||
metadata.contract_source = "documented"
|
||||
elif metadata.description:
|
||||
metadata.contract_source = "inferred"
|
||||
else:
|
||||
metadata.contract_source = "unknown"
|
||||
|
||||
# ── 9. Check for orphaned placeholders ────────────────────────────────
|
||||
if not metadata.used_by.prompts and not metadata.used_by.pipelines and not metadata.used_by.charts:
|
||||
metadata.orphaned_placeholder = True
|
||||
|
||||
# ── 10. Set unresolved fields ──────────────────────────────────────────
|
||||
metadata.unresolved_fields = unresolved
|
||||
|
||||
# ── 11. Calculate completeness score ───────────────────────────────────
|
||||
metadata.metadata_completeness_score = calculate_completeness_score(metadata.to_dict())
|
||||
|
||||
# ── 12. Set schema status ──────────────────────────────────────────────
|
||||
if metadata.metadata_completeness_score >= 80 and len(unresolved) == 0:
|
||||
metadata.schema_status = "validated"
|
||||
elif metadata.metadata_completeness_score >= 50:
|
||||
metadata.schema_status = "draft"
|
||||
else:
|
||||
metadata.schema_status = "incomplete"
|
||||
|
||||
return registry
|
||||
|
||||
|
||||
def generate_qa_report(registry) -> str:
|
||||
"""
|
||||
Generate QA report with quality metrics.
|
||||
"""
|
||||
all_metadata = registry.get_all()
|
||||
total = len(all_metadata)
|
||||
|
||||
# Collect metrics
|
||||
category_unknown = sum(1 for m in all_metadata.values() if m.category == "Unknown")
|
||||
no_description = sum(1 for m in all_metadata.values() if not m.description or "No description" in m.description)
|
||||
tw_unknown = sum(1 for m in all_metadata.values() if m.time_window == TimeWindow.UNKNOWN)
|
||||
no_quality_filter = sum(1 for m in all_metadata.values() if not m.quality_filter_policy and 'activity' in m.key.lower())
|
||||
no_confidence = sum(1 for m in all_metadata.values() if not m.confidence_logic and m.source.data_layer_module)
|
||||
legacy_mismatch = sum(1 for m in all_metadata.values() if m.legacy_contract_mismatch)
|
||||
orphaned = sum(1 for m in all_metadata.values() if m.orphaned_placeholder)
|
||||
|
||||
# Find problematic placeholders
|
||||
problematic = []
|
||||
for key, m in all_metadata.items():
|
||||
score = m.metadata_completeness_score
|
||||
unresolved_count = len(m.unresolved_fields)
|
||||
issues_count = len(m.known_issues)
|
||||
|
||||
problem_score = (100 - score) + (unresolved_count * 10) + (issues_count * 5)
|
||||
if problem_score > 0:
|
||||
problematic.append((key, problem_score, score, unresolved_count, issues_count))
|
||||
|
||||
problematic.sort(key=lambda x: x[1], reverse=True)
|
||||
|
||||
# Build report
|
||||
lines = [
|
||||
"# Placeholder Metadata QA Report",
|
||||
"",
|
||||
f"**Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
|
||||
f"**Total Placeholders:** {total}",
|
||||
"",
|
||||
"## Quality Metrics",
|
||||
"",
|
||||
f"- **Category Unknown:** {category_unknown} ({category_unknown/total*100:.1f}%)",
|
||||
f"- **No Description:** {no_description} ({no_description/total*100:.1f}%)",
|
||||
f"- **Time Window Unknown:** {tw_unknown} ({tw_unknown/total*100:.1f}%)",
|
||||
f"- **Activity without Quality Filter:** {no_quality_filter}",
|
||||
f"- **Data Layer without Confidence Logic:** {no_confidence}",
|
||||
f"- **Legacy/Implementation Mismatch:** {legacy_mismatch}",
|
||||
f"- **Orphaned (unused):** {orphaned}",
|
||||
"",
|
||||
"## Completeness Distribution",
|
||||
"",
|
||||
]
|
||||
|
||||
# Completeness buckets
|
||||
buckets = {
|
||||
"90-100%": sum(1 for m in all_metadata.values() if m.metadata_completeness_score >= 90),
|
||||
"70-89%": sum(1 for m in all_metadata.values() if 70 <= m.metadata_completeness_score < 90),
|
||||
"50-69%": sum(1 for m in all_metadata.values() if 50 <= m.metadata_completeness_score < 70),
|
||||
"0-49%": sum(1 for m in all_metadata.values() if m.metadata_completeness_score < 50),
|
||||
}
|
||||
|
||||
for bucket, count in buckets.items():
|
||||
lines.append(f"- **{bucket}:** {count} placeholders ({count/total*100:.1f}%)")
|
||||
|
||||
lines.append("")
|
||||
lines.append("## Top 20 Most Problematic Placeholders")
|
||||
lines.append("")
|
||||
lines.append("| Rank | Placeholder | Completeness | Unresolved | Issues |")
|
||||
lines.append("|------|-------------|--------------|------------|--------|")
|
||||
|
||||
for i, (key, _, score, unresolved_count, issues_count) in enumerate(problematic[:20], 1):
|
||||
lines.append(f"| {i} | `{{{{{key}}}}}` | {score}% | {unresolved_count} | {issues_count} |")
|
||||
|
||||
lines.append("")
|
||||
lines.append("## Schema Status Distribution")
|
||||
lines.append("")
|
||||
|
||||
status_counts = {}
|
||||
for m in all_metadata.values():
|
||||
status_counts[m.schema_status] = status_counts.get(m.schema_status, 0) + 1
|
||||
|
||||
for status, count in sorted(status_counts.items()):
|
||||
lines.append(f"- **{status}:** {count} ({count/total*100:.1f}%)")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def generate_unresolved_report(registry) -> dict:
|
||||
"""
|
||||
Generate unresolved fields report as JSON.
|
||||
"""
|
||||
all_metadata = registry.get_all()
|
||||
|
||||
unresolved_by_placeholder = {}
|
||||
unresolved_by_field = {}
|
||||
|
||||
for key, m in all_metadata.items():
|
||||
if m.unresolved_fields:
|
||||
unresolved_by_placeholder[key] = m.unresolved_fields
|
||||
|
||||
for field in m.unresolved_fields:
|
||||
if field not in unresolved_by_field:
|
||||
unresolved_by_field[field] = []
|
||||
unresolved_by_field[field].append(key)
|
||||
|
||||
return {
|
||||
"generated_at": datetime.now().isoformat(),
|
||||
"total_placeholders_with_unresolved": len(unresolved_by_placeholder),
|
||||
"by_placeholder": unresolved_by_placeholder,
|
||||
"by_field": unresolved_by_field,
|
||||
"summary": {
|
||||
field: len(placeholders)
|
||||
for field, placeholders in unresolved_by_field.items()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
"""Main execution."""
|
||||
print("="*60)
|
||||
print("ENHANCED PLACEHOLDER METADATA GENERATION V2")
|
||||
print("="*60)
|
||||
print()
|
||||
|
||||
try:
|
||||
# Build registry
|
||||
print("Building metadata registry...")
|
||||
registry = build_complete_metadata_registry()
|
||||
print(f"Loaded {registry.count()} placeholders")
|
||||
print()
|
||||
|
||||
# Apply enhanced corrections
|
||||
print("Applying enhanced corrections...")
|
||||
registry = apply_enhanced_corrections(registry)
|
||||
print("Enhanced corrections applied")
|
||||
print()
|
||||
|
||||
# Generate reports
|
||||
print("Generating QA report...")
|
||||
qa_report = generate_qa_report(registry)
|
||||
qa_path = Path(__file__).parent.parent / "docs" / "PLACEHOLDER_METADATA_QA_REPORT.md"
|
||||
with open(qa_path, 'w', encoding='utf-8') as f:
|
||||
f.write(qa_report)
|
||||
print(f"QA Report: {qa_path}")
|
||||
|
||||
print("Generating unresolved report...")
|
||||
unresolved = generate_unresolved_report(registry)
|
||||
unresolved_path = Path(__file__).parent.parent / "docs" / "PLACEHOLDER_METADATA_UNRESOLVED.json"
|
||||
with open(unresolved_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(unresolved, f, indent=2, ensure_ascii=False)
|
||||
print(f"Unresolved Report: {unresolved_path}")
|
||||
|
||||
# Summary
|
||||
all_metadata = registry.get_all()
|
||||
avg_completeness = sum(m.metadata_completeness_score for m in all_metadata.values()) / len(all_metadata)
|
||||
validated_count = sum(1 for m in all_metadata.values() if m.schema_status == "validated")
|
||||
|
||||
print()
|
||||
print("="*60)
|
||||
print("SUMMARY")
|
||||
print("="*60)
|
||||
print(f"Total Placeholders: {len(all_metadata)}")
|
||||
print(f"Average Completeness: {avg_completeness:.1f}%")
|
||||
print(f"Validated: {validated_count} ({validated_count/len(all_metadata)*100:.1f}%)")
|
||||
print(f"Time Window Unknown: {sum(1 for m in all_metadata.values() if m.time_window == TimeWindow.UNKNOWN)}")
|
||||
print(f"Orphaned: {sum(1 for m in all_metadata.values() if m.orphaned_placeholder)}")
|
||||
|
||||
return 0
|
||||
|
||||
except Exception as e:
|
||||
print(f"\nERROR: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,530 @@
|
||||
"""
|
||||
Placeholder Catalog Generator
|
||||
|
||||
Generates comprehensive documentation for all placeholders:
|
||||
1. PLACEHOLDER_CATALOG_EXTENDED.json - Machine-readable full metadata
|
||||
2. PLACEHOLDER_CATALOG_EXTENDED.md - Human-readable catalog
|
||||
3. PLACEHOLDER_GAP_REPORT.md - Technical gaps and issues
|
||||
4. PLACEHOLDER_EXPORT_SPEC.md - Export format specification
|
||||
|
||||
This implements the normative standard for placeholder documentation.
|
||||
"""
|
||||
import sys
|
||||
import json
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
from typing import Dict, List, Any
|
||||
|
||||
# Add backend to path
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
|
||||
from placeholder_metadata import (
|
||||
PlaceholderMetadata,
|
||||
PlaceholderType,
|
||||
TimeWindow,
|
||||
OutputType,
|
||||
METADATA_REGISTRY
|
||||
)
|
||||
from placeholder_metadata_extractor import build_complete_metadata_registry
|
||||
from generate_complete_metadata import apply_manual_corrections, generate_gap_report
|
||||
|
||||
|
||||
# ── 1. JSON Catalog ───────────────────────────────────────────────────────────
|
||||
|
||||
def generate_json_catalog(registry, output_dir: Path):
|
||||
"""Generate PLACEHOLDER_CATALOG_EXTENDED.json"""
|
||||
all_metadata = registry.get_all()
|
||||
|
||||
catalog = {
|
||||
"schema_version": "1.0.0",
|
||||
"generated_at": datetime.now().isoformat(),
|
||||
"normative_standard": "PLACEHOLDER_METADATA_REQUIREMENTS_V2_NORMATIVE.md",
|
||||
"total_placeholders": len(all_metadata),
|
||||
"placeholders": {}
|
||||
}
|
||||
|
||||
for key, metadata in sorted(all_metadata.items()):
|
||||
catalog["placeholders"][key] = metadata.to_dict()
|
||||
|
||||
output_path = output_dir / "PLACEHOLDER_CATALOG_EXTENDED.json"
|
||||
with open(output_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(catalog, f, indent=2, ensure_ascii=False)
|
||||
|
||||
print(f"Generated: {output_path}")
|
||||
return output_path
|
||||
|
||||
|
||||
# ── 2. Markdown Catalog ───────────────────────────────────────────────────────
|
||||
|
||||
def generate_markdown_catalog(registry, output_dir: Path):
|
||||
"""Generate PLACEHOLDER_CATALOG_EXTENDED.md"""
|
||||
all_metadata = registry.get_all()
|
||||
by_category = registry.get_by_category()
|
||||
|
||||
md = []
|
||||
md.append("# Placeholder Catalog (Extended)")
|
||||
md.append("")
|
||||
md.append(f"**Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
md.append(f"**Total Placeholders:** {len(all_metadata)}")
|
||||
md.append(f"**Normative Standard:** PLACEHOLDER_METADATA_REQUIREMENTS_V2_NORMATIVE.md")
|
||||
md.append("")
|
||||
md.append("---")
|
||||
md.append("")
|
||||
|
||||
# Summary Statistics
|
||||
md.append("## Summary Statistics")
|
||||
md.append("")
|
||||
|
||||
# By Type
|
||||
by_type = {}
|
||||
for metadata in all_metadata.values():
|
||||
ptype = metadata.type.value
|
||||
by_type[ptype] = by_type.get(ptype, 0) + 1
|
||||
|
||||
md.append("### By Type")
|
||||
md.append("")
|
||||
md.append("| Type | Count | Percentage |")
|
||||
md.append("|------|-------|------------|")
|
||||
for ptype, count in sorted(by_type.items()):
|
||||
pct = count / len(all_metadata) * 100
|
||||
md.append(f"| {ptype} | {count} | {pct:.1f}% |")
|
||||
md.append("")
|
||||
|
||||
# By Category
|
||||
md.append("### By Category")
|
||||
md.append("")
|
||||
md.append("| Category | Count |")
|
||||
md.append("|----------|-------|")
|
||||
for category, metadata_list in sorted(by_category.items()):
|
||||
md.append(f"| {category} | {len(metadata_list)} |")
|
||||
md.append("")
|
||||
|
||||
md.append("---")
|
||||
md.append("")
|
||||
|
||||
# Detailed Catalog by Category
|
||||
md.append("## Detailed Placeholder Catalog")
|
||||
md.append("")
|
||||
|
||||
for category, metadata_list in sorted(by_category.items()):
|
||||
md.append(f"### {category} ({len(metadata_list)} placeholders)")
|
||||
md.append("")
|
||||
|
||||
for metadata in sorted(metadata_list, key=lambda m: m.key):
|
||||
md.append(f"#### `{{{{{metadata.key}}}}}`")
|
||||
md.append("")
|
||||
md.append(f"**Description:** {metadata.description}")
|
||||
md.append("")
|
||||
md.append(f"**Semantic Contract:** {metadata.semantic_contract}")
|
||||
md.append("")
|
||||
|
||||
# Metadata table
|
||||
md.append("| Property | Value |")
|
||||
md.append("|----------|-------|")
|
||||
md.append(f"| Type | `{metadata.type.value}` |")
|
||||
md.append(f"| Time Window | `{metadata.time_window.value}` |")
|
||||
md.append(f"| Output Type | `{metadata.output_type.value}` |")
|
||||
md.append(f"| Unit | {metadata.unit or 'None'} |")
|
||||
md.append(f"| Format Hint | {metadata.format_hint or 'None'} |")
|
||||
md.append(f"| Version | {metadata.version} |")
|
||||
md.append(f"| Deprecated | {metadata.deprecated} |")
|
||||
md.append("")
|
||||
|
||||
# Source
|
||||
md.append("**Source:**")
|
||||
md.append(f"- Resolver: `{metadata.source.resolver}`")
|
||||
md.append(f"- Module: `{metadata.source.module}`")
|
||||
if metadata.source.function:
|
||||
md.append(f"- Function: `{metadata.source.function}`")
|
||||
if metadata.source.data_layer_module:
|
||||
md.append(f"- Data Layer: `{metadata.source.data_layer_module}`")
|
||||
if metadata.source.source_tables:
|
||||
tables = ", ".join([f"`{t}`" for t in metadata.source.source_tables])
|
||||
md.append(f"- Tables: {tables}")
|
||||
md.append("")
|
||||
|
||||
# Known Issues
|
||||
if metadata.known_issues:
|
||||
md.append("**Known Issues:**")
|
||||
for issue in metadata.known_issues:
|
||||
md.append(f"- {issue}")
|
||||
md.append("")
|
||||
|
||||
# Notes
|
||||
if metadata.notes:
|
||||
md.append("**Notes:**")
|
||||
for note in metadata.notes:
|
||||
md.append(f"- {note}")
|
||||
md.append("")
|
||||
|
||||
md.append("---")
|
||||
md.append("")
|
||||
|
||||
output_path = output_dir / "PLACEHOLDER_CATALOG_EXTENDED.md"
|
||||
with open(output_path, 'w', encoding='utf-8') as f:
|
||||
f.write("\n".join(md))
|
||||
|
||||
print(f"Generated: {output_path}")
|
||||
return output_path
|
||||
|
||||
|
||||
# ── 3. Gap Report ─────────────────────────────────────────────────────────────
|
||||
|
||||
def generate_gap_report_md(registry, gaps: Dict, output_dir: Path):
|
||||
"""Generate PLACEHOLDER_GAP_REPORT.md"""
|
||||
all_metadata = registry.get_all()
|
||||
total = len(all_metadata)
|
||||
|
||||
md = []
|
||||
md.append("# Placeholder Metadata Gap Report")
|
||||
md.append("")
|
||||
md.append(f"**Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
md.append(f"**Total Placeholders:** {total}")
|
||||
md.append("")
|
||||
md.append("This report identifies placeholders with incomplete or unresolved metadata fields.")
|
||||
md.append("")
|
||||
md.append("---")
|
||||
md.append("")
|
||||
|
||||
# Summary
|
||||
gap_count = sum(len(v) for v in gaps.values())
|
||||
coverage = (1 - gap_count / (total * 6)) * 100 # 6 gap types
|
||||
|
||||
md.append("## Summary")
|
||||
md.append("")
|
||||
md.append(f"- **Total Gap Instances:** {gap_count}")
|
||||
md.append(f"- **Metadata Coverage:** {coverage:.1f}%")
|
||||
md.append("")
|
||||
|
||||
# Detailed Gaps
|
||||
md.append("## Detailed Gap Analysis")
|
||||
md.append("")
|
||||
|
||||
for gap_type, placeholders in sorted(gaps.items()):
|
||||
if not placeholders:
|
||||
continue
|
||||
|
||||
md.append(f"### {gap_type.replace('_', ' ').title()}")
|
||||
md.append("")
|
||||
md.append(f"**Count:** {len(placeholders)}")
|
||||
md.append("")
|
||||
|
||||
# Get category for each placeholder
|
||||
by_cat = {}
|
||||
for key in placeholders:
|
||||
metadata = registry.get(key)
|
||||
if metadata:
|
||||
cat = metadata.category
|
||||
if cat not in by_cat:
|
||||
by_cat[cat] = []
|
||||
by_cat[cat].append(key)
|
||||
|
||||
for category, keys in sorted(by_cat.items()):
|
||||
md.append(f"#### {category}")
|
||||
md.append("")
|
||||
for key in sorted(keys):
|
||||
md.append(f"- `{{{{{key}}}}}`")
|
||||
md.append("")
|
||||
|
||||
# Recommendations
|
||||
md.append("---")
|
||||
md.append("")
|
||||
md.append("## Recommendations")
|
||||
md.append("")
|
||||
|
||||
if gaps.get('unknown_time_window'):
|
||||
md.append("### Time Window Resolution")
|
||||
md.append("")
|
||||
md.append("Placeholders with unknown time windows should be analyzed to determine:")
|
||||
md.append("- Whether they use `latest`, `7d`, `28d`, `30d`, `90d`, or `custom`")
|
||||
md.append("- Document in semantic_contract if time window is variable")
|
||||
md.append("")
|
||||
|
||||
if gaps.get('legacy_unknown_type'):
|
||||
md.append("### Type Classification")
|
||||
md.append("")
|
||||
md.append("Placeholders with `legacy_unknown` type should be classified as:")
|
||||
md.append("- `atomic` - Single atomic value")
|
||||
md.append("- `raw_data` - Structured raw data (JSON, lists)")
|
||||
md.append("- `interpreted` - AI-interpreted or derived values")
|
||||
md.append("")
|
||||
|
||||
if gaps.get('missing_data_layer_module'):
|
||||
md.append("### Data Layer Tracking")
|
||||
md.append("")
|
||||
md.append("Placeholders without data_layer_module should be investigated:")
|
||||
md.append("- Check if they call data_layer functions")
|
||||
md.append("- Document direct database access if no data_layer function exists")
|
||||
md.append("")
|
||||
|
||||
output_path = output_dir / "PLACEHOLDER_GAP_REPORT.md"
|
||||
with open(output_path, 'w', encoding='utf-8') as f:
|
||||
f.write("\n".join(md))
|
||||
|
||||
print(f"Generated: {output_path}")
|
||||
return output_path
|
||||
|
||||
|
||||
# ── 4. Export Spec ────────────────────────────────────────────────────────────
|
||||
|
||||
def generate_export_spec_md(output_dir: Path):
|
||||
"""Generate PLACEHOLDER_EXPORT_SPEC.md"""
|
||||
md = []
|
||||
md.append("# Placeholder Export Specification")
|
||||
md.append("")
|
||||
md.append(f"**Version:** 1.0.0")
|
||||
md.append(f"**Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
md.append(f"**Normative Standard:** PLACEHOLDER_METADATA_REQUIREMENTS_V2_NORMATIVE.md")
|
||||
md.append("")
|
||||
md.append("---")
|
||||
md.append("")
|
||||
|
||||
# Overview
|
||||
md.append("## Overview")
|
||||
md.append("")
|
||||
md.append("The Placeholder Export API provides two endpoints:")
|
||||
md.append("")
|
||||
md.append("1. **Legacy Export** (`/api/prompts/placeholders/export-values`)")
|
||||
md.append(" - Backward-compatible format")
|
||||
md.append(" - Simple key-value pairs")
|
||||
md.append(" - Organized by category")
|
||||
md.append("")
|
||||
md.append("2. **Extended Export** (`/api/prompts/placeholders/export-values-extended`)")
|
||||
md.append(" - Complete normative metadata")
|
||||
md.append(" - Runtime value resolution")
|
||||
md.append(" - Gap analysis")
|
||||
md.append(" - Validation results")
|
||||
md.append("")
|
||||
|
||||
# Extended Export Format
|
||||
md.append("## Extended Export Format")
|
||||
md.append("")
|
||||
md.append("### Root Structure")
|
||||
md.append("")
|
||||
md.append("```json")
|
||||
md.append("{")
|
||||
md.append(' "schema_version": "1.0.0",')
|
||||
md.append(' "export_date": "2026-03-29T12:00:00Z",')
|
||||
md.append(' "profile_id": "user-123",')
|
||||
md.append(' "legacy": { ... },')
|
||||
md.append(' "metadata": { ... },')
|
||||
md.append(' "validation": { ... }')
|
||||
md.append("}")
|
||||
md.append("```")
|
||||
md.append("")
|
||||
|
||||
# Legacy Section
|
||||
md.append("### Legacy Section")
|
||||
md.append("")
|
||||
md.append("Maintains backward compatibility with existing export consumers.")
|
||||
md.append("")
|
||||
md.append("```json")
|
||||
md.append('"legacy": {')
|
||||
md.append(' "all_placeholders": {')
|
||||
md.append(' "weight_aktuell": "85.8 kg",')
|
||||
md.append(' "name": "Max Mustermann",')
|
||||
md.append(' ...')
|
||||
md.append(' },')
|
||||
md.append(' "placeholders_by_category": {')
|
||||
md.append(' "Körper": [')
|
||||
md.append(' {')
|
||||
md.append(' "key": "{{weight_aktuell}}",')
|
||||
md.append(' "description": "Aktuelles Gewicht in kg",')
|
||||
md.append(' "value": "85.8 kg",')
|
||||
md.append(' "example": "85.8 kg"')
|
||||
md.append(' },')
|
||||
md.append(' ...')
|
||||
md.append(' ],')
|
||||
md.append(' ...')
|
||||
md.append(' },')
|
||||
md.append(' "count": 116')
|
||||
md.append('}')
|
||||
md.append("```")
|
||||
md.append("")
|
||||
|
||||
# Metadata Section
|
||||
md.append("### Metadata Section")
|
||||
md.append("")
|
||||
md.append("Complete normative metadata for all placeholders.")
|
||||
md.append("")
|
||||
md.append("```json")
|
||||
md.append('"metadata": {')
|
||||
md.append(' "flat": [')
|
||||
md.append(' {')
|
||||
md.append(' "key": "weight_aktuell",')
|
||||
md.append(' "placeholder": "{{weight_aktuell}}",')
|
||||
md.append(' "category": "Körper",')
|
||||
md.append(' "type": "atomic",')
|
||||
md.append(' "description": "Aktuelles Gewicht in kg",')
|
||||
md.append(' "semantic_contract": "Letzter verfügbarer Gewichtseintrag...",')
|
||||
md.append(' "unit": "kg",')
|
||||
md.append(' "time_window": "latest",')
|
||||
md.append(' "output_type": "number",')
|
||||
md.append(' "format_hint": "85.8 kg",')
|
||||
md.append(' "value_display": "85.8 kg",')
|
||||
md.append(' "value_raw": 85.8,')
|
||||
md.append(' "available": true,')
|
||||
md.append(' "source": {')
|
||||
md.append(' "resolver": "get_latest_weight",')
|
||||
md.append(' "module": "placeholder_resolver.py",')
|
||||
md.append(' "function": "get_latest_weight_data",')
|
||||
md.append(' "data_layer_module": "body_metrics",')
|
||||
md.append(' "source_tables": ["weight_log"]')
|
||||
md.append(' },')
|
||||
md.append(' ...')
|
||||
md.append(' },')
|
||||
md.append(' ...')
|
||||
md.append(' ],')
|
||||
md.append(' "by_category": { ... },')
|
||||
md.append(' "summary": {')
|
||||
md.append(' "total_placeholders": 116,')
|
||||
md.append(' "available": 98,')
|
||||
md.append(' "missing": 18,')
|
||||
md.append(' "by_type": {')
|
||||
md.append(' "atomic": 85,')
|
||||
md.append(' "interpreted": 20,')
|
||||
md.append(' "raw_data": 8,')
|
||||
md.append(' "legacy_unknown": 3')
|
||||
md.append(' },')
|
||||
md.append(' "coverage": {')
|
||||
md.append(' "fully_resolved": 75,')
|
||||
md.append(' "partially_resolved": 30,')
|
||||
md.append(' "unresolved": 11')
|
||||
md.append(' }')
|
||||
md.append(' },')
|
||||
md.append(' "gaps": {')
|
||||
md.append(' "unknown_time_window": ["placeholder1", ...],')
|
||||
md.append(' "missing_semantic_contract": [...],')
|
||||
md.append(' ...')
|
||||
md.append(' }')
|
||||
md.append('}')
|
||||
md.append("```")
|
||||
md.append("")
|
||||
|
||||
# Validation Section
|
||||
md.append("### Validation Section")
|
||||
md.append("")
|
||||
md.append("Results of normative standard validation.")
|
||||
md.append("")
|
||||
md.append("```json")
|
||||
md.append('"validation": {')
|
||||
md.append(' "compliant": 89,')
|
||||
md.append(' "non_compliant": 27,')
|
||||
md.append(' "issues": [')
|
||||
md.append(' {')
|
||||
md.append(' "placeholder": "activity_summary",')
|
||||
md.append(' "violations": [')
|
||||
md.append(' {')
|
||||
md.append(' "field": "time_window",')
|
||||
md.append(' "issue": "Time window UNKNOWN should be resolved",')
|
||||
md.append(' "severity": "warning"')
|
||||
md.append(' }')
|
||||
md.append(' ]')
|
||||
md.append(' },')
|
||||
md.append(' ...')
|
||||
md.append(' ]')
|
||||
md.append('}')
|
||||
md.append("```")
|
||||
md.append("")
|
||||
|
||||
# Usage
|
||||
md.append("## API Usage")
|
||||
md.append("")
|
||||
md.append("### Legacy Export")
|
||||
md.append("")
|
||||
md.append("```bash")
|
||||
md.append("GET /api/prompts/placeholders/export-values")
|
||||
md.append("Header: X-Auth-Token: <token>")
|
||||
md.append("```")
|
||||
md.append("")
|
||||
|
||||
md.append("### Extended Export")
|
||||
md.append("")
|
||||
md.append("```bash")
|
||||
md.append("GET /api/prompts/placeholders/export-values-extended")
|
||||
md.append("Header: X-Auth-Token: <token>")
|
||||
md.append("```")
|
||||
md.append("")
|
||||
|
||||
# Standards Compliance
|
||||
md.append("## Standards Compliance")
|
||||
md.append("")
|
||||
md.append("The extended export implements the following normative requirements:")
|
||||
md.append("")
|
||||
md.append("1. **Non-Breaking:** Legacy export remains unchanged")
|
||||
md.append("2. **Complete Metadata:** All fields from normative standard")
|
||||
md.append("3. **Runtime Resolution:** Values resolved for current profile")
|
||||
md.append("4. **Gap Transparency:** Unresolved fields explicitly marked")
|
||||
md.append("5. **Validation:** Automated compliance checking")
|
||||
md.append("6. **Versioning:** Schema version for future evolution")
|
||||
md.append("")
|
||||
|
||||
output_path = output_dir / "PLACEHOLDER_EXPORT_SPEC.md"
|
||||
with open(output_path, 'w', encoding='utf-8') as f:
|
||||
f.write("\n".join(md))
|
||||
|
||||
print(f"Generated: {output_path}")
|
||||
return output_path
|
||||
|
||||
|
||||
# ── Main ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
def main():
|
||||
"""Main catalog generation function."""
|
||||
print("="*60)
|
||||
print("PLACEHOLDER CATALOG GENERATOR")
|
||||
print("="*60)
|
||||
print()
|
||||
|
||||
# Setup output directory
|
||||
output_dir = Path(__file__).parent.parent / "docs"
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
print(f"Output directory: {output_dir}")
|
||||
print()
|
||||
|
||||
try:
|
||||
# Build registry
|
||||
print("Building metadata registry...")
|
||||
registry = build_complete_metadata_registry()
|
||||
registry = apply_manual_corrections(registry)
|
||||
print(f"Loaded {registry.count()} placeholders")
|
||||
print()
|
||||
|
||||
# Generate gap report data
|
||||
print("Analyzing gaps...")
|
||||
gaps = generate_gap_report(registry)
|
||||
print()
|
||||
|
||||
# Generate all documentation files
|
||||
print("Generating documentation files...")
|
||||
print()
|
||||
|
||||
generate_json_catalog(registry, output_dir)
|
||||
generate_markdown_catalog(registry, output_dir)
|
||||
generate_gap_report_md(registry, gaps, output_dir)
|
||||
generate_export_spec_md(output_dir)
|
||||
|
||||
print()
|
||||
print("="*60)
|
||||
print("CATALOG GENERATION COMPLETE")
|
||||
print("="*60)
|
||||
print()
|
||||
print("Generated files:")
|
||||
print(f" 1. {output_dir}/PLACEHOLDER_CATALOG_EXTENDED.json")
|
||||
print(f" 2. {output_dir}/PLACEHOLDER_CATALOG_EXTENDED.md")
|
||||
print(f" 3. {output_dir}/PLACEHOLDER_GAP_REPORT.md")
|
||||
print(f" 4. {output_dir}/PLACEHOLDER_EXPORT_SPEC.md")
|
||||
print()
|
||||
|
||||
return 0
|
||||
|
||||
except Exception as e:
|
||||
print()
|
||||
print(f"ERROR: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,568 @@
|
||||
"""
|
||||
Goal Utilities - Abstraction Layer for Focus Weights & Universal Value Fetcher
|
||||
|
||||
This module provides:
|
||||
1. Abstraction layer between goal modes and focus weights (Phase 1)
|
||||
2. Universal value fetcher for dynamic goal types (Phase 1.5)
|
||||
|
||||
Version History:
|
||||
- V1 (Phase 1): Maps goal_mode to predefined weights
|
||||
- V1.5 (Phase 1.5): Universal value fetcher for DB-registry goal types
|
||||
- V2 (future): Reads from focus_areas table with custom user weights
|
||||
|
||||
Part of Phase 1 + Phase 1.5: Flexible Goal System
|
||||
"""
|
||||
|
||||
from typing import Dict, Optional, Any, List
|
||||
from datetime import date, timedelta
|
||||
from decimal import Decimal
|
||||
import json
|
||||
from db import get_cursor, get_db
|
||||
|
||||
|
||||
def get_focus_weights(conn, profile_id: str) -> Dict[str, float]:
|
||||
"""
|
||||
Get focus area weights for a profile.
|
||||
|
||||
V2 (Goal System v2.0): Reads from focus_areas table with custom user weights.
|
||||
Falls back to goal_mode mapping if focus_areas not set.
|
||||
|
||||
Args:
|
||||
conn: Database connection
|
||||
profile_id: User's profile ID
|
||||
|
||||
Returns:
|
||||
Dict with focus weights (sum = 1.0):
|
||||
{
|
||||
'weight_loss': 0.3, # Fat loss priority
|
||||
'muscle_gain': 0.2, # Muscle gain priority
|
||||
'strength': 0.25, # Strength training priority
|
||||
'endurance': 0.25, # Cardio/endurance priority
|
||||
'flexibility': 0.0, # Mobility priority
|
||||
'health': 0.0 # General health maintenance
|
||||
}
|
||||
|
||||
Example Usage in Phase 0b:
|
||||
weights = get_focus_weights(conn, profile_id)
|
||||
|
||||
# Score calculation considers user's focus
|
||||
overall_score = (
|
||||
body_score * weights['weight_loss'] +
|
||||
strength_score * weights['strength'] +
|
||||
cardio_score * weights['endurance']
|
||||
)
|
||||
"""
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# V2: Try to fetch from focus_areas table
|
||||
cur.execute("""
|
||||
SELECT weight_loss_pct, muscle_gain_pct, strength_pct,
|
||||
endurance_pct, flexibility_pct, health_pct
|
||||
FROM focus_areas
|
||||
WHERE profile_id = %s AND active = true
|
||||
LIMIT 1
|
||||
""", (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
|
||||
if row:
|
||||
# Convert percentages to weights (0-1 range)
|
||||
return {
|
||||
'weight_loss': row['weight_loss_pct'] / 100.0,
|
||||
'muscle_gain': row['muscle_gain_pct'] / 100.0,
|
||||
'strength': row['strength_pct'] / 100.0,
|
||||
'endurance': row['endurance_pct'] / 100.0,
|
||||
'flexibility': row['flexibility_pct'] / 100.0,
|
||||
'health': row['health_pct'] / 100.0
|
||||
}
|
||||
|
||||
# V1 Fallback: Use goal_mode if focus_areas not set
|
||||
cur.execute(
|
||||
"SELECT goal_mode FROM profiles WHERE id = %s",
|
||||
(profile_id,)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row:
|
||||
# Ultimate fallback: balanced health focus
|
||||
return {
|
||||
'weight_loss': 0.0,
|
||||
'muscle_gain': 0.0,
|
||||
'strength': 0.10,
|
||||
'endurance': 0.20,
|
||||
'flexibility': 0.15,
|
||||
'health': 0.55
|
||||
}
|
||||
|
||||
goal_mode = row['goal_mode']
|
||||
|
||||
if not goal_mode:
|
||||
return {
|
||||
'weight_loss': 0.0,
|
||||
'muscle_gain': 0.0,
|
||||
'strength': 0.10,
|
||||
'endurance': 0.20,
|
||||
'flexibility': 0.15,
|
||||
'health': 0.55
|
||||
}
|
||||
|
||||
# V1: Predefined weight mappings per goal_mode (fallback)
|
||||
WEIGHT_MAPPINGS = {
|
||||
'weight_loss': {
|
||||
'weight_loss': 0.60,
|
||||
'endurance': 0.20,
|
||||
'muscle_gain': 0.0,
|
||||
'strength': 0.10,
|
||||
'flexibility': 0.05,
|
||||
'health': 0.05
|
||||
},
|
||||
'strength': {
|
||||
'strength': 0.50,
|
||||
'muscle_gain': 0.40,
|
||||
'endurance': 0.10,
|
||||
'weight_loss': 0.0,
|
||||
'flexibility': 0.0,
|
||||
'health': 0.0
|
||||
},
|
||||
'endurance': {
|
||||
'endurance': 0.70,
|
||||
'health': 0.20,
|
||||
'flexibility': 0.10,
|
||||
'weight_loss': 0.0,
|
||||
'muscle_gain': 0.0,
|
||||
'strength': 0.0
|
||||
},
|
||||
'recomposition': {
|
||||
'weight_loss': 0.30,
|
||||
'muscle_gain': 0.30,
|
||||
'strength': 0.25,
|
||||
'endurance': 0.10,
|
||||
'flexibility': 0.05,
|
||||
'health': 0.0
|
||||
},
|
||||
'health': {
|
||||
'health': 0.50,
|
||||
'endurance': 0.20,
|
||||
'flexibility': 0.15,
|
||||
'strength': 0.10,
|
||||
'weight_loss': 0.05,
|
||||
'muscle_gain': 0.0
|
||||
}
|
||||
}
|
||||
|
||||
return WEIGHT_MAPPINGS.get(goal_mode, WEIGHT_MAPPINGS['health'])
|
||||
|
||||
|
||||
def get_primary_focus(conn, profile_id: str) -> str:
|
||||
"""
|
||||
Get the primary focus area for a profile.
|
||||
|
||||
Returns the focus area with the highest weight.
|
||||
Useful for UI labels and simple decision logic.
|
||||
|
||||
Args:
|
||||
conn: Database connection
|
||||
profile_id: User's profile ID
|
||||
|
||||
Returns:
|
||||
Primary focus area name (e.g., 'weight_loss', 'strength')
|
||||
"""
|
||||
weights = get_focus_weights(conn, profile_id)
|
||||
return max(weights.items(), key=lambda x: x[1])[0]
|
||||
|
||||
|
||||
def get_focus_description(focus_area: str) -> str:
|
||||
"""
|
||||
Get human-readable description for a focus area.
|
||||
|
||||
Args:
|
||||
focus_area: Focus area key (e.g., 'weight_loss')
|
||||
|
||||
Returns:
|
||||
German description for UI display
|
||||
"""
|
||||
descriptions = {
|
||||
'weight_loss': 'Gewichtsreduktion & Fettabbau',
|
||||
'muscle_gain': 'Muskelaufbau & Hypertrophie',
|
||||
'strength': 'Kraftsteigerung & Performance',
|
||||
'endurance': 'Ausdauer & aerobe Kapazität',
|
||||
'flexibility': 'Beweglichkeit & Mobilität',
|
||||
'health': 'Allgemeine Gesundheit & Erhaltung'
|
||||
}
|
||||
return descriptions.get(focus_area, focus_area)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Phase 1.5: Universal Value Fetcher for Dynamic Goal Types
|
||||
# ============================================================================
|
||||
|
||||
def get_goal_type_config(conn, type_key: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Get goal type configuration from database registry.
|
||||
|
||||
Args:
|
||||
conn: Database connection
|
||||
type_key: Goal type key (e.g., 'weight', 'meditation_minutes')
|
||||
|
||||
Returns:
|
||||
Dict with config or None if not found/inactive
|
||||
"""
|
||||
cur = get_cursor(conn)
|
||||
|
||||
cur.execute("""
|
||||
SELECT type_key, source_table, source_column, aggregation_method,
|
||||
calculation_formula, filter_conditions, label_de, unit, icon, category
|
||||
FROM goal_type_definitions
|
||||
WHERE type_key = %s AND is_active = true
|
||||
LIMIT 1
|
||||
""", (type_key,))
|
||||
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def get_current_value_for_goal(conn, profile_id: str, goal_type: str) -> Optional[float]:
|
||||
"""
|
||||
Universal value fetcher for any goal type.
|
||||
|
||||
Reads configuration from goal_type_definitions table and executes
|
||||
appropriate query based on aggregation_method or calculation_formula.
|
||||
|
||||
Args:
|
||||
conn: Database connection
|
||||
profile_id: User's profile ID
|
||||
goal_type: Goal type key (e.g., 'weight', 'meditation_minutes')
|
||||
|
||||
Returns:
|
||||
Current value as float or None if not available
|
||||
"""
|
||||
config = get_goal_type_config(conn, goal_type)
|
||||
|
||||
if not config:
|
||||
print(f"[WARNING] Goal type '{goal_type}' not found or inactive")
|
||||
return None
|
||||
|
||||
# Complex calculation (e.g., lean_mass)
|
||||
if config['calculation_formula']:
|
||||
return _execute_calculation_formula(conn, profile_id, config['calculation_formula'])
|
||||
|
||||
# Simple aggregation
|
||||
return _fetch_by_aggregation_method(
|
||||
conn,
|
||||
profile_id,
|
||||
config['source_table'],
|
||||
config['source_column'],
|
||||
config['aggregation_method'],
|
||||
config.get('filter_conditions')
|
||||
)
|
||||
|
||||
|
||||
def _fetch_by_aggregation_method(
|
||||
conn,
|
||||
profile_id: str,
|
||||
table: str,
|
||||
column: str,
|
||||
method: str,
|
||||
filter_conditions: Optional[Any] = None
|
||||
) -> Optional[float]:
|
||||
"""
|
||||
Fetch value using specified aggregation method.
|
||||
|
||||
Supported methods:
|
||||
- latest: Most recent value
|
||||
- avg_7d: 7-day average
|
||||
- avg_30d: 30-day average
|
||||
- sum_30d: 30-day sum
|
||||
- count_7d: Count of entries in last 7 days
|
||||
- count_30d: Count of entries in last 30 days
|
||||
- min_30d: Minimum value in last 30 days
|
||||
- max_30d: Maximum value in last 30 days
|
||||
|
||||
Args:
|
||||
filter_conditions: Optional JSON filters (e.g., {"training_category": "strength"})
|
||||
"""
|
||||
# Guard: source_table/column required for simple aggregation
|
||||
if not table or not column:
|
||||
print(f"[WARNING] Missing source_table or source_column for aggregation")
|
||||
return None
|
||||
|
||||
# Table-specific date column mapping (some tables use different column names)
|
||||
DATE_COLUMN_MAP = {
|
||||
'blood_pressure_log': 'measured_at',
|
||||
'activity_log': 'date',
|
||||
'weight_log': 'date',
|
||||
'circumference_log': 'date',
|
||||
'caliper_log': 'date',
|
||||
'nutrition_log': 'date',
|
||||
'sleep_log': 'date',
|
||||
'vitals_baseline': 'date',
|
||||
'rest_days': 'date',
|
||||
'fitness_tests': 'test_date'
|
||||
}
|
||||
date_col = DATE_COLUMN_MAP.get(table, 'date')
|
||||
|
||||
# Build filter SQL from JSON conditions
|
||||
filter_sql = ""
|
||||
filter_params = []
|
||||
|
||||
if filter_conditions:
|
||||
try:
|
||||
if isinstance(filter_conditions, str):
|
||||
filters = json.loads(filter_conditions)
|
||||
else:
|
||||
filters = filter_conditions
|
||||
|
||||
for filter_col, filter_val in filters.items():
|
||||
if isinstance(filter_val, list):
|
||||
# IN clause for multiple values
|
||||
placeholders = ', '.join(['%s'] * len(filter_val))
|
||||
filter_sql += f" AND {filter_col} IN ({placeholders})"
|
||||
filter_params.extend(filter_val)
|
||||
else:
|
||||
# Single value equality
|
||||
filter_sql += f" AND {filter_col} = %s"
|
||||
filter_params.append(filter_val)
|
||||
except (json.JSONDecodeError, TypeError, AttributeError) as e:
|
||||
print(f"[WARNING] Invalid filter_conditions: {e}, ignoring filters")
|
||||
|
||||
cur = get_cursor(conn)
|
||||
|
||||
try:
|
||||
if method == 'latest':
|
||||
params = [profile_id] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT {column} FROM {table}
|
||||
WHERE profile_id = %s AND {column} IS NOT NULL{filter_sql}
|
||||
ORDER BY {date_col} DESC LIMIT 1
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
return float(row[column]) if row else None
|
||||
|
||||
elif method == 'avg_7d':
|
||||
days_ago = date.today() - timedelta(days=7)
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT AVG({column}) as avg_value FROM {table}
|
||||
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
return float(row['avg_value']) if row and row['avg_value'] is not None else None
|
||||
|
||||
elif method == 'avg_30d':
|
||||
days_ago = date.today() - timedelta(days=30)
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT AVG({column}) as avg_value FROM {table}
|
||||
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
return float(row['avg_value']) if row and row['avg_value'] is not None else None
|
||||
|
||||
elif method == 'sum_30d':
|
||||
days_ago = date.today() - timedelta(days=30)
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT SUM({column}) as sum_value FROM {table}
|
||||
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
return float(row['sum_value']) if row and row['sum_value'] is not None else None
|
||||
|
||||
elif method == 'count_7d':
|
||||
days_ago = date.today() - timedelta(days=7)
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT COUNT(*) as count_value FROM {table}
|
||||
WHERE profile_id = %s AND {date_col} >= %s{filter_sql}
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
return float(row['count_value']) if row else 0.0
|
||||
|
||||
elif method == 'count_30d':
|
||||
days_ago = date.today() - timedelta(days=30)
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT COUNT(*) as count_value FROM {table}
|
||||
WHERE profile_id = %s AND {date_col} >= %s{filter_sql}
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
return float(row['count_value']) if row else 0.0
|
||||
|
||||
elif method == 'min_30d':
|
||||
days_ago = date.today() - timedelta(days=30)
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT MIN({column}) as min_value FROM {table}
|
||||
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
return float(row['min_value']) if row and row['min_value'] is not None else None
|
||||
|
||||
elif method == 'max_30d':
|
||||
days_ago = date.today() - timedelta(days=30)
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT MAX({column}) as max_value FROM {table}
|
||||
WHERE profile_id = %s AND {date_col} >= %s AND {column} IS NOT NULL{filter_sql}
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
return float(row['max_value']) if row and row['max_value'] is not None else None
|
||||
|
||||
elif method == 'avg_per_week_30d':
|
||||
# Average count per week over 30 days
|
||||
# Use case: Training frequency per week (smoothed over 4.3 weeks)
|
||||
days_ago = date.today() - timedelta(days=30)
|
||||
params = [profile_id, days_ago] + filter_params
|
||||
cur.execute(f"""
|
||||
SELECT COUNT(*) as count_value FROM {table}
|
||||
WHERE profile_id = %s AND {date_col} >= %s{filter_sql}
|
||||
""", params)
|
||||
row = cur.fetchone()
|
||||
if row and row['count_value'] is not None:
|
||||
# 30 days = 4.285 weeks (30/7)
|
||||
return round(float(row['count_value']) / 4.285, 2)
|
||||
return None
|
||||
|
||||
else:
|
||||
print(f"[WARNING] Unknown aggregation method: {method}")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
# Log detailed error for debugging
|
||||
print(f"[ERROR] Failed to fetch value from {table}.{column} using {method}: {e}")
|
||||
print(f"[ERROR] Filter conditions: {filter_conditions}")
|
||||
print(f"[ERROR] Filter SQL: {filter_sql}")
|
||||
print(f"[ERROR] Filter params: {filter_params}")
|
||||
|
||||
# CRITICAL: Rollback transaction to avoid InFailedSqlTransaction errors
|
||||
try:
|
||||
conn.rollback()
|
||||
print(f"[INFO] Transaction rolled back after query error")
|
||||
except Exception as rollback_err:
|
||||
print(f"[WARNING] Rollback failed: {rollback_err}")
|
||||
|
||||
# Return None so goal creation can continue without current_value
|
||||
# (current_value will be NULL in the goal record)
|
||||
return None
|
||||
|
||||
|
||||
def _execute_calculation_formula(conn, profile_id: str, formula_json: str) -> Optional[float]:
|
||||
"""
|
||||
Execute complex calculation formula.
|
||||
|
||||
Currently supports:
|
||||
- lean_mass: weight - (weight * body_fat_pct / 100)
|
||||
|
||||
Future: Parse JSON formula and execute dynamically.
|
||||
|
||||
Args:
|
||||
conn: Database connection
|
||||
profile_id: User's profile ID
|
||||
formula_json: JSON string with calculation config
|
||||
|
||||
Returns:
|
||||
Calculated value or None
|
||||
"""
|
||||
try:
|
||||
formula = json.loads(formula_json)
|
||||
calc_type = formula.get('type')
|
||||
|
||||
if calc_type == 'lean_mass':
|
||||
# Get dependencies
|
||||
cur = get_cursor(conn)
|
||||
|
||||
cur.execute("""
|
||||
SELECT weight FROM weight_log
|
||||
WHERE profile_id = %s
|
||||
ORDER BY date DESC LIMIT 1
|
||||
""", (profile_id,))
|
||||
weight_row = cur.fetchone()
|
||||
|
||||
cur.execute("""
|
||||
SELECT body_fat_pct FROM caliper_log
|
||||
WHERE profile_id = %s
|
||||
ORDER BY date DESC LIMIT 1
|
||||
""", (profile_id,))
|
||||
bf_row = cur.fetchone()
|
||||
|
||||
if weight_row and bf_row:
|
||||
weight = float(weight_row['weight'])
|
||||
bf_pct = float(bf_row['body_fat_pct'])
|
||||
lean_mass = weight - (weight * bf_pct / 100.0)
|
||||
return round(lean_mass, 2)
|
||||
|
||||
return None
|
||||
|
||||
else:
|
||||
print(f"[WARNING] Unknown calculation type: {calc_type}")
|
||||
return None
|
||||
|
||||
except (json.JSONDecodeError, KeyError, ValueError, TypeError) as e:
|
||||
print(f"[ERROR] Formula execution failed: {e}, formula={formula_json}")
|
||||
return None
|
||||
|
||||
|
||||
# Future V2 Implementation (commented out for reference):
|
||||
"""
|
||||
def get_focus_weights_v2(conn, profile_id: str) -> Dict[str, float]:
|
||||
'''V2: Read from focus_areas table with custom user weights'''
|
||||
cur = get_cursor(conn)
|
||||
|
||||
cur.execute('''
|
||||
SELECT weight_loss_pct, muscle_gain_pct, endurance_pct,
|
||||
strength_pct, flexibility_pct, health_pct
|
||||
FROM focus_areas
|
||||
WHERE profile_id = %s AND active = true
|
||||
LIMIT 1
|
||||
''', (profile_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
|
||||
if not row:
|
||||
# Fallback to V1 behavior
|
||||
return get_focus_weights(conn, profile_id)
|
||||
|
||||
# Convert percentages to weights (0-1 range)
|
||||
return {
|
||||
'weight_loss': row['weight_loss_pct'] / 100.0,
|
||||
'muscle_gain': row['muscle_gain_pct'] / 100.0,
|
||||
'endurance': row['endurance_pct'] / 100.0,
|
||||
'strength': row['strength_pct'] / 100.0,
|
||||
'flexibility': row['flexibility_pct'] / 100.0,
|
||||
'health': row['health_pct'] / 100.0
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def get_active_goals(profile_id: str) -> List[Dict]:
|
||||
"""
|
||||
Get all active goals for a profile.
|
||||
Returns list of goal dicts with id, type, target_value, current_value, etc.
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT id, goal_type, name, target_value, target_date,
|
||||
current_value, start_value, start_date, progress_pct,
|
||||
status, is_primary, created_at
|
||||
FROM goals
|
||||
WHERE profile_id = %s
|
||||
AND status IN ('active', 'in_progress')
|
||||
ORDER BY is_primary DESC, created_at DESC
|
||||
""", (profile_id,))
|
||||
|
||||
return [dict(row) for row in cur.fetchall()]
|
||||
|
||||
|
||||
def get_goal_by_id(goal_id: str) -> Optional[Dict]:
|
||||
"""Get a single goal by ID"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("""
|
||||
SELECT id, profile_id, goal_type, target_value, target_date,
|
||||
current_value, start_value, progress_pct, status, is_primary
|
||||
FROM goals
|
||||
WHERE id = %s
|
||||
""", (goal_id,))
|
||||
|
||||
row = cur.fetchone()
|
||||
return dict(row) if row else None
|
||||
@@ -0,0 +1,396 @@
|
||||
"""
|
||||
Join Evaluator (Phase 4)
|
||||
|
||||
Evaluiert Join-Knoten: Sammelt incoming paths, prüft Strategien, konsolidiert Ergebnisse.
|
||||
|
||||
Join-Strategien:
|
||||
- wait_all: Alle eingehenden Pfade müssen ausgeführt sein (strikt)
|
||||
- wait_any: Mindestens ein Pfad muss ausgeführt sein
|
||||
- best_effort: Verwendet verfügbare Pfade (fehlertoleranz)
|
||||
|
||||
Skip-Handling:
|
||||
- ignore_skipped: Übersprungene Pfade nicht in Ergebnis
|
||||
- use_placeholder: Platzhalter für übersprungene Pfade
|
||||
- require_minimum: Mindestanzahl erforderlich
|
||||
|
||||
Konzept-Basis: konzept_workflow_engine_konsolidated.md (Sektion 8.8)
|
||||
Anforderungsanalyse: phase4_anforderungsanalyse.md
|
||||
"""
|
||||
|
||||
from typing import Dict, Any, Optional, List, NamedTuple
|
||||
from pydantic import BaseModel, Field
|
||||
import logging
|
||||
|
||||
from workflow_models import (
|
||||
WorkflowNode,
|
||||
WorkflowGraph,
|
||||
JoinStrategy,
|
||||
SkipHandling,
|
||||
NodeStatus,
|
||||
NormalizedSignal
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ── Data Structures ───────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class PathStatus(NamedTuple):
|
||||
"""
|
||||
Status eines eingehenden Pfads am Join-Node.
|
||||
|
||||
Attributes:
|
||||
node_id: ID des Source-Nodes (Node vor dem Join)
|
||||
status: Ausführungsstatus (EXECUTED, SKIPPED, FAILED)
|
||||
analysis_core: Analyseinhalt (wenn vorhanden)
|
||||
signals: Normalisierte Signale des Nodes (question_type → Signal)
|
||||
"""
|
||||
node_id: str
|
||||
status: NodeStatus
|
||||
analysis_core: Optional[str]
|
||||
signals: Dict[str, NormalizedSignal] # Converted from List to Dict by _collect_incoming_paths
|
||||
|
||||
|
||||
class JoinResult(BaseModel):
|
||||
"""
|
||||
Ergebnis der Join-Evaluation.
|
||||
|
||||
Enthält konsolidierte Daten aller eingehenden Pfade.
|
||||
"""
|
||||
ready: bool = Field(..., description="Sind erforderliche Pfade verfügbar?")
|
||||
consolidated_analysis_core: Dict[str, str] = Field(
|
||||
default_factory=dict,
|
||||
description="Konsolidierte Analysekerne: node_id → analysis_core"
|
||||
)
|
||||
consolidated_signals: Dict[str, NormalizedSignal] = Field(
|
||||
default_factory=dict,
|
||||
description="Konsolidierte Signale: node_id.question_id → signal"
|
||||
)
|
||||
metadata: Dict[str, Any] = Field(
|
||||
default_factory=dict,
|
||||
description="Pfad-Status, Statistiken, Hinweise"
|
||||
)
|
||||
error: Optional[str] = Field(None, description="Fehler bei nicht erfüllter Strategie")
|
||||
|
||||
|
||||
# ── Helper Functions ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _collect_incoming_paths(
|
||||
node: WorkflowNode,
|
||||
graph: WorkflowGraph,
|
||||
context: Dict[str, Any]
|
||||
) -> List[PathStatus]:
|
||||
"""
|
||||
Sammelt alle eingehenden Pfade eines Join-Nodes.
|
||||
|
||||
Args:
|
||||
node: Join-Node
|
||||
graph: Workflow-Graph
|
||||
context: Execution context mit node_results
|
||||
|
||||
Returns:
|
||||
List[PathStatus] - Status aller eingehenden Pfade
|
||||
|
||||
Details:
|
||||
- Findet alle Edges mit to_node == join_node.id
|
||||
- Extrahiert NodeExecutionState aus context["node_results"]
|
||||
- Erstellt PathStatus für jeden incoming node
|
||||
"""
|
||||
incoming_edges = [e for e in graph.edges if e.to_node == node.id]
|
||||
paths: List[PathStatus] = []
|
||||
|
||||
logger.debug(f"Join node {node.id}: Found {len(incoming_edges)} incoming edges")
|
||||
|
||||
for edge in incoming_edges:
|
||||
source_node_id = edge.from_node
|
||||
|
||||
# Hole NodeExecutionState aus context
|
||||
node_state = context["node_results"].get(source_node_id)
|
||||
|
||||
if node_state:
|
||||
# Node wurde ausgeführt
|
||||
# Convert List[NormalizedSignal] to Dict[question_type → Signal]
|
||||
signals_dict = {}
|
||||
if node_state.normalized_signals:
|
||||
for signal in node_state.normalized_signals:
|
||||
signals_dict[signal.question_type] = signal
|
||||
|
||||
path = PathStatus(
|
||||
node_id=source_node_id,
|
||||
status=node_state.status,
|
||||
analysis_core=node_state.analysis_core,
|
||||
signals=signals_dict
|
||||
)
|
||||
paths.append(path)
|
||||
logger.debug(f" Path {source_node_id}: {node_state.status.value}")
|
||||
else:
|
||||
# Node nicht in node_results → wurde nicht besucht (unreachable)
|
||||
path = PathStatus(
|
||||
node_id=source_node_id,
|
||||
status=NodeStatus.SKIPPED,
|
||||
analysis_core=None,
|
||||
signals={}
|
||||
)
|
||||
paths.append(path)
|
||||
logger.debug(f" Path {source_node_id}: not visited (unreachable)")
|
||||
|
||||
return paths
|
||||
|
||||
|
||||
def _check_join_strategy(
|
||||
paths: List[PathStatus],
|
||||
strategy: JoinStrategy
|
||||
) -> tuple[bool, Optional[str]]:
|
||||
"""
|
||||
Prüft ob Join-Strategie erfüllt ist.
|
||||
|
||||
Args:
|
||||
paths: Liste aller eingehenden Pfade
|
||||
strategy: Join-Strategie (wait_all, wait_any, best_effort)
|
||||
|
||||
Returns:
|
||||
(ready: bool, error: Optional[str])
|
||||
- ready: True wenn Strategie erfüllt
|
||||
- error: Fehlermeldung wenn nicht erfüllt
|
||||
|
||||
Strategien:
|
||||
- wait_all: Alle Pfade EXECUTED (strikt)
|
||||
- wait_any: Mindestens ein Pfad EXECUTED
|
||||
- best_effort: Immer ready (fehlertoleranz)
|
||||
"""
|
||||
executed_paths = [p for p in paths if p.status == NodeStatus.EXECUTED]
|
||||
failed_paths = [p for p in paths if p.status == NodeStatus.FAILED]
|
||||
skipped_paths = [p for p in paths if p.status == NodeStatus.SKIPPED]
|
||||
|
||||
logger.debug(f"Join strategy check: {strategy.value}")
|
||||
logger.debug(f" Executed: {len(executed_paths)}/{len(paths)}")
|
||||
logger.debug(f" Failed: {len(failed_paths)}")
|
||||
logger.debug(f" Skipped: {len(skipped_paths)}")
|
||||
|
||||
if strategy == JoinStrategy.WAIT_ALL:
|
||||
# Alle Pfade müssen EXECUTED sein
|
||||
if len(executed_paths) < len(paths):
|
||||
missing = [p.node_id for p in paths if p.status != NodeStatus.EXECUTED]
|
||||
error = f"wait_all strategy failed: {len(executed_paths)}/{len(paths)} paths executed. Missing: {missing}"
|
||||
logger.warning(error)
|
||||
return False, error
|
||||
return True, None
|
||||
|
||||
elif strategy == JoinStrategy.WAIT_ANY:
|
||||
# Mindestens ein Pfad EXECUTED
|
||||
if len(executed_paths) == 0:
|
||||
error = f"wait_any strategy failed: no paths executed ({len(failed_paths)} failed, {len(skipped_paths)} skipped)"
|
||||
logger.warning(error)
|
||||
return False, error
|
||||
return True, None
|
||||
|
||||
elif strategy == JoinStrategy.BEST_EFFORT:
|
||||
# Immer bereit (fehlertoleranz)
|
||||
if len(executed_paths) == 0:
|
||||
logger.info(f"best_effort: No paths executed, but continuing (fehlertoleranz)")
|
||||
return True, None
|
||||
|
||||
else:
|
||||
# Unbekannte Strategie
|
||||
error = f"Unknown join strategy: {strategy}"
|
||||
logger.error(error)
|
||||
return False, error
|
||||
|
||||
|
||||
def _merge_analysis_cores(
|
||||
paths: List[PathStatus],
|
||||
skip_handling: Optional[SkipHandling]
|
||||
) -> Dict[str, str]:
|
||||
"""
|
||||
Merged Analysekerne aller eingehenden Pfade.
|
||||
|
||||
Args:
|
||||
paths: Liste aller Pfade
|
||||
skip_handling: Umgang mit übersprungenen Pfaden
|
||||
|
||||
Returns:
|
||||
Dict[node_id → analysis_core]
|
||||
|
||||
Details:
|
||||
- EXECUTED Pfade: analysis_core übernehmen
|
||||
- SKIPPED Pfade: abhängig von skip_handling
|
||||
- IGNORE_SKIPPED: nicht in Ergebnis
|
||||
- USE_PLACEHOLDER: Platzhalter "[Skipped: {node_id}]"
|
||||
- FAILED Pfade: Platzhalter "[Failed: {node_id}]"
|
||||
"""
|
||||
merged: Dict[str, str] = {}
|
||||
|
||||
for path in paths:
|
||||
if path.status == NodeStatus.EXECUTED and path.analysis_core:
|
||||
# Normale Übernahme
|
||||
merged[path.node_id] = path.analysis_core
|
||||
|
||||
elif path.status == NodeStatus.SKIPPED:
|
||||
# Skip-Handling
|
||||
if skip_handling == SkipHandling.USE_PLACEHOLDER:
|
||||
merged[path.node_id] = f"[Path skipped: {path.node_id}]"
|
||||
elif skip_handling == SkipHandling.IGNORE_SKIPPED:
|
||||
# Nicht in Ergebnis
|
||||
pass
|
||||
# REQUIRE_MINIMUM wird in _check_join_strategy behandelt
|
||||
|
||||
elif path.status == NodeStatus.FAILED:
|
||||
# Failed Pfade dokumentieren
|
||||
merged[path.node_id] = f"[Path failed: {path.node_id}]"
|
||||
|
||||
logger.debug(f"Merged analysis cores: {len(merged)} entries")
|
||||
return merged
|
||||
|
||||
|
||||
def _combine_signals(
|
||||
paths: List[PathStatus]
|
||||
) -> Dict[str, NormalizedSignal]:
|
||||
"""
|
||||
Kombiniert Signale aller eingehenden Pfade.
|
||||
|
||||
Args:
|
||||
paths: Liste aller Pfade
|
||||
|
||||
Returns:
|
||||
Dict[node_id.question_id → NormalizedSignal]
|
||||
|
||||
Details:
|
||||
- Signal-Namen werden mit node_id geprefixed (verhindert Kollision)
|
||||
- Format: "node_id.question_id" → Signal
|
||||
- Nur EXECUTED Pfade werden berücksichtigt
|
||||
|
||||
Beispiel:
|
||||
path_a.relevanz → Signal(value="hoch", ...)
|
||||
path_b.relevanz → Signal(value="mittel", ...)
|
||||
"""
|
||||
combined: Dict[str, NormalizedSignal] = {}
|
||||
|
||||
for path in paths:
|
||||
if path.status != NodeStatus.EXECUTED:
|
||||
# Nur ausgeführte Pfade haben valide Signale
|
||||
continue
|
||||
|
||||
for signal_key, signal in path.signals.items():
|
||||
# Präfix mit node_id (verhindert Kollision)
|
||||
prefixed_key = f"{path.node_id}.{signal_key}"
|
||||
combined[prefixed_key] = signal
|
||||
|
||||
logger.debug(f"Combined signals: {len(combined)} entries")
|
||||
return combined
|
||||
|
||||
|
||||
# ── Main Function ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def evaluate_join_node(
|
||||
node: WorkflowNode,
|
||||
graph: WorkflowGraph,
|
||||
context: Dict[str, Any]
|
||||
) -> JoinResult:
|
||||
"""
|
||||
Evaluiert Join-Node: Sammelt Pfade, prüft Strategie, konsolidiert Ergebnisse.
|
||||
|
||||
Args:
|
||||
node: Join-Node aus Workflow-Graph
|
||||
graph: Gesamter Workflow-Graph
|
||||
context: Execution context mit node_results
|
||||
|
||||
Returns:
|
||||
JoinResult mit konsolidierten Daten
|
||||
|
||||
Workflow:
|
||||
1. Sammle incoming paths (_collect_incoming_paths)
|
||||
2. Prüfe Join-Strategie (_check_join_strategy)
|
||||
3. Merge analysis_cores (_merge_analysis_cores)
|
||||
4. Combine signals (_combine_signals)
|
||||
5. Baue metadata (Pfad-Status, Statistiken)
|
||||
|
||||
Beispiel:
|
||||
>>> result = evaluate_join_node(join_node, graph, context)
|
||||
>>> result.ready
|
||||
True
|
||||
>>> result.consolidated_analysis_core
|
||||
{"path_a": "Analysis A...", "path_b": "Analysis B..."}
|
||||
"""
|
||||
logger.info(f"Evaluating join node: {node.id}")
|
||||
|
||||
# 1. Sammle incoming paths
|
||||
paths = _collect_incoming_paths(node, graph, context)
|
||||
|
||||
if not paths:
|
||||
# Kein eingehender Pfad (Fehlkonfiguration)
|
||||
logger.warning(f"Join node {node.id}: No incoming edges found")
|
||||
return JoinResult(
|
||||
ready=False,
|
||||
error="No incoming edges for join node",
|
||||
metadata={"note": "Configuration error: join node must have incoming edges"}
|
||||
)
|
||||
|
||||
# 2. Prüfe Join-Strategie
|
||||
strategy = node.join_strategy or JoinStrategy.WAIT_ALL # Default
|
||||
skip_handling = node.skip_handling or SkipHandling.IGNORE_SKIPPED # Default
|
||||
|
||||
ready, strategy_error = _check_join_strategy(paths, strategy)
|
||||
|
||||
if not ready:
|
||||
# Strategie nicht erfüllt
|
||||
executed_list = [p.node_id for p in paths if p.status == NodeStatus.EXECUTED]
|
||||
skipped_list = [p.node_id for p in paths if p.status == NodeStatus.SKIPPED]
|
||||
failed_list = [p.node_id for p in paths if p.status == NodeStatus.FAILED]
|
||||
|
||||
return JoinResult(
|
||||
ready=False,
|
||||
error=strategy_error,
|
||||
metadata={
|
||||
"join_strategy": strategy.value,
|
||||
"total_paths": len(paths),
|
||||
"executed_paths": len(executed_list),
|
||||
"skipped_paths": len(skipped_list),
|
||||
"failed_paths": len(failed_list),
|
||||
"path_details": {
|
||||
"executed": executed_list,
|
||||
"skipped": skipped_list,
|
||||
"failed": failed_list
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
# 3. Merge analysis_cores
|
||||
merged_cores = _merge_analysis_cores(paths, skip_handling)
|
||||
|
||||
# 4. Combine signals
|
||||
combined_signals = _combine_signals(paths)
|
||||
|
||||
# 5. Baue metadata
|
||||
executed_count = sum(1 for p in paths if p.status == NodeStatus.EXECUTED)
|
||||
skipped_count = sum(1 for p in paths if p.status == NodeStatus.SKIPPED)
|
||||
failed_count = sum(1 for p in paths if p.status == NodeStatus.FAILED)
|
||||
|
||||
metadata = {
|
||||
"join_strategy": strategy.value,
|
||||
"skip_handling": skip_handling.value,
|
||||
"total_paths": len(paths),
|
||||
"executed_paths": executed_count,
|
||||
"skipped_paths": skipped_count,
|
||||
"failed_paths": failed_count,
|
||||
"path_details": {
|
||||
"executed": [p.node_id for p in paths if p.status == NodeStatus.EXECUTED],
|
||||
"skipped": [p.node_id for p in paths if p.status == NodeStatus.SKIPPED],
|
||||
"failed": [p.node_id for p in paths if p.status == NodeStatus.FAILED]
|
||||
}
|
||||
}
|
||||
|
||||
# Spezielle Hinweise
|
||||
if executed_count == 0 and strategy == JoinStrategy.BEST_EFFORT:
|
||||
metadata["note"] = "No paths executed, but best_effort allows empty consolidation"
|
||||
|
||||
logger.info(f"Join node {node.id}: Consolidated {executed_count}/{len(paths)} paths")
|
||||
|
||||
return JoinResult(
|
||||
ready=True,
|
||||
consolidated_analysis_core=merged_cores,
|
||||
consolidated_signals=combined_signals,
|
||||
metadata=metadata
|
||||
)
|
||||
@@ -0,0 +1,268 @@
|
||||
"""
|
||||
Logic Evaluator (Phase 3)
|
||||
|
||||
Rein deterministischer boolescher Evaluator für Workflow-Bedingungen.
|
||||
Keine KI, keine Interpretation - nur strikte Logik-Auswertung.
|
||||
|
||||
Unterstützt:
|
||||
- Vergleichsoperatoren: EQ, NEQ, IN, NOT_IN, GT, LT, GTE, LTE, CONTAINS
|
||||
- Logische Operatoren: AND, OR, NOT
|
||||
- Verschachtelung via operands
|
||||
"""
|
||||
|
||||
from typing import Dict, Any, Optional, Tuple, List
|
||||
import logging
|
||||
from workflow_models import (
|
||||
LogicExpression,
|
||||
LogicOperator,
|
||||
NormalizedSignal,
|
||||
SignalStatus
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def evaluate_logic_expression(
|
||||
expression: LogicExpression,
|
||||
context: Dict[str, Any]
|
||||
) -> Tuple[bool, Optional[str]]:
|
||||
"""
|
||||
Evaluiert LogicExpression gegen context.
|
||||
|
||||
Args:
|
||||
expression: Die auszuwertende Bedingung
|
||||
context: Execution context mit node_results
|
||||
|
||||
Returns:
|
||||
(result: bool, error: Optional[str])
|
||||
- result: True/False basierend auf Auswertung
|
||||
- error: Fehlermeldung wenn Evaluation fehlschlägt
|
||||
|
||||
Beispiel:
|
||||
expression = LogicExpression(
|
||||
operator=LogicOperator.EQ,
|
||||
ref="body.relevanz",
|
||||
value="decrease"
|
||||
)
|
||||
result, error = evaluate_logic_expression(expression, context)
|
||||
"""
|
||||
try:
|
||||
operator = expression.operator
|
||||
|
||||
# Logische Operatoren (verschachtelt)
|
||||
if operator == LogicOperator.AND:
|
||||
return _evaluate_and(expression, context)
|
||||
elif operator == LogicOperator.OR:
|
||||
return _evaluate_or(expression, context)
|
||||
elif operator == LogicOperator.NOT:
|
||||
return _evaluate_not(expression, context)
|
||||
|
||||
# Vergleichsoperatoren (benötigen ref)
|
||||
elif operator in [
|
||||
LogicOperator.EQ, LogicOperator.NEQ,
|
||||
LogicOperator.IN, LogicOperator.NOT_IN,
|
||||
LogicOperator.GT, LogicOperator.LT,
|
||||
LogicOperator.GTE, LogicOperator.LTE,
|
||||
LogicOperator.CONTAINS
|
||||
]:
|
||||
return _evaluate_comparison(expression, context)
|
||||
|
||||
else:
|
||||
return False, f"Unknown operator: {operator}"
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Logic evaluation failed: {e}", exc_info=True)
|
||||
return False, str(e)
|
||||
|
||||
|
||||
def _evaluate_and(
|
||||
expression: LogicExpression,
|
||||
context: Dict[str, Any]
|
||||
) -> Tuple[bool, Optional[str]]:
|
||||
"""Evaluiert AND - alle operands müssen True sein."""
|
||||
if not expression.operands:
|
||||
return False, "AND requires operands"
|
||||
|
||||
for operand in expression.operands:
|
||||
result, error = evaluate_logic_expression(operand, context)
|
||||
if error:
|
||||
return False, f"AND operand failed: {error}"
|
||||
if not result:
|
||||
return False, None # Short-circuit: einer False → gesamt False
|
||||
|
||||
return True, None
|
||||
|
||||
|
||||
def _evaluate_or(
|
||||
expression: LogicExpression,
|
||||
context: Dict[str, Any]
|
||||
) -> Tuple[bool, Optional[str]]:
|
||||
"""Evaluiert OR - mindestens ein operand muss True sein."""
|
||||
if not expression.operands:
|
||||
return False, "OR requires operands"
|
||||
|
||||
errors = []
|
||||
for operand in expression.operands:
|
||||
result, error = evaluate_logic_expression(operand, context)
|
||||
if error:
|
||||
errors.append(error)
|
||||
continue
|
||||
if result:
|
||||
return True, None # Short-circuit: einer True → gesamt True
|
||||
|
||||
# Alle False oder Fehler
|
||||
if errors:
|
||||
return False, f"All OR operands failed: {', '.join(errors)}"
|
||||
return False, None
|
||||
|
||||
|
||||
def _evaluate_not(
|
||||
expression: LogicExpression,
|
||||
context: Dict[str, Any]
|
||||
) -> Tuple[bool, Optional[str]]:
|
||||
"""Evaluiert NOT - negiert operand."""
|
||||
if not expression.operands or len(expression.operands) != 1:
|
||||
return False, "NOT requires exactly one operand"
|
||||
|
||||
result, error = evaluate_logic_expression(expression.operands[0], context)
|
||||
if error:
|
||||
return False, f"NOT operand failed: {error}"
|
||||
|
||||
return not result, None
|
||||
|
||||
|
||||
def _evaluate_comparison(
|
||||
expression: LogicExpression,
|
||||
context: Dict[str, Any]
|
||||
) -> Tuple[bool, Optional[str]]:
|
||||
"""Evaluiert Vergleichsoperator."""
|
||||
if not expression.ref:
|
||||
return False, f"{expression.operator} requires ref"
|
||||
|
||||
# Signal auflösen
|
||||
signal, error = resolve_signal_reference(expression.ref, context)
|
||||
if error:
|
||||
return False, error
|
||||
if signal is None:
|
||||
return False, f"Signal not found: {expression.ref}"
|
||||
|
||||
# Prüfe Signal-Status
|
||||
if signal.status in [SignalStatus.UNCLEAR, SignalStatus.INVALID, SignalStatus.NOT_DECIDABLE]:
|
||||
return False, f"Signal '{expression.ref}' has status {signal.status} - cannot evaluate"
|
||||
|
||||
# Vergleich durchführen
|
||||
left_value = signal.normalized_value or signal.raw_value
|
||||
right_value = expression.value
|
||||
|
||||
return compare_values(expression.operator, left_value, right_value)
|
||||
|
||||
|
||||
def resolve_signal_reference(
|
||||
ref: str,
|
||||
context: Dict[str, Any]
|
||||
) -> Tuple[Optional[NormalizedSignal], Optional[str]]:
|
||||
"""
|
||||
Löst Referenz wie "node_1.relevanz" auf.
|
||||
|
||||
Args:
|
||||
ref: Signal-Referenz im Format "node_id.question_type"
|
||||
context: Execution context mit node_results
|
||||
|
||||
Returns:
|
||||
(signal, error_message)
|
||||
|
||||
Error wenn:
|
||||
- Node existiert nicht in context
|
||||
- Signal-Typ existiert nicht für diesen Node
|
||||
"""
|
||||
# Parse reference
|
||||
parts = ref.split(".")
|
||||
if len(parts) != 2:
|
||||
return None, f"Invalid reference format: '{ref}' (expected 'node_id.question_type')"
|
||||
|
||||
node_id, question_type = parts
|
||||
|
||||
# Hole Node-Results aus context
|
||||
node_results = context.get("node_results", {})
|
||||
if node_id not in node_results:
|
||||
return None, f"Node '{node_id}' not found in context"
|
||||
|
||||
node_state = node_results[node_id]
|
||||
|
||||
# Suche Signal
|
||||
for signal in node_state.normalized_signals:
|
||||
if signal.question_type == question_type:
|
||||
return signal, None
|
||||
|
||||
return None, f"Signal '{question_type}' not found in node '{node_id}'"
|
||||
|
||||
|
||||
def compare_values(
|
||||
operator: LogicOperator,
|
||||
left: Any,
|
||||
right: Any
|
||||
) -> Tuple[bool, Optional[str]]:
|
||||
"""
|
||||
Führt Vergleichsoperation durch.
|
||||
|
||||
Args:
|
||||
operator: Vergleichsoperator
|
||||
left: Linker Wert (aus Signal)
|
||||
right: Rechter Wert (aus Expression)
|
||||
|
||||
Returns:
|
||||
(result: bool, error: Optional[str])
|
||||
"""
|
||||
try:
|
||||
if operator == LogicOperator.EQ:
|
||||
return left == right, None
|
||||
|
||||
elif operator == LogicOperator.NEQ:
|
||||
return left != right, None
|
||||
|
||||
elif operator == LogicOperator.IN:
|
||||
if not isinstance(right, (list, tuple, set)):
|
||||
return False, f"IN operator requires list, got {type(right)}"
|
||||
return left in right, None
|
||||
|
||||
elif operator == LogicOperator.NOT_IN:
|
||||
if not isinstance(right, (list, tuple, set)):
|
||||
return False, f"NOT_IN operator requires list, got {type(right)}"
|
||||
return left not in right, None
|
||||
|
||||
elif operator == LogicOperator.CONTAINS:
|
||||
# left enthält right (z.B. String-Suche)
|
||||
if isinstance(left, str) and isinstance(right, str):
|
||||
return right in left, None
|
||||
elif isinstance(left, (list, tuple, set)):
|
||||
return right in left, None
|
||||
else:
|
||||
return False, f"CONTAINS not supported for types {type(left)}/{type(right)}"
|
||||
|
||||
elif operator == LogicOperator.GT:
|
||||
return _numeric_compare(left, right, lambda a, b: a > b)
|
||||
|
||||
elif operator == LogicOperator.LT:
|
||||
return _numeric_compare(left, right, lambda a, b: a < b)
|
||||
|
||||
elif operator == LogicOperator.GTE:
|
||||
return _numeric_compare(left, right, lambda a, b: a >= b)
|
||||
|
||||
elif operator == LogicOperator.LTE:
|
||||
return _numeric_compare(left, right, lambda a, b: a <= b)
|
||||
|
||||
else:
|
||||
return False, f"Unknown comparison operator: {operator}"
|
||||
|
||||
except Exception as e:
|
||||
return False, f"Comparison failed: {e}"
|
||||
|
||||
|
||||
def _numeric_compare(left: Any, right: Any, compare_fn) -> Tuple[bool, Optional[str]]:
|
||||
"""Hilfsfunktion für numerische Vergleiche."""
|
||||
try:
|
||||
left_num = float(left) if not isinstance(left, (int, float)) else left
|
||||
right_num = float(right) if not isinstance(right, (int, float)) else right
|
||||
return compare_fn(left_num, right_num), None
|
||||
except (ValueError, TypeError) as e:
|
||||
return False, f"Cannot compare as numbers: {left} vs {right} ({e})"
|
||||
+56
-1
@@ -18,6 +18,19 @@ 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)
|
||||
from routers import goals, focus_areas # v9e/v9g Goal System v2.0 (Dynamic Focus Areas)
|
||||
from routers import goal_types, goal_progress, training_phases, fitness_tests # v9h Goal System (Split routers)
|
||||
from routers import charts # Phase 0c Multi-Layer Architecture
|
||||
from routers import workflow_questions # Phase 1 Workflow Engine - Question Catalog
|
||||
from routers import workflows # Phase 2 Workflow Engine - Execution
|
||||
from routers import reference_values # Persönliche Referenzwerte (Profil)
|
||||
from routers import admin_reference_value_types # Admin: Referenzwert-Typen
|
||||
from routers import app_dashboard # Geschützter App-Bereich: Dashboard-Lab Layout
|
||||
|
||||
# ── App Configuration ─────────────────────────────────────────────────────────
|
||||
DATA_DIR = Path(os.getenv("DATA_DIR", "./data"))
|
||||
@@ -51,6 +64,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 +87,43 @@ 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)
|
||||
app.include_router(goals.router) # /api/goals/* (v9h Goal System Core CRUD + Focus Areas)
|
||||
app.include_router(goal_types.router) # /api/goals/goal-types/* (v9h Goal Type Definitions)
|
||||
app.include_router(goal_progress.router) # /api/goals/{goal_id}/progress/* (v9h Progress Tracking)
|
||||
app.include_router(training_phases.router) # /api/goals/phases/* (v9h Training Phases)
|
||||
app.include_router(fitness_tests.router) # /api/goals/tests/* (v9h Fitness Tests)
|
||||
app.include_router(focus_areas.router) # /api/focus-areas/* (v9g Focus Area System v2.0 - Dynamic)
|
||||
|
||||
# Phase 0c Multi-Layer Architecture
|
||||
app.include_router(charts.router) # /api/charts/* (Phase 0c Charts API)
|
||||
|
||||
# Phase 1-2 Workflow Engine
|
||||
app.include_router(workflow_questions.router) # /api/workflow/questions/* (Phase 1 Question Catalog)
|
||||
app.include_router(workflows.router) # /api/workflows/* (Phase 2 Execution)
|
||||
app.include_router(reference_values.router) # /api/reference-value-types, /api/profile-reference-values
|
||||
app.include_router(admin_reference_value_types.router) # /api/admin/reference-value-types
|
||||
app.include_router(app_dashboard.router) # /api/app/dashboard-layout
|
||||
|
||||
# ── 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,35 @@
|
||||
-- Migration 016: Workflow Support in ai_prompts (Phase 5)
|
||||
-- Erweitert ai_prompts für type='workflow' (Option B - Backward-kompatibel)
|
||||
|
||||
-- Neue Spalte für Workflow-Graphen
|
||||
ALTER TABLE ai_prompts ADD COLUMN graph_data JSONB;
|
||||
|
||||
-- Index für Workflow-Queries
|
||||
CREATE INDEX IF NOT EXISTS idx_ai_prompts_type ON ai_prompts(type);
|
||||
CREATE INDEX IF NOT EXISTS idx_ai_prompts_graph_data ON ai_prompts USING GIN (graph_data);
|
||||
|
||||
-- Kommentar
|
||||
COMMENT ON COLUMN ai_prompts.graph_data IS 'Workflow-Graph (nur für type=workflow): {nodes: [...], edges: [...], metadata: {...}}';
|
||||
|
||||
-- Beispiel-Struktur (Dokumentation):
|
||||
-- {
|
||||
-- "nodes": [
|
||||
-- {"id": "start", "type": "start", "label": "Start", "position": {"x": 100, "y": 100}},
|
||||
-- {"id": "analysis_1", "type": "analysis", "prompt_id": 5, "questions": [...], ...},
|
||||
-- {"id": "logic_1", "type": "logic", "condition": {...}, ...},
|
||||
-- {"id": "join_1", "type": "join", "join_strategy": "wait_all", ...},
|
||||
-- {"id": "end", "type": "end", "label": "Ende", "position": {"x": 500, "y": 300}}
|
||||
-- ],
|
||||
-- "edges": [
|
||||
-- {"id": "e1", "source": "start", "target": "analysis_1"},
|
||||
-- {"id": "e2", "source": "analysis_1", "target": "logic_1"},
|
||||
-- {"id": "e3", "source": "logic_1", "target": "join_1"},
|
||||
-- {"id": "e4", "source": "join_1", "target": "end"}
|
||||
-- ],
|
||||
-- "metadata": {
|
||||
-- "created_at": "2026-04-04T12:00:00Z",
|
||||
-- "version": "1.0"
|
||||
-- }
|
||||
-- }
|
||||
|
||||
-- Migration erfolgreich
|
||||
@@ -0,0 +1,22 @@
|
||||
-- Migration 017: AI Prompts Flexibilisierung (Issue #28)
|
||||
-- Add category column to ai_prompts for better organization and filtering
|
||||
|
||||
-- Add category column
|
||||
ALTER TABLE ai_prompts ADD COLUMN IF NOT EXISTS category VARCHAR(20) DEFAULT 'ganzheitlich';
|
||||
|
||||
-- Create index for category filtering
|
||||
CREATE INDEX IF NOT EXISTS idx_ai_prompts_category ON ai_prompts(category);
|
||||
|
||||
-- Add comment
|
||||
COMMENT ON COLUMN ai_prompts.category IS 'Prompt category: körper, ernährung, training, schlaf, vitalwerte, ziele, ganzheitlich';
|
||||
|
||||
-- Update existing prompts with appropriate categories
|
||||
-- Based on slug patterns and content
|
||||
UPDATE ai_prompts SET category = 'körper' WHERE slug IN ('koerperkomposition', 'gewichtstrend', 'umfaenge', 'caliper');
|
||||
UPDATE ai_prompts SET category = 'ernährung' WHERE slug IN ('ernaehrung', 'kalorienbilanz', 'protein', 'makros');
|
||||
UPDATE ai_prompts SET category = 'training' WHERE slug IN ('aktivitaet', 'trainingsanalyse', 'erholung', 'leistung');
|
||||
UPDATE ai_prompts SET category = 'schlaf' WHERE slug LIKE '%schlaf%';
|
||||
UPDATE ai_prompts SET category = 'vitalwerte' WHERE slug IN ('vitalwerte', 'herzfrequenz', 'ruhepuls', 'hrv');
|
||||
UPDATE ai_prompts SET category = 'ziele' WHERE slug LIKE '%ziel%' OR slug LIKE '%goal%';
|
||||
|
||||
-- Pipeline prompts remain 'ganzheitlich' (default)
|
||||
@@ -0,0 +1,20 @@
|
||||
-- Migration 018: Add display_name to ai_prompts for user-facing labels
|
||||
|
||||
ALTER TABLE ai_prompts ADD COLUMN IF NOT EXISTS display_name VARCHAR(100);
|
||||
|
||||
-- Migrate existing prompts from hardcoded SLUG_LABELS
|
||||
UPDATE ai_prompts SET display_name = '🔍 Gesamtanalyse' WHERE slug = 'gesamt' AND display_name IS NULL;
|
||||
UPDATE ai_prompts SET display_name = '🫧 Körperkomposition' WHERE slug = 'koerper' AND display_name IS NULL;
|
||||
UPDATE ai_prompts SET display_name = '🍽️ Ernährung' WHERE slug = 'ernaehrung' AND display_name IS NULL;
|
||||
UPDATE ai_prompts SET display_name = '🏋️ Aktivität' WHERE slug = 'aktivitaet' AND display_name IS NULL;
|
||||
UPDATE ai_prompts SET display_name = '❤️ Gesundheitsindikatoren' WHERE slug = 'gesundheit' AND display_name IS NULL;
|
||||
UPDATE ai_prompts SET display_name = '🎯 Zielfortschritt' WHERE slug = 'ziele' AND display_name IS NULL;
|
||||
UPDATE ai_prompts SET display_name = '🔬 Mehrstufige Gesamtanalyse' WHERE slug = 'pipeline' AND display_name IS NULL;
|
||||
UPDATE ai_prompts SET display_name = '🔬 Pipeline: Körper-Analyse (JSON)' WHERE slug = 'pipeline_body' AND display_name IS NULL;
|
||||
UPDATE ai_prompts SET display_name = '🔬 Pipeline: Ernährungs-Analyse (JSON)' WHERE slug = 'pipeline_nutrition' AND display_name IS NULL;
|
||||
UPDATE ai_prompts SET display_name = '🔬 Pipeline: Aktivitäts-Analyse (JSON)' WHERE slug = 'pipeline_activity' AND display_name IS NULL;
|
||||
UPDATE ai_prompts SET display_name = '🔬 Pipeline: Synthese' WHERE slug = 'pipeline_synthesis' AND display_name IS NULL;
|
||||
UPDATE ai_prompts SET display_name = '🔬 Pipeline: Zielabgleich' WHERE slug = 'pipeline_goals' AND display_name IS NULL;
|
||||
|
||||
-- Fallback: use name as display_name if still NULL
|
||||
UPDATE ai_prompts SET display_name = name WHERE display_name IS NULL;
|
||||
@@ -0,0 +1,157 @@
|
||||
-- Migration 019: Pipeline-System - Konfigurierbare mehrstufige Analysen
|
||||
-- Ermöglicht Admin-Verwaltung von Pipeline-Konfigurationen (Issue #28)
|
||||
-- Created: 2026-03-25
|
||||
|
||||
-- ========================================
|
||||
-- 1. Erweitere ai_prompts für Reset-Feature
|
||||
-- ========================================
|
||||
ALTER TABLE ai_prompts
|
||||
ADD COLUMN IF NOT EXISTS is_system_default BOOLEAN DEFAULT FALSE,
|
||||
ADD COLUMN IF NOT EXISTS default_template TEXT;
|
||||
|
||||
COMMENT ON COLUMN ai_prompts.is_system_default IS 'true = System-Prompt mit Reset-Funktion';
|
||||
COMMENT ON COLUMN ai_prompts.default_template IS 'Original-Template für Reset-to-Default';
|
||||
|
||||
-- Markiere bestehende Pipeline-Prompts als System-Defaults
|
||||
UPDATE ai_prompts
|
||||
SET
|
||||
is_system_default = true,
|
||||
default_template = template
|
||||
WHERE slug LIKE 'pipeline_%';
|
||||
|
||||
-- ========================================
|
||||
-- 2. Create pipeline_configs table
|
||||
-- ========================================
|
||||
CREATE TABLE IF NOT EXISTS pipeline_configs (
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
name VARCHAR(255) NOT NULL UNIQUE,
|
||||
description TEXT,
|
||||
is_default BOOLEAN DEFAULT FALSE,
|
||||
active BOOLEAN DEFAULT TRUE,
|
||||
|
||||
-- Module configuration: which data sources to include
|
||||
modules JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
-- Example: {"körper": true, "ernährung": true, "training": true, "schlaf": false}
|
||||
|
||||
-- Timeframes per module (days)
|
||||
timeframes JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
-- Example: {"körper": 30, "ernährung": 30, "training": 14}
|
||||
|
||||
-- Stage 1 prompts (parallel execution)
|
||||
stage1_prompts TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[],
|
||||
-- Example: ARRAY['pipeline_body', 'pipeline_nutrition', 'pipeline_activity']
|
||||
|
||||
-- Stage 2 prompt (synthesis)
|
||||
stage2_prompt VARCHAR(100) NOT NULL,
|
||||
-- Example: 'pipeline_synthesis'
|
||||
|
||||
-- Stage 3 prompt (optional, e.g., goals)
|
||||
stage3_prompt VARCHAR(100),
|
||||
-- Example: 'pipeline_goals'
|
||||
|
||||
created TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
updated TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- ========================================
|
||||
-- 3. Create indexes
|
||||
-- ========================================
|
||||
CREATE INDEX IF NOT EXISTS idx_pipeline_configs_default ON pipeline_configs(is_default) WHERE is_default = true;
|
||||
CREATE INDEX IF NOT EXISTS idx_pipeline_configs_active ON pipeline_configs(active);
|
||||
|
||||
-- ========================================
|
||||
-- 4. Seed: Standard-Pipeline "Alltags-Check"
|
||||
-- ========================================
|
||||
INSERT INTO pipeline_configs (
|
||||
name,
|
||||
description,
|
||||
is_default,
|
||||
modules,
|
||||
timeframes,
|
||||
stage1_prompts,
|
||||
stage2_prompt,
|
||||
stage3_prompt
|
||||
) VALUES (
|
||||
'Alltags-Check',
|
||||
'Standard-Analyse: Körper, Ernährung, Training über die letzten 2-4 Wochen',
|
||||
true,
|
||||
'{"körper": true, "ernährung": true, "training": true, "schlaf": false, "vitalwerte": false, "mentales": false, "ziele": false}'::jsonb,
|
||||
'{"körper": 30, "ernährung": 30, "training": 14}'::jsonb,
|
||||
ARRAY['pipeline_body', 'pipeline_nutrition', 'pipeline_activity'],
|
||||
'pipeline_synthesis',
|
||||
'pipeline_goals'
|
||||
) ON CONFLICT (name) DO NOTHING;
|
||||
|
||||
-- ========================================
|
||||
-- 5. Seed: Erweiterte Pipelines (optional)
|
||||
-- ========================================
|
||||
|
||||
-- Schlaf-Fokus Pipeline (wenn Schlaf-Prompts existieren)
|
||||
INSERT INTO pipeline_configs (
|
||||
name,
|
||||
description,
|
||||
is_default,
|
||||
modules,
|
||||
timeframes,
|
||||
stage1_prompts,
|
||||
stage2_prompt,
|
||||
stage3_prompt
|
||||
) VALUES (
|
||||
'Schlaf & Erholung',
|
||||
'Analyse von Schlaf, Vitalwerten und Erholungsstatus',
|
||||
false,
|
||||
'{"schlaf": true, "vitalwerte": true, "training": true, "körper": false, "ernährung": false, "mentales": false, "ziele": false}'::jsonb,
|
||||
'{"schlaf": 14, "vitalwerte": 7, "training": 14}'::jsonb,
|
||||
ARRAY['pipeline_sleep', 'pipeline_vitals', 'pipeline_activity'],
|
||||
'pipeline_synthesis',
|
||||
NULL
|
||||
) ON CONFLICT (name) DO NOTHING;
|
||||
|
||||
-- Wettkampf-Analyse (langfristiger Trend)
|
||||
INSERT INTO pipeline_configs (
|
||||
name,
|
||||
description,
|
||||
is_default,
|
||||
modules,
|
||||
timeframes,
|
||||
stage1_prompts,
|
||||
stage2_prompt,
|
||||
stage3_prompt
|
||||
) VALUES (
|
||||
'Wettkampf-Analyse',
|
||||
'Langfristige Analyse für Wettkampfvorbereitung (90 Tage)',
|
||||
false,
|
||||
'{"körper": true, "training": true, "vitalwerte": true, "ernährung": true, "schlaf": false, "mentales": false, "ziele": true}'::jsonb,
|
||||
'{"körper": 90, "training": 90, "vitalwerte": 30, "ernährung": 60}'::jsonb,
|
||||
ARRAY['pipeline_body', 'pipeline_activity', 'pipeline_vitals', 'pipeline_nutrition'],
|
||||
'pipeline_synthesis',
|
||||
'pipeline_goals'
|
||||
) ON CONFLICT (name) DO NOTHING;
|
||||
|
||||
-- ========================================
|
||||
-- 6. Trigger für updated timestamp
|
||||
-- ========================================
|
||||
DROP TRIGGER IF EXISTS trigger_pipeline_configs_updated ON pipeline_configs;
|
||||
CREATE TRIGGER trigger_pipeline_configs_updated
|
||||
BEFORE UPDATE ON pipeline_configs
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_updated_timestamp();
|
||||
|
||||
-- ========================================
|
||||
-- 7. Constraints & Validation
|
||||
-- ========================================
|
||||
|
||||
-- Only one default config allowed (enforced via partial unique index)
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_pipeline_configs_single_default
|
||||
ON pipeline_configs(is_default)
|
||||
WHERE is_default = true;
|
||||
|
||||
-- ========================================
|
||||
-- 8. Comments (Documentation)
|
||||
-- ========================================
|
||||
COMMENT ON TABLE pipeline_configs IS 'v9f Issue #28: Konfigurierbare Pipeline-Analysen. Admins können mehrere Pipeline-Configs erstellen mit unterschiedlichen Modulen und Zeiträumen.';
|
||||
COMMENT ON COLUMN pipeline_configs.modules IS 'JSONB: Welche Module aktiv sind (boolean flags)';
|
||||
COMMENT ON COLUMN pipeline_configs.timeframes IS 'JSONB: Zeiträume pro Modul in Tagen';
|
||||
COMMENT ON COLUMN pipeline_configs.stage1_prompts IS 'Array von slug-Werten für parallele Stage-1-Prompts';
|
||||
COMMENT ON COLUMN pipeline_configs.stage2_prompt IS 'Slug des Synthese-Prompts (kombiniert Stage-1-Ergebnisse)';
|
||||
COMMENT ON COLUMN pipeline_configs.stage3_prompt IS 'Optionaler Slug für Stage-3-Prompt (z.B. Zielabgleich)';
|
||||
@@ -0,0 +1,128 @@
|
||||
-- Migration 020: Unified Prompt System (Issue #28)
|
||||
-- Consolidate ai_prompts and pipeline_configs into single system
|
||||
-- Type: 'base' (reusable building blocks) or 'pipeline' (workflows)
|
||||
|
||||
-- Step 1: Add new columns to ai_prompts and make template nullable
|
||||
ALTER TABLE ai_prompts
|
||||
ADD COLUMN IF NOT EXISTS type VARCHAR(20) DEFAULT 'pipeline',
|
||||
ADD COLUMN IF NOT EXISTS stages JSONB,
|
||||
ADD COLUMN IF NOT EXISTS output_format VARCHAR(10) DEFAULT 'text',
|
||||
ADD COLUMN IF NOT EXISTS output_schema JSONB;
|
||||
|
||||
-- Make template nullable (pipeline-type prompts use stages instead)
|
||||
ALTER TABLE ai_prompts
|
||||
ALTER COLUMN template DROP NOT NULL;
|
||||
|
||||
-- Step 2: Migrate existing single-prompts to 1-stage pipeline format
|
||||
-- All existing prompts become single-stage pipelines with inline source
|
||||
UPDATE ai_prompts
|
||||
SET
|
||||
type = 'pipeline',
|
||||
stages = jsonb_build_array(
|
||||
jsonb_build_object(
|
||||
'stage', 1,
|
||||
'prompts', jsonb_build_array(
|
||||
jsonb_build_object(
|
||||
'source', 'inline',
|
||||
'template', template,
|
||||
'output_key', REPLACE(slug, 'pipeline_', ''),
|
||||
'output_format', 'text'
|
||||
)
|
||||
)
|
||||
)
|
||||
),
|
||||
output_format = 'text'
|
||||
WHERE stages IS NULL;
|
||||
|
||||
-- Step 3: Migrate pipeline_configs into ai_prompts as multi-stage pipelines
|
||||
-- Each pipeline_config becomes a pipeline-type prompt with multiple stages
|
||||
INSERT INTO ai_prompts (
|
||||
slug,
|
||||
name,
|
||||
description,
|
||||
type,
|
||||
stages,
|
||||
output_format,
|
||||
active,
|
||||
is_system_default,
|
||||
category
|
||||
)
|
||||
SELECT
|
||||
'pipeline_config_' || LOWER(REPLACE(pc.name, ' ', '_')) || '_' || SUBSTRING(pc.id::TEXT FROM 1 FOR 8) as slug,
|
||||
pc.name,
|
||||
pc.description,
|
||||
'pipeline' as type,
|
||||
-- Build stages JSONB: combine stage1_prompts, stage2_prompt, stage3_prompt
|
||||
(
|
||||
-- Stage 1: Convert array to prompts
|
||||
SELECT jsonb_agg(stage_obj ORDER BY stage_num)
|
||||
FROM (
|
||||
SELECT 1 as stage_num,
|
||||
jsonb_build_object(
|
||||
'stage', 1,
|
||||
'prompts', (
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'source', 'reference',
|
||||
'slug', s1.slug_val,
|
||||
'output_key', REPLACE(s1.slug_val, 'pipeline_', 'stage1_'),
|
||||
'output_format', 'json'
|
||||
)
|
||||
)
|
||||
FROM UNNEST(pc.stage1_prompts) AS s1(slug_val)
|
||||
)
|
||||
) as stage_obj
|
||||
WHERE array_length(pc.stage1_prompts, 1) > 0
|
||||
|
||||
UNION ALL
|
||||
|
||||
SELECT 2 as stage_num,
|
||||
jsonb_build_object(
|
||||
'stage', 2,
|
||||
'prompts', jsonb_build_array(
|
||||
jsonb_build_object(
|
||||
'source', 'reference',
|
||||
'slug', pc.stage2_prompt,
|
||||
'output_key', 'synthesis',
|
||||
'output_format', 'text'
|
||||
)
|
||||
)
|
||||
) as stage_obj
|
||||
WHERE pc.stage2_prompt IS NOT NULL
|
||||
|
||||
UNION ALL
|
||||
|
||||
SELECT 3 as stage_num,
|
||||
jsonb_build_object(
|
||||
'stage', 3,
|
||||
'prompts', jsonb_build_array(
|
||||
jsonb_build_object(
|
||||
'source', 'reference',
|
||||
'slug', pc.stage3_prompt,
|
||||
'output_key', 'goals',
|
||||
'output_format', 'text'
|
||||
)
|
||||
)
|
||||
) as stage_obj
|
||||
WHERE pc.stage3_prompt IS NOT NULL
|
||||
) all_stages
|
||||
) as stages,
|
||||
'text' as output_format,
|
||||
pc.active,
|
||||
pc.is_default as is_system_default,
|
||||
'pipeline' as category
|
||||
FROM pipeline_configs pc;
|
||||
|
||||
-- Step 4: Add indices for performance
|
||||
CREATE INDEX IF NOT EXISTS idx_ai_prompts_type ON ai_prompts(type);
|
||||
CREATE INDEX IF NOT EXISTS idx_ai_prompts_stages ON ai_prompts USING GIN (stages);
|
||||
|
||||
-- Step 5: Add comment explaining stages structure
|
||||
COMMENT ON COLUMN ai_prompts.stages IS 'JSONB array of stages, each with prompts array. Structure: [{"stage":1,"prompts":[{"source":"reference|inline","slug":"...","template":"...","output_key":"key","output_format":"text|json"}]}]';
|
||||
|
||||
-- Step 6: Backup pipeline_configs before eventual deletion
|
||||
CREATE TABLE IF NOT EXISTS pipeline_configs_backup_pre_020 AS
|
||||
SELECT * FROM pipeline_configs;
|
||||
|
||||
-- Note: We keep pipeline_configs table for now during transition period
|
||||
-- It can be dropped in a later migration once all code is migrated
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Migration 021: Add metadata column to ai_insights for storing debug info
|
||||
-- Date: 2026-03-26
|
||||
-- Purpose: Store resolved placeholder values with descriptions for transparency
|
||||
|
||||
ALTER TABLE ai_insights ADD COLUMN IF NOT EXISTS metadata JSONB DEFAULT NULL;
|
||||
|
||||
COMMENT ON COLUMN ai_insights.metadata IS 'Debug info: resolved placeholders, descriptions, etc.';
|
||||
@@ -0,0 +1,135 @@
|
||||
-- Migration 022: Goal System (Strategic + Tactical)
|
||||
-- Date: 2026-03-26
|
||||
-- Purpose: Two-level goal architecture for AI-driven coaching
|
||||
|
||||
-- ============================================================================
|
||||
-- STRATEGIC LAYER: Goal Modes
|
||||
-- ============================================================================
|
||||
|
||||
-- Add goal_mode to profiles (strategic training direction)
|
||||
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS goal_mode VARCHAR(50) DEFAULT 'health';
|
||||
|
||||
COMMENT ON COLUMN profiles.goal_mode IS
|
||||
'Strategic goal mode: weight_loss, strength, endurance, recomposition, health.
|
||||
Determines score weights and interpretation context for all analyses.';
|
||||
|
||||
-- ============================================================================
|
||||
-- TACTICAL LAYER: Concrete Goal Targets
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS goals (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
|
||||
-- Goal Classification
|
||||
goal_type VARCHAR(50) NOT NULL, -- weight, body_fat, lean_mass, vo2max, strength, flexibility, bp, rhr
|
||||
is_primary BOOLEAN DEFAULT false,
|
||||
status VARCHAR(20) DEFAULT 'active', -- draft, active, reached, abandoned, expired
|
||||
|
||||
-- Target Values
|
||||
target_value DECIMAL(10,2),
|
||||
current_value DECIMAL(10,2),
|
||||
start_value DECIMAL(10,2),
|
||||
unit VARCHAR(20), -- kg, %, ml/kg/min, bpm, mmHg, cm, reps
|
||||
|
||||
-- Timeline
|
||||
start_date DATE DEFAULT CURRENT_DATE,
|
||||
target_date DATE,
|
||||
reached_date DATE,
|
||||
|
||||
-- Metadata
|
||||
name VARCHAR(100), -- e.g., "Sommerfigur 2026"
|
||||
description TEXT,
|
||||
|
||||
-- Progress Tracking
|
||||
progress_pct DECIMAL(5,2), -- Auto-calculated: (current - start) / (target - start) * 100
|
||||
projection_date DATE, -- Prognose wann Ziel erreicht wird
|
||||
on_track BOOLEAN, -- true wenn Prognose <= target_date
|
||||
|
||||
-- Timestamps
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_goals_profile ON goals(profile_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_goals_status ON goals(profile_id, status);
|
||||
CREATE INDEX IF NOT EXISTS idx_goals_primary ON goals(profile_id, is_primary) WHERE is_primary = true;
|
||||
|
||||
COMMENT ON TABLE goals IS 'Concrete user goals (tactical targets)';
|
||||
COMMENT ON COLUMN goals.goal_type IS 'Type of goal: weight, body_fat, lean_mass, vo2max, strength, flexibility, bp, rhr';
|
||||
COMMENT ON COLUMN goals.is_primary IS 'Primary goal gets highest priority in scoring and charts';
|
||||
COMMENT ON COLUMN goals.status IS 'draft = not yet started, active = in progress, reached = successfully completed, abandoned = given up, expired = deadline passed';
|
||||
COMMENT ON COLUMN goals.progress_pct IS 'Percentage progress: (current_value - start_value) / (target_value - start_value) * 100';
|
||||
COMMENT ON COLUMN goals.projection_date IS 'Projected date when goal will be reached based on current trend';
|
||||
COMMENT ON COLUMN goals.on_track IS 'true if projection_date <= target_date (goal reachable on time)';
|
||||
|
||||
-- ============================================================================
|
||||
-- TRAINING PHASES (Auto-Detection)
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS training_phases (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
|
||||
-- Phase Classification
|
||||
phase_type VARCHAR(50) NOT NULL, -- calorie_deficit, calorie_surplus, deload, maintenance, periodization
|
||||
detected_automatically BOOLEAN DEFAULT false,
|
||||
confidence_score DECIMAL(3,2), -- 0.00 - 1.00 (Wie sicher ist die Erkennung?)
|
||||
status VARCHAR(20) DEFAULT 'suggested', -- suggested, accepted, active, completed, rejected
|
||||
|
||||
-- Timeframe
|
||||
start_date DATE NOT NULL,
|
||||
end_date DATE,
|
||||
duration_days INT,
|
||||
|
||||
-- Detection Criteria (JSONB für Flexibilität)
|
||||
detection_params JSONB, -- { "avg_calories": 1800, "weight_trend": -0.3, ... }
|
||||
|
||||
-- User Notes
|
||||
notes TEXT,
|
||||
|
||||
-- Timestamps
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_training_phases_profile ON training_phases(profile_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_training_phases_status ON training_phases(profile_id, status);
|
||||
CREATE INDEX IF NOT EXISTS idx_training_phases_dates ON training_phases(profile_id, start_date, end_date);
|
||||
|
||||
COMMENT ON TABLE training_phases IS 'Training phases detected from data patterns or manually defined';
|
||||
COMMENT ON COLUMN training_phases.phase_type IS 'calorie_deficit, calorie_surplus, deload, maintenance, periodization';
|
||||
COMMENT ON COLUMN training_phases.detected_automatically IS 'true if AI detected this phase from data patterns';
|
||||
COMMENT ON COLUMN training_phases.confidence_score IS 'AI confidence in detection (0.0 - 1.0)';
|
||||
COMMENT ON COLUMN training_phases.status IS 'suggested = AI proposed, accepted = user confirmed, active = currently running, completed = finished, rejected = user dismissed';
|
||||
COMMENT ON COLUMN training_phases.detection_params IS 'JSON with detection criteria: avg_calories, weight_trend, activity_volume, etc.';
|
||||
|
||||
-- ============================================================================
|
||||
-- FITNESS TESTS (Standardized Performance Tests)
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS fitness_tests (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
|
||||
-- Test Type
|
||||
test_type VARCHAR(50) NOT NULL, -- cooper_12min, step_test, pushups_max, plank_max, flexibility_sit_reach, vo2max_est, strength_1rm_squat, strength_1rm_bench
|
||||
result_value DECIMAL(10,2) NOT NULL,
|
||||
result_unit VARCHAR(20) NOT NULL, -- meters, bpm, reps, seconds, cm, ml/kg/min, kg
|
||||
|
||||
-- Test Metadata
|
||||
test_date DATE NOT NULL,
|
||||
test_conditions TEXT, -- Optional: Notizen zu Bedingungen
|
||||
norm_category VARCHAR(30), -- sehr gut, gut, durchschnitt, unterdurchschnitt, schlecht
|
||||
|
||||
-- Timestamps
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_fitness_tests_profile ON fitness_tests(profile_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_fitness_tests_type ON fitness_tests(profile_id, test_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_fitness_tests_date ON fitness_tests(profile_id, test_date);
|
||||
|
||||
COMMENT ON TABLE fitness_tests IS 'Standardized fitness tests (Cooper, step test, strength tests, etc.)';
|
||||
COMMENT ON COLUMN fitness_tests.test_type IS 'cooper_12min, step_test, pushups_max, plank_max, flexibility_sit_reach, vo2max_est, strength_1rm_squat, strength_1rm_bench';
|
||||
COMMENT ON COLUMN fitness_tests.norm_category IS 'Performance category based on age/gender norms';
|
||||
@@ -0,0 +1,185 @@
|
||||
-- Migration 024: Goal Type Registry (Flexible Goal System)
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Enable dynamic goal types without code changes
|
||||
|
||||
-- ============================================================================
|
||||
-- Goal Type Definitions
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS goal_type_definitions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
|
||||
-- Unique identifier (used in code)
|
||||
type_key VARCHAR(50) UNIQUE NOT NULL,
|
||||
|
||||
-- Display metadata
|
||||
label_de VARCHAR(100) NOT NULL,
|
||||
label_en VARCHAR(100),
|
||||
unit VARCHAR(20) NOT NULL,
|
||||
icon VARCHAR(10),
|
||||
category VARCHAR(50), -- body, mind, activity, nutrition, recovery, custom
|
||||
|
||||
-- Data source configuration
|
||||
source_table VARCHAR(50), -- Which table to query
|
||||
source_column VARCHAR(50), -- Which column to fetch
|
||||
aggregation_method VARCHAR(20), -- How to aggregate: latest, avg_7d, avg_30d, sum_30d, count_7d, count_30d, min_30d, max_30d
|
||||
|
||||
-- Complex calculations (optional)
|
||||
-- For types like lean_mass that need custom logic
|
||||
-- JSON format: {"type": "formula", "dependencies": ["weight", "body_fat"], "expression": "..."}
|
||||
calculation_formula TEXT,
|
||||
|
||||
-- Metadata
|
||||
description TEXT,
|
||||
is_active BOOLEAN DEFAULT true,
|
||||
is_system BOOLEAN DEFAULT false, -- System types cannot be deleted
|
||||
|
||||
-- Audit
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_goal_type_definitions_active ON goal_type_definitions(is_active) WHERE is_active = true;
|
||||
CREATE INDEX IF NOT EXISTS idx_goal_type_definitions_category ON goal_type_definitions(category);
|
||||
|
||||
COMMENT ON TABLE goal_type_definitions IS 'Registry of available goal types - allows dynamic goal creation without code changes';
|
||||
COMMENT ON COLUMN goal_type_definitions.type_key IS 'Unique key used in code (e.g., weight, meditation_minutes)';
|
||||
COMMENT ON COLUMN goal_type_definitions.aggregation_method IS 'latest = most recent value, avg_7d = 7-day average, count_7d = count in last 7 days, etc.';
|
||||
COMMENT ON COLUMN goal_type_definitions.calculation_formula IS 'JSON for complex calculations like lean_mass = weight - (weight * bf_pct / 100)';
|
||||
COMMENT ON COLUMN goal_type_definitions.is_system IS 'System types are protected from deletion (core functionality)';
|
||||
|
||||
-- ============================================================================
|
||||
-- Seed Data: Migrate existing 8 goal types
|
||||
-- ============================================================================
|
||||
|
||||
-- 1. Weight (simple - latest value)
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'weight', 'Gewicht', 'Weight', 'kg', '⚖️', 'body',
|
||||
'weight_log', 'weight', 'latest',
|
||||
'Aktuelles Körpergewicht', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 2. Body Fat (simple - latest value)
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'body_fat', 'Körperfett', 'Body Fat', '%', '📊', 'body',
|
||||
'caliper_log', 'body_fat_pct', 'latest',
|
||||
'Körperfettanteil aus Caliper-Messung', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 3. Lean Mass (complex - calculation formula)
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
calculation_formula,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'lean_mass', 'Muskelmasse', 'Lean Mass', 'kg', '💪', 'body',
|
||||
'{"type": "lean_mass", "dependencies": ["weight_log.weight", "caliper_log.body_fat_pct"], "formula": "weight - (weight * body_fat_pct / 100)"}',
|
||||
'Fettfreie Körpermasse (berechnet aus Gewicht und Körperfett)', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 4. VO2 Max (simple - latest value)
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'vo2max', 'VO2Max', 'VO2Max', 'ml/kg/min', '🫁', 'recovery',
|
||||
'vitals_baseline', 'vo2_max', 'latest',
|
||||
'Maximale Sauerstoffaufnahme (geschätzt oder gemessen)', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 5. Resting Heart Rate (simple - latest value)
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'rhr', 'Ruhepuls', 'Resting Heart Rate', 'bpm', '💓', 'recovery',
|
||||
'vitals_baseline', 'resting_hr', 'latest',
|
||||
'Ruhepuls morgens vor dem Aufstehen', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 6. Blood Pressure (placeholder - compound goal for v2.0)
|
||||
-- Currently limited to single value, v2.0 will support systolic/diastolic
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'bp', 'Blutdruck', 'Blood Pressure', 'mmHg', '❤️', 'recovery',
|
||||
'blood_pressure_log', 'systolic', 'latest',
|
||||
'Blutdruck (aktuell nur systolisch, v2.0: beide Werte)', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 7. Strength (placeholder - no data source yet)
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
description, is_system, is_active
|
||||
) VALUES (
|
||||
'strength', 'Kraft', 'Strength', 'kg', '🏋️', 'activity',
|
||||
'Maximalkraft (Platzhalter, Datenquelle in v2.0)', true, false
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 8. Flexibility (placeholder - no data source yet)
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
description, is_system, is_active
|
||||
) VALUES (
|
||||
'flexibility', 'Beweglichkeit', 'Flexibility', 'cm', '🤸', 'activity',
|
||||
'Beweglichkeit (Platzhalter, Datenquelle in v2.0)', true, false
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- ============================================================================
|
||||
-- Example: Future custom goal types (commented out, for reference)
|
||||
-- ============================================================================
|
||||
|
||||
/*
|
||||
-- Meditation Minutes (avg last 7 days)
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'meditation_minutes', 'Meditation', 'min/Tag', '🧘', 'mind',
|
||||
'meditation_log', 'duration_minutes', 'avg_7d',
|
||||
'Durchschnittliche Meditationsdauer pro Tag (7 Tage)', false
|
||||
);
|
||||
|
||||
-- Training Frequency (count last 7 days)
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'training_frequency', 'Trainingshäufigkeit', 'x/Woche', '📅', 'activity',
|
||||
'activity_log', 'id', 'count_7d',
|
||||
'Anzahl Trainingseinheiten pro Woche', false
|
||||
);
|
||||
|
||||
-- Sleep Quality (avg last 7 days)
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'sleep_quality', 'Schlafqualität', '%', '💤', 'recovery',
|
||||
'sleep_log', 'quality_score', 'avg_7d',
|
||||
'Durchschnittliche Schlafqualität (Deep+REM Anteil)', false
|
||||
);
|
||||
*/
|
||||
@@ -0,0 +1,103 @@
|
||||
-- Migration 025: Cleanup goal_type_definitions
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Remove problematic FK columns and ensure seed data
|
||||
|
||||
-- Remove created_by/updated_by columns if they exist
|
||||
-- (May have been created by failed Migration 024)
|
||||
ALTER TABLE goal_type_definitions DROP COLUMN IF EXISTS created_by;
|
||||
ALTER TABLE goal_type_definitions DROP COLUMN IF EXISTS updated_by;
|
||||
|
||||
-- Re-insert seed data (ON CONFLICT ensures idempotency)
|
||||
-- This fixes cases where Migration 024 created table but failed to seed
|
||||
|
||||
-- 1. Weight
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'weight', 'Gewicht', 'Weight', 'kg', '⚖️', 'body',
|
||||
'weight_log', 'weight', 'latest',
|
||||
'Aktuelles Körpergewicht', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 2. Body Fat
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'body_fat', 'Körperfett', 'Body Fat', '%', '📊', 'body',
|
||||
'caliper_log', 'body_fat_pct', 'latest',
|
||||
'Körperfettanteil aus Caliper-Messung', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 3. Lean Mass
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
calculation_formula,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'lean_mass', 'Muskelmasse', 'Lean Mass', 'kg', '💪', 'body',
|
||||
'{"type": "lean_mass", "dependencies": ["weight_log.weight", "caliper_log.body_fat_pct"], "formula": "weight - (weight * body_fat_pct / 100)"}',
|
||||
'Fettfreie Körpermasse (berechnet aus Gewicht und Körperfett)', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 4. VO2 Max
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'vo2max', 'VO2Max', 'VO2Max', 'ml/kg/min', '🫁', 'recovery',
|
||||
'vitals_baseline', 'vo2_max', 'latest',
|
||||
'Maximale Sauerstoffaufnahme (geschätzt oder gemessen)', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 5. Resting Heart Rate
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'rhr', 'Ruhepuls', 'Resting Heart Rate', 'bpm', '💓', 'recovery',
|
||||
'vitals_baseline', 'resting_hr', 'latest',
|
||||
'Ruhepuls morgens vor dem Aufstehen', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 6. Blood Pressure
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'bp', 'Blutdruck', 'Blood Pressure', 'mmHg', '❤️', 'recovery',
|
||||
'blood_pressure_log', 'systolic', 'latest',
|
||||
'Blutdruck (aktuell nur systolisch, v2.0: beide Werte)', true
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 7. Strength (inactive placeholder)
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
description, is_system, is_active
|
||||
) VALUES (
|
||||
'strength', 'Kraft', 'Strength', 'kg', '🏋️', 'activity',
|
||||
'Maximalkraft (Platzhalter, Datenquelle in v2.0)', true, false
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- 8. Flexibility (inactive placeholder)
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
description, is_system, is_active
|
||||
) VALUES (
|
||||
'flexibility', 'Beweglichkeit', 'Flexibility', 'cm', '🤸', 'activity',
|
||||
'Beweglichkeit (Platzhalter, Datenquelle in v2.0)', true, false
|
||||
)
|
||||
ON CONFLICT (type_key) DO NOTHING;
|
||||
@@ -0,0 +1,40 @@
|
||||
-- Migration 026: Goal Type Filters
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Enable filtered counting/aggregation (e.g., count only strength training)
|
||||
|
||||
-- Add filter_conditions column for flexible filtering
|
||||
ALTER TABLE goal_type_definitions
|
||||
ADD COLUMN IF NOT EXISTS filter_conditions JSONB;
|
||||
|
||||
COMMENT ON COLUMN goal_type_definitions.filter_conditions IS
|
||||
'Optional filter conditions as JSON. Example: {"training_type": "strength"} to count only strength training sessions.
|
||||
Supports any column in the source table. Format: {"column_name": "value"} or {"column_name": ["value1", "value2"]} for IN clause.';
|
||||
|
||||
-- Example usage (commented out):
|
||||
/*
|
||||
-- Count only strength training sessions per week
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
filter_conditions,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'strength_frequency', 'Krafttraining Häufigkeit', 'x/Woche', '🏋️', 'activity',
|
||||
'activity_log', 'id', 'count_7d',
|
||||
'{"training_type": "strength"}',
|
||||
'Anzahl Krafttraining-Einheiten pro Woche', false
|
||||
) ON CONFLICT (type_key) DO NOTHING;
|
||||
|
||||
-- Count only cardio sessions per week
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
filter_conditions,
|
||||
description, is_system
|
||||
) VALUES (
|
||||
'cardio_frequency', 'Cardio Häufigkeit', 'x/Woche', '🏃', 'activity',
|
||||
'activity_log', 'id', 'count_7d',
|
||||
'{"training_type": "cardio"}',
|
||||
'Anzahl Cardio-Einheiten pro Woche', false
|
||||
) ON CONFLICT (type_key) DO NOTHING;
|
||||
*/
|
||||
@@ -0,0 +1,125 @@
|
||||
-- Migration 027: Focus Areas System (Goal System v2.0)
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Replace single primary goal with weighted multi-goal system
|
||||
|
||||
-- ============================================================================
|
||||
-- Focus Areas Table
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS focus_areas (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
|
||||
-- Six focus dimensions (percentages, sum = 100)
|
||||
weight_loss_pct INTEGER DEFAULT 0 CHECK (weight_loss_pct >= 0 AND weight_loss_pct <= 100),
|
||||
muscle_gain_pct INTEGER DEFAULT 0 CHECK (muscle_gain_pct >= 0 AND muscle_gain_pct <= 100),
|
||||
strength_pct INTEGER DEFAULT 0 CHECK (strength_pct >= 0 AND strength_pct <= 100),
|
||||
endurance_pct INTEGER DEFAULT 0 CHECK (endurance_pct >= 0 AND endurance_pct <= 100),
|
||||
flexibility_pct INTEGER DEFAULT 0 CHECK (flexibility_pct >= 0 AND flexibility_pct <= 100),
|
||||
health_pct INTEGER DEFAULT 0 CHECK (health_pct >= 0 AND health_pct <= 100),
|
||||
|
||||
-- Status
|
||||
active BOOLEAN DEFAULT true,
|
||||
|
||||
-- Audit
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW(),
|
||||
|
||||
-- Constraints
|
||||
CONSTRAINT sum_equals_100 CHECK (
|
||||
weight_loss_pct + muscle_gain_pct + strength_pct +
|
||||
endurance_pct + flexibility_pct + health_pct = 100
|
||||
)
|
||||
);
|
||||
|
||||
-- Only one active focus_areas per profile
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_focus_areas_profile_active
|
||||
ON focus_areas(profile_id) WHERE active = true;
|
||||
|
||||
COMMENT ON TABLE focus_areas IS 'User-defined focus area weights (replaces simple goal_mode). Enables multi-goal prioritization with custom percentages.';
|
||||
COMMENT ON COLUMN focus_areas.weight_loss_pct IS 'Focus on fat loss (0-100%)';
|
||||
COMMENT ON COLUMN focus_areas.muscle_gain_pct IS 'Focus on muscle growth (0-100%)';
|
||||
COMMENT ON COLUMN focus_areas.strength_pct IS 'Focus on strength gains (0-100%)';
|
||||
COMMENT ON COLUMN focus_areas.endurance_pct IS 'Focus on aerobic capacity (0-100%)';
|
||||
COMMENT ON COLUMN focus_areas.flexibility_pct IS 'Focus on mobility/flexibility (0-100%)';
|
||||
COMMENT ON COLUMN focus_areas.health_pct IS 'Focus on general health (0-100%)';
|
||||
|
||||
-- ============================================================================
|
||||
-- Migrate existing goal_mode to focus_areas
|
||||
-- ============================================================================
|
||||
|
||||
-- For each profile with a goal_mode, create initial focus_areas
|
||||
INSERT INTO focus_areas (
|
||||
profile_id,
|
||||
weight_loss_pct, muscle_gain_pct, strength_pct,
|
||||
endurance_pct, flexibility_pct, health_pct
|
||||
)
|
||||
SELECT
|
||||
id AS profile_id,
|
||||
CASE goal_mode
|
||||
WHEN 'weight_loss' THEN 60
|
||||
WHEN 'recomposition' THEN 30
|
||||
WHEN 'health' THEN 5
|
||||
ELSE 0
|
||||
END AS weight_loss_pct,
|
||||
|
||||
CASE goal_mode
|
||||
WHEN 'strength' THEN 40 ELSE 0
|
||||
END +
|
||||
CASE goal_mode
|
||||
WHEN 'recomposition' THEN 30 ELSE 0
|
||||
END AS muscle_gain_pct,
|
||||
|
||||
CASE goal_mode
|
||||
WHEN 'strength' THEN 50
|
||||
WHEN 'recomposition' THEN 25
|
||||
WHEN 'weight_loss' THEN 10
|
||||
WHEN 'health' THEN 10
|
||||
ELSE 0
|
||||
END AS strength_pct,
|
||||
|
||||
CASE goal_mode
|
||||
WHEN 'endurance' THEN 70
|
||||
WHEN 'recomposition' THEN 10
|
||||
WHEN 'weight_loss' THEN 20
|
||||
WHEN 'health' THEN 20
|
||||
ELSE 0
|
||||
END AS endurance_pct,
|
||||
|
||||
CASE goal_mode
|
||||
WHEN 'endurance' THEN 10 ELSE 0
|
||||
END +
|
||||
CASE goal_mode
|
||||
WHEN 'health' THEN 15 ELSE 0
|
||||
END +
|
||||
CASE goal_mode
|
||||
WHEN 'recomposition' THEN 5 ELSE 0
|
||||
END +
|
||||
CASE goal_mode
|
||||
WHEN 'weight_loss' THEN 5 ELSE 0
|
||||
END AS flexibility_pct,
|
||||
|
||||
CASE goal_mode
|
||||
WHEN 'health' THEN 50
|
||||
WHEN 'endurance' THEN 20
|
||||
WHEN 'strength' THEN 10
|
||||
WHEN 'weight_loss' THEN 5
|
||||
ELSE 0
|
||||
END AS health_pct
|
||||
FROM profiles
|
||||
WHERE goal_mode IS NOT NULL
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- For profiles without goal_mode, use balanced health focus
|
||||
INSERT INTO focus_areas (
|
||||
profile_id,
|
||||
weight_loss_pct, muscle_gain_pct, strength_pct,
|
||||
endurance_pct, flexibility_pct, health_pct
|
||||
)
|
||||
SELECT
|
||||
id AS profile_id,
|
||||
0, 0, 10, 20, 15, 55
|
||||
FROM profiles
|
||||
WHERE goal_mode IS NULL
|
||||
AND id NOT IN (SELECT profile_id FROM focus_areas WHERE active = true)
|
||||
ON CONFLICT DO NOTHING;
|
||||
@@ -0,0 +1,57 @@
|
||||
-- Migration 028: Goal Categories and Priorities
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Multi-dimensional goal priorities (one primary goal per category)
|
||||
|
||||
-- ============================================================================
|
||||
-- Add category and priority columns
|
||||
-- ============================================================================
|
||||
|
||||
ALTER TABLE goals
|
||||
ADD COLUMN category VARCHAR(50),
|
||||
ADD COLUMN priority INTEGER DEFAULT 2 CHECK (priority >= 1 AND priority <= 3);
|
||||
|
||||
COMMENT ON COLUMN goals.category IS 'Goal category: body, training, nutrition, recovery, health, other';
|
||||
COMMENT ON COLUMN goals.priority IS 'Priority level: 1=high, 2=medium, 3=low';
|
||||
|
||||
-- ============================================================================
|
||||
-- Migrate existing goals to categories based on goal_type
|
||||
-- ============================================================================
|
||||
|
||||
UPDATE goals SET category = CASE
|
||||
-- Body composition goals
|
||||
WHEN goal_type IN ('weight', 'body_fat', 'lean_mass') THEN 'body'
|
||||
|
||||
-- Training goals
|
||||
WHEN goal_type IN ('strength', 'flexibility', 'training_frequency') THEN 'training'
|
||||
|
||||
-- Health/cardio goals
|
||||
WHEN goal_type IN ('vo2max', 'rhr', 'bp', 'hrv') THEN 'health'
|
||||
|
||||
-- Recovery goals
|
||||
WHEN goal_type IN ('sleep_quality', 'sleep_duration', 'rest_days') THEN 'recovery'
|
||||
|
||||
-- Nutrition goals
|
||||
WHEN goal_type IN ('calories', 'protein', 'healthy_eating') THEN 'nutrition'
|
||||
|
||||
-- Default
|
||||
ELSE 'other'
|
||||
END
|
||||
WHERE category IS NULL;
|
||||
|
||||
-- ============================================================================
|
||||
-- Set priority based on is_primary
|
||||
-- ============================================================================
|
||||
|
||||
UPDATE goals SET priority = CASE
|
||||
WHEN is_primary = true THEN 1 -- Primary goals get priority 1
|
||||
ELSE 2 -- Others get priority 2 (medium)
|
||||
END;
|
||||
|
||||
-- ============================================================================
|
||||
-- Create index for category-based queries
|
||||
-- ============================================================================
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_goals_category_priority
|
||||
ON goals(profile_id, category, priority);
|
||||
|
||||
COMMENT ON INDEX idx_goals_category_priority IS 'Fast lookup for category-grouped goals sorted by priority';
|
||||
@@ -0,0 +1,74 @@
|
||||
-- Migration 029: Fix Missing Goal Types (flexibility, strength)
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Ensure flexibility and strength goal types are active and properly configured
|
||||
|
||||
-- These types were created earlier but are inactive or misconfigured
|
||||
-- This migration fixes them without breaking if they don't exist
|
||||
|
||||
-- ============================================================================
|
||||
-- Upsert flexibility goal type
|
||||
-- ============================================================================
|
||||
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
calculation_formula, filter_conditions, description, is_active
|
||||
) VALUES (
|
||||
'flexibility',
|
||||
'Beweglichkeit',
|
||||
'Flexibility',
|
||||
'cm',
|
||||
'🤸',
|
||||
'training',
|
||||
NULL, -- No automatic data source
|
||||
NULL,
|
||||
'latest',
|
||||
NULL,
|
||||
NULL,
|
||||
'Beweglichkeit und Mobilität - manuelle Erfassung',
|
||||
true
|
||||
)
|
||||
ON CONFLICT (type_key)
|
||||
DO UPDATE SET
|
||||
label_de = 'Beweglichkeit',
|
||||
label_en = 'Flexibility',
|
||||
unit = 'cm',
|
||||
icon = '🤸',
|
||||
category = 'training',
|
||||
is_active = true,
|
||||
description = 'Beweglichkeit und Mobilität - manuelle Erfassung';
|
||||
|
||||
-- ============================================================================
|
||||
-- Upsert strength goal type
|
||||
-- ============================================================================
|
||||
|
||||
INSERT INTO goal_type_definitions (
|
||||
type_key, label_de, label_en, unit, icon, category,
|
||||
source_table, source_column, aggregation_method,
|
||||
calculation_formula, filter_conditions, description, is_active
|
||||
) VALUES (
|
||||
'strength',
|
||||
'Kraftniveau',
|
||||
'Strength',
|
||||
'Punkte',
|
||||
'💪',
|
||||
'training',
|
||||
NULL, -- No automatic data source
|
||||
NULL,
|
||||
'latest',
|
||||
NULL,
|
||||
NULL,
|
||||
'Allgemeines Kraftniveau - manuelle Erfassung',
|
||||
true
|
||||
)
|
||||
ON CONFLICT (type_key)
|
||||
DO UPDATE SET
|
||||
label_de = 'Kraftniveau',
|
||||
label_en = 'Strength',
|
||||
unit = 'Punkte',
|
||||
icon = '💪',
|
||||
category = 'training',
|
||||
is_active = true,
|
||||
description = 'Allgemeines Kraftniveau - manuelle Erfassung';
|
||||
|
||||
COMMENT ON TABLE goal_type_definitions IS 'Goal type registry - defines all available goal types (v1.5: DB-driven, flexible system)';
|
||||
@@ -0,0 +1,64 @@
|
||||
-- Migration 030: Goal Progress Log
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Track progress history for all goals (especially custom goals without data source)
|
||||
|
||||
-- ============================================================================
|
||||
-- Goal Progress Log Table
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS goal_progress_log (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
goal_id UUID NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
|
||||
-- Progress data
|
||||
date DATE NOT NULL,
|
||||
value DECIMAL(10,2) NOT NULL,
|
||||
note TEXT,
|
||||
|
||||
-- Metadata
|
||||
source VARCHAR(20) DEFAULT 'manual' CHECK (source IN ('manual', 'automatic', 'import')),
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW(),
|
||||
|
||||
-- Constraints
|
||||
CONSTRAINT unique_progress_per_day UNIQUE(goal_id, date)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_goal_progress_goal_date ON goal_progress_log(goal_id, date DESC);
|
||||
CREATE INDEX idx_goal_progress_profile ON goal_progress_log(profile_id);
|
||||
|
||||
COMMENT ON TABLE goal_progress_log IS 'Progress history for goals - enables manual tracking for custom goals and charts';
|
||||
COMMENT ON COLUMN goal_progress_log.value IS 'Progress value in goal unit (e.g., kg, cm, points)';
|
||||
COMMENT ON COLUMN goal_progress_log.source IS 'manual: user entered, automatic: computed from data source, import: CSV/API';
|
||||
|
||||
-- ============================================================================
|
||||
-- Function: Update goal current_value from latest progress
|
||||
-- ============================================================================
|
||||
|
||||
CREATE OR REPLACE FUNCTION update_goal_current_value()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
-- Update current_value in goals table with latest progress entry
|
||||
UPDATE goals
|
||||
SET current_value = (
|
||||
SELECT value
|
||||
FROM goal_progress_log
|
||||
WHERE goal_id = NEW.goal_id
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
),
|
||||
updated_at = NOW()
|
||||
WHERE id = NEW.goal_id;
|
||||
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- Trigger: Auto-update current_value when progress is added/updated
|
||||
CREATE TRIGGER trigger_update_goal_current_value
|
||||
AFTER INSERT OR UPDATE ON goal_progress_log
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_goal_current_value();
|
||||
|
||||
COMMENT ON FUNCTION update_goal_current_value IS 'Auto-update goal.current_value when new progress is logged';
|
||||
@@ -0,0 +1,254 @@
|
||||
-- Migration 031: Focus Area System v2.0
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Dynamic, extensible focus areas with Many-to-Many goal contributions
|
||||
|
||||
-- ============================================================================
|
||||
-- Part 1: New Tables
|
||||
-- ============================================================================
|
||||
|
||||
-- Focus Area Definitions (dynamic, user-extensible)
|
||||
CREATE TABLE IF NOT EXISTS focus_area_definitions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
key VARCHAR(50) UNIQUE NOT NULL, -- e.g. 'strength', 'aerobic_endurance'
|
||||
name_de VARCHAR(100) NOT NULL,
|
||||
name_en VARCHAR(100),
|
||||
icon VARCHAR(10),
|
||||
description TEXT,
|
||||
category VARCHAR(50), -- 'body_composition', 'training', 'endurance', 'coordination', 'mental', 'recovery', 'health'
|
||||
is_active BOOLEAN DEFAULT true,
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_focus_area_key ON focus_area_definitions(key);
|
||||
CREATE INDEX idx_focus_area_category ON focus_area_definitions(category);
|
||||
|
||||
COMMENT ON TABLE focus_area_definitions IS 'Dynamic focus area registry - defines all available focus dimensions';
|
||||
COMMENT ON COLUMN focus_area_definitions.key IS 'Unique identifier for programmatic access';
|
||||
COMMENT ON COLUMN focus_area_definitions.category IS 'Grouping for UI display';
|
||||
|
||||
-- Many-to-Many: Goals contribute to Focus Areas
|
||||
CREATE TABLE IF NOT EXISTS goal_focus_contributions (
|
||||
goal_id UUID NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
|
||||
focus_area_id UUID NOT NULL REFERENCES focus_area_definitions(id) ON DELETE CASCADE,
|
||||
contribution_weight DECIMAL(5,2) DEFAULT 100.00 CHECK (contribution_weight >= 0 AND contribution_weight <= 100),
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
PRIMARY KEY (goal_id, focus_area_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_gfc_goal ON goal_focus_contributions(goal_id);
|
||||
CREATE INDEX idx_gfc_focus_area ON goal_focus_contributions(focus_area_id);
|
||||
|
||||
COMMENT ON TABLE goal_focus_contributions IS 'Maps goals to focus areas with contribution weights (0-100%)';
|
||||
COMMENT ON COLUMN goal_focus_contributions.contribution_weight IS 'How much this goal contributes to the focus area (0-100%)';
|
||||
|
||||
-- ============================================================================
|
||||
-- Part 2: Rename existing focus_areas table
|
||||
-- ============================================================================
|
||||
|
||||
-- Old focus_areas table becomes user_focus_preferences
|
||||
ALTER TABLE focus_areas RENAME TO user_focus_preferences;
|
||||
|
||||
-- Add reference to new focus_area_definitions (for future use)
|
||||
ALTER TABLE user_focus_preferences ADD COLUMN IF NOT EXISTS notes TEXT;
|
||||
|
||||
COMMENT ON TABLE user_focus_preferences IS 'User-specific focus area weightings (legacy flat structure + new references)';
|
||||
|
||||
-- ============================================================================
|
||||
-- Part 3: Seed Data - Basis Focus Areas
|
||||
-- ============================================================================
|
||||
|
||||
INSERT INTO focus_area_definitions (key, name_de, name_en, icon, category, description) VALUES
|
||||
-- Body Composition
|
||||
('weight_loss', 'Gewichtsverlust', 'Weight Loss', '📉', 'body_composition', 'Körpergewicht reduzieren'),
|
||||
('muscle_gain', 'Muskelaufbau', 'Muscle Gain', '💪', 'body_composition', 'Muskelmasse aufbauen'),
|
||||
('body_recomposition', 'Body Recomposition', 'Body Recomposition', '⚖️', 'body_composition', 'Gleichzeitig Fett abbauen und Muskeln aufbauen'),
|
||||
|
||||
-- Training - Kraft
|
||||
('strength', 'Maximalkraft', 'Strength', '🏋️', 'training', 'Maximale Kraftfähigkeit'),
|
||||
('strength_endurance', 'Kraftausdauer', 'Strength Endurance', '💪🏃', 'training', 'Kraft über längere Zeit aufrechterhalten'),
|
||||
('power', 'Schnellkraft', 'Power', '⚡', 'training', 'Kraft in kurzer Zeit entfalten'),
|
||||
|
||||
-- Training - Beweglichkeit
|
||||
('flexibility', 'Beweglichkeit', 'Flexibility', '🤸', 'training', 'Gelenkigkeit und Bewegungsumfang'),
|
||||
('mobility', 'Mobilität', 'Mobility', '🦴', 'training', 'Aktive Beweglichkeit und Kontrolle'),
|
||||
|
||||
-- Ausdauer
|
||||
('aerobic_endurance', 'Aerobe Ausdauer', 'Aerobic Endurance', '🫁', 'endurance', 'VO2Max, lange moderate Belastung'),
|
||||
('anaerobic_endurance', 'Anaerobe Ausdauer', 'Anaerobic Endurance', '⚡', 'endurance', 'Laktattoleranz, kurze intensive Belastung'),
|
||||
('cardiovascular_health', 'Herz-Kreislauf', 'Cardiovascular Health', '❤️', 'endurance', 'Herzgesundheit und Ausdauer'),
|
||||
|
||||
-- Koordination
|
||||
('balance', 'Gleichgewicht', 'Balance', '⚖️', 'coordination', 'Statisches und dynamisches Gleichgewicht'),
|
||||
('reaction', 'Reaktionsfähigkeit', 'Reaction', '⚡', 'coordination', 'Schnelligkeit der Reaktion auf Reize'),
|
||||
('rhythm', 'Rhythmusgefühl', 'Rhythm', '🎵', 'coordination', 'Zeitliche Abstimmung von Bewegungen'),
|
||||
('coordination', 'Koordination', 'Coordination', '🎯', 'coordination', 'Zusammenspiel verschiedener Bewegungen'),
|
||||
|
||||
-- Mental
|
||||
('stress_resistance', 'Stressresistenz', 'Stress Resistance', '🧘', 'mental', 'Umgang mit mentalem und physischem Stress'),
|
||||
('concentration', 'Konzentration', 'Concentration', '🎯', 'mental', 'Fokussierung und Aufmerksamkeit'),
|
||||
('willpower', 'Willenskraft', 'Willpower', '💎', 'mental', 'Durchhaltevermögen und Selbstdisziplin'),
|
||||
('mental_health', 'Mentale Gesundheit', 'Mental Health', '🧠', 'mental', 'Psychisches Wohlbefinden'),
|
||||
|
||||
-- Recovery
|
||||
('sleep_quality', 'Schlafqualität', 'Sleep Quality', '😴', 'recovery', 'Erholsamer Schlaf'),
|
||||
('regeneration', 'Regeneration', 'Regeneration', '♻️', 'recovery', 'Körperliche Erholung'),
|
||||
('rest', 'Ruhe', 'Rest', '🛌', 'recovery', 'Aktive und passive Erholung'),
|
||||
|
||||
-- Health
|
||||
('metabolic_health', 'Stoffwechselgesundheit', 'Metabolic Health', '🔥', 'health', 'Blutzucker, Insulin, Stoffwechsel'),
|
||||
('blood_pressure', 'Blutdruck', 'Blood Pressure', '❤️🩹', 'health', 'Gesunder Blutdruck'),
|
||||
('hrv', 'Herzratenvariabilität', 'HRV', '💓', 'health', 'Autonomes Nervensystem'),
|
||||
('general_health', 'Allgemeine Gesundheit', 'General Health', '🏥', 'health', 'Vitale Gesundheit und Wohlbefinden')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
|
||||
-- ============================================================================
|
||||
-- Part 4: Auto-Mapping - Bestehende Goals zu Focus Areas
|
||||
-- ============================================================================
|
||||
|
||||
-- Helper function to get focus_area_id by key
|
||||
CREATE OR REPLACE FUNCTION get_focus_area_id(area_key VARCHAR)
|
||||
RETURNS UUID AS $$
|
||||
BEGIN
|
||||
RETURN (SELECT id FROM focus_area_definitions WHERE key = area_key LIMIT 1);
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- Weight goals → weight_loss (100%)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, get_focus_area_id('weight_loss'), 100.00
|
||||
FROM goals g
|
||||
WHERE g.goal_type = 'weight'
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Body Fat goals → weight_loss (60%) + body_recomposition (40%)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, fa.id,
|
||||
CASE fa.key
|
||||
WHEN 'weight_loss' THEN 60.00
|
||||
WHEN 'body_recomposition' THEN 40.00
|
||||
END
|
||||
FROM goals g
|
||||
CROSS JOIN focus_area_definitions fa
|
||||
WHERE g.goal_type = 'body_fat'
|
||||
AND fa.key IN ('weight_loss', 'body_recomposition')
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Lean Mass goals → muscle_gain (70%) + body_recomposition (30%)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, fa.id,
|
||||
CASE fa.key
|
||||
WHEN 'muscle_gain' THEN 70.00
|
||||
WHEN 'body_recomposition' THEN 30.00
|
||||
END
|
||||
FROM goals g
|
||||
CROSS JOIN focus_area_definitions fa
|
||||
WHERE g.goal_type = 'lean_mass'
|
||||
AND fa.key IN ('muscle_gain', 'body_recomposition')
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Strength goals → strength (70%) + muscle_gain (30%)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, fa.id,
|
||||
CASE fa.key
|
||||
WHEN 'strength' THEN 70.00
|
||||
WHEN 'muscle_gain' THEN 30.00
|
||||
END
|
||||
FROM goals g
|
||||
CROSS JOIN focus_area_definitions fa
|
||||
WHERE g.goal_type = 'strength'
|
||||
AND fa.key IN ('strength', 'muscle_gain')
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Flexibility goals → flexibility (100%)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, get_focus_area_id('flexibility'), 100.00
|
||||
FROM goals g
|
||||
WHERE g.goal_type = 'flexibility'
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- VO2Max goals → aerobic_endurance (80%) + cardiovascular_health (20%)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, fa.id,
|
||||
CASE fa.key
|
||||
WHEN 'aerobic_endurance' THEN 80.00
|
||||
WHEN 'cardiovascular_health' THEN 20.00
|
||||
END
|
||||
FROM goals g
|
||||
CROSS JOIN focus_area_definitions fa
|
||||
WHERE g.goal_type = 'vo2max'
|
||||
AND fa.key IN ('aerobic_endurance', 'cardiovascular_health')
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Resting Heart Rate goals → cardiovascular_health (100%)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, get_focus_area_id('cardiovascular_health'), 100.00
|
||||
FROM goals g
|
||||
WHERE g.goal_type = 'rhr'
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Blood Pressure goals → blood_pressure (80%) + cardiovascular_health (20%)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, fa.id,
|
||||
CASE fa.key
|
||||
WHEN 'blood_pressure' THEN 80.00
|
||||
WHEN 'cardiovascular_health' THEN 20.00
|
||||
END
|
||||
FROM goals g
|
||||
CROSS JOIN focus_area_definitions fa
|
||||
WHERE g.goal_type = 'bp'
|
||||
AND fa.key IN ('blood_pressure', 'cardiovascular_health')
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- HRV goals → hrv (70%) + stress_resistance (30%)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, fa.id,
|
||||
CASE fa.key
|
||||
WHEN 'hrv' THEN 70.00
|
||||
WHEN 'stress_resistance' THEN 30.00
|
||||
END
|
||||
FROM goals g
|
||||
CROSS JOIN focus_area_definitions fa
|
||||
WHERE g.goal_type = 'hrv'
|
||||
AND fa.key IN ('hrv', 'stress_resistance')
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Sleep Quality goals → sleep_quality (100%)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, get_focus_area_id('sleep_quality'), 100.00
|
||||
FROM goals g
|
||||
WHERE g.goal_type = 'sleep_quality'
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Training Frequency goals → general catch-all (strength + endurance)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, fa.id,
|
||||
CASE fa.key
|
||||
WHEN 'strength' THEN 40.00
|
||||
WHEN 'aerobic_endurance' THEN 40.00
|
||||
WHEN 'general_health' THEN 20.00
|
||||
END
|
||||
FROM goals g
|
||||
CROSS JOIN focus_area_definitions fa
|
||||
WHERE g.goal_type = 'training_frequency'
|
||||
AND fa.key IN ('strength', 'aerobic_endurance', 'general_health')
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Cleanup helper function
|
||||
DROP FUNCTION IF EXISTS get_focus_area_id(VARCHAR);
|
||||
|
||||
-- ============================================================================
|
||||
-- Summary
|
||||
-- ============================================================================
|
||||
|
||||
COMMENT ON TABLE focus_area_definitions IS
|
||||
'v2.0: Dynamic focus areas - replaces hardcoded 6-dimension system.
|
||||
26 base areas across 7 categories. User-extensible via admin UI.';
|
||||
|
||||
COMMENT ON TABLE goal_focus_contributions IS
|
||||
'Many-to-Many mapping: Goals contribute to multiple focus areas with weights.
|
||||
Auto-mapped from goal_type, editable by user.';
|
||||
|
||||
COMMENT ON TABLE user_focus_preferences IS
|
||||
'Legacy flat structure (weight_loss_pct, muscle_gain_pct, etc.) remains for backward compatibility.
|
||||
Future: Use focus_area_definitions + dynamic preferences.';
|
||||
@@ -0,0 +1,53 @@
|
||||
-- Migration 032: User Focus Area Weights
|
||||
-- Date: 2026-03-27
|
||||
-- Purpose: Allow users to set custom weights for focus areas (dynamic preferences)
|
||||
|
||||
-- ============================================================================
|
||||
-- User Focus Area Weights (many-to-many with weights)
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_focus_area_weights (
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
focus_area_id UUID NOT NULL REFERENCES focus_area_definitions(id) ON DELETE CASCADE,
|
||||
weight INTEGER NOT NULL DEFAULT 0 CHECK (weight >= 0 AND weight <= 100),
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW(),
|
||||
PRIMARY KEY (profile_id, focus_area_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_user_focus_weights_profile ON user_focus_area_weights(profile_id);
|
||||
CREATE INDEX idx_user_focus_weights_area ON user_focus_area_weights(focus_area_id);
|
||||
|
||||
COMMENT ON TABLE user_focus_area_weights IS 'User-specific weights for focus areas (dynamic system)';
|
||||
COMMENT ON COLUMN user_focus_area_weights.weight IS 'Relative weight (0-100) - will be normalized to percentages in UI';
|
||||
|
||||
-- ============================================================================
|
||||
-- Migrate legacy preferences to dynamic weights
|
||||
-- ============================================================================
|
||||
|
||||
-- For each user with legacy preferences, create weights for the 6 base areas
|
||||
INSERT INTO user_focus_area_weights (profile_id, focus_area_id, weight)
|
||||
SELECT
|
||||
ufp.profile_id,
|
||||
fad.id as focus_area_id,
|
||||
CASE fad.key
|
||||
WHEN 'weight_loss' THEN ufp.weight_loss_pct
|
||||
WHEN 'muscle_gain' THEN ufp.muscle_gain_pct
|
||||
WHEN 'strength' THEN ufp.strength_pct
|
||||
WHEN 'aerobic_endurance' THEN ufp.endurance_pct
|
||||
WHEN 'flexibility' THEN ufp.flexibility_pct
|
||||
WHEN 'general_health' THEN ufp.health_pct
|
||||
ELSE 0
|
||||
END as weight
|
||||
FROM user_focus_preferences ufp
|
||||
CROSS JOIN focus_area_definitions fad
|
||||
WHERE fad.key IN ('weight_loss', 'muscle_gain', 'strength', 'aerobic_endurance', 'flexibility', 'general_health')
|
||||
AND (
|
||||
(fad.key = 'weight_loss' AND ufp.weight_loss_pct > 0) OR
|
||||
(fad.key = 'muscle_gain' AND ufp.muscle_gain_pct > 0) OR
|
||||
(fad.key = 'strength' AND ufp.strength_pct > 0) OR
|
||||
(fad.key = 'aerobic_endurance' AND ufp.endurance_pct > 0) OR
|
||||
(fad.key = 'flexibility' AND ufp.flexibility_pct > 0) OR
|
||||
(fad.key = 'general_health' AND ufp.health_pct > 0)
|
||||
)
|
||||
ON CONFLICT (profile_id, focus_area_id) DO NOTHING;
|
||||
@@ -0,0 +1,97 @@
|
||||
-- Migration 033: Nutrition Focus Areas
|
||||
-- Date: 2026-03-28
|
||||
-- Purpose: Add missing nutrition category to complete focus area coverage
|
||||
|
||||
-- ============================================================================
|
||||
-- Part 1: Add Nutrition Focus Areas
|
||||
-- ============================================================================
|
||||
|
||||
INSERT INTO focus_area_definitions (key, name_de, name_en, icon, category, description) VALUES
|
||||
-- Nutrition Category
|
||||
('protein_intake', 'Proteinzufuhr', 'Protein Intake', '🥩', 'nutrition', 'Ausreichend Protein für Muskelaufbau/-erhalt'),
|
||||
('calorie_balance', 'Kalorienbilanz', 'Calorie Balance', '⚖️', 'nutrition', 'Energiebilanz passend zum Ziel (Defizit/Überschuss)'),
|
||||
('macro_consistency', 'Makro-Konsistenz', 'Macro Consistency', '📊', 'nutrition', 'Gleichmäßige Makronährstoff-Verteilung'),
|
||||
('meal_timing', 'Mahlzeiten-Timing', 'Meal Timing', '⏰', 'nutrition', 'Regelmäßige Mahlzeiten und optimales Timing'),
|
||||
('hydration', 'Flüssigkeitszufuhr', 'Hydration', '💧', 'nutrition', 'Ausreichende Flüssigkeitsaufnahme')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
|
||||
-- ============================================================================
|
||||
-- Part 2: Auto-Mapping for Nutrition-Related Goals
|
||||
-- ============================================================================
|
||||
|
||||
-- Helper function to get focus_area_id by key
|
||||
CREATE OR REPLACE FUNCTION get_focus_area_id(area_key VARCHAR)
|
||||
RETURNS UUID AS $$
|
||||
BEGIN
|
||||
RETURN (SELECT id FROM focus_area_definitions WHERE key = area_key LIMIT 1);
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- Weight Loss goals → calorie_balance (40%) + protein_intake (30%)
|
||||
-- (Already mapped to weight_loss in migration 031, adding nutrition aspects)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, fa.id,
|
||||
CASE fa.key
|
||||
WHEN 'calorie_balance' THEN 40.00
|
||||
WHEN 'protein_intake' THEN 30.00
|
||||
END
|
||||
FROM goals g
|
||||
CROSS JOIN focus_area_definitions fa
|
||||
WHERE g.goal_type = 'weight'
|
||||
AND fa.key IN ('calorie_balance', 'protein_intake')
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Body Fat goals → calorie_balance (30%) + protein_intake (40%)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, fa.id,
|
||||
CASE fa.key
|
||||
WHEN 'calorie_balance' THEN 30.00
|
||||
WHEN 'protein_intake' THEN 40.00
|
||||
END
|
||||
FROM goals g
|
||||
CROSS JOIN focus_area_definitions fa
|
||||
WHERE g.goal_type = 'body_fat'
|
||||
AND fa.key IN ('calorie_balance', 'protein_intake')
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Lean Mass goals → protein_intake (60%) + calorie_balance (20%)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, fa.id,
|
||||
CASE fa.key
|
||||
WHEN 'protein_intake' THEN 60.00
|
||||
WHEN 'calorie_balance' THEN 20.00
|
||||
END
|
||||
FROM goals g
|
||||
CROSS JOIN focus_area_definitions fa
|
||||
WHERE g.goal_type = 'lean_mass'
|
||||
AND fa.key IN ('protein_intake', 'calorie_balance')
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Strength goals → protein_intake (20%)
|
||||
INSERT INTO goal_focus_contributions (goal_id, focus_area_id, contribution_weight)
|
||||
SELECT g.id, get_focus_area_id('protein_intake'), 20.00
|
||||
FROM goals g
|
||||
WHERE g.goal_type = 'strength'
|
||||
ON CONFLICT (goal_id, focus_area_id) DO NOTHING;
|
||||
|
||||
-- Cleanup helper function
|
||||
DROP FUNCTION IF EXISTS get_focus_area_id(VARCHAR);
|
||||
|
||||
-- ============================================================================
|
||||
-- Summary
|
||||
-- ============================================================================
|
||||
|
||||
COMMENT ON COLUMN focus_area_definitions.category IS
|
||||
'Categories: body_composition, training, endurance, coordination, mental, recovery, health, nutrition';
|
||||
|
||||
-- Count nutrition focus areas
|
||||
DO $$
|
||||
DECLARE
|
||||
nutrition_count INT;
|
||||
BEGIN
|
||||
SELECT COUNT(*) INTO nutrition_count
|
||||
FROM focus_area_definitions
|
||||
WHERE category = 'nutrition';
|
||||
|
||||
RAISE NOTICE 'Migration 033 complete: % nutrition focus areas added', nutrition_count;
|
||||
END $$;
|
||||
@@ -0,0 +1,132 @@
|
||||
-- Migration 034: Workflow Foundation
|
||||
-- Phase 0: Datenmodell für Workflow-Erweiterung der Prompt Engine
|
||||
-- Erstellt: 2026-04-03
|
||||
|
||||
-- ============================================================
|
||||
-- Tabelle: workflow_definitions
|
||||
-- Speichert Workflow-Graphen (Knoten + Kanten)
|
||||
-- ============================================================
|
||||
CREATE TABLE IF NOT EXISTS workflow_definitions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name VARCHAR(255) NOT NULL,
|
||||
slug VARCHAR(100) UNIQUE NOT NULL,
|
||||
description TEXT,
|
||||
graph JSONB NOT NULL, -- Der Workflow-Graph (Knoten + Kanten)
|
||||
version INTEGER DEFAULT 1,
|
||||
active BOOLEAN DEFAULT TRUE,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_workflow_definitions_slug ON workflow_definitions(slug);
|
||||
CREATE INDEX IF NOT EXISTS idx_workflow_definitions_active ON workflow_definitions(active);
|
||||
|
||||
-- ============================================================
|
||||
-- Tabelle: workflow_question_catalog
|
||||
-- Katalog der Fragenergänzungen (6 Grundtypen)
|
||||
-- ============================================================
|
||||
CREATE TABLE IF NOT EXISTS workflow_question_catalog (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
question_type VARCHAR(50) NOT NULL, -- relevanz, prioritaet, selektion, ausschluss, eskalation, unsicherheit
|
||||
label VARCHAR(255) NOT NULL,
|
||||
question_template TEXT NOT NULL, -- Template für die Frage
|
||||
answer_spectrum JSONB NOT NULL, -- z.B. ["ja", "nein", "unklar"]
|
||||
normalization_rules JSONB, -- Regeln für Normalisierung (Synonyme, etc.)
|
||||
active BOOLEAN DEFAULT TRUE,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_workflow_question_catalog_type ON workflow_question_catalog(question_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_workflow_question_catalog_active ON workflow_question_catalog(active);
|
||||
|
||||
-- Seed: 6 Grundtypen der Fragenergänzungen
|
||||
INSERT INTO workflow_question_catalog (question_type, label, question_template, answer_spectrum, normalization_rules, active) VALUES
|
||||
(
|
||||
'relevanz',
|
||||
'Relevanz-Frage',
|
||||
'Ist eine vertiefte Analyse in diesem Bereich relevant?',
|
||||
'["ja", "nein", "unklar"]'::JSONB,
|
||||
'{"synonyms": {"ja": ["yes", "Ja", "JA", "relevant", "sinnvoll"], "nein": ["no", "Nein", "NEIN", "nicht relevant", "unwichtig"], "unklar": ["unclear", "unsure", "vielleicht", "möglicherweise"]}}'::JSONB,
|
||||
true
|
||||
),
|
||||
(
|
||||
'prioritaet',
|
||||
'Prioritäts-Frage',
|
||||
'Wie hoch ist die Priorität für eine Analyse in diesem Bereich?',
|
||||
'["hoch", "mittel", "niedrig", "unklar"]'::JSONB,
|
||||
'{"synonyms": {"hoch": ["high", "Hoch", "HOCH", "urgent", "dringend"], "mittel": ["medium", "Mittel", "MITTEL", "moderat"], "niedrig": ["low", "Niedrig", "NIEDRIG", "gering"], "unklar": ["unclear", "unsure", "kann nicht einschätzen"]}}'::JSONB,
|
||||
true
|
||||
),
|
||||
(
|
||||
'selektion',
|
||||
'Selektions-Frage',
|
||||
'Soll dieser Pfad ausgewählt werden?',
|
||||
'["ja", "nein", "unklar"]'::JSONB,
|
||||
'{"synonyms": {"ja": ["yes", "Ja", "JA", "auswählen", "select"], "nein": ["no", "Nein", "NEIN", "nicht auswählen", "skip"], "unklar": ["unclear", "unsure", "vielleicht"]}}'::JSONB,
|
||||
true
|
||||
),
|
||||
(
|
||||
'ausschluss',
|
||||
'Ausschluss-Frage',
|
||||
'Soll dieser Pfad ausgeschlossen werden?',
|
||||
'["ja", "nein", "unklar"]'::JSONB,
|
||||
'{"synonyms": {"ja": ["yes", "Ja", "JA", "ausschließen", "exclude"], "nein": ["no", "Nein", "NEIN", "nicht ausschließen", "include"], "unklar": ["unclear", "unsure", "vielleicht"]}}'::JSONB,
|
||||
true
|
||||
),
|
||||
(
|
||||
'eskalation',
|
||||
'Eskalations-Frage',
|
||||
'Ist eine Eskalation oder besondere Aufmerksamkeit erforderlich?',
|
||||
'["ja", "nein", "unklar"]'::JSONB,
|
||||
'{"synonyms": {"ja": ["yes", "Ja", "JA", "eskalieren", "alert"], "nein": ["no", "Nein", "NEIN", "normal", "routine"], "unklar": ["unclear", "unsure", "vielleicht"]}}'::JSONB,
|
||||
true
|
||||
),
|
||||
(
|
||||
'unsicherheit',
|
||||
'Unsicherheits-Frage',
|
||||
'Besteht Unsicherheit in der Bewertung?',
|
||||
'["ja", "nein", "unklar"]'::JSONB,
|
||||
'{"synonyms": {"ja": ["yes", "Ja", "JA", "unsicher", "uncertain"], "nein": ["no", "Nein", "NEIN", "sicher", "certain"], "unklar": ["unclear", "unsure", "vielleicht"]}}'::JSONB,
|
||||
true
|
||||
);
|
||||
|
||||
-- ============================================================
|
||||
-- Tabelle: workflow_executions
|
||||
-- Ausführungs-Log für Workflow-Runs
|
||||
-- ============================================================
|
||||
CREATE TABLE IF NOT EXISTS workflow_executions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
workflow_id UUID REFERENCES workflow_definitions(id) ON DELETE CASCADE,
|
||||
profile_id UUID REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'running', -- running, completed, failed, partial
|
||||
node_states JSONB, -- Status jedes Knotens (executed, skipped, unclear, failed)
|
||||
execution_log JSONB, -- Detaillierter Ablauf
|
||||
started_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
completed_at TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_workflow_executions_workflow_id ON workflow_executions(workflow_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_workflow_executions_profile_id ON workflow_executions(profile_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_workflow_executions_status ON workflow_executions(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_workflow_executions_started_at ON workflow_executions(started_at DESC);
|
||||
|
||||
-- ============================================================
|
||||
-- Erweiterung bestehende Tabelle: ai_prompts
|
||||
-- Optionale Prompt-gebundene Standard-Fragenergänzungen
|
||||
-- (Sekundär: Knotenspezifische Fragen haben Vorrang)
|
||||
-- ============================================================
|
||||
ALTER TABLE ai_prompts
|
||||
ADD COLUMN IF NOT EXISTS question_augmentations JSONB;
|
||||
|
||||
COMMENT ON COLUMN ai_prompts.question_augmentations IS 'Optionale Standard-Fragenergänzungen für diesen Prompt. Knotenspezifische Fragen im Workflow-Graph haben Vorrang (Hybridmodell mit Vorrangregel).';
|
||||
|
||||
-- ============================================================
|
||||
-- Kommentare für Dokumentation
|
||||
-- ============================================================
|
||||
COMMENT ON TABLE workflow_definitions IS 'Workflow-Graphen (Knoten + Kanten) als JSONB. Erweitert die Prompt Engine um verzweigbare, bedingte Analysen.';
|
||||
COMMENT ON TABLE workflow_question_catalog IS 'Katalog der 6 Grundtypen von Fragenergänzungen mit Antwortspektren und Normalisierungsregeln.';
|
||||
COMMENT ON TABLE workflow_executions IS 'Ausführungs-Log für Workflow-Runs mit Knoten-Status und detailliertem Ablauf.';
|
||||
|
||||
COMMENT ON COLUMN workflow_definitions.graph IS 'JSONB: {nodes: [{id, type, prompt_slug, question_augmentations, position}, ...], edges: [{id, from, to}, ...]}';
|
||||
COMMENT ON COLUMN workflow_executions.node_states IS 'JSONB: {node_id: {status: "executed|skipped|unclear|failed", ...}, ...}';
|
||||
COMMENT ON COLUMN workflow_executions.execution_log IS 'JSONB: Chronologischer Ablauf mit Timestamps, Entscheidungen, normalisierten Signalen.';
|
||||
@@ -0,0 +1,24 @@
|
||||
-- Migration 035: Backfill caliper lean_mass / fat_mass from nearest weight_log row
|
||||
-- Date: 2026-04-06
|
||||
|
||||
UPDATE caliper_log c
|
||||
SET
|
||||
lean_mass = sub.lean_mass,
|
||||
fat_mass = sub.fat_mass
|
||||
FROM (
|
||||
SELECT
|
||||
c2.id,
|
||||
round((wl.weight::numeric - (wl.weight::numeric * c2.body_fat_pct::numeric / 100.0))::numeric, 2) AS lean_mass,
|
||||
round((wl.weight::numeric * c2.body_fat_pct::numeric / 100.0)::numeric, 2) AS fat_mass
|
||||
FROM caliper_log c2
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT w.weight
|
||||
FROM weight_log w
|
||||
WHERE w.profile_id = c2.profile_id
|
||||
ORDER BY abs(w.date - c2.date) ASC
|
||||
LIMIT 1
|
||||
) wl
|
||||
WHERE c2.body_fat_pct IS NOT NULL
|
||||
AND (c2.lean_mass IS NULL OR c2.fat_mass IS NULL)
|
||||
) sub
|
||||
WHERE c.id = sub.id;
|
||||
@@ -0,0 +1,36 @@
|
||||
-- Migration 036: Focus Area — erlaubte Nutzungstypen (Referenz + M:N)
|
||||
-- Date: 2026-04-06
|
||||
-- Purpose: System-seeded usage types; optional Zuordnung pro Focus Area (kein Auto-Backfill)
|
||||
|
||||
-- Referenztabelle: feste, systemdefinierte Nutzungstypen
|
||||
CREATE TABLE IF NOT EXISTS focus_area_usage_types (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
key VARCHAR(64) UNIQUE NOT NULL,
|
||||
label_de VARCHAR(160),
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
||||
);
|
||||
|
||||
COMMENT ON TABLE focus_area_usage_types IS
|
||||
'Systemdefinierte Nutzungsarten für Focus Areas (kein Admin-CRUD in v1)';
|
||||
|
||||
-- M:N: welche Nutzungstypen für eine Focus Area erlaubt sind (leer = noch nicht klassifiziert)
|
||||
CREATE TABLE IF NOT EXISTS focus_area_definition_usage_types (
|
||||
focus_area_id UUID NOT NULL REFERENCES focus_area_definitions(id) ON DELETE CASCADE,
|
||||
usage_type_id UUID NOT NULL REFERENCES focus_area_usage_types(id) ON DELETE CASCADE,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
PRIMARY KEY (focus_area_id, usage_type_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_fadut_focus_area ON focus_area_definition_usage_types(focus_area_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_fadut_usage_type ON focus_area_definition_usage_types(usage_type_id);
|
||||
|
||||
COMMENT ON TABLE focus_area_definition_usage_types IS
|
||||
'Zuordnung Focus Area → erlaubte Nutzungstypen (kein automatisches Befüllen bestehender Areas)';
|
||||
|
||||
-- Seed: nur die drei Typen — keine Zeilen in der Junction-Tabelle
|
||||
INSERT INTO focus_area_usage_types (key, label_de, sort_order) VALUES
|
||||
('goal_priority', 'Ziele / Prioritäten', 1),
|
||||
('expected_training_effect', 'Erwartetes Trainingseffekt-Profil', 2),
|
||||
('concrete_training_contribution', 'Konkrete Trainings-Beiträge / Belastungsausprägung', 3)
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
@@ -0,0 +1,99 @@
|
||||
-- Migration 037: Persönliche Referenzwerte (Typkatalog + historische Werte pro Profil)
|
||||
-- Date: 2026-04-06
|
||||
-- Purpose: System-definierte Referenztyp-Schlüssel; Nutzer pflegt nur historische Einträge.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS reference_value_types (
|
||||
id SERIAL PRIMARY KEY,
|
||||
key VARCHAR(64) NOT NULL UNIQUE,
|
||||
label VARCHAR(200) NOT NULL,
|
||||
description TEXT,
|
||||
default_unit VARCHAR(32),
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
metadata JSONB NOT NULL DEFAULT '{}',
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
COMMENT ON TABLE reference_value_types IS
|
||||
'Systemdefinierte Typen persönlicher Referenzwerte (kein Nutzer-CRUD auf Typen)';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS profile_reference_values (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
reference_value_type_id INT NOT NULL REFERENCES reference_value_types(id) ON DELETE RESTRICT,
|
||||
effective_date DATE NOT NULL,
|
||||
value_numeric NUMERIC(18, 6),
|
||||
value_text TEXT,
|
||||
unit VARCHAR(32) NOT NULL,
|
||||
source TEXT,
|
||||
confidence NUMERIC(5, 2),
|
||||
method TEXT,
|
||||
notes TEXT,
|
||||
extra JSONB NOT NULL DEFAULT '{}',
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT profile_reference_values_value_ck CHECK (
|
||||
value_numeric IS NOT NULL OR (value_text IS NOT NULL AND length(trim(value_text)) > 0)
|
||||
)
|
||||
);
|
||||
|
||||
COMMENT ON TABLE profile_reference_values IS
|
||||
'Historische Referenzwerte pro Profil (kein Überschreiben eines Einzel-»aktuellen« Werts)';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_prv_profile_type_date
|
||||
ON profile_reference_values (profile_id, reference_value_type_id, effective_date DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_prv_profile
|
||||
ON profile_reference_values (profile_id);
|
||||
|
||||
-- Seed: nur Typdefinitionen, keine Benutzerwerte
|
||||
INSERT INTO reference_value_types (key, label, description, default_unit, sort_order, active) VALUES
|
||||
(
|
||||
'max_heart_rate',
|
||||
'Maximale Herzfrequenz',
|
||||
'Individuelle HRmax (z. B. aus Leistungstest oder geschätzt).',
|
||||
'bpm',
|
||||
10,
|
||||
TRUE
|
||||
),
|
||||
(
|
||||
'anaerobic_threshold_hr',
|
||||
'Anaerober Schwellenwert (Herzfrequenz)',
|
||||
'Laktatschwelle / anaerober Schwellenpuls.',
|
||||
'bpm',
|
||||
20,
|
||||
TRUE
|
||||
),
|
||||
(
|
||||
'aerobic_threshold_hr',
|
||||
'Aerober Schwellenwert (Herzfrequenz)',
|
||||
'Erster aerobet/schwellenanaloger Trainingsbereich (GA2).',
|
||||
'bpm',
|
||||
30,
|
||||
TRUE
|
||||
),
|
||||
(
|
||||
'training_frequency_weekly',
|
||||
'Trainingshäufigkeit',
|
||||
'Geplante oder beobachtete Einheiten pro Woche.',
|
||||
'Sessions/Woche',
|
||||
40,
|
||||
TRUE
|
||||
),
|
||||
(
|
||||
'fitness_level',
|
||||
'Fitnesslevel',
|
||||
'Subjektive oder normierte Einstufung (Zahl oder Kurzbeschreibung im Freitextfeld).',
|
||||
'Stufe',
|
||||
50,
|
||||
TRUE
|
||||
),
|
||||
(
|
||||
'resting_heart_rate',
|
||||
'Ruhepuls (Referenz)',
|
||||
'Ruheherzfrequenz als persönliche Referenz (z. B. morgens).',
|
||||
'bpm',
|
||||
15,
|
||||
TRUE
|
||||
)
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
@@ -0,0 +1,54 @@
|
||||
-- Migration 038: Referenzwert-Typen — Kategorie, Datentyp, Plausibilisierung; confidence als Diskretwert
|
||||
-- Date: 2026-04-06
|
||||
|
||||
ALTER TABLE reference_value_types ADD COLUMN IF NOT EXISTS category TEXT;
|
||||
|
||||
ALTER TABLE reference_value_types ADD COLUMN IF NOT EXISTS value_data_type VARCHAR(32) NOT NULL DEFAULT 'decimal';
|
||||
|
||||
ALTER TABLE reference_value_types ADD COLUMN IF NOT EXISTS validation_rules JSONB NOT NULL DEFAULT '{}';
|
||||
|
||||
ALTER TABLE reference_value_types DROP CONSTRAINT IF EXISTS rvt_value_data_type_chk;
|
||||
|
||||
ALTER TABLE reference_value_types ADD CONSTRAINT rvt_value_data_type_chk CHECK (
|
||||
value_data_type IN ('integer', 'decimal', 'percentage', 'text', 'enum')
|
||||
);
|
||||
|
||||
COMMENT ON COLUMN reference_value_types.category IS 'Freitext-Kategorie (UI/Admin)';
|
||||
COMMENT ON COLUMN reference_value_types.value_data_type IS 'Logischer Wert-Typ für Erfassung & Validierung';
|
||||
COMMENT ON COLUMN reference_value_types.validation_rules IS 'JSON: min, max, positive_only, max_length, not_empty, allowed_values[]';
|
||||
|
||||
-- Bestehende Seeds mit sinnvollen Defaults
|
||||
UPDATE reference_value_types SET
|
||||
value_data_type = 'integer',
|
||||
validation_rules = '{"min": 40, "max": 240, "positive_only": true}'::jsonb
|
||||
WHERE key IN ('max_heart_rate', 'resting_heart_rate');
|
||||
|
||||
UPDATE reference_value_types SET
|
||||
value_data_type = 'integer',
|
||||
validation_rules = '{"min": 80, "max": 210, "positive_only": true}'::jsonb
|
||||
WHERE key IN ('anaerobic_threshold_hr', 'aerobic_threshold_hr');
|
||||
|
||||
UPDATE reference_value_types SET
|
||||
value_data_type = 'integer',
|
||||
validation_rules = '{"min": 0, "max": 21, "positive_only": false}'::jsonb
|
||||
WHERE key = 'training_frequency_weekly';
|
||||
|
||||
UPDATE reference_value_types SET
|
||||
value_data_type = 'text',
|
||||
validation_rules = '{"max_length": 200, "not_empty": true}'::jsonb
|
||||
WHERE key = 'fitness_level';
|
||||
|
||||
-- profile_reference_values.confidence: von NUMERIC auf diskrete Stufen
|
||||
ALTER TABLE profile_reference_values ALTER COLUMN confidence DROP DEFAULT;
|
||||
|
||||
ALTER TABLE profile_reference_values
|
||||
ALTER COLUMN confidence TYPE VARCHAR(32)
|
||||
USING (NULL::varchar(32));
|
||||
|
||||
COMMENT ON COLUMN profile_reference_values.confidence IS 'high | medium | low | unknown';
|
||||
|
||||
-- Optionaler leerer Text (not_empty=false): leere Zeichenkette statt „kein Wert“
|
||||
ALTER TABLE profile_reference_values DROP CONSTRAINT IF EXISTS profile_reference_values_value_ck;
|
||||
ALTER TABLE profile_reference_values ADD CONSTRAINT profile_reference_values_value_ck CHECK (
|
||||
value_numeric IS NOT NULL OR value_text IS NOT NULL
|
||||
);
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Nutzer-Dashboard: Layout (JSONB) für geschützten App-Lab-Bereich (Issue #65, Phase 1)
|
||||
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS dashboard_layout JSONB DEFAULT NULL;
|
||||
|
||||
COMMENT ON COLUMN profiles.dashboard_layout IS
|
||||
'Optional: konfigurierbare Dashboard-Widget-Reihenfolge/Sichtbarkeit (v1 JSON). NULL = Standard.';
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Globale System-Konfiguration (Key/Value, JSONB)
|
||||
CREATE TABLE IF NOT EXISTS system_config (
|
||||
key VARCHAR(64) PRIMARY KEY,
|
||||
value JSONB NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_system_config_updated_at ON system_config (updated_at);
|
||||
@@ -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,8 @@ 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
|
||||
email: Optional[str] = None # Self-service; leer = entfernen; Änderung setzt Verifikation zurück
|
||||
|
||||
|
||||
# ── Tracking Models ───────────────────────────────────────────────────────────
|
||||
@@ -84,6 +86,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 +115,12 @@ class PasswordResetConfirm(BaseModel):
|
||||
new_password: str
|
||||
|
||||
|
||||
class RegisterRequest(BaseModel):
|
||||
name: str
|
||||
email: str
|
||||
password: str
|
||||
|
||||
|
||||
# ── Admin Models ──────────────────────────────────────────────────────────────
|
||||
|
||||
class AdminProfileUpdate(BaseModel):
|
||||
@@ -117,3 +128,120 @@ class AdminProfileUpdate(BaseModel):
|
||||
ai_enabled: Optional[int] = None
|
||||
ai_limit_day: Optional[int] = None
|
||||
export_enabled: Optional[int] = None
|
||||
|
||||
|
||||
# ── Prompt Models (Issue #28) ────────────────────────────────────────────────
|
||||
|
||||
class PromptCreate(BaseModel):
|
||||
name: str
|
||||
slug: str
|
||||
display_name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
template: str
|
||||
category: str = 'ganzheitlich'
|
||||
active: bool = True
|
||||
sort_order: int = 0
|
||||
|
||||
|
||||
class PromptUpdate(BaseModel):
|
||||
name: Optional[str] = None
|
||||
display_name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
template: Optional[str] = None
|
||||
category: Optional[str] = None
|
||||
active: Optional[bool] = None
|
||||
sort_order: Optional[int] = None
|
||||
|
||||
|
||||
class PromptGenerateRequest(BaseModel):
|
||||
goal: str
|
||||
data_categories: list[str]
|
||||
example_output: Optional[str] = None
|
||||
|
||||
|
||||
# ── Unified Prompt System Models (Issue #28 Phase 2) ───────────────────────
|
||||
|
||||
class StagePromptCreate(BaseModel):
|
||||
"""Single prompt within a stage"""
|
||||
source: str # 'inline' or 'reference'
|
||||
slug: Optional[str] = None # Required if source='reference'
|
||||
template: Optional[str] = None # Required if source='inline'
|
||||
output_key: str # Key for storing result (e.g., 'nutrition', 'stage1_body')
|
||||
output_format: str = 'text' # 'text' or 'json'
|
||||
output_schema: Optional[dict] = None # JSON schema if output_format='json'
|
||||
|
||||
|
||||
class StageCreate(BaseModel):
|
||||
"""Single stage with multiple prompts"""
|
||||
stage: int # Stage number (1, 2, 3, ...)
|
||||
prompts: list[StagePromptCreate]
|
||||
|
||||
|
||||
class UnifiedPromptCreate(BaseModel):
|
||||
"""Create a new unified prompt (base, pipeline, or workflow type)"""
|
||||
name: str
|
||||
slug: Optional[str] = None # Auto-generated from name if not provided
|
||||
display_name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
type: str # 'base' | 'pipeline' | 'workflow'
|
||||
category: str = 'ganzheitlich'
|
||||
active: bool = True
|
||||
sort_order: int = 0
|
||||
|
||||
# For base prompts (single reusable template)
|
||||
template: Optional[str] = None # Required if type='base'
|
||||
output_format: str = 'text'
|
||||
output_schema: Optional[dict] = None
|
||||
|
||||
# For pipeline prompts (multi-stage workflow)
|
||||
stages: Optional[list[StageCreate]] = None # Required if type='pipeline'
|
||||
|
||||
# For workflow prompts (visual graph editor)
|
||||
graph_data: Optional[dict] = None # Required if type='workflow'
|
||||
|
||||
|
||||
class UnifiedPromptUpdate(BaseModel):
|
||||
"""Update an existing unified prompt"""
|
||||
name: Optional[str] = None
|
||||
display_name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
type: Optional[str] = None
|
||||
category: Optional[str] = None
|
||||
active: Optional[bool] = None
|
||||
sort_order: Optional[int] = None
|
||||
template: Optional[str] = None
|
||||
output_format: Optional[str] = None
|
||||
output_schema: Optional[dict] = None
|
||||
stages: Optional[list[StageCreate]] = None
|
||||
graph_data: Optional[dict] = None # For workflow type
|
||||
|
||||
|
||||
# ── Pipeline Config Models (Issue #28) ─────────────────────────────────────
|
||||
# NOTE: These will be deprecated in favor of UnifiedPrompt models above
|
||||
|
||||
class PipelineConfigCreate(BaseModel):
|
||||
name: str
|
||||
description: Optional[str] = None
|
||||
is_default: bool = False
|
||||
active: bool = True
|
||||
modules: dict # {"körper": true, "ernährung": true, ...}
|
||||
timeframes: dict # {"körper": 30, "ernährung": 30, ...}
|
||||
stage1_prompts: list[str] # Array of slugs
|
||||
stage2_prompt: str # slug
|
||||
stage3_prompt: Optional[str] = None # slug
|
||||
|
||||
|
||||
class PipelineConfigUpdate(BaseModel):
|
||||
name: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
is_default: Optional[bool] = None
|
||||
active: Optional[bool] = None
|
||||
modules: Optional[dict] = None
|
||||
timeframes: Optional[dict] = None
|
||||
stage1_prompts: Optional[list[str]] = None
|
||||
stage2_prompt: Optional[str] = None
|
||||
stage3_prompt: Optional[str] = None
|
||||
|
||||
|
||||
class PipelineExecuteRequest(BaseModel):
|
||||
config_id: Optional[str] = None # None = use default config
|
||||
@@ -0,0 +1,237 @@
|
||||
"""
|
||||
Normalization Engine (Phase 2)
|
||||
|
||||
Normalisiert decision_signals gegen answer_spectrum mit Synonymen.
|
||||
|
||||
Konzept-Basis: konzept_workflow_engine_konsolidated.md (Sektion 8.5)
|
||||
Anforderungsanalyse: anforderungsanalyse_umsetzungsplan.md (Phase 2)
|
||||
"""
|
||||
from typing import Dict, List, Optional
|
||||
from workflow_models import NormalizedSignal, SignalStatus
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def normalize_decision_signal(
|
||||
question_type: str,
|
||||
raw_value: str,
|
||||
answer_spectrum: List[str],
|
||||
normalization_rules: Optional[Dict] = None
|
||||
) -> NormalizedSignal:
|
||||
"""
|
||||
Normalisiert ein einzelnes Entscheidungssignal.
|
||||
|
||||
Normalisierungs-Kaskade:
|
||||
1. Exakte Übereinstimmung → valid
|
||||
2. Case-insensitive Übereinstimmung → normalized
|
||||
3. Synonym-Mapping (aus normalization_rules) → normalized
|
||||
4. Keine Übereinstimmung → invalid
|
||||
|
||||
Args:
|
||||
question_type: Typ der Frage (z.B. "relevanz")
|
||||
raw_value: Rohe LLM-Antwort (z.B. "JA", "yes", "ja")
|
||||
answer_spectrum: Erlaubte Werte (z.B. ["ja", "nein", "unklar"])
|
||||
normalization_rules: Optional: {"synonyms": {"ja": ["yes", "Ja", "JA"], ...}}
|
||||
|
||||
Returns:
|
||||
NormalizedSignal mit status + normalized_value
|
||||
|
||||
Beispiele:
|
||||
>>> normalize_decision_signal("relevanz", "ja", ["ja", "nein"])
|
||||
NormalizedSignal(status=VALID, normalized_value="ja")
|
||||
|
||||
>>> normalize_decision_signal("relevanz", "JA", ["ja", "nein"])
|
||||
NormalizedSignal(status=NORMALIZED, normalized_value="ja")
|
||||
|
||||
>>> normalize_decision_signal("relevanz", "yes", ["ja", "nein"],
|
||||
... {"synonyms": {"ja": ["yes", "Yes"]}})
|
||||
NormalizedSignal(status=NORMALIZED, normalized_value="ja")
|
||||
|
||||
>>> normalize_decision_signal("relevanz", "vielleicht", ["ja", "nein"])
|
||||
NormalizedSignal(status=INVALID, normalized_value=None)
|
||||
"""
|
||||
# 1. Exakte Übereinstimmung
|
||||
if raw_value in answer_spectrum:
|
||||
logger.debug(f"{question_type}: '{raw_value}' → valid (exact match)")
|
||||
return NormalizedSignal(
|
||||
question_type=question_type,
|
||||
raw_value=raw_value,
|
||||
normalized_value=raw_value,
|
||||
status=SignalStatus.VALID
|
||||
)
|
||||
|
||||
# 2. Case-insensitive Matching
|
||||
raw_lower = raw_value.strip().lower()
|
||||
for allowed in answer_spectrum:
|
||||
if raw_lower == allowed.lower():
|
||||
logger.debug(f"{question_type}: '{raw_value}' → normalized (case-insensitive)")
|
||||
return NormalizedSignal(
|
||||
question_type=question_type,
|
||||
raw_value=raw_value,
|
||||
normalized_value=allowed,
|
||||
status=SignalStatus.NORMALIZED,
|
||||
metadata={"method": "case_insensitive"}
|
||||
)
|
||||
|
||||
# 3. Synonym Mapping
|
||||
if normalization_rules and "synonyms" in normalization_rules:
|
||||
normalized = apply_synonym_mapping(
|
||||
raw_value=raw_value,
|
||||
synonyms=normalization_rules["synonyms"]
|
||||
)
|
||||
if normalized:
|
||||
logger.debug(f"{question_type}: '{raw_value}' → normalized (synonym → '{normalized}')")
|
||||
return NormalizedSignal(
|
||||
question_type=question_type,
|
||||
raw_value=raw_value,
|
||||
normalized_value=normalized,
|
||||
status=SignalStatus.NORMALIZED,
|
||||
metadata={"method": "synonym"}
|
||||
)
|
||||
|
||||
# 4. Keine Übereinstimmung
|
||||
logger.warning(f"{question_type}: '{raw_value}' → invalid (no match in spectrum {answer_spectrum})")
|
||||
return NormalizedSignal(
|
||||
question_type=question_type,
|
||||
raw_value=raw_value,
|
||||
normalized_value=None,
|
||||
status=SignalStatus.INVALID
|
||||
)
|
||||
|
||||
|
||||
def apply_synonym_mapping(
|
||||
raw_value: str,
|
||||
synonyms: Dict[str, List[str]]
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
Mappt raw_value auf Synonym-Gruppe (case-insensitive).
|
||||
|
||||
Args:
|
||||
raw_value: "yes" oder "YES" oder "Yes"
|
||||
synonyms: {"ja": ["yes", "Ja", "JA"], "nein": ["no", "No"]}
|
||||
|
||||
Returns:
|
||||
"ja" (Schlüssel der Gruppe) oder None
|
||||
|
||||
Beispiele:
|
||||
>>> apply_synonym_mapping("yes", {"ja": ["yes", "Yes"], "nein": ["no"]})
|
||||
"ja"
|
||||
|
||||
>>> apply_synonym_mapping("YES", {"ja": ["yes"], "nein": ["no"]})
|
||||
"ja"
|
||||
|
||||
>>> apply_synonym_mapping("vielleicht", {"ja": ["yes"], "nein": ["no"]})
|
||||
None
|
||||
"""
|
||||
raw_lower = raw_value.strip().lower()
|
||||
|
||||
for canonical_value, synonym_list in synonyms.items():
|
||||
# Check case-insensitive gegen alle Synonyme
|
||||
for syn in synonym_list:
|
||||
if raw_lower == syn.lower():
|
||||
return canonical_value
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def normalize_all_signals(
|
||||
decision_signals: Dict[str, str],
|
||||
catalog_dict: Dict[str, Dict]
|
||||
) -> List[NormalizedSignal]:
|
||||
"""
|
||||
Normalisiert alle decision_signals gegen Katalog.
|
||||
|
||||
Args:
|
||||
decision_signals: {"relevanz": "ja", "prioritaet": "HOCH"}
|
||||
catalog_dict: {
|
||||
"relevanz": {
|
||||
"answer_spectrum": ["ja", "nein", "unklar"],
|
||||
"normalization_rules": {"synonyms": {...}}
|
||||
},
|
||||
...
|
||||
}
|
||||
|
||||
Returns:
|
||||
Liste von NormalizedSignal (ein Signal pro question_type)
|
||||
|
||||
Beispiele:
|
||||
>>> signals = {"relevanz": "ja", "prioritaet": "HOCH"}
|
||||
>>> catalog = {
|
||||
... "relevanz": {"answer_spectrum": ["ja", "nein"], "normalization_rules": None},
|
||||
... "prioritaet": {"answer_spectrum": ["hoch", "mittel", "niedrig"], "normalization_rules": None}
|
||||
... }
|
||||
>>> normalized = normalize_all_signals(signals, catalog)
|
||||
>>> len(normalized)
|
||||
2
|
||||
>>> normalized[0].status
|
||||
<SignalStatus.VALID: 'valid'>
|
||||
>>> normalized[1].status
|
||||
<SignalStatus.NORMALIZED: 'normalized'>
|
||||
"""
|
||||
normalized = []
|
||||
|
||||
for question_type, raw_value in decision_signals.items():
|
||||
if question_type not in catalog_dict:
|
||||
logger.warning(f"Question type '{question_type}' not in catalog → not_decidable")
|
||||
normalized.append(NormalizedSignal(
|
||||
question_type=question_type,
|
||||
raw_value=raw_value,
|
||||
normalized_value=None,
|
||||
status=SignalStatus.NOT_DECIDABLE,
|
||||
metadata={"error": "not_in_catalog"}
|
||||
))
|
||||
continue
|
||||
|
||||
catalog_entry = catalog_dict[question_type]
|
||||
signal = normalize_decision_signal(
|
||||
question_type=question_type,
|
||||
raw_value=raw_value,
|
||||
answer_spectrum=catalog_entry["answer_spectrum"],
|
||||
normalization_rules=catalog_entry.get("normalization_rules")
|
||||
)
|
||||
normalized.append(signal)
|
||||
|
||||
return normalized
|
||||
|
||||
|
||||
def load_question_catalog(db_connection) -> Dict[str, Dict]:
|
||||
"""
|
||||
Lädt workflow_question_catalog aus DB.
|
||||
|
||||
Returns:
|
||||
{
|
||||
"relevanz": {
|
||||
"answer_spectrum": ["ja", "nein", "unklar"],
|
||||
"normalization_rules": {"synonyms": {"ja": ["yes", "Yes"], ...}}
|
||||
},
|
||||
"prioritaet": {...},
|
||||
...
|
||||
}
|
||||
|
||||
Beispiel:
|
||||
>>> from db import get_db
|
||||
>>> with get_db() as conn:
|
||||
... catalog = load_question_catalog(conn)
|
||||
... assert "relevanz" in catalog
|
||||
... assert "answer_spectrum" in catalog["relevanz"]
|
||||
"""
|
||||
from db import get_cursor
|
||||
|
||||
cur = get_cursor(db_connection)
|
||||
cur.execute("""
|
||||
SELECT question_type, answer_spectrum, normalization_rules
|
||||
FROM workflow_question_catalog
|
||||
WHERE active = true
|
||||
""")
|
||||
rows = cur.fetchall()
|
||||
|
||||
catalog = {}
|
||||
for row in rows:
|
||||
catalog[row['question_type']] = {
|
||||
"answer_spectrum": row['answer_spectrum'], # JSONB already parsed by psycopg2
|
||||
"normalization_rules": row['normalization_rules'] # JSONB or None
|
||||
}
|
||||
|
||||
logger.info(f"Loaded question catalog: {len(catalog)} types")
|
||||
return catalog
|
||||
Loaded 100 of 370 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user