Author SHA1 Message Date
Lars e7dedd527f feat: Implement focus area usage types management in API and UI
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
- Added endpoints for listing and updating focus area usage types in the backend.
- Enhanced the AdminFocusAreasPage to display and manage allowed usage types for focus areas.
- Introduced a new state for usage types catalog and integrated it into the focus area editing process.
- Updated API utility functions to support new usage types operations.
2026-04-06 07:28:19 +02:00
Lars 49e9c9c214 feat: Integrate caliper data enrichment and weight loading in API responses
Deploy Development / deploy (push) Successful in 1m0s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- Enhanced the caliper listing and export functionalities to include enriched data from weight logs.
- Updated the upsert and update operations to utilize new composition functions for body composition calculations.
- Refactored the CaliperScreen component to streamline payload construction by removing unnecessary parameters.
2026-04-06 06:08:37 +02:00
Lars 00437a92ab feat: Enhance sleep module with CSV import functionality and date parsing improvements
Deploy Development / deploy (push) Successful in 56s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
2026-04-05 17:35:48 +02:00
Lars 24f60c0a6d feat: Update documentation for GUI, Admin navigation, and responsive UI integration
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
2026-04-05 12:25:28 +02:00
Lars fdaf4471da feat: Adjust navigation height and padding for improved layout and responsiveness
Deploy Development / deploy (push) Successful in 54s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
2026-04-05 12:16:24 +02:00
Lars 6e952f9277 feat: Enhance navigation and dashboard with goals integration and UI improvements
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
2026-04-05 12:07:11 +02:00
Lars 952cb90973 feat: Update deployment scripts to use git fetch and reset for more reliable state management
Deploy Development / deploy (push) Successful in 55s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
2026-04-05 11:39:15 +02:00
Lars bd694b30a6 feat: Add admin access denial alert to Dashboard with timeout handling
Deploy Development / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
2026-04-05 11:28:33 +02:00
28 changed files with 1295 additions and 172 deletions

No files matched your search

