shinkan-jinkendo/backend/routers/training_framework_programs.py
Lars b4495e39c1
Some checks failed
Deploy Development / deploy (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 44s
chore: update versioning and enhance Training Framework features
- Incremented APP_VERSION to 0.8.9 and DB_SCHEMA_VERSION to 20260505036.
- Added changelog entry for version 0.8.9 detailing database and API changes.
- Updated TrainingFrameworkProgramEditPage to manage focus areas, style directions, training types, and target groups.
- Enhanced TrainingFrameworkProgramsListPage with context teasers for better user information.
- Improved CSS styles for framework catalog checkgrid and check components for better layout and usability.
2026-05-05 13:11:17 +02:00

460 lines
16 KiB
Python

"""
Trainingsrahmenprogramm — wiederverwendbare Vorlage (Bibliothek) über mehrere Session-Slots.
Zuordnung zu Trainingsgruppen / konkreten Einheiten erfolgt aus der Planung (Kopie + Lineage),
nicht über group_id oder training_unit_id am Rahmen.
AuthZ wie Planungs-Vorlagen: Admin sieht alle, sonst nur eigene Artefakte; Schreibzugriff mit Planungsrolle.
"""
from typing import Any, Dict, List, Optional, Sequence
from fastapi import APIRouter, Depends, HTTPException
from auth import require_auth
from db import get_db, get_cursor, r2d
from routers.training_planning import (
_has_planning_role,
_optional_positive_int,
_validate_variant_for_exercise,
)
router = APIRouter(prefix="/api", tags=["training_framework_programs"])
_VALID_VISIBILITY = frozenset({"private", "club", "official"})
def _framework_access(cur, framework_id: int, profile_id: int, role: str) -> Dict[str, Any]:
cur.execute("SELECT * FROM training_framework_programs WHERE id = %s", (framework_id,))
r = cur.fetchone()
if not r:
raise HTTPException(status_code=404, detail="Trainingsrahmen nicht gefunden")
row = r2d(r)
if role in ("admin", "superadmin"):
return row
if row.get("created_by") != profile_id:
raise HTTPException(status_code=403, detail="Keine Berechtigung für diesen Trainingsrahmen")
return row
def _fetch_slot_exercises(cur, slot_id: int) -> List[Dict[str, Any]]:
cur.execute(
"""
SELECT t.id, t.slot_id, t.exercise_id, t.exercise_variant_id, t.order_index,
e.title AS exercise_title,
ev.variant_name AS exercise_variant_name
FROM training_framework_slot_exercises t
LEFT JOIN exercises e ON e.id = t.exercise_id
LEFT JOIN exercise_variants ev ON ev.id = t.exercise_variant_id
WHERE t.slot_id = %s
ORDER BY t.order_index
""",
(slot_id,),
)
return [r2d(x) for x in cur.fetchall()]
def _training_type_ids(cur, framework_id: int) -> List[int]:
cur.execute(
"""
SELECT training_type_id
FROM training_framework_program_training_types
WHERE framework_program_id = %s
ORDER BY training_type_id
""",
(framework_id,),
)
return [r["training_type_id"] for r in cur.fetchall()]
def _target_group_ids(cur, framework_id: int) -> List[int]:
cur.execute(
"""
SELECT target_group_id
FROM training_framework_program_target_groups
WHERE framework_program_id = %s
ORDER BY target_group_id
""",
(framework_id,),
)
return [r["target_group_id"] for r in cur.fetchall()]
def _hydrate_framework(cur, row: Dict[str, Any]) -> Dict[str, Any]:
fid = row["id"]
cur.execute(
"""
SELECT id, framework_program_id, sort_order, title, notes
FROM training_framework_goals
WHERE framework_program_id = %s
ORDER BY sort_order
""",
(fid,),
)
row["goals"] = [r2d(g) for g in cur.fetchall()]
cur.execute(
"""
SELECT id, framework_program_id, sort_order, title, notes
FROM training_framework_slots
WHERE framework_program_id = %s
ORDER BY sort_order
""",
(fid,),
)
slots = [r2d(s) for s in cur.fetchall()]
for s in slots:
s["exercises"] = _fetch_slot_exercises(cur, s["id"])
row["slots"] = slots
row["training_type_ids"] = _training_type_ids(cur, fid)
row["target_group_ids"] = _target_group_ids(cur, fid)
return row
def _assert_visibility(val: Optional[str]) -> Optional[str]:
if val is None:
return None
if val not in _VALID_VISIBILITY:
raise HTTPException(
status_code=400,
detail="visibility muss private, club oder official sein",
)
return val
def _parse_positive_int_ids(raw: Any, label: str) -> List[int]:
if raw is None:
return []
if not isinstance(raw, list):
raise HTTPException(status_code=400, detail=f"{label} muss eine Liste von IDs sein")
out: List[int] = []
for item in raw:
if item in (None, ""):
continue
try:
n = int(item)
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail=f"{label}: ungültige ID") from None
if n <= 0:
raise HTTPException(status_code=400, detail=f"{label}: ungültige ID")
if n not in out:
out.append(n)
return out
def _replace_training_types(cur, framework_id: int, ids: Sequence[int]) -> None:
cur.execute(
"DELETE FROM training_framework_program_training_types WHERE framework_program_id = %s",
(framework_id,),
)
for tid in ids:
cur.execute(
"""
INSERT INTO training_framework_program_training_types (framework_program_id, training_type_id)
VALUES (%s, %s)
ON CONFLICT DO NOTHING
""",
(framework_id, tid),
)
def _replace_target_groups(cur, framework_id: int, ids: Sequence[int]) -> None:
cur.execute(
"DELETE FROM training_framework_program_target_groups WHERE framework_program_id = %s",
(framework_id,),
)
for gid in ids:
cur.execute(
"""
INSERT INTO training_framework_program_target_groups (framework_program_id, target_group_id)
VALUES (%s, %s)
ON CONFLICT DO NOTHING
""",
(framework_id, gid),
)
def _insert_goal_rows(cur, framework_id: int, goals_in: List[Any]) -> None:
if not goals_in:
raise HTTPException(status_code=400, detail="Mindestens ein Entwicklungsziel (goals) ist erforderlich")
for gi, g in enumerate(goals_in):
title_g = (g.get("title") or "").strip()
if not title_g:
raise HTTPException(status_code=400, detail="Jedes Ziel braucht ein nicht-leeres title")
order_ix = g.get("sort_order")
if order_ix is None:
order_ix = gi
cur.execute(
"""
INSERT INTO training_framework_goals (
framework_program_id, sort_order, title, notes
) VALUES (%s, %s, %s, %s)
""",
(framework_id, int(order_ix), title_g[:500], g.get("notes")),
)
def _insert_slots_and_exercises(
cur,
framework_id: int,
slots_in: Optional[List[Any]],
) -> None:
if slots_in is None:
return
for si, slot in enumerate(slots_in):
order_ix = slot.get("sort_order")
if order_ix is None:
order_ix = si
title_s = slot.get("title")
if title_s is not None:
title_s = title_s.strip() or None
cur.execute(
"""
INSERT INTO training_framework_slots (
framework_program_id, sort_order, title, notes, training_unit_id
) VALUES (%s, %s, %s, %s, NULL)
RETURNING id
""",
(
framework_id,
int(order_ix),
title_s,
slot.get("notes"),
),
)
sid = cur.fetchone()["id"]
ex_items = slot.get("exercises") or []
for ej, raw in enumerate(ex_items):
eid = raw.get("exercise_id")
if not eid:
continue
eid = int(eid)
vid = _optional_positive_int(raw.get("exercise_variant_id"), "exercise_variant_id")
_validate_variant_for_exercise(cur, eid, vid)
oidx = raw.get("order_index")
if oidx is None:
oidx = ej
cur.execute(
"""
INSERT INTO training_framework_slot_exercises (
slot_id, exercise_id, exercise_variant_id, order_index
) VALUES (%s, %s, %s, %s)
""",
(sid, eid, vid, int(oidx)),
)
@router.get("/training-framework-programs")
def list_training_framework_programs(session=Depends(require_auth)):
profile_id = session["profile_id"]
role = session.get("role")
with get_db() as conn:
cur = get_cursor(conn)
base_sel = """
SELECT fp.*,
fa.name AS focus_area_name,
sd.name AS style_direction_name,
(SELECT COUNT(*)::int FROM training_framework_goals g WHERE g.framework_program_id = fp.id)
AS goals_count,
(SELECT COUNT(*)::int FROM training_framework_slots s WHERE s.framework_program_id = fp.id)
AS slots_count,
(SELECT COUNT(*)::int FROM training_framework_program_training_types t
WHERE t.framework_program_id = fp.id) AS training_types_count,
(SELECT COUNT(*)::int FROM training_framework_program_target_groups tg
WHERE tg.framework_program_id = fp.id) AS target_groups_count
FROM training_framework_programs fp
LEFT JOIN focus_areas fa ON fa.id = fp.focus_area_id
LEFT JOIN style_directions sd ON sd.id = fp.style_direction_id
"""
if role in ("admin", "superadmin"):
cur.execute(base_sel + " ORDER BY fp.updated_at DESC NULLS LAST, fp.title")
else:
cur.execute(
base_sel + " WHERE fp.created_by = %s ORDER BY fp.updated_at DESC NULLS LAST, fp.title",
(profile_id,),
)
return [r2d(r) for r in cur.fetchall()]
@router.get("/training-framework-programs/{framework_id}")
def get_training_framework_program(framework_id: int, session=Depends(require_auth)):
profile_id = session["profile_id"]
role = session.get("role")
with get_db() as conn:
cur = get_cursor(conn)
row = _framework_access(cur, framework_id, profile_id, role)
return _hydrate_framework(cur, row)
@router.post("/training-framework-programs")
def create_training_framework_program(data: dict, session=Depends(require_auth)):
profile_id = session["profile_id"]
role = session.get("role")
if not _has_planning_role(role):
raise HTTPException(status_code=403, detail="Nur Planungsberechtigte dürfen Rahmenprogramme anlegen")
title = (data.get("title") or "").strip()
if not title:
raise HTTPException(status_code=400, detail="title ist Pflicht")
vis = data.get("visibility") or "private"
vis = _assert_visibility(vis)
club_id = data.get("club_id")
goals_in = data.get("goals")
slots_in = data.get("slots")
if not isinstance(goals_in, list) or not goals_in:
raise HTTPException(status_code=400, detail="goals als Liste mit mindestens einem Eintrag ist Pflicht")
fa_id = _optional_positive_int(data.get("focus_area_id"), "focus_area_id")
sd_id = _optional_positive_int(data.get("style_direction_id"), "style_direction_id")
tt_ids = _parse_positive_int_ids(data.get("training_type_ids"), "training_type_ids")
tg_ids = _parse_positive_int_ids(data.get("target_group_ids"), "target_group_ids")
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
INSERT INTO training_framework_programs (
title, description,
planned_period_start, planned_period_end,
visibility, club_id, created_by,
focus_area_id, style_direction_id
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
""",
(
title[:200],
data.get("description"),
data.get("planned_period_start"),
data.get("planned_period_end"),
vis,
club_id,
profile_id,
fa_id,
sd_id,
),
)
fid = cur.fetchone()["id"]
_insert_goal_rows(cur, fid, goals_in)
_insert_slots_and_exercises(cur, fid, slots_in)
_replace_training_types(cur, fid, tt_ids)
_replace_target_groups(cur, fid, tg_ids)
conn.commit()
return get_training_framework_program(fid, session)
@router.put("/training-framework-programs/{framework_id}")
def update_training_framework_program(framework_id: int, data: dict, session=Depends(require_auth)):
profile_id = session["profile_id"]
role = session.get("role")
if not _has_planning_role(role):
raise HTTPException(status_code=403, detail="Keine Berechtigung")
with get_db() as conn:
cur = get_cursor(conn)
_framework_access(cur, framework_id, profile_id, role)
header_fields = []
header_params: List[Any] = []
if "title" in data:
tit = (data.get("title") or "").strip()
if not tit:
raise HTTPException(status_code=400, detail="title ist Pflicht")
header_fields.append("title = %s")
header_params.append(tit[:200])
if "description" in data:
header_fields.append("description = %s")
header_params.append(data.get("description"))
if "planned_period_start" in data:
header_fields.append("planned_period_start = %s")
header_params.append(data.get("planned_period_start"))
if "planned_period_end" in data:
header_fields.append("planned_period_end = %s")
header_params.append(data.get("planned_period_end"))
if "visibility" in data:
v = _assert_visibility(data.get("visibility"))
if v is None:
raise HTTPException(status_code=400, detail="visibility fehlt")
header_fields.append("visibility = %s")
header_params.append(v)
if "club_id" in data:
header_fields.append("club_id = %s")
header_params.append(data.get("club_id"))
if "focus_area_id" in data:
fidv = data.get("focus_area_id")
header_fields.append("focus_area_id = %s")
header_params.append(
None if fidv in (None, "") else _optional_positive_int(fidv, "focus_area_id")
)
if "style_direction_id" in data:
sidv = data.get("style_direction_id")
header_fields.append("style_direction_id = %s")
header_params.append(
None if sidv in (None, "") else _optional_positive_int(sidv, "style_direction_id")
)
if header_fields:
header_fields.append("updated_at = NOW()")
header_params.append(framework_id)
cur.execute(
f"""
UPDATE training_framework_programs
SET {", ".join(header_fields)}
WHERE id = %s
""",
tuple(header_params),
)
if "training_type_ids" in data:
tt_ids = _parse_positive_int_ids(data.get("training_type_ids"), "training_type_ids")
_replace_training_types(cur, framework_id, tt_ids)
if "target_group_ids" in data:
tg_ids = _parse_positive_int_ids(data.get("target_group_ids"), "target_group_ids")
_replace_target_groups(cur, framework_id, tg_ids)
if "goals" in data:
goals_in = data["goals"]
if not isinstance(goals_in, list) or not goals_in:
raise HTTPException(status_code=400, detail="goals als Liste mit mindestens einem Eintrag ist Pflicht")
cur.execute(
"DELETE FROM training_framework_goals WHERE framework_program_id = %s",
(framework_id,),
)
_insert_goal_rows(cur, framework_id, goals_in)
if "slots" in data:
cur.execute(
"DELETE FROM training_framework_slots WHERE framework_program_id = %s",
(framework_id,),
)
_insert_slots_and_exercises(cur, framework_id, data.get("slots") or [])
if header_fields or "goals" in data or "slots" in data or "training_type_ids" in data or "target_group_ids" in data:
cur.execute(
"UPDATE training_framework_programs SET updated_at = NOW() WHERE id = %s",
(framework_id,),
)
conn.commit()
return get_training_framework_program(framework_id, session)
@router.delete("/training-framework-programs/{framework_id}")
def delete_training_framework_program(framework_id: int, session=Depends(require_auth)):
profile_id = session["profile_id"]
role = session.get("role")
with get_db() as conn:
cur = get_cursor(conn)
_framework_access(cur, framework_id, profile_id, role)
cur.execute(
"DELETE FROM training_framework_programs WHERE id = %s",
(framework_id,),
)
conn.commit()
return {"ok": True}