feat: enhance exercise management features and UI
Deploy Development / deploy (push) Successful in 40s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 27s
Deploy Development / deploy (push) Successful in 40s
Test Suite / pytest-backend (push) Successful in 6s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 6s
Test Suite / playwright-tests (push) Failing after 27s
- Introduced new function `club_admin_shares_club_with_creator` to check club admin permissions for shared clubs. - Updated `can_manage_club_org` to incorporate new role checks. - Enhanced exercise deletion logic to include checks for club admin roles and shared club memberships. - Added new filters for exercise visibility and status in the ExercisesListPage, allowing users to exclude specific criteria. - Implemented functionality to save user-specific exercise list preferences, improving user experience. - Updated API interactions to support new filtering options and preferences for exercise management.
This commit is contained in:
1 parent
8eec145393
commit
585ee8c90d
13 files changed
+619
-59
No files matched your search
+154
-22
@@ -17,6 +17,8 @@ from pydantic import BaseModel, Field, model_validator
|
||||
from db import get_db, get_cursor, r2d
|
||||
from club_tenancy import (
|
||||
assert_valid_governance_visibility,
|
||||
club_admin_shares_club_with_creator,
|
||||
has_club_role,
|
||||
is_platform_admin,
|
||||
library_content_visible_to_profile,
|
||||
)
|
||||
@@ -232,6 +234,8 @@ class ExerciseVariantsReorder(BaseModel):
|
||||
|
||||
|
||||
_VALID_EXERCISE_STATUS_BULK = frozenset({"draft", "in_review", "approved", "archived"})
|
||||
_LIST_FILTER_VISIBILITY = frozenset({"private", "club", "official"})
|
||||
_LIST_FILTER_STATUS = frozenset({"draft", "in_review", "approved", "archived"})
|
||||
_MAX_BULK_METADATA_IDS = 500
|
||||
_MAX_BULK_RELATION_IDS_PER_KIND = 80
|
||||
|
||||
@@ -657,6 +661,96 @@ def _merge_str_any(multi: list[str], single: Optional[str]) -> list[str]:
|
||||
return out
|
||||
|
||||
|
||||
def _normalize_choice_list(raw: list[str], allowed: frozenset, label: str) -> list[str]:
|
||||
out = []
|
||||
seen = set()
|
||||
for x in raw or []:
|
||||
s = str(x).strip().lower()
|
||||
if not s or s in seen:
|
||||
continue
|
||||
if s not in allowed:
|
||||
raise HTTPException(status_code=400, detail=f"Ungültiger Wert in {label}")
|
||||
seen.add(s)
|
||||
out.append(s)
|
||||
return out
|
||||
|
||||
|
||||
def _exercise_delete_usage_counts(cur, exercise_id: int) -> dict:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
(SELECT COUNT(*)::int FROM exercise_block_items WHERE exercise_id = %s) AS block_items,
|
||||
(SELECT COUNT(*)::int FROM training_unit_section_items WHERE exercise_id = %s) AS section_items,
|
||||
(SELECT COUNT(*)::int FROM exercise_progression_edges
|
||||
WHERE from_exercise_id = %s OR to_exercise_id = %s) AS prog_edges
|
||||
""",
|
||||
(exercise_id, exercise_id, exercise_id, exercise_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return dict(row) if row else {"block_items": 0, "section_items": 0, "prog_edges": 0}
|
||||
|
||||
|
||||
def _exercise_delete_usage_message(counts: dict) -> str:
|
||||
bi = int(counts.get("block_items") or 0)
|
||||
si = int(counts.get("section_items") or 0)
|
||||
pe = int(counts.get("prog_edges") or 0)
|
||||
parts = []
|
||||
if bi:
|
||||
parts.append(f"{bi}× in Übungsblöcken")
|
||||
if si:
|
||||
parts.append(f"{si}× in Trainingsplänen oder Rahmenabläufen")
|
||||
if pe:
|
||||
parts.append(f"{pe}× in Progressionsgraphen (Kanten)")
|
||||
if not parts:
|
||||
return ""
|
||||
return (
|
||||
"Die Übung wird noch verwendet und kann nicht gelöscht werden. Bitte auf „archiviert“ setzen. "
|
||||
"Verwendung: " + ", ".join(parts) + "."
|
||||
)
|
||||
|
||||
|
||||
def _assert_can_delete_exercise(cur, tenant: TenantContext, row: dict) -> None:
|
||||
pid = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
vis = str(row.get("visibility") or "private").strip().lower()
|
||||
cid = row.get("club_id")
|
||||
creator = row.get("created_by")
|
||||
try:
|
||||
creator_int = int(creator) if creator is not None else None
|
||||
except (TypeError, ValueError):
|
||||
creator_int = None
|
||||
|
||||
if vis == "official":
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Globale Übungen dürfen nur von Plattform-Admins gelöscht werden.",
|
||||
)
|
||||
if vis == "club":
|
||||
try:
|
||||
ex_club = int(cid) if cid is not None else None
|
||||
except (TypeError, ValueError):
|
||||
ex_club = None
|
||||
if ex_club is None:
|
||||
raise HTTPException(status_code=400, detail="Vereins-Übung ohne gültige Vereinszuordnung")
|
||||
if not has_club_role(cur, pid, ex_club, "club_admin"):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Nur Vereins-Admins dürfen Vereins-Übungen löschen.",
|
||||
)
|
||||
return
|
||||
|
||||
if creator_int is not None and creator_int == pid:
|
||||
return
|
||||
if creator_int is not None and club_admin_shares_club_with_creator(cur, pid, creator_int):
|
||||
return
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Keine Berechtigung zum Löschen dieser Übung.",
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/exercises/bulk-metadata")
|
||||
def bulk_patch_exercises_metadata(
|
||||
body: ExerciseBulkMetadataPatch,
|
||||
@@ -850,6 +944,20 @@ def list_exercises(
|
||||
default=False,
|
||||
description="Wenn true: Feld variants[] pro Übung (id, variant_name, sequence_order) für Planung/UI",
|
||||
),
|
||||
visibility_exclude_any: list[str] = Query(
|
||||
default=[], description="Keine dieser Sichtbarkeiten (Negativliste)"
|
||||
),
|
||||
status_exclude_any: list[str] = Query(
|
||||
default=[], description="Keiner dieser Statuswerte (Negativliste)"
|
||||
),
|
||||
exclude_without_focus: bool = Query(
|
||||
default=False,
|
||||
description="Wenn true: nur Übungen mit mindestens einem Fokusbereich",
|
||||
),
|
||||
include_archived: bool = Query(
|
||||
default=False,
|
||||
description="Archivierte einbeziehen; Standard false (außer Statusfilter enthält archived)",
|
||||
),
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
"""
|
||||
@@ -889,6 +997,36 @@ def list_exercises(
|
||||
where.append(f"e.status IN ({ph})")
|
||||
params.extend(st_list)
|
||||
|
||||
includes_archived = any(str(x).strip().lower() == "archived" for x in st_list)
|
||||
if not include_archived and not includes_archived:
|
||||
where.append("COALESCE(e.status, '') <> %s")
|
||||
params.append("archived")
|
||||
|
||||
vis_excl = _normalize_choice_list(
|
||||
list(visibility_exclude_any),
|
||||
_LIST_FILTER_VISIBILITY,
|
||||
"visibility_exclude_any",
|
||||
)
|
||||
if vis_excl:
|
||||
ph = ",".join(["%s"] * len(vis_excl))
|
||||
where.append(f"(e.visibility IS NULL OR LOWER(TRIM(e.visibility::text)) NOT IN ({ph}))")
|
||||
params.extend(vis_excl)
|
||||
|
||||
st_excl = _normalize_choice_list(
|
||||
list(status_exclude_any),
|
||||
_LIST_FILTER_STATUS,
|
||||
"status_exclude_any",
|
||||
)
|
||||
if st_excl:
|
||||
ph = ",".join(["%s"] * len(st_excl))
|
||||
where.append(f"(e.status IS NULL OR LOWER(TRIM(e.status::text)) NOT IN ({ph}))")
|
||||
params.extend(st_excl)
|
||||
|
||||
if exclude_without_focus:
|
||||
where.append(
|
||||
"EXISTS (SELECT 1 FROM exercise_focus_areas efa WHERE efa.exercise_id = e.id)"
|
||||
)
|
||||
|
||||
fa_ids = _merge_ids(focus_area_ids, focus_area)
|
||||
if fa_ids:
|
||||
ph = ",".join(["%s"] * len(fa_ids))
|
||||
@@ -1241,38 +1379,32 @@ def delete_exercise(
|
||||
):
|
||||
"""
|
||||
Löscht eine Übung.
|
||||
Nur Owner oder Admin darf löschen.
|
||||
"""
|
||||
profile_id = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
|
||||
Berechtigung: Plattform-Admin (alle); Vereins-Admin Vereins-Übungen seines Vereins;
|
||||
Ersteller nur eigene private Übungen; Vereins-Admin zusätzlich private Übungen von Mitgliedern,
|
||||
mit denen er einen Verein teilt.
|
||||
|
||||
Bei Verwendung in Blöcken, Trainingsplänen oder Progressionsgraphen: 409 — bitte archivieren.
|
||||
"""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Existiert die Übung?
|
||||
cur.execute("SELECT created_by FROM exercises WHERE id = %s", (exercise_id,))
|
||||
cur.execute(
|
||||
"SELECT id, created_by, visibility, club_id FROM exercises WHERE id = %s",
|
||||
(exercise_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Übung nicht gefunden")
|
||||
ex = r2d(row)
|
||||
|
||||
# Permission Check
|
||||
if _row_created_by(row) != profile_id and not is_platform_admin(role):
|
||||
raise HTTPException(status_code=403, detail="Nur Ersteller oder Admin darf löschen")
|
||||
_assert_can_delete_exercise(cur, tenant, ex)
|
||||
|
||||
# Prüfen ob Übung in Block-Items verwendet wird
|
||||
cur.execute(
|
||||
"SELECT COUNT(*) AS cnt FROM exercise_block_items WHERE exercise_id = %s",
|
||||
(exercise_id,)
|
||||
)
|
||||
crow = cur.fetchone()
|
||||
count = crow["cnt"] if isinstance(crow, dict) else crow[0]
|
||||
if count > 0:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail=f"Übung wird in {count} Block-Item(s) verwendet und kann nicht gelöscht werden"
|
||||
)
|
||||
counts = _exercise_delete_usage_counts(cur, exercise_id)
|
||||
usage_msg = _exercise_delete_usage_message(counts)
|
||||
if usage_msg:
|
||||
raise HTTPException(status_code=409, detail=usage_msg)
|
||||
|
||||
# DELETE (Cascade löscht M:N Zuordnungen automatisch)
|
||||
cur.execute("DELETE FROM exercises WHERE id = %s", (exercise_id,))
|
||||
conn.commit()
|
||||
|
||||
|
||||
Reference in new issue
Block a user