+2 -1
View File
@@ -13,7 +13,8 @@ jobs:
set -e set -e
echo "=== Deploying to DEVELOPMENT ===" echo "=== Deploying to DEVELOPMENT ==="
cd /home/lars/docker/bodytrack-dev 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 build --no-cache
docker compose -f docker-compose.dev-env.yml up -d docker compose -f docker-compose.dev-env.yml up -d
sleep 5 sleep 5
+3 -1
View File
@@ -13,7 +13,9 @@ jobs:
set -e set -e
echo "=== Deploying to PRODUCTION ===" echo "=== Deploying to PRODUCTION ==="
cd /home/lars/docker/bodytrack 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 build --no-cache
docker compose -f docker-compose.yml up -d docker compose -f docker-compose.yml up -d
sleep 5 sleep 5
+2 -1
View File
@@ -64,4 +64,5 @@ tmp/
# Cursor MCP mit Secrets (Example: .cursor/mcp.json.example) # Cursor MCP mit Secrets (Example: .cursor/mcp.json.example)
.cursor/mcp.json .cursor/mcp.json
.claude/settings.local.jsonfrontend/package-lock.json .claude/settings.local.json
frontend/package-lock.json
+7
View File
@@ -6,6 +6,7 @@
> | Architektur-Regeln | `.claude/rules/ARCHITECTURE.md` | > | Architektur-Regeln | `.claude/rules/ARCHITECTURE.md` |
> | Coding-Regeln | `.claude/rules/CODING_RULES.md` | > | Coding-Regeln | `.claude/rules/CODING_RULES.md` |
> | Lessons Learned | `.claude/rules/LESSONS_LEARNED.md` | > | Lessons Learned | `.claude/rules/LESSONS_LEARNED.md` |
> | **GUI / IA / Admin / Nav / PWA-Leiste** | **`docs/issues/GUI_IA_ADMIN_NAV_2026-04-05.md`** |
## Claude Code Verantwortlichkeiten ## Claude Code Verantwortlichkeiten
@@ -69,6 +70,8 @@ backend/
frontend/src/ frontend/src/
├── App.jsx # Root, Auth-Gates, Navigation ├── App.jsx # Root, Auth-Gates, Navigation
├── app.css # CSS-Variablen + globale Styles ├── app.css # CSS-Variablen + globale Styles
├── config/ # appNav.js · adminNav.js (Single Source für Main/Admin-Nav)
├── layouts/ # AdminShell · RequireAdmin
├── context/ # AuthContext · ProfileContext ├── context/ # AuthContext · ProfileContext
├── pages/ # Alle Screens ├── pages/ # Alle Screens
└── utils/ └── utils/
@@ -90,6 +93,10 @@ frontend/src/
**Branch:** develop **Branch:** develop
**Nächster Schritt:** Frontend Chart Integration → Testing → Prod Deploy v0.9i **Nächster Schritt:** Frontend Chart Integration → Testing → Prod Deploy v0.9i
### GUI / Informationsarchitektur (Abnahme dieser Iteration, 2026-04-05)
Admin-Bereich (`AdminShell`, Hub-Routen), Hauptnavigation inkl. **Ziele** (`config/appNav.js`), Einstellungen nur aktives Profil + E-Mail, KI-Analyse Ergebnis in rechter Spalte, **PWA** Bottom-Nav inkl. iOS Safe Area. Zentrale Agent-Doku: **`docs/issues/GUI_IA_ADMIN_NAV_2026-04-05.md`**. Responsive-Epic **Gitea #30:** Phasenplan `docs/issues/PHASE_PLAN_RESPONSIVE_UI.md` — **P7 Kern erledigt**, **P8** (Regression/Abnahme) ausstehend; Issue bewusst **nicht** geschlossen.
### Updates (28.03.2026 - Phase 0c Multi-Layer Architecture Complete) 🆕 ### Updates (28.03.2026 - Phase 0c Multi-Layer Architecture Complete) 🆕
#### Phase 0c: Multi-Layer Data Architecture ✅ **COMPLETED** #### Phase 0c: Multi-Layer Data Architecture ✅ **COMPLETED**
+111
View File
@@ -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
+20
View File
@@ -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,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;
+8 -1
View File
@@ -14,6 +14,7 @@ from auth import require_auth, check_feature_access, increment_feature_usage
from models import CaliperEntry from models import CaliperEntry
from routers.profiles import get_pid from routers.profiles import get_pid
from feature_logger import log_feature_usage from feature_logger import log_feature_usage
from caliper_composition import enrich_caliper_row_for_response, fill_caliper_body_comp, load_weight_rows
router = APIRouter(prefix="/api/caliper", tags=["caliper"]) router = APIRouter(prefix="/api/caliper", tags=["caliper"])
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -27,7 +28,11 @@ def list_caliper(limit: int=100, x_profile_id: Optional[str]=Header(default=None
cur = get_cursor(conn) cur = get_cursor(conn)
cur.execute( cur.execute(
"SELECT * FROM caliper_log WHERE profile_id=%s ORDER BY date DESC LIMIT %s", (pid,limit)) "SELECT * FROM caliper_log WHERE profile_id=%s ORDER BY date DESC LIMIT %s", (pid,limit))
return [r2d(r) for r in cur.fetchall()] rows = [r2d(r) for r in cur.fetchall()]
weight_rows = load_weight_rows(conn, pid)
for row in rows:
enrich_caliper_row_for_response(row, weight_rows)
return rows
@router.post("") @router.post("")
@@ -55,6 +60,7 @@ def upsert_caliper(e: CaliperEntry, x_profile_id: Optional[str]=Header(default=N
cur.execute("SELECT id FROM caliper_log WHERE profile_id=%s AND date=%s", (pid,e.date)) cur.execute("SELECT id FROM caliper_log WHERE profile_id=%s AND date=%s", (pid,e.date))
ex = cur.fetchone() ex = cur.fetchone()
d = e.model_dump() d = e.model_dump()
fill_caliper_body_comp(d, conn, pid)
is_new_entry = not ex is_new_entry = not ex
if ex: if ex:
@@ -86,6 +92,7 @@ def update_caliper(eid: str, e: CaliperEntry, x_profile_id: Optional[str]=Header
pid = get_pid(x_profile_id) pid = get_pid(x_profile_id)
with get_db() as conn: with get_db() as conn:
d = e.model_dump() d = e.model_dump()
fill_caliper_body_comp(d, conn, pid)
cur = get_cursor(conn) cur = get_cursor(conn)
cur.execute(f"UPDATE caliper_log SET {', '.join(f'{k}=%s' for k in d)} WHERE id=%s AND profile_id=%s", cur.execute(f"UPDATE caliper_log SET {', '.join(f'{k}=%s' for k in d)} WHERE id=%s AND profile_id=%s",
list(d.values())+[eid,pid]) list(d.values())+[eid,pid])
+20 -4
View File
@@ -21,6 +21,7 @@ from db import get_db, get_cursor, r2d
from auth import require_auth, check_feature_access, increment_feature_usage from auth import require_auth, check_feature_access, increment_feature_usage
from routers.profiles import get_pid from routers.profiles import get_pid
from feature_logger import log_feature_usage from feature_logger import log_feature_usage
from caliper_composition import enrich_caliper_row_for_response, load_weight_rows
router = APIRouter(prefix="/api/export", tags=["export"]) router = APIRouter(prefix="/api/export", tags=["export"])
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -68,10 +69,21 @@ def export_csv(x_profile_id: Optional[str]=Header(default=None), session: dict=D
details = f"Taille:{float(r['c_waist'])}cm Bauch:{float(r['c_belly'])}cm Hüfte:{float(r['c_hip'])}cm" details = f"Taille:{float(r['c_waist'])}cm Bauch:{float(r['c_belly'])}cm Hüfte:{float(r['c_hip'])}cm"
writer.writerow(["Umfänge", r['date'], "", details]) writer.writerow(["Umfänge", r['date'], "", details])
# Caliper # Caliper (Magermasse aus Gewicht + KF% nachziehen wenn in DB leer)
cur.execute("SELECT date, body_fat_pct, lean_mass FROM caliper_log WHERE profile_id=%s ORDER BY date", (pid,)) cur.execute(
for r in cur.fetchall(): "SELECT date, body_fat_pct, lean_mass, fat_mass FROM caliper_log WHERE profile_id=%s ORDER BY date",
writer.writerow(["Caliper", r['date'], f"{float(r['body_fat_pct'])}%", f"Magermasse:{float(r['lean_mass'])}kg"]) (pid,),
)
cal_rows = [r2d(r) for r in cur.fetchall()]
weight_rows = load_weight_rows(conn, pid)
for r in cal_rows:
enrich_caliper_row_for_response(r, weight_rows)
if r.get("body_fat_pct") is None:
continue
bf = float(r["body_fat_pct"])
lm = r.get("lean_mass")
details = f"Magermasse:{float(lm)}kg" if lm is not None else ""
writer.writerow(["Caliper", r["date"], f"{bf}%", details])
# Nutrition # Nutrition
cur.execute("SELECT date, kcal, protein_g FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,)) cur.execute("SELECT date, kcal, protein_g FROM nutrition_log WHERE profile_id=%s ORDER BY date", (pid,))
@@ -141,6 +153,10 @@ def export_json(x_profile_id: Optional[str]=Header(default=None), session: dict=
cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,)) cur.execute("SELECT * FROM ai_insights WHERE profile_id=%s ORDER BY created DESC", (pid,))
data['insights'] = [r2d(r) for r in cur.fetchall()] data['insights'] = [r2d(r) for r in cur.fetchall()]
w_rows = [{'date': x['date'], 'weight': x['weight']} for x in data.get('weight', [])]
for row in data.get('caliper', []):
enrich_caliper_row_for_response(row, w_rows)
def decimal_handler(obj): def decimal_handler(obj):
if isinstance(obj, Decimal): if isinstance(obj, Decimal):
return float(obj) return float(obj)
+112 -3
View File
@@ -3,10 +3,11 @@ Focus Areas Router
Manages dynamic focus area definitions and user preferences Manages dynamic focus area definitions and user preferences
""" """
from fastapi import APIRouter, HTTPException, Depends from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel from pydantic import BaseModel, Field
from typing import Optional, List from typing import Optional, List
from db import get_db, get_cursor, r2d from db import get_db, get_cursor, r2d
from auth import require_auth from auth import require_auth
from focus_area_usage_helpers import coerce_usage_type_keys
router = APIRouter(prefix="/api/focus-areas", tags=["focus-areas"]) router = APIRouter(prefix="/api/focus-areas", tags=["focus-areas"])
@@ -36,6 +37,11 @@ class UserFocusPreferences(BaseModel):
"""User's focus area weightings (dynamic)""" """User's focus area weightings (dynamic)"""
preferences: dict # {focus_area_id: weight_pct} preferences: dict # {focus_area_id: weight_pct}
class FocusAreaUsageTypesUpdate(BaseModel):
"""Replace all usage-type assignments for one focus area (admin)."""
usage_type_keys: List[str] = Field(default_factory=list)
# ============================================================================ # ============================================================================
# Focus Area Definitions (Admin) # Focus Area Definitions (Admin)
# ============================================================================ # ============================================================================
@@ -58,14 +64,27 @@ def list_focus_area_definitions(
query = """ query = """
SELECT id, key, name_de, name_en, icon, description, category, is_active, SELECT id, key, name_de, name_en, icon, description, category, is_active,
created_at, updated_at created_at, updated_at,
COALESCE(
(
SELECT json_agg(faut.key ORDER BY faut.sort_order, faut.key)
FROM focus_area_definition_usage_types fadut
JOIN focus_area_usage_types faut ON faut.id = fadut.usage_type_id
WHERE fadut.focus_area_id = focus_area_definitions.id
),
'[]'::json
) AS allowed_usage_type_keys
FROM focus_area_definitions FROM focus_area_definitions
WHERE is_active = true OR %s WHERE is_active = true OR %s
ORDER BY category, name_de ORDER BY category, name_de
""" """
cur.execute(query, (include_inactive,)) cur.execute(query, (include_inactive,))
areas = [r2d(row) for row in cur.fetchall()] areas = []
for row in cur.fetchall():
d = r2d(row)
d['allowed_usage_type_keys'] = coerce_usage_type_keys(d.get('allowed_usage_type_keys'))
areas.append(d)
# Group by category # Group by category
grouped = {} grouped = {}
@@ -75,6 +94,10 @@ def list_focus_area_definitions(
grouped[cat] = [] grouped[cat] = []
grouped[cat].append(area) grouped[cat].append(area)
if session.get('role') != 'admin':
for area in areas:
area.pop('allowed_usage_type_keys', None)
return { return {
"areas": areas, "areas": areas,
"grouped": grouped, "grouped": grouped,
@@ -226,6 +249,92 @@ def delete_focus_area_definition(
return {"message": "Focus Area gelöscht"} return {"message": "Focus Area gelöscht"}
@router.get("/usage-types")
def list_focus_area_usage_types(session: dict = Depends(require_auth)):
"""
Liste aller systemdefinierten Nutzungstypen (Admin, Konfigurations-UI).
Keine freie Anlage neuer Typen über die API.
"""
if session.get('role') != 'admin':
raise HTTPException(status_code=403, detail="Admin-Rechte erforderlich")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute("""
SELECT id, key, label_de, sort_order
FROM focus_area_usage_types
ORDER BY sort_order, key
""")
rows = [r2d(r) for r in cur.fetchall()]
return {"usage_types": rows, "total": len(rows)}
@router.put("/definitions/{area_id}/usage-types")
def replace_focus_area_usage_types(
area_id: str,
data: FocusAreaUsageTypesUpdate,
session: dict = Depends(require_auth),
):
"""
Ersetzt die Nutzungstyp-Zuweisungen einer Focus Area (Admin).
Leere Liste entfernt alle Zuordnungen. Unbekannte Keys → 400.
"""
if session.get('role') != 'admin':
raise HTTPException(status_code=403, detail="Admin-Rechte erforderlich")
keys = list(dict.fromkeys(data.usage_type_keys)) # dedupe, preserve order
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"SELECT id FROM focus_area_definitions WHERE id = %s",
(area_id,),
)
if not cur.fetchone():
raise HTTPException(status_code=404, detail="Focus Area nicht gefunden")
if not keys:
cur.execute(
"DELETE FROM focus_area_definition_usage_types WHERE focus_area_id = %s",
(area_id,),
)
return {"message": "Nutzungstyp-Zuweisungen entfernt", "usage_type_keys": []}
placeholders = ','.join(['%s'] * len(keys))
cur.execute(
f"""
SELECT id, key FROM focus_area_usage_types
WHERE key IN ({placeholders})
""",
keys,
)
found = {row['key']: row['id'] for row in cur.fetchall()}
missing = [k for k in keys if k not in found]
if missing:
raise HTTPException(
status_code=400,
detail=f"Unbekannte Nutzungstyp-Keys: {', '.join(missing)}",
)
cur.execute(
"DELETE FROM focus_area_definition_usage_types WHERE focus_area_id = %s",
(area_id,),
)
for k in keys:
ut_id = found[k]
cur.execute(
"""
INSERT INTO focus_area_definition_usage_types (focus_area_id, usage_type_id)
VALUES (%s, %s)
ON CONFLICT (focus_area_id, usage_type_id) DO NOTHING
""",
(area_id, ut_id),
)
return {"message": "Nutzungstyp-Zuweisungen aktualisiert", "usage_type_keys": keys}
# ============================================================================ # ============================================================================
# User Focus Preferences # User Focus Preferences
# ============================================================================ # ============================================================================
+7 -2
View File
@@ -16,6 +16,7 @@ from db import get_db, get_cursor, r2d
from auth import require_auth, check_feature_access, increment_feature_usage from auth import require_auth, check_feature_access, increment_feature_usage
from routers.profiles import get_pid from routers.profiles import get_pid
from feature_logger import log_feature_usage from feature_logger import log_feature_usage
from caliper_composition import compute_lean_fat_kg, nearest_weight_kg_from_map
router = APIRouter(prefix="/api/nutrition", tags=["nutrition"]) router = APIRouter(prefix="/api/nutrition", tags=["nutrition"])
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -202,8 +203,12 @@ def nutrition_correlations(x_profile_id: Optional[str]=Header(default=None), ses
if d in cal_by_date: if d in cal_by_date:
lm = cal_by_date[d].get('lean_mass') lm = cal_by_date[d].get('lean_mass')
bf = cal_by_date[d].get('body_fat_pct') bf = cal_by_date[d].get('body_fat_pct')
row['lean_mass']=float(lm) if lm is not None else None if bf is not None and lm is None:
row['body_fat_pct']=float(bf) if bf is not None else None wkg = nearest_weight_kg_from_map(wlog, d)
if wkg is not None:
lm, _fat = compute_lean_fat_kg(wkg, float(bf))
row['lean_mass'] = float(lm) if lm is not None else None
row['body_fat_pct'] = float(bf) if bf is not None else None
result.append(row) result.append(row)
return result return result
+199 -80
View File
@@ -9,7 +9,8 @@ Endpoints:
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
from pydantic import BaseModel from pydantic import BaseModel
from typing import Literal from typing import Literal
from datetime import datetime, timedelta from datetime import datetime, timedelta, date
from decimal import Decimal, InvalidOperation
import csv import csv
import io import io
import json import json
@@ -19,6 +20,174 @@ from db import get_db, get_cursor
router = APIRouter(prefix="/api/sleep", tags=["sleep"]) router = APIRouter(prefix="/api/sleep", tags=["sleep"])
def _strip_row_keys(row: dict) -> dict:
return {(k or "").strip(): (v.strip() if isinstance(v, str) else v) for k, v in row.items()}
def _safe_float(value) -> float | None:
if value is None or value == "":
return None
if isinstance(value, (int, float)):
return float(value)
if isinstance(value, Decimal):
return float(value)
try:
s = str(value).strip().replace(",", ".")
return float(s)
except (ValueError, InvalidOperation):
return None
def _parse_apple_sleep_datetime(value: str) -> datetime:
raw = (value or "").strip()
if not raw:
raise ValueError("empty datetime")
fmts = (
"%Y-%m-%d %H:%M:%S %z",
"%d.%m.%y %H:%M:%S",
"%d.%m.%Y %H:%M:%S",
"%Y-%m-%d %H:%M:%S",
)
last_err = None
for fmt in fmts:
try:
return datetime.strptime(raw, fmt)
except ValueError as e:
last_err = e
raise ValueError(f"Unbekanntes Datumsformat: {raw!r}") from last_err
def _hr_to_minutes(hours: float | None) -> int:
if hours is None:
return 0
return int(round(float(hours) * 60))
def _detect_apple_sleep_csv_format(fieldnames: list[str] | None) -> Literal["segments", "summary"]:
if not fieldnames:
raise HTTPException(
status_code=400,
detail="CSV enthält keine Spaltenüberschriften.",
)
fn = {(f or "").strip() for f in fieldnames}
if {"Start", "End", "Duration (hr)", "Value"}.issubset(fn):
return "segments"
if "Start" in fn and "End" in fn and "Total Sleep (hr)" in fn:
return "summary"
raise HTTPException(
status_code=400,
detail=(
"Unbekanntes Apple-Health-Schlaf-CSV. "
"Erwartet wird entweder der Segment-Export (Spalten Start, End, Duration (hr), Value) "
"oder die Schlafanalyse mit Nacht-Zusammenfassung (u. a. Total Sleep (hr), Core/Light, Deep, REM)."
),
)
def _build_nights_from_apple_summary(reader: csv.DictReader) -> dict[date, dict]:
nights_dict: dict[date, dict] = {}
for raw in reader:
row = _strip_row_keys(raw)
start_s = row.get("Start") or ""
end_s = row.get("End") or ""
if not start_s or not end_s:
continue
try:
start_dt = _parse_apple_sleep_datetime(start_s)
end_dt = _parse_apple_sleep_datetime(end_s)
except ValueError:
continue
dt_key = (row.get("Date/Time") or row.get("Datum/Uhrzeit") or "").strip()
if dt_key:
try:
wake_d = datetime.strptime(dt_key[:10], "%Y-%m-%d").date()
except ValueError:
wake_d = end_dt.date()
else:
wake_d = end_dt.date()
core_hr = _safe_float(row.get("Core (hr)"))
if core_hr is None:
core_hr = _safe_float(row.get("Light (hr)")) or 0.0
deep_min = _hr_to_minutes(_safe_float(row.get("Deep (hr)")))
rem_min = _hr_to_minutes(_safe_float(row.get("REM (hr)")))
light_min = _hr_to_minutes(core_hr)
awake_min = _hr_to_minutes(_safe_float(row.get("Awake (hr)")))
nights_dict[wake_d] = {
"bedtime": start_dt,
"wake_time": end_dt,
"segments": [],
"deep_minutes": deep_min,
"rem_minutes": rem_min,
"light_minutes": light_min,
"awake_minutes": awake_min,
}
return nights_dict
def _build_nights_from_apple_segments(reader: csv.DictReader, phase_map: dict) -> dict[date, dict]:
segments = []
for raw in reader:
row = _strip_row_keys(raw)
phase_key = (row.get("Value") or "").strip()
phase_en = phase_map.get(phase_key)
if phase_en is None:
continue
try:
start_dt = _parse_apple_sleep_datetime(row.get("Start") or "")
end_dt = _parse_apple_sleep_datetime(row.get("End") or "")
duration_hr = _safe_float(row.get("Duration (hr)"))
if duration_hr is None:
continue
except (ValueError, TypeError):
continue
duration_min = int(duration_hr * 60)
segments.append({
"start": start_dt,
"end": end_dt,
"duration_min": duration_min,
"phase": phase_en,
})
segments.sort(key=lambda s: s["start"])
nights = []
current_night = None
for seg in segments:
if current_night is None or (seg["start"] - current_night["wake_time"]).total_seconds() > 7200:
current_night = {
"bedtime": seg["start"],
"wake_time": seg["end"],
"segments": [],
"deep_minutes": 0,
"rem_minutes": 0,
"light_minutes": 0,
"awake_minutes": 0,
}
nights.append(current_night)
current_night["segments"].append(seg)
current_night["wake_time"] = max(current_night["wake_time"], seg["end"])
current_night["bedtime"] = min(current_night["bedtime"], seg["start"])
if seg["phase"] == "deep":
current_night["deep_minutes"] += seg["duration_min"]
elif seg["phase"] == "rem":
current_night["rem_minutes"] += seg["duration_min"]
elif seg["phase"] == "light":
current_night["light_minutes"] += seg["duration_min"]
elif seg["phase"] == "awake":
current_night["awake_minutes"] += seg["duration_min"]
nights_dict: dict[date, dict] = {}
for night in nights:
wake_date = night["wake_time"].date()
nights_dict[wake_date] = night
return nights_dict
# ── Models ──────────────────────────────────────────────────────────────────── # ── Models ────────────────────────────────────────────────────────────────────
class SleepCreate(BaseModel): class SleepCreate(BaseModel):
@@ -460,96 +629,46 @@ async def import_apple_health_sleep(
""" """
Import sleep data from Apple Health CSV export. Import sleep data from Apple Health CSV export.
Expected CSV format: Supports:
Start,End,Duration (hr),Value,Source - Segment-Export: Start, End, Duration (hr), Value (Kern/Tief/REM/Wach oder Core/Deep/…)
2026-03-14 22:44:23,2026-03-14 23:00:19,0.266,Kern,Apple Watch - Schlafanalyse (Nacht-Zusammenfassung): Date/Time, Start, End, Total Sleep (hr),
Core/Light (hr), Deep (hr), REM (hr), Awake (hr), …
- Aggregates segments by night (wake date) - Aggregates segments by night (wake date) where applicable
- Maps German phase names: Kern→light, REM→rem, Tief→deep, Wach→awake - Stores Roh-Segmente in JSONB (bei Zusammenfassung oft leer)
- Stores raw segments in JSONB - Überschreibt keine manuellen Einträge (source='manual')
- Does NOT overwrite manual entries (source='manual')
""" """
pid = session['profile_id'] pid = session['profile_id']
# Read CSV
content = await file.read() content = await file.read()
csv_text = content.decode('utf-8-sig') # Handle BOM csv_text = content.decode('utf-8-sig')
reader = csv.DictReader(io.StringIO(csv_text)) reader = csv.DictReader(io.StringIO(csv_text))
fmt = _detect_apple_sleep_csv_format(reader.fieldnames)
# Phase mapping (German → English)
phase_map = { phase_map = {
'Kern': 'light', "Kern": "light",
'REM': 'rem', "Core": "light",
'Tief': 'deep', "Light": "light",
'Wach': 'awake', "REM": "rem",
'Schlafend': None # Ignore initial sleep entry "Tief": "deep",
"Deep": "deep",
"Wach": "awake",
"Awake": "awake",
"Schlafend": None,
"Asleep": None,
"In Bed": None,
} }
# Parse segments if fmt == "summary":
segments = [] nights_dict = _build_nights_from_apple_summary(reader)
for row in reader: else:
phase_de = row['Value'].strip() nights_dict = _build_nights_from_apple_segments(reader, phase_map)
phase_en = phase_map.get(phase_de)
if phase_en is None: # Skip "Schlafend" if not nights_dict:
continue raise HTTPException(
status_code=400,
start_dt = datetime.strptime(row['Start'], '%Y-%m-%d %H:%M:%S') detail="Keine importierbaren Schlafzeilen gefunden (prüfe Start/Ende und Format).",
end_dt = datetime.strptime(row['End'], '%Y-%m-%d %H:%M:%S') )
duration_hr = float(row['Duration (hr)'])
duration_min = int(duration_hr * 60)
segments.append({
'start': start_dt,
'end': end_dt,
'duration_min': duration_min,
'phase': phase_en
})
# Sort segments chronologically
segments.sort(key=lambda s: s['start'])
# Group segments into nights (gap-based)
# If gap between segments > 2 hours → new night
nights = []
current_night = None
for seg in segments:
# Start new night if:
# 1. First segment
# 2. Gap > 2 hours since last segment
if current_night is None or (seg['start'] - current_night['wake_time']).total_seconds() > 7200:
current_night = {
'bedtime': seg['start'],
'wake_time': seg['end'],
'segments': [],
'deep_minutes': 0,
'rem_minutes': 0,
'light_minutes': 0,
'awake_minutes': 0
}
nights.append(current_night)
# Add segment to current night
current_night['segments'].append(seg)
current_night['wake_time'] = max(current_night['wake_time'], seg['end'])
current_night['bedtime'] = min(current_night['bedtime'], seg['start'])
# Sum phases
if seg['phase'] == 'deep':
current_night['deep_minutes'] += seg['duration_min']
elif seg['phase'] == 'rem':
current_night['rem_minutes'] += seg['duration_min']
elif seg['phase'] == 'light':
current_night['light_minutes'] += seg['duration_min']
elif seg['phase'] == 'awake':
current_night['awake_minutes'] += seg['duration_min']
# Convert nights list to dict with wake_date as key
nights_dict = {}
for night in nights:
wake_date = night['wake_time'].date() # Date when you woke up
nights_dict[wake_date] = night
# Insert nights # Insert nights
imported = 0 imported = 0
@@ -0,0 +1,127 @@
"""
Tests: Focus Area Nutzungstypen (Migration 036, Router-Helfer).
Ohne MITAI_INTEGRATION_DB=1 werden nur SQL-Datei und reine Python-Helfer geprüft.
Mit gesetztem Flag optional Verifikation gegen eine PostgreSQL-Instanz (Migration 036 angewendet).
"""
from __future__ import annotations
import os
import sys
import uuid
from pathlib import Path
import pytest
BACKEND_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(BACKEND_ROOT))
def test_migration_036_defines_schema_and_seeds_keys():
p = BACKEND_ROOT / "migrations" / "036_focus_area_usage_types.sql"
assert p.is_file(), f"expected {p}"
text = p.read_text(encoding="utf-8")
assert "CREATE TABLE IF NOT EXISTS focus_area_usage_types" in text
assert "CREATE TABLE IF NOT EXISTS focus_area_definition_usage_types" in text
for key in (
"goal_priority",
"expected_training_effect",
"concrete_training_contribution",
):
assert key in text
assert "ON CONFLICT (key) DO NOTHING" in text
# Explizit: kein automatisches Befüllen der M:N-Tabelle
assert "INSERT INTO focus_area_definition_usage_types" not in text
def test_coerce_usage_type_keys_normalizes_values():
from focus_area_usage_helpers import coerce_usage_type_keys
assert coerce_usage_type_keys(None) == []
assert coerce_usage_type_keys([]) == []
assert coerce_usage_type_keys(["goal_priority", "expected_training_effect"]) == [
"goal_priority",
"expected_training_effect",
]
assert coerce_usage_type_keys('["concrete_training_contribution"]') == [
"concrete_training_contribution"
]
@pytest.mark.skipif(
os.getenv("MITAI_INTEGRATION_DB") != "1",
reason="Set MITAI_INTEGRATION_DB=1 plus DB_* env to run DB checks (nur Dev/CI!)",
)
def test_integration_focus_area_usage_types_seeded_and_junction_writable():
"""Nur gegen Dev-DB ausführen. Nutzt temporäre focus_area_definitions-Zeile, keine bestehenden Daten."""
from db import get_db, get_cursor
from focus_area_usage_helpers import coerce_usage_type_keys
tmp_id = str(uuid.uuid4())
tmp_key = f"tmp_usage_{tmp_id[:8]}"
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT key FROM focus_area_usage_types
ORDER BY sort_order, key
"""
)
keys = [row["key"] for row in cur.fetchall()]
assert keys == [
"goal_priority",
"expected_training_effect",
"concrete_training_contribution",
]
cur.execute(
"""
INSERT INTO focus_area_definitions
(id, key, name_de, category, is_active)
VALUES (%s, %s, 'tmp_test_usage', 'custom', false)
""",
(tmp_id, tmp_key),
)
cur.execute(
"""
SELECT COALESCE(
(
SELECT json_agg(faut.key ORDER BY faut.sort_order, faut.key)
FROM focus_area_definition_usage_types fadut
JOIN focus_area_usage_types faut ON faut.id = fadut.usage_type_id
WHERE fadut.focus_area_id = %s
),
'[]'::json
) AS allowed_usage_type_keys
""",
(tmp_id,),
)
assert coerce_usage_type_keys(cur.fetchone()["allowed_usage_type_keys"]) == []
cur.execute(
"""
INSERT INTO focus_area_definition_usage_types (focus_area_id, usage_type_id)
SELECT %s, u.id FROM focus_area_usage_types u WHERE u.key = %s
""",
(tmp_id, "goal_priority"),
)
cur.execute(
"""
INSERT INTO focus_area_definition_usage_types (focus_area_id, usage_type_id)
SELECT %s, u.id FROM focus_area_usage_types u WHERE u.key = %s
""",
(tmp_id, "expected_training_effect"),
)
cur.execute(
"""
SELECT COUNT(*) AS n
FROM focus_area_definition_usage_types
WHERE focus_area_id = %s
""",
(tmp_id,),
)
assert cur.fetchone()["n"] == 2
cur.execute("DELETE FROM focus_area_definitions WHERE id = %s", (tmp_id,))
@@ -0,0 +1,95 @@
# GUI, Informationsarchitektur, Admin & Navigation (Abnahme 2026-04-05)
> **Zweck:** Einheitliche Referenz für Menschen und Code-Agents (Cursor, Claude Code, …).
> **Gitea:** Teilaspekte zu [#30 Responsive UI](http://192.168.2.144:3000/Lars/mitai-jinkendo/issues/30); Admin-Layout kein separates Issue.
> **Branch-Realität:** Umsetzung auf `develop`, Deploy nach `main` wie üblich.
---
## Kurzüberblick
| Thema | Kern |
|-------|------|
| **Admin** | Eigener Bereich mit Shell wie KI-Analyse: Gruppen-Chips (mobil) / Sidebar (Desktop), Hub `/admin/g/:groupId`, Route-Guard `RequireAdmin` |
| **Ziele** | Eigener Hauptnav-Punkt `/goals`; nicht mehr primär unter Analyse; Dashboard + Einstellungen als Sekundär-Einstiege |
| **Einstellungen / Profil** | Nur **aktives** Profil inline; E-Mail-Self-Service; neue Profile nur **Admin → Benutzerverwaltung** |
| **KI-Analyse** | Neue Ergebnis-Karte im **rechten** Spalt der `analysis-split`, damit Kategorie-Nav nicht verdrängt wird |
| **PWA / iPhone** | Bottom-Nav: Safe Area auf **`.bottom-nav`**, kein Clipping durch `overflow-y` + `safe-area` auf Items |
| **Deploy Prod** | Workflow: `git fetch` + `git reset --hard origin/<branch>` statt `pull` bei schmutziger `package-lock` |
| **#14 Icon Picker** | Erledigt (`EmojiIconPicker`); Gitea geschlossen |
---
## Dateien (Single Source of Truth im Code)
| Bereich | Pfade |
|---------|--------|
| Hauptnavigation | `frontend/src/config/appNav.js` (`getMainNavItems`) |
| Active-State Bottom + Sidebar | `frontend/src/App.jsx` (`navItemActive`), `frontend/src/components/DesktopSidebar.jsx` |
| Admin Shell & Routing | `frontend/src/layouts/AdminShell.jsx`, `frontend/src/layouts/RequireAdmin.jsx`, `frontend/src/config/adminNav.js` (`ADMIN_GROUPS`, Hubs) |
| Admin-Seiten | `frontend/src/pages/AdminHomePage.jsx`, `AdminGroupHubPage.jsx`, `AdminUsersPage.jsx`, `AdminSystemPage.jsx`, … |
| Einstellungen Profil | `frontend/src/pages/SettingsPage.jsx`, `.settings-page__field` in `app.css` |
| KI-Analyse Layout | `frontend/src/pages/Analysis.jsx` + `.analysis-split*` in `app.css` |
| Admin-Zugriff verweigert | `frontend/src/pages/Dashboard.jsx` (`adminDenied` State aus `location.state`) |
| Bottom-Nav / Safe Area | `frontend/src/app.css` (`--nav-h`, `--nav-pad-top`, `.bottom-nav`, `.app-main` padding-bottom) |
| Deploy | `.gitea/workflows/deploy-prod.yml`, `deploy-dev.yml` |
| Backend Profil E-Mail | `backend/models.py` (`ProfileUpdate.email`), `backend/routers/profiles.py` (`update_profile` + Eindeutigkeit / Verifikation) |
| .gitignore Fix | `frontend/package-lock.json` eigene Zeile (war mit `settings.local` verklebt) |
---
## Navigation: Reihenfolge (Mobile & Desktop)
Übersicht → Erfassen → Verlauf → **Ziele** → Analyse → Einstellungen → **[Admin]**
- **Ziele:** `NavLink` mit `end: true` (exakt `/goals`).
- **Admin:** nur wenn `session.role === 'admin'`; Highlight bei `pathname.startsWith('/admin')`.
---
## Admin-Bereich (IA)
1. **Shell** nutzt dieselben UI-Klassen wie die Analyse: `.analysis-split`, `.analysis-split__nav-wrap`, `.analysis-split__main`.
2. **Nur Gruppen** in der Shell-Nav (inkl. Zähler pro Gruppe).
3. Konkrete Seiten: Karten auf **`/admin/g/:groupId`** (z. B. `features`, `prompts`, `system`).
4. **KI-Prompts** eigene Gruppe; **Basiseinstellungen** = SMTP + Placeholder-Export (`/admin/system`).
5. Kein Admin-Block mehr in den **Einstellungen** (nur Admin-Hinweis-Link zu Benutzerverwaltung).
---
## Backend-Hinweis Profil
`PUT /api/profile` akzeptiert `email`; Änderung setzt `email_verified` u. a. zurück (siehe `profiles.py`).
---
## Gitea / Issues (manuell oder `scripts/gitea/gitea_api.py`)
| Issue | Empfehlung |
|-------|------------|
| **#30** | Offen lassen oder TEILWEISE: Desktop-Sidebar existiert; ergänzt um Admin-Shell, scrollable Bottom-Nav, iOS Safe-Area. Kommentar mit Link **auf dieses Dokument**. |
| **#14** | Bereits geschlossen (Icon-Picker). |
| **Kein eigenes Admin-IA-Issue** | Optional: Sub-Issue „Admin Shell P7“ schließen oder mit #30 verknüpfen. |
Schließe **kein** großes #30 ohne Abnahme „volle Responsive-Spec“ – diese Session liefert nur einen **abgegrenzten** GUI-Stand.
---
## Checks für Folge-Agents
1. `frontend`: `npm run build`
2. Admin-Route als Nicht-Admin: Redirect `/`, Dashboard-Hinweis
3. iPhone PWA: Bottom-Nav nicht beschnitten; Content nicht hinter Home-Indicator
4. `develop` → nach Abnahme `main` + Deploy (siehe aktualisierte Workflows)
---
## Changelog-Kurz
- Admin: Shell, Hub-Routen, `RequireAdmin`, entfernt aus Settings.
- Ziele: `appNav`, Dashboard, Settings, Analyse nur noch Hinweis-Link.
- Settings: Mein Profil, E-Mail, keine Profilliste.
- Analyse: `newResult` in `analysis-split__main`.
- CSS: Bottom-Nav scroll + Safe Area + `--nav-pad-top`.
- Deploy: `reset --hard` auf Runner-Arbeitskopie.
- Review-Liste: #14 erledigt (siehe `REVIEW_OPEN_ISSUES_2026-04-04.md`).
+4 -2
View File
@@ -3,7 +3,7 @@
> **Gitea:** [#30 – Responsive UI](http://192.168.2.144:3000/Lars/mitai-jinkendo/issues/30) > **Gitea:** [#30 – Responsive UI](http://192.168.2.144:3000/Lars/mitai-jinkendo/issues/30)
> **Spec:** `.claude/docs/functional/RESPONSIVE_UI.md` > **Spec:** `.claude/docs/functional/RESPONSIVE_UI.md`
> **Breakpoint:** `<1024px` = Mobile (Bottom-Nav, bestehendes Verhalten), `≥1024px` = Desktop (Sidebar 220px) > **Breakpoint:** `<1024px` = Mobile (Bottom-Nav, bestehendes Verhalten), `≥1024px` = Desktop (Sidebar 220px)
> **Letzte Plan-Aktualisierung:** 2026-04-04 (P6; P7 Admin bewusst offen) > **Letzte Plan-Aktualisierung:** 2026-04-05 (P7 Admin-Shell umgesetzt; Doku `GUI_IA_ADMIN_NAV_2026-04-05.md`; P8 ausstehend)
--- ---
@@ -18,7 +18,7 @@
| P4 | Verlauf (Tabs links / Content rechts) | ☑ erledigt | `History.jsx` + `.history-*` in `app.css`; Tab-State bei `location.state.tab` | | P4 | Verlauf (Tabs links / Content rechts) | ☑ erledigt | `History.jsx` + `.history-*` in `app.css`; Tab-State bei `location.state.tab` |
| P5 | Analyse (Prompts links / Ergebnis rechts) | ☑ erledigt | `Analysis.jsx` + `.analysis-split*` in `app.css` | | P5 | Analyse (Prompts links / Ergebnis rechts) | ☑ erledigt | `Analysis.jsx` + `.analysis-split*` in `app.css` |
| P6 | Erfassung / Capture & Formularseiten | ☑ erledigt | `.capture-page` + `--capture-content-max` (eine Desktop-Breite); CaptureShell-Navigation | | P6 | Erfassung / Capture & Formularseiten | ☑ erledigt | `.capture-page` + `--capture-content-max` (eine Desktop-Breite); CaptureShell-Navigation |
| P7 | Admin & restliche Vollbreiten-Seiten | ⏸ Konzeption | Layout nach Abstimmung; nicht mit P6 mitgezogen | | P7 | Admin & restliche Vollbreiten-Seiten | ☑ erledigt (Kern) | **2026-04-05:** `AdminShell` + Hub-Routen + `adminNav`; Tabellen/„volle Breite“ weiter iterativ laut Spec §5.5 |
| P8 | Abschluss, Regression, Spec-Pflege | ☐ pending | | | P8 | Abschluss, Regression, Spec-Pflege | ☐ pending | |
**Status-Legende:** `☐ pending` · `◐ in Arbeit` · `☑ erledigt` · `⏸ blockiert` **Status-Legende:** `☐ pending` · `◐ in Arbeit` · `☑ erledigt` · `⏸ blockiert`
@@ -202,6 +202,8 @@ Spec **§5.4**: Desktop Formulare **zentriert**, **max-width ~600px** im Content
## Phase P7 – Admin & übrige Seiten ## Phase P7 – Admin & übrige Seiten
**Stand 2026-04-05:** Admin nutzt **dedizierte Shell** mit Gruppen-Navigation und Hubs (`AdminShell`, `adminNav.js`, `RequireAdmin`) — IA- und Routing-Grundlage erledigt. Tabellen „mehr Breite“ / feinere Layout-Tuning gemäß §5.5 können weiterlaufen ohne Shell-Refactor. Doku: `GUI_IA_ADMIN_NAV_2026-04-05.md`.
### Ziel ### Ziel
Spec **§5.5**: Admin-Tabellen nutzen auf Desktop **mehr Breite**; Mobile weiterhin horizontales Scrollen wo nötig. Spec **§5.5**: Admin-Tabellen nutzen auf Desktop **mehr Breite**; Mobile weiterhin horizontales Scrollen wo nötig.
+8 -11
View File
@@ -17,14 +17,14 @@
| # | Titel (gekürzt) | Vorschlag | Notiz | | # | Titel (gekürzt) | Vorschlag | Notiz |
|---|-----------------|-----------|--------| |---|-----------------|-----------|--------|
| 14 | Icon Picker Trainingstypen | OFFEN | Nur Freitext-Feld `icon` | | 14 | Icon Picker Trainingstypen | **ERLEDIGT** | `EmojiIconPicker` in `AdminTrainingTypesPage.jsx`; Gitea #14 geschlossen (2026-04) |
| 15 | Quality-Filter KI & Charts | TEILWEISE | Registry/Charts Confidence, kein durchgängiges Produkt | | 15 | Quality-Filter KI & Charts | TEILWEISE | Registry/Charts Confidence, kein durchgängiges Produkt |
| 21 | Universeller CSV-Parser + Mapping | OFFEN | Modul-spezifische Parser | | 21 | Universeller CSV-Parser + Mapping | OFFEN | Modul-spezifische Parser |
| 25 | Ziele-System Goals | DONE? | GoalsPage, Router, Focus Areas | | 25 | Ziele-System Goals | DONE? | GoalsPage, Router, Focus Areas |
| 26 | Charts erweitern | TEILWEISE | Phase-0c API + History/NutritionCharts | | 26 | Charts erweitern | TEILWEISE | Phase-0c API + History/NutritionCharts |
| 27 | Korrelationen & Insights | TEILWEISE | C-Charts + offene Data-Layer-TODOs | | 27 | Korrelationen & Insights | TEILWEISE | C-Charts + offene Data-Layer-TODOs |
| 29 | Abilities-Matrix UI | TEILWEISE | Admin/ProfileBuilder, UX offen | | 29 | Abilities-Matrix UI | TEILWEISE | Admin/ProfileBuilder, UX offen |
| 30 | Responsive UI Sidebar | OFFEN | Weiterhin Bottom-Nav-fokussiert | | 30 | Responsive UI Sidebar | **TEILWEISE** | P1–P6 + **P7 Admin-Shell** + iOS Bottom-Nav Safe-Area; SSoT-Doku: **`GUI_IA_ADMIN_NAV_2026-04-05.md`**; #30 bleibt offen bis P8/Abnahme |
| 32 | Version-System (inkl. ehem. #33) | OFFEN | Gitea: Body/Titel 2026-04-04 aktualisiert; Runner/Build-Git bewusst später | | 32 | Version-System (inkl. ehem. #33) | OFFEN | Gitea: Body/Titel 2026-04-04 aktualisiert; Runner/Build-Git bewusst später |
| 33 | — | GESCHLOSSEN | In #32 konsolidiert (superseded) | | 33 | — | GESCHLOSSEN | In #32 konsolidiert (superseded) |
| 34 | External Volumes Doku | PRÜFEN | Gegen Compose abgleichen | | 34 | External Volumes Doku | PRÜFEN | Gegen Compose abgleichen |
@@ -48,14 +48,11 @@
## Details je Issue (älteste zuerst) ## Details je Issue (älteste zuerst)
### #14 – [FEAT-001] Icon Picker für Trainingstypen ### #14 – [FEAT-001] Icon Picker für Trainingstypen — **ERLEDIGT**
**Code-Stand:** `AdminTrainingTypesPage.jsx` nutzt ein **Textfeld** `icon` (frei, z. B. Emoji). Kein dedizierter Icon-Picker (Palette, Vorschau, Kategorien). **Code-Stand:** `AdminTrainingTypesPage.jsx` nutzt **`EmojiIconPicker`** (`frontend/src/components/EmojiIconPicker.jsx`) für Neu- und Bearbeiten-Dialoge; Wert bleibt String in `training_types.icon`.
**Vorschlag:** `OFFEN` – Issue beibehalten; optional präzisieren: „Emoji-Picker oder vordefinierte Icon-Liste statt Freitext“. **Gitea:** Issue **#14 geschlossen** (Kommentar + Close, Stand 2026-04).
**Kommentar-Entwurf für Gitea:**
> Stand Backend/Frontend: `icon` wird als String in `training_types` gespeichert, Eingabe ist Freitext. Icon-Picker-UX steht noch aus.
--- ---
@@ -115,11 +112,11 @@
### #30 – [FEAT] Responsive UI – Desktop Sidebar + 2-spaltig ### #30 – [FEAT] Responsive UI – Desktop Sidebar + 2-spaltig
**Code-Stand:** Weiterhin stark **Mobile-first** (z. B. `bottom-nav` in `App.jsx`); keine ausgebaute Desktop-Sidebar wie im klassischen Admin-Dashboard. **Code-Stand (2026-04-05):** **Desktop-Sidebar** (`DesktopSidebar`, `config/appNav.js`) und **Mobile Bottom-Nav** mit horizontalem Scroll + **Safe Area** (`app.css`); **Admin** eigener Bereich **`AdminShell`** mit Gruppen-Hub wie Analyse (`adminNav.js`, `/admin/g/:groupId`, `RequireAdmin`). Siehe **`docs/issues/GUI_IA_ADMIN_NAV_2026-04-05.md`** (Dateipfade, IA, Deploy-Hinweis).
**Umsetzungsplan:** `docs/issues/PHASE_PLAN_RESPONSIVE_UI.md` (Phasen P0–P8, Abnahmekriterien & Tests, Fortschrittstabelle). **Umsetzungsplan:** `docs/issues/PHASE_PLAN_RESPONSIVE_UI.md` (Phasen P0–P8). **P7** Kern umgesetzt; **P8** (Regression, finale Abnahme) stehen noch aus – Issue **nicht** schließen ohne P8-Checkliste.
**Vorschlag:** `OFFEN`. **Vorschlag:** `TEILWEISE` – Gitea-Kommentar mit Link auf die GUI-Doku; Titel/Beschreibung optional um „Admin-Shell / Ziele-Nav / iOS PWA-Leiste“ ergänzen.
--- ---
@@ -0,0 +1,202 @@
# Umsetzungsplan: Sportspezifisch auswertbare Trainingsprofile
**Status:** Konzept für fachliche Abstimmung / Konzeptagent
**Datum:** 2026-04-05
**Bezug:** Fachliches Teilkonzept „Sportspezifisch auswertbare Trainingsprofile“ (User-Entwurf)
**Hinweis:** Keine Implementierung ohne Freigabe der unter [Offene Fragen](#offene-fragen-für-den-fachlichen-konzeptagenten) gekläerten Punkte.
---
## 1. Kurzfazit: Machbarkeit
**Fachlich und technisch grundsätzlich machbar** als gestaffelte Erweiterung auf dem bestehenden System:
- `training_types.profile` (JSONB)
- `TrainingProfileEvaluator` (`backend/profile_evaluator.py`)
- Persistenz: `activity_log.evaluation`, `quality_label`, `overall_score`
**Engpass:** Viele im Teilkonzept genannten Kriterien (z. B. Muskelgruppen, Nähe zum muskulären Versagen, detaillierte Zonenzeiten) **lassen sich aus der aktuellen `activity_log`-Datenbasis nicht zuverlässig ableiten**. Dafür braucht es zusätzliche Erfassung, Importfelder oder explizite „niedrige Evidenz / unbekannt“-Markierung in Metriken und KI-Kontext (Placeholder-Registry, Erklärbarkeit).
---
## 2. Ist-Analyse (Abhängigkeiten)
### 2.1 Daten & Konfiguration
| Baustein | Rolle |
|---------|--------|
| `training_types` | `category`, `subcategory`, `name_*`, optional `abilities` (JSONB), `profile` (JSONB) |
| `activity_type_mappings` | Import/manuelles Mapping `activity_type` → `training_type_id` (unverändert lassen) |
| `training_parameters` | Registry messbarer Parameter für Regeln (`source_field` → `activity_log`) |
| `activity_log` | u. a. `training_type_id`, `evaluation`, `quality_label`, `overall_score` |
### 2.2 Bewertung heute
- Der Evaluator läuft über mehrere **rule_sets** (Minimumanforderungen, Zonen, Effekte, Periodisierung, KPI, Safety).
- **Ein** zusammengefasster `overall_score` und **ein** `quality_label` (`excellent` | `good` | `acceptable` | `poor`).
- **Relevanz, intrinsische Qualität, Zielbezug, Platzierung** sind im Ergebnis **nicht formal getrennt**; Periodisierung/Performance sind teils **MVP/vereinfacht**.
### 2.3 Downstream (nicht brechen)
- **Issue #31 / Quality Filter:** `profiles.quality_filter_level`, `quality_filter.py` (SQL-Fragmente nach `quality_label`)
- **Frontend:** Badges in Aktivitäts-UI, History-Hinweise
- **Data Layer / Charts:** u. a. `calculate_quality_sessions_pct`, `activity_score`, Korrelationen
- **Placeholder Registry:** u. a. `quality_sessions_pct` (bekannte Semantik-/Label-Diskrepanz, siehe unten)
### 2.4 Bekannte technische Inkonsistenz (Bestand)
`calculate_quality_sessions_pct` filtert u. a. auf `quality_label IN (..., 'very_good', ...)`, der `TrainingProfileEvaluator` setzt **`very_good` nicht**. Das sollte **vor oder zusammen mit** größeren Profil-Erweiterungen bereinigt werden, damit neue Dimensionen nicht auf wackeliger Basis validiert werden.
---
## 3. Umsetzungsprinzipien (Kompatibilität)
1. **Kein Big-Bang:** Consumer erwarten weiterhin sinnvolle `quality_label` / `overall_score`, es sei denn, es gibt eine **versionierte Cutover-Strategie**.
2. **Additive JSON-Struktur** in `evaluation` (z. B. mehrdimensionale Teilergebnisse), ohne bestehende Schlüssel willkürlich zu entfernen.
3. **Legacy-Vertrag festlegen:** z. B. `overall_score` = **primär intrinsische** Qualität (oder explizit „Legacy-Komposit“ mit `schema_version`).
4. **`training_types` bleibt Single Source** für Typ + Profil; Mapping-Import-Logik nicht „mitziehen“, außer es ist fachlich nötig.
5. **Neue Coach-Metriken:** über Placeholder Registry, mit Evidence-Tags; keine doppelte Wahrheit neben der Registry.
6. **KI:** `ai_context` / `interpretation_boundary` im Profil ausbaubar machen (was erlaubt/verboten ist, bei Datenlücken).
---
## 4. Phasenplan
### Phase 0 – Begriffe, Verträge, Bestandsaufnahme
- Glossar: Relevanz, intrinsische Qualität, Zielbeitrag, Platzierung, Belastung, sportspezifische Qualität → **Mapping auf bestehende `rule_sets`**.
- Vollständige Liste: wer liest `quality_label` / `evaluation` / `overall_score` (APIs, SQL, Frontend).
- Align: `very_good` vs. Evaluator-Labels; optional: Rolle von `acceptable` in „Qualitätssessions“ vs. globalem Filter **fachlich** klären.
### Phase 1 – Metamodell im Profil-JSON
- Erweiterung `training_types.profile`: z. B. `sport_logic`, `dimensions_config`, `goal_linkage`, `load_character`, `recovery_character`, `interference`, `ai_interpretation`.
- Evaluator liefert **Teilscores + Begründungen** pro Dimension; **Legacy-Felder** ableitbar und dokumentiert.
### Phase 2 – Zielbezug
- Input: aktive Ziele, `goal_mode`, Focus-Gewichte (`user_focus_area_weights`).
- Ausgabe: eigene Dimension **`goal_fit`**, ohne intrinsische Bewertung zu überschreiben.
### Phase 3 – Wochenkontext / Platzierung / Interferenz
- Kontext in `load_evaluation_context` erweitern (Reihenfolge, Vortag, Ruhetage, optional Vitals/Schlaf).
- Regeln schrittweise; False-Positive-Risiko beachten.
### Phase 4 – Sportspezifische Templates
- Profilvorlagen pro `sport_logic` (analog `profile_templates.py`), unterschiedliche Parameter und Schwellen.
- `confidence` / `data_sufficiency` pro Dimension.
### Phase 5 – Coach-Metriken & Placeholder
- Neue Platzhalter nur bei klarer Semantik; ggf. `quality_sessions_pct` **umschreiben** oder durch neuen Key ersetzen + Deprecation-Plan.
### Phase 6 – Frontend / Admin
- Dimensionen sichtbar machen; Badges können vorerst Legacy-Score anzeigen.
---
## 5. Risiken (Kurz)
| Risiko | Maßnahme |
|--------|----------|
| Bedeutung von `quality_label` wechselt still | `evaluation.schema_version`, dokumentierter Vertrag, ggf. separates `intrinsic_quality_label` nach Cutover |
| Charts/Scores springen | Shadow-Vergleich, gestuftes Rollout |
| KI übertreibt bei Datenlücken | `ai_interpretation` + Metadata-Evidence |
| Registry-Drift | Alle neuen Kennzahlen registrieren |
---
## Offene Fragen für den fachlichen Konzeptagenten
Die folgenden Blöcke sind bewusst als Markdown-Codeblöcke formatiert, damit sie **unverändert** in Prompts oder Tickets übernommen werden können.
### Block A – Priorität & Konflikte zwischen Dimensionen
```markdown
Wenn sich Dimensionen widersprechen (z. B. intrinsische Qualität „hoch“, Zielpassung „niedrig“, Platzierung „problematisch“):
1. Welche Dimension soll für die **primäre Nutzer-/Coach-Aussage** in der UI führend sein?
2. Gibt es eine **feste Prioritätsreihenfolge** (z. B. Sicherheit > Platzierung > Zielpassung > intrinsische Qualität) oder ist sie kontextabhängig?
3. Soll es eine **explizite „Gesamt-Coach-Empfehlung“** geben, die aus den Dimensionen kombiniert wird, oder nur parallele Teilurteile ohne Gesamtnote?
```
### Block B – Minimaldatensatz & Sportlogiken
```markdown
Pro Trainingsfamilie / „sport_logic“ (Kraft, Cardio, Schnellkraft, Kampfsport, Mobility, Erholung aktiv, Geist & Meditation):
1. Welche **messbaren Felder** sind minimal nötig, damit eine sportspezifische Bewertung **fachlich vertretbar** ist (nicht nur „nice to have“)?
2. Welche Aussagen dürfen **ohne** diese Felder **nicht** getroffen werden (nur „unbekannt“ / Confidence niedrig)?
3. Sollen fehlende Daten die **intrinsische** Bewertung hart begrenzen (Cap), oder nur **Zusatzdimensionen** betreffen?
```
### Block C – Einzeltraining vs. Wochenkontext
```markdown
Platzierung / Kontextqualität:
1. Darf schlechte Platzierung die **sichtbare Einheit-Qualität** numerisch senken, oder nur **Flags/Hinweise** erzeugen?
2. Welche zeitliche Auflösung ist Pflicht: nur **Datum** oder auch **start_time** / Reihenfolge am Tag?
3. Wie gehen wir mit **unvollständiger Historie** um (Importlücken, manuell gelöschte Einträge)?
```
### Block D – Ziele & Multi-Ziel
```markdown
Zielbezug (goal_fit):
1. Bewertung strikt gegen **ein Primärziel**, oder gewichtet gegen **alle aktiven Ziele**?
2. Wie werden **Focus Areas** vs. **konkrete Goals** priorisiert, wenn sie sich widersprechen?
3. Soll „behindert das Ziel“ (Teilkonzept) ein **eigener Score** oder nur eine **kategorische** Aussage sein?
```
### Block E – KI & Haftung / Grenzen
```markdown
KI-Interpretationsrahmen (pro Profil oder global):
1. Welche Formulierungen sind **verboten** (medizinische Diagnosen, absolute Leistungsversprechen, …)?
2. Muss jede KI-gestützte Aussage einen **Evidenz-Hinweis** tragen („basierend auf Dauer/HF“, „Muskelgruppen nicht erfasst“)?
3. Soll der Nutzer **opt-in** für interpretative Texte jenseits der Regeln haben?
```
### Block F – Legacy-Metriken & Filter
```markdown
Bestehende Kennzahlen:
1. Soll `quality_label` / `overall_score` dauerhaft **nur intrinsisch** bedeuten, oder ein **Komposit** aus mehreren Dimensionen?
2. Wie sollen `quality_sessions_pct` und der globale **Quality Filter** künftig mit mehrdimensionalen Urteilen umgehen (nur intrinsisch filtern vs. Kombination)?
3. Ist `acceptable` fachlich eine „Qualitätssession“ oder nur „formal ok“?
```
### Block G – Abnahme / Akzeptanz
```markdown
Abnahme:
1. Welche **messbaren** Abnahmekriterien gelten pro Phase (z. B. % konsistent bewerteter Sessions, keine Regression bei Filter-Charts)?
2. Wer **fachlich** sign-off: Rolle „Domain Owner“ vs. Entwicklung?
```
---
## Anhang: Referenz im Repository
| Thema | Pfad (orientierend) |
|-------|---------------------|
| Evaluator | `backend/profile_evaluator.py` |
| Regeln | `backend/rule_engine.py` |
| Auswertung + Kontext | `backend/evaluation_helper.py` |
| Profile JSON / Migration | `backend/migrations/014_training_profiles.sql`, Templates `backend/profile_templates.py` |
| Quality Filter | `backend/quality_filter.py` |
| Aktivitäts-API inkl. Eval | `backend/routers/activity.py` |
| Quality-Sessions-Metrik | `backend/data_layer/activity_metrics.py` (`calculate_quality_sessions_pct`) |
| Placeholder Registry | `backend/placeholder_registrations/activity_metrics.py` |
---
*Ende des Dokuments.*
+58 -19
View File
@@ -12,7 +12,9 @@
--accent-dark: #0a5c43; --accent-dark: #0a5c43;
--danger: #D85A30; --danger: #D85A30;
--warn: #EF9F27; --warn: #EF9F27;
--nav-h: 64px; /* Höhe der eigentlichen Tab-Zeile (ohne Abstand/Home-Indicator) */
--nav-h: 56px;
--nav-pad-top: 8px;
--header-h: 52px; --header-h: 52px;
--font: system-ui, -apple-system, 'Segoe UI', sans-serif; --font: system-ui, -apple-system, 'Segoe UI', sans-serif;
--capture-content-max: 800px; --capture-content-max: 800px;
@@ -36,20 +38,61 @@ body { font-family: var(--font); background: var(--bg); color: var(--text1); -we
position: sticky; top: 0; z-index: 10; position: sticky; top: 0; z-index: 10;
} }
.app-logo { font-size: 18px; font-weight: 700; color: var(--accent); letter-spacing: -0.02em; } .app-logo { font-size: 18px; font-weight: 700; color: var(--accent); letter-spacing: -0.02em; }
.app-main { flex: 1; overflow-y: auto; padding: 16px 16px calc(var(--nav-h) + 16px); } /* unten: Tab-Leiste + Abstand nach oben zur Leiste + Home-Indicator (iPhone) */
.app-main {
flex: 1;
overflow-y: auto;
padding: 16px 16px calc(var(--nav-h) + var(--nav-pad-top) + env(safe-area-inset-bottom, 0px) + 20px);
}
.bottom-nav { .bottom-nav {
position: fixed; bottom: 0; left: 50%; transform: translateX(-50%); position: fixed;
width: 100%; max-width: 600px; bottom: 0;
height: var(--nav-h); display: flex; align-items: stretch; left: 50%;
background: var(--surface); border-top: 1px solid var(--border); transform: translateX(-50%);
width: 100%;
max-width: 600px;
display: flex;
align-items: center;
background: var(--surface);
border-top: 1px solid var(--border);
z-index: 20; z-index: 20;
overflow-x: auto;
overflow-y: visible;
-webkit-overflow-scrolling: touch;
scrollbar-width: none;
-ms-overflow-style: none;
justify-content: flex-start;
gap: 2px;
padding: var(--nav-pad-top) 6px env(safe-area-inset-bottom, 0px);
min-height: calc(var(--nav-h) + var(--nav-pad-top) + env(safe-area-inset-bottom, 0px));
height: auto;
box-sizing: border-box;
}
.bottom-nav::-webkit-scrollbar {
display: none;
} }
.nav-item { .nav-item {
flex: 1; display: flex; flex-direction: column; align-items: center; flex: 0 0 auto;
justify-content: center; gap: 3px; color: var(--text3); min-width: 56px;
text-decoration: none; font-size: 10px; font-weight: 500; max-width: 96px;
transition: color 0.15s; padding-bottom: env(safe-area-inset-bottom, 0); display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 3px;
color: var(--text3);
text-decoration: none;
font-weight: 500;
transition: color 0.15s;
padding: 2px 4px 4px;
box-sizing: border-box;
}
.nav-item span {
font-size: 10px;
line-height: 1.15;
text-align: center;
max-width: 100%;
} }
.nav-item.active { color: var(--accent); } .nav-item.active { color: var(--accent); }
.nav-item svg { flex-shrink: 0; } .nav-item svg { flex-shrink: 0; }
@@ -256,11 +299,15 @@ body { font-family: var(--font); background: var(--bg); color: var(--text1); -we
.analysis-page__header { .analysis-page__header {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: flex-start;
margin-bottom: 16px; margin-bottom: 16px;
gap: 12px; gap: 12px;
flex-wrap: wrap; flex-wrap: wrap;
} }
.analysis-page__header > div:first-child {
flex: 1;
min-width: 0;
}
.analysis-split { .analysis-split {
display: flex; display: flex;
@@ -544,14 +591,6 @@ a.analysis-split__nav-item {
} }
} }
/* 6-item nav - smaller labels */
.nav-item span { font-size: 11px; }
/* 7-item nav scrollable */
.bottom-nav { overflow-x: auto; }
.nav-item span { font-size: 11px; }
.nav-item { min-width: 60px; }
/* Header with profile avatar */ /* Header with profile avatar */
.app-header { display:flex; align-items:center; justify-content:space-between; } .app-header { display:flex; align-items:center; justify-content:space-between; }
.app-header a { display:flex; } .app-header a { display:flex; }
+3
View File
@@ -2,6 +2,7 @@ import {
LayoutDashboard, LayoutDashboard,
PlusSquare, PlusSquare,
TrendingUp, TrendingUp,
Target,
BarChart2, BarChart2,
Settings, Settings,
Shield Shield
@@ -18,6 +19,7 @@ function baseItems() {
{ to: '/', label: 'Übersicht', end: true }, { to: '/', label: 'Übersicht', end: true },
{ to: '/capture', label: 'Erfassen' }, { to: '/capture', label: 'Erfassen' },
{ to: '/history', label: 'Verlauf' }, { to: '/history', label: 'Verlauf' },
{ to: '/goals', label: 'Ziele', shortLabel: 'Ziele', end: true },
{ to: '/analysis', label: 'Analyse' }, { to: '/analysis', label: 'Analyse' },
{ to: '/settings', label: 'Einstellungen', shortLabel: 'Einst.' } { to: '/settings', label: 'Einstellungen', shortLabel: 'Einst.' }
] ]
@@ -29,6 +31,7 @@ export function getMainNavItems(isAdmin) {
LayoutDashboard, LayoutDashboard,
PlusSquare, PlusSquare,
TrendingUp, TrendingUp,
Target,
BarChart2, BarChart2,
Settings Settings
] ]
+137 -13
View File
@@ -14,8 +14,19 @@ const CATEGORIES = [
{ value: 'custom', label: 'Eigene' } { value: 'custom', label: 'Eigene' }
] ]
function groupAreasByCategory(areas) {
const grouped = {}
for (const area of areas) {
const cat = area.category || 'other'
if (!grouped[cat]) grouped[cat] = []
grouped[cat].push(area)
}
return grouped
}
export default function AdminFocusAreasPage() { export default function AdminFocusAreasPage() {
const [data, setData] = useState({ areas: [], grouped: {}, total: 0 }) const [data, setData] = useState({ areas: [], grouped: {}, total: 0 })
const [usageTypesCatalog, setUsageTypesCatalog] = useState([])
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [error, setError] = useState(null) const [error, setError] = useState(null)
const [showInactive, setShowInactive] = useState(false) const [showInactive, setShowInactive] = useState(false)
@@ -34,11 +45,35 @@ export default function AdminFocusAreasPage() {
loadData() loadData()
}, [showInactive]) }, [showInactive])
useEffect(() => {
let cancelled = false
;(async () => {
try {
const r = await api.listFocusAreaUsageTypes()
if (!cancelled) setUsageTypesCatalog(r.usage_types || [])
} catch (e) {
console.error('usage-types catalog:', e)
if (!cancelled) setUsageTypesCatalog([])
}
})()
return () => { cancelled = true }
}, [])
const loadData = async () => { const loadData = async () => {
try { try {
setLoading(true) setLoading(true)
const result = await api.listFocusAreaDefinitions(showInactive) const result = await api.listFocusAreaDefinitions(showInactive)
setData(result) const areas = (result.areas || []).map(a => ({
...a,
allowed_usage_type_keys: Array.isArray(a.allowed_usage_type_keys)
? a.allowed_usage_type_keys
: []
}))
setData({
areas,
grouped: groupAreasByCategory(areas),
total: result.total ?? areas.length
})
setError(null) setError(null)
} catch (err) { } catch (err) {
console.error('Failed to load focus areas:', err) console.error('Failed to load focus areas:', err)
@@ -74,14 +109,20 @@ export default function AdminFocusAreasPage() {
const handleUpdate = async (id) => { const handleUpdate = async (id) => {
try { try {
const area = data.areas.find(a => a.id === id) const area = data.areas.find(a => a.id === id)
await api.updateFocusAreaDefinition(id, { const usageKeys = Array.isArray(area.allowed_usage_type_keys)
name_de: area.name_de, ? area.allowed_usage_type_keys
name_en: area.name_en, : []
icon: area.icon, await Promise.all([
description: area.description, api.updateFocusAreaDefinition(id, {
category: area.category, name_de: area.name_de,
is_active: area.is_active name_en: area.name_en,
}) icon: area.icon,
description: area.description,
category: area.category,
is_active: area.is_active
}),
api.setFocusAreaUsageTypes(id, usageKeys)
])
setEditingId(null) setEditingId(null)
await loadData() await loadData()
} catch (err) { } catch (err) {
@@ -113,12 +154,25 @@ export default function AdminFocusAreasPage() {
} }
const updateField = (id, field, value) => { const updateField = (id, field, value) => {
setData(prev => ({ setData(prev => {
...prev, const areas = prev.areas.map(a =>
areas: prev.areas.map(a =>
a.id === id ? { ...a, [field]: value } : a a.id === id ? { ...a, [field]: value } : a
) )
})) return { ...prev, areas, grouped: groupAreasByCategory(areas), total: areas.length }
})
}
const toggleUsageTypeKey = (areaId, key, checked) => {
setData(prev => {
const areas = prev.areas.map(a => {
if (a.id !== areaId) return a
const cur = new Set(Array.isArray(a.allowed_usage_type_keys) ? a.allowed_usage_type_keys : [])
if (checked) cur.add(key)
else cur.delete(key)
return { ...a, allowed_usage_type_keys: [...cur] }
})
return { ...prev, areas, grouped: groupAreasByCategory(areas), total: areas.length }
})
} }
if (loading) { if (loading) {
@@ -364,6 +418,45 @@ export default function AdminFocusAreasPage() {
/> />
</div> </div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 6 }}>
Erlaubte Nutzungstypen
</label>
{usageTypesCatalog.length === 0 ? (
<span style={{ fontSize: 12, color: 'var(--text3)' }}>
Kein Katalog geladen (Backend / Migration prüfen).
</span>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{usageTypesCatalog.map(ut => (
<label
key={ut.id}
style={{
fontSize: 13,
display: 'flex',
alignItems: 'flex-start',
gap: 8,
cursor: 'pointer'
}}
>
<input
type="checkbox"
style={{ marginTop: 3 }}
checked={(area.allowed_usage_type_keys || []).includes(ut.key)}
onChange={(e) =>
toggleUsageTypeKey(area.id, ut.key, e.target.checked)
}
/>
<span>
<span style={{ display: 'block' }}>{ut.label_de}</span>
<code style={{ fontSize: 11, color: 'var(--text3)' }}>{ut.key}</code>
</span>
</label>
))}
</div>
)}
</div>
<div style={{ display: 'flex', gap: 8 }}> <div style={{ display: 'flex', gap: 8 }}>
<button <button
className="btn-primary" className="btn-primary"
@@ -430,6 +523,37 @@ export default function AdminFocusAreasPage() {
{area.description} {area.description}
</div> </div>
)} )}
{(area.allowed_usage_type_keys || []).length > 0 && (
<div
style={{
fontSize: 12,
marginTop: 8,
display: 'flex',
flexWrap: 'wrap',
gap: 6
}}
>
{(area.allowed_usage_type_keys || []).map(k => {
const ut = usageTypesCatalog.find(x => x.key === k)
return (
<span
key={k}
style={{
padding: '2px 8px',
borderRadius: 6,
background: 'var(--surface2)',
border: '1px solid var(--border)',
color: 'var(--text2)'
}}
title={k}
>
{ut?.label_de || k}
</span>
)
})}
</div>
)}
</div> </div>
<div style={{ display: 'flex', gap: 6, flexShrink: 0 }}> <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
+25 -14
View File
@@ -1,6 +1,6 @@
import React, { useState, useEffect, useMemo } from 'react' import React, { useState, useEffect, useMemo } from 'react'
import { Brain, Trash2, ChevronDown, ChevronUp, Target } from 'lucide-react' import { Brain, Trash2, ChevronDown, ChevronUp } from 'lucide-react'
import { useNavigate } from 'react-router-dom' import { Link } from 'react-router-dom'
import { api } from '../utils/api' import { api } from '../utils/api'
import { useAuth } from '../context/AuthContext' import { useAuth } from '../context/AuthContext'
import Markdown from '../utils/Markdown' import Markdown from '../utils/Markdown'
@@ -330,7 +330,6 @@ function InsightCard({ ins, onDelete, defaultOpen=false, prompts=[] }) {
export default function Analysis() { export default function Analysis() {
const { canUseAI } = useAuth() const { canUseAI } = useAuth()
const navigate = useNavigate()
const [prompts, setPrompts] = useState([]) const [prompts, setPrompts] = useState([])
const [allInsights, setAllInsights] = useState([]) const [allInsights, setAllInsights] = useState([])
const [loading, setLoading] = useState(null) const [loading, setLoading] = useState(null)
@@ -474,15 +473,14 @@ export default function Analysis() {
return ( return (
<div className="analysis-page"> <div className="analysis-page">
<div className="analysis-page__header"> <div className="analysis-page__header">
<h1 className="page-title" style={{ margin: 0 }}>KI-Analyse</h1> <div>
<button <h1 className="page-title" style={{ margin: 0 }}>KI-Analyse</h1>
type="button" <p style={{ fontSize: 12, color: 'var(--text3)', margin: '8px 0 0', lineHeight: 1.5, maxWidth: 520 }}>
className="btn btn-secondary" Ziele und Fokusbereiche steuern den Kontext der Auswertungen –{' '}
onClick={() => navigate('/goals')} <Link to="/goals" style={{ color: 'var(--accent)', fontWeight: 600 }}>unter „Ziele“ konfigurieren</Link>
style={{ fontSize: 13, padding: '6px 12px' }} {' '}(auch über die untere Navigation).
> </p>
<Target size={14} /> Ziele </div>
</button>
</div> </div>
<div className="tabs"> <div className="tabs">
@@ -508,8 +506,8 @@ export default function Analysis() {
{/* ── Analysen starten ── */} {/* ── Analysen starten ── */}
{tab==='run' && ( {tab==='run' && (
<div> <div>
{/* Fresh result shown immediately */} {/* Fallback: Ergebnis oben nur wenn keine Pipeline-Split-Ansicht (z. B. keine Prompts) */}
{newResult && ( {newResult && !(canUseAI && pipelinePrompts.length > 0) && (
<div style={{marginBottom:16}}> <div style={{marginBottom:16}}>
<div style={{fontSize:12,fontWeight:600,color:'var(--accent)',marginBottom:8}}> <div style={{fontSize:12,fontWeight:600,color:'var(--accent)',marginBottom:8}}>
✅ Neue Analyse erstellt: ✅ Neue Analyse erstellt:
@@ -565,6 +563,19 @@ export default function Analysis() {
</nav> </nav>
</div> </div>
<div className="analysis-split__main"> <div className="analysis-split__main">
{newResult && (
<div style={{ marginBottom: 20 }}>
<div style={{ fontSize: 12, fontWeight: 600, color: 'var(--accent)', marginBottom: 8 }}>
✅ Neue Analyse erstellt:
</div>
<InsightCard
ins={{ ...newResult, created: new Date().toISOString() }}
onDelete={deleteInsight}
defaultOpen={true}
prompts={prompts}
/>
</div>
)}
{activeCategoryKey && (() => { {activeCategoryKey && (() => {
const group = pipelineGroups.find(g => g.categoryKey === activeCategoryKey) const group = pipelineGroups.find(g => g.categoryKey === activeCategoryKey)
if (!group?.prompts?.length) return null if (!group?.prompts?.length) return null
+8 -12
View File
@@ -19,7 +19,6 @@ function emptyForm() {
function CaliperForm({ form, setForm, profile, onSave, onCancel, saveLabel='Speichern', saving=false, error=null, usage=null }) { function CaliperForm({ form, setForm, profile, onSave, onCancel, saveLabel='Speichern', saving=false, error=null, usage=null }) {
const sex = profile?.sex||'m' const sex = profile?.sex||'m'
const age = profile?.dob ? Math.floor((Date.now()-new Date(profile.dob))/(365.25*24*3600*1000)) : 30 const age = profile?.dob ? Math.floor((Date.now()-new Date(profile.dob))/(365.25*24*3600*1000)) : 30
const weight = form.weight || 80
const sfPoints = METHOD_POINTS[form.sf_method]?.[sex] || [] const sfPoints = METHOD_POINTS[form.sf_method]?.[sex] || []
const sfVals = {} const sfVals = {}
sfPoints.forEach(k=>{ const v=form[`sf_${k}`]; if(v!==''&&v!=null) sfVals[k]=parseFloat(v) }) sfPoints.forEach(k=>{ const v=form[`sf_${k}`]; if(v!==''&&v!=null) sfVals[k]=parseFloat(v) })
@@ -79,7 +78,7 @@ function CaliperForm({ form, setForm, profile, onSave, onCancel, saveLabel='Spei
<button <button
className="btn btn-primary" className="btn btn-primary"
style={{width:'100%', cursor: (usage && !usage.allowed) ? 'not-allowed' : 'pointer'}} style={{width:'100%', cursor: (usage && !usage.allowed) ? 'not-allowed' : 'pointer'}}
onClick={()=>onSave(bfPct, sex)} onClick={()=>onSave(bfPct)}
disabled={saving || (usage && !usage.allowed)} disabled={saving || (usage && !usage.allowed)}
> >
{(usage && !usage.allowed) ? '🔒 Limit erreicht' : saveLabel} {(usage && !usage.allowed) ? '🔒 Limit erreicht' : saveLabel}
@@ -117,22 +116,19 @@ export default function CaliperScreen() {
loadUsage() loadUsage()
},[]) },[])
const buildPayload = (f, bfPct, sex) => { const buildPayload = (f, bfPct) => {
const weight = profile?.weight || null
const payload = { date: f.date, sf_method: f.sf_method, notes: f.notes } const payload = { date: f.date, sf_method: f.sf_method, notes: f.notes }
Object.entries(f).forEach(([k,v])=>{ if(k.startsWith('sf_')&&v!==''&&v!=null) payload[k]=parseFloat(v) }) Object.entries(f).forEach(([k,v])=>{ if(k.startsWith('sf_')&&v!==''&&v!=null) payload[k]=parseFloat(v) })
if(bfPct!=null) { if (bfPct != null) payload.body_fat_pct = bfPct
payload.body_fat_pct = bfPct // lean_mass / fat_mass: Backend leitet aus nächstem weight_log zum Messdatum ab
// get latest weight from profile or skip lean/fat
}
return payload return payload
} }
const handleSave = async (bfPct, sex) => { const handleSave = async (bfPct) => {
setSaving(true) setSaving(true)
setError(null) setError(null)
try { try {
const payload = buildPayload(form, bfPct, sex) const payload = buildPayload(form, bfPct)
await api.upsertCaliper(payload) await api.upsertCaliper(payload)
setSaved(true) setSaved(true)
await load() await load()
@@ -148,8 +144,8 @@ export default function CaliperScreen() {
} }
} }
const handleUpdate = async (bfPct, sex) => { const handleUpdate = async (bfPct) => {
const payload = buildPayload(editing, bfPct, sex) const payload = buildPayload(editing, bfPct)
await api.updateCaliper(editing.id, payload) await api.updateCaliper(editing.id, payload)
setEditing(null); await load() setEditing(null); await load()
} }
+50 -5
View File
@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom' import { useNavigate, useLocation } from 'react-router-dom'
import { Check, Brain } from 'lucide-react' import { Check, Brain } from 'lucide-react'
import { import {
LineChart, Line, XAxis, YAxis, Tooltip, LineChart, Line, XAxis, YAxis, Tooltip,
@@ -252,8 +252,12 @@ function ComboChart({ weights, nutrition }) {
// ── Main Dashboard ──────────────────────────────────────────────────────────── // ── Main Dashboard ────────────────────────────────────────────────────────────
export default function Dashboard() { export default function Dashboard() {
const nav = useNavigate() const nav = useNavigate()
const location = useLocation()
const { activeProfile } = useProfile() const { activeProfile } = useProfile()
const [adminDeniedHint, setAdminDeniedHint] = useState(false)
const [goalsCount, setGoalsCount] = useState(null)
const [stats, setStats] = useState(null) const [stats, setStats] = useState(null)
const [weights, setWeights] = useState([]) const [weights, setWeights] = useState([])
const [calipers, setCalipers] = useState([]) const [calipers, setCalipers] = useState([])
@@ -299,6 +303,21 @@ export default function Dashboard() {
useEffect(()=>{ load() },[]) useEffect(()=>{ load() },[])
useEffect(() => {
if (!location.state?.adminDenied) return
setAdminDeniedHint(true)
nav('.', { replace: true, state: null })
const clear = window.setTimeout(() => setAdminDeniedHint(false), 8000)
return () => window.clearTimeout(clear)
}, [location.state, nav])
useEffect(() => {
if (!activeProfile?.id) return
api.listGoals()
.then((list) => setGoalsCount(Array.isArray(list) ? list.length : 0))
.catch(() => setGoalsCount(null))
}, [activeProfile?.id])
if (loading) return <div className="empty-state"><div className="spinner"/></div> if (loading) return <div className="empty-state"><div className="spinner"/></div>
const latestCal = calipers[0] const latestCal = calipers[0]
@@ -349,6 +368,24 @@ export default function Dashboard() {
return ( return (
<div className="dashboard-page"> <div className="dashboard-page">
{adminDeniedHint && (
<div
role="alert"
style={{
marginBottom: 14,
padding: '12px 14px',
borderRadius: 10,
background: '#FCEBEB',
border: '1px solid #D85A3033',
fontSize: 13,
color: '#D85A30',
lineHeight: 1.5,
}}
>
<strong>Kein Admin-Zugriff.</strong> Dieser Bereich ist nur für Konten mit Administrator-Rolle.
Du wurdest zur Übersicht weitergeleitet.
</div>
)}
{/* Header greeting */} {/* Header greeting */}
<div className="dashboard-greeting"> <div className="dashboard-greeting">
<h1 style={{fontSize:22,fontWeight:800,margin:0,color:'var(--text1)'}}> <h1 style={{fontSize:22,fontWeight:800,margin:0,color:'var(--text1)'}}>
@@ -559,18 +596,26 @@ export default function Dashboard() {
<DashboardSection <DashboardSection
title="Ziele & Fokus" title="Ziele & Fokus"
description="Trainingsmodus, Schwerpunkte und konkrete Ziele für die KI." description="Strategische Ziele und Schwerpunkte – eigener Menüpunkt „Ziele“, Kontext für KI und Dashboard."
headerRight={ headerRight={
<button type="button" className="btn btn-secondary" style={{ fontSize: 12, padding: '6px 12px' }} <button type="button" className="btn btn-secondary" style={{ fontSize: 12, padding: '6px 12px' }}
onClick={(e)=>{ e.stopPropagation(); nav('/goals') }}> onClick={(e)=>{ e.stopPropagation(); nav('/goals') }}>
Verwalten → Ziele bearbeiten →
</button> </button>
} }
> >
<DashboardTile> <DashboardTile>
<div className="card section-gap" style={{ cursor: 'pointer' }} onClick={()=>nav('/goals')}> <div className="card section-gap" style={{ cursor: 'pointer' }} onClick={()=>nav('/goals')}>
<div style={{fontSize:12,color:'var(--text2)',padding:'8px 0'}}> {goalsCount != null && (
Definiere deine Trainingsmodus und konkrete Ziele für bessere KI-Analysen <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text1)', marginBottom: 8 }}>
{goalsCount === 0
? 'Noch keine Ziele angelegt.'
: `${goalsCount} ${goalsCount === 1 ? 'Ziel' : 'Ziele'} im System.`}
</div>
)}
<div style={{ fontSize: 12, color: 'var(--text2)', padding: goalsCount != null ? '0 0 8px' : '8px 0' }}>
Hier pflegst du Focus Areas, Meilensteine und Fortschritt – unabhängig von der KI-Analyse-Seite.
Tippen zum Öffnen oder unten in der Navigation <strong>Ziele</strong> wählen.
</div> </div>
</div> </div>
</DashboardTile> </DashboardTile>
+14 -1
View File
@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import { Save, Download, Upload, Check, LogOut, Key, BarChart3 } from 'lucide-react' import { Save, Download, Upload, Check, LogOut, Key, BarChart3, Target } from 'lucide-react'
import { Link } from 'react-router-dom' import { Link } from 'react-router-dom'
import { useProfile } from '../context/ProfileContext' import { useProfile } from '../context/ProfileContext'
import { useAuth } from '../context/AuthContext' import { useAuth } from '../context/AuthContext'
@@ -428,6 +428,19 @@ export default function SettingsPage() {
</button> </button>
</div> </div>
<div className="card section-gap">
<div className="card-title" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<Target size={15} color="var(--accent)" /> Strategische Ziele
</div>
<p style={{ fontSize: 13, color: 'var(--text2)', marginBottom: 12, lineHeight: 1.6 }}>
Konkrete Ziele, Focus Areas und Fortschritt – eigener Bereich{' '}
<strong>Ziele</strong> in der Navigation (nicht in der KI-Analyse).
</p>
<Link to="/goals" className="btn btn-secondary btn-full" style={{ textAlign: 'center', textDecoration: 'none', boxSizing: 'border-box' }}>
Zu den Zielen
</Link>
</div>
{/* Auth actions */} {/* Auth actions */}
<div className="card section-gap"> <div className="card section-gap">
<div className="card-title">🔐 Konto</div> <div className="card-title">🔐 Konto</div>
+3
View File
@@ -375,6 +375,9 @@ export const api = {
getUserFocusPreferences: () => req('/focus-areas/user-preferences'), getUserFocusPreferences: () => req('/focus-areas/user-preferences'),
updateUserFocusPreferences: (d) => req('/focus-areas/user-preferences', jput(d)), updateUserFocusPreferences: (d) => req('/focus-areas/user-preferences', jput(d)),
getFocusAreaStats: () => req('/focus-areas/stats'), getFocusAreaStats: () => req('/focus-areas/stats'),
listFocusAreaUsageTypes: () => req('/focus-areas/usage-types'),
setFocusAreaUsageTypes: (id, usageTypeKeys) =>
req(`/focus-areas/definitions/${id}/usage-types`, jput({ usage_type_keys: usageTypeKeys })),
// Chart Endpoints (Phase 0c - Phase 1: Nutrition + Recovery) // Chart Endpoints (Phase 0c - Phase 1: Nutrition + Recovery)
// Nutrition Charts (E1-E5) // Nutrition Charts (E1-E5)
+1
View File
@@ -34,6 +34,7 @@ python scripts/gitea/gitea_api.py issues create --title "Fix: …" --body-file p
# Kommentar # Kommentar
python scripts/gitea/gitea_api.py issues comment 42 --body "…" python scripts/gitea/gitea_api.py issues comment 42 --body "…"
python scripts/gitea/gitea_api.py issues comment 42 --body-file path/to/comment.md
# Schließen / wieder öffnen # Schließen / wieder öffnen
python scripts/gitea/gitea_api.py issues close 42 python scripts/gitea/gitea_api.py issues close 42
+9 -2
View File
@@ -71,8 +71,14 @@ def cmd_issues_create(args: argparse.Namespace, base: str, token: str, owner: st
def cmd_issues_comment(args: argparse.Namespace, base: str, token: str, owner: str, repo: str) -> None: def cmd_issues_comment(args: argparse.Namespace, base: str, token: str, owner: str, repo: str) -> None:
body = args.body or ""
if getattr(args, "body_file", None):
body = Path(args.body_file).read_text(encoding="utf-8")
if not body.strip():
sys.stderr.write("issues comment: --body oder --body-file mit Inhalt erforderlich\n")
sys.exit(2)
status, payload = issues_comment( status, payload = issues_comment(
base, token, owner, repo, args.number, args.body base, token, owner, repo, args.number, body
) )
print(json.dumps(payload, indent=2, ensure_ascii=False)) print(json.dumps(payload, indent=2, ensure_ascii=False))
if status >= 400: if status >= 400:
@@ -149,7 +155,8 @@ def main() -> None:
p_co = i_sub.add_parser("comment", help="Add comment") p_co = i_sub.add_parser("comment", help="Add comment")
p_co.add_argument("number", type=int) p_co.add_argument("number", type=int)
p_co.add_argument("--body", required=True) p_co.add_argument("--body", default="")
p_co.add_argument("--body-file", help="Kommentar aus Datei (UTF-8); überschreibt --body wenn gesetzt")
p_co.set_defaults(_handler=cmd_issues_comment) p_co.set_defaults(_handler=cmd_issues_comment)
p_cl = i_sub.add_parser("close", help="Close issue") p_cl = i_sub.add_parser("close", help="Close issue")