Phase 0a Mandantenfähigkeit
This commit is contained in:
1 parent
0748990328
commit
0c044249d9
15 files changed
+982
-193
No files matched your search
+303
-158
@@ -3,11 +3,18 @@ Club & Organization Management Endpoints for Shinkan Jinkendo
|
||||
|
||||
Handles CRUD operations for clubs, divisions, and training groups.
|
||||
"""
|
||||
from typing import Optional
|
||||
from typing import Any, List, Optional
|
||||
from fastapi import APIRouter, HTTPException, Depends, Query
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth
|
||||
from club_tenancy import (
|
||||
assert_club_member,
|
||||
can_manage_club_org,
|
||||
can_plan_in_club,
|
||||
club_ids_for_profile,
|
||||
is_platform_admin,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["clubs"])
|
||||
|
||||
@@ -16,24 +23,33 @@ router = APIRouter(prefix="/api", tags=["clubs"])
|
||||
@router.get("/clubs")
|
||||
def list_clubs(
|
||||
status: Optional[str] = Query(default=None),
|
||||
session=Depends(require_auth)
|
||||
session=Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
List all clubs (public for authenticated users).
|
||||
|
||||
Filters:
|
||||
- status: active, inactive
|
||||
Vereine: für normale Nutzer nur Mitgliedschaft-Vereine; Plattform-Admins sehen alle.
|
||||
"""
|
||||
role = session.get("role")
|
||||
profile_id = session["profile_id"]
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
query = "SELECT * FROM clubs"
|
||||
params = []
|
||||
params: List[Any] = []
|
||||
conds = []
|
||||
|
||||
if not is_platform_admin(role):
|
||||
cids = club_ids_for_profile(cur, profile_id)
|
||||
if not cids:
|
||||
return []
|
||||
conds.append("id IN (" + ",".join(["%s"] * len(cids)) + ")")
|
||||
params.extend(sorted(cids))
|
||||
|
||||
if status:
|
||||
query += " WHERE status = %s"
|
||||
conds.append("status = %s")
|
||||
params.append(status)
|
||||
|
||||
if conds:
|
||||
query += " WHERE " + " AND ".join(conds)
|
||||
|
||||
query += " ORDER BY name"
|
||||
|
||||
cur.execute(query, params)
|
||||
@@ -44,9 +60,13 @@ def list_clubs(
|
||||
# ── Get Club ──────────────────────────────────────────────────────────
|
||||
@router.get("/clubs/{club_id}")
|
||||
def get_club(club_id: int, session=Depends(require_auth)):
|
||||
"""Get club by ID with divisions and groups."""
|
||||
"""Get club by ID with divisions and groups – nur Mitglied oder Plattform-Admin."""
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if not is_platform_admin(role):
|
||||
assert_club_member(cur, profile_id, club_id)
|
||||
|
||||
# Get club
|
||||
cur.execute("SELECT * FROM clubs WHERE id = %s", (club_id,))
|
||||
@@ -58,23 +78,29 @@ def get_club(club_id: int, session=Depends(require_auth)):
|
||||
club = r2d(club)
|
||||
|
||||
# Get divisions
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT * FROM divisions
|
||||
WHERE club_id = %s
|
||||
ORDER BY name
|
||||
""", (club_id,))
|
||||
club['divisions'] = [r2d(r) for r in cur.fetchall()]
|
||||
""",
|
||||
(club_id,),
|
||||
)
|
||||
club["divisions"] = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
# Get training groups
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT g.*,
|
||||
p.name as trainer_name
|
||||
FROM training_groups g
|
||||
LEFT JOIN profiles p ON g.trainer_id = p.id
|
||||
WHERE g.club_id = %s
|
||||
ORDER BY g.weekday, g.time_start
|
||||
""", (club_id,))
|
||||
club['training_groups'] = [r2d(r) for r in cur.fetchall()]
|
||||
""",
|
||||
(club_id,),
|
||||
)
|
||||
club["training_groups"] = [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
return club
|
||||
|
||||
@@ -82,30 +108,67 @@ def get_club(club_id: int, session=Depends(require_auth)):
|
||||
# ── Create Club ───────────────────────────────────────────────────────
|
||||
@router.post("/clubs")
|
||||
def create_club(data: dict, session=Depends(require_auth)):
|
||||
"""Create new club (Admin oder Trainer — MVP ohne separates Vereins-Onboarding)."""
|
||||
role = session.get('role')
|
||||
if role not in ['admin', 'superadmin', 'trainer', 'user']:
|
||||
raise HTTPException(403, "Keine Berechtigung, Vereine anzulegen")
|
||||
"""Neuen Verein anlegen – nur Plattform-Admin; Pflicht: primary_admin_profile_id (Hauptverwalter:in)."""
|
||||
role = session.get("role")
|
||||
if not is_platform_admin(role):
|
||||
raise HTTPException(403, "Nur Plattform-Administratoren dürfen neue Vereine anlegen")
|
||||
|
||||
name = data.get('name')
|
||||
name = data.get("name")
|
||||
primary_admin_profile_id = data.get("primary_admin_profile_id")
|
||||
if not name:
|
||||
raise HTTPException(400, "Name ist Pflichtfeld")
|
||||
if not primary_admin_profile_id:
|
||||
raise HTTPException(400, "primary_admin_profile_id ist Pflichtfeld (Hauptverwalter:in)")
|
||||
|
||||
try:
|
||||
aid = int(primary_admin_profile_id)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(400, "primary_admin_profile_id ungültig")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT id FROM profiles WHERE id = %s", (aid,))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Profil für Hauptverwalter nicht gefunden")
|
||||
|
||||
cur.execute("""
|
||||
INSERT INTO clubs (name, abbreviation, description, status)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO clubs (name, abbreviation, description, status, primary_admin_profile_id)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""", (
|
||||
name,
|
||||
data.get('abbreviation'),
|
||||
data.get('description'),
|
||||
data.get('status', 'active')
|
||||
))
|
||||
""",
|
||||
(
|
||||
name,
|
||||
data.get("abbreviation"),
|
||||
data.get("description"),
|
||||
data.get("status", "active"),
|
||||
aid,
|
||||
),
|
||||
)
|
||||
|
||||
club_id = cur.fetchone()["id"]
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO club_members (profile_id, club_id, status)
|
||||
VALUES (%s, %s, 'active')
|
||||
ON CONFLICT (profile_id, club_id)
|
||||
DO UPDATE SET status = 'active', updated_at = NOW()
|
||||
RETURNING id
|
||||
""",
|
||||
(aid, club_id),
|
||||
)
|
||||
cm_id = cur.fetchone()["id"]
|
||||
for rc in ("club_admin", "trainer"):
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO club_member_roles (club_member_id, role_code)
|
||||
VALUES (%s, %s)
|
||||
ON CONFLICT (club_member_id, role_code) DO NOTHING
|
||||
""",
|
||||
(cm_id, rc),
|
||||
)
|
||||
|
||||
club_id = cur.fetchone()['id']
|
||||
conn.commit()
|
||||
|
||||
return get_club(club_id, session)
|
||||
@@ -114,10 +177,9 @@ def create_club(data: dict, session=Depends(require_auth)):
|
||||
# ── Update Club ───────────────────────────────────────────────────────
|
||||
@router.put("/clubs/{club_id}")
|
||||
def update_club(club_id: int, data: dict, session=Depends(require_auth)):
|
||||
"""Update club (admin only)."""
|
||||
role = session.get('role')
|
||||
if role not in ['admin', 'superadmin']:
|
||||
raise HTTPException(403, "Nur Admins dürfen Vereine bearbeiten")
|
||||
"""Verein bearbeiten – Plattform-Admin oder Vereinsadmin."""
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
@@ -127,22 +189,35 @@ def update_club(club_id: int, data: dict, session=Depends(require_auth)):
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Verein nicht gefunden")
|
||||
|
||||
if not can_manage_club_org(cur, profile_id, club_id, role):
|
||||
raise HTTPException(403, "Keine Berechtigung für diesen Verein")
|
||||
|
||||
# Nur Plattform-Admin darf primary_admin_profile_id ändern
|
||||
if "primary_admin_profile_id" in data and data["primary_admin_profile_id"] is not None:
|
||||
if not is_platform_admin(role):
|
||||
raise HTTPException(403, "Nur Plattform-Admins dürfen den Hauptverwalter ändern")
|
||||
|
||||
# Update
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE clubs SET
|
||||
name = %s,
|
||||
abbreviation = %s,
|
||||
description = %s,
|
||||
status = %s,
|
||||
name = COALESCE(%s, name),
|
||||
abbreviation = COALESCE(%s, abbreviation),
|
||||
description = COALESCE(%s, description),
|
||||
status = COALESCE(%s, status),
|
||||
primary_admin_profile_id = COALESCE(%s, primary_admin_profile_id),
|
||||
updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""", (
|
||||
data.get('name'),
|
||||
data.get('abbreviation'),
|
||||
data.get('description'),
|
||||
data.get('status'),
|
||||
club_id
|
||||
))
|
||||
""",
|
||||
(
|
||||
data.get("name"),
|
||||
data.get("abbreviation"),
|
||||
data.get("description"),
|
||||
data.get("status"),
|
||||
data.get("primary_admin_profile_id"),
|
||||
club_id,
|
||||
),
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
|
||||
@@ -176,22 +251,41 @@ def delete_club(club_id: int, session=Depends(require_auth)):
|
||||
@router.get("/divisions")
|
||||
def list_divisions(
|
||||
club_id: Optional[int] = Query(default=None),
|
||||
session=Depends(require_auth)
|
||||
session=Depends(require_auth),
|
||||
):
|
||||
"""List divisions (optional filter by club)."""
|
||||
"""Sparten – ohne Admin-Rechte nur in eigenen Vereinen sichtbar."""
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
mine = club_ids_for_profile(cur, profile_id)
|
||||
if not is_platform_admin(role) and not mine:
|
||||
return []
|
||||
|
||||
query = """
|
||||
SELECT d.*, c.name as club_name
|
||||
FROM divisions d
|
||||
LEFT JOIN clubs c ON d.club_id = c.id
|
||||
"""
|
||||
where = []
|
||||
params = []
|
||||
|
||||
if club_id:
|
||||
query += " WHERE d.club_id = %s"
|
||||
if club_id is not None:
|
||||
where.append("d.club_id = %s")
|
||||
params.append(club_id)
|
||||
if not is_platform_admin(role) and club_id not in mine:
|
||||
return []
|
||||
|
||||
if not is_platform_admin(role):
|
||||
where.append(
|
||||
"d.club_id IN (" + ",".join(["%s"] * len(mine)) + ")"
|
||||
)
|
||||
params.extend(sorted(mine))
|
||||
|
||||
if where:
|
||||
query += " WHERE " + " AND ".join(where)
|
||||
|
||||
query += " ORDER BY d.name"
|
||||
|
||||
@@ -203,13 +297,12 @@ def list_divisions(
|
||||
# ── Create Division ───────────────────────────────────────────────────
|
||||
@router.post("/divisions")
|
||||
def create_division(data: dict, session=Depends(require_auth)):
|
||||
"""Create new division (admin only)."""
|
||||
role = session.get('role')
|
||||
if role not in ['admin', 'superadmin']:
|
||||
raise HTTPException(403, "Nur Admins dürfen Sparten erstellen")
|
||||
"""Create new division – Vereinsadmin / Plattform-Admin."""
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
|
||||
club_id = data.get('club_id')
|
||||
name = data.get('name')
|
||||
club_id = data.get("club_id")
|
||||
name = data.get("name")
|
||||
|
||||
if not club_id or not name:
|
||||
raise HTTPException(400, "club_id und name sind Pflichtfelder")
|
||||
@@ -217,93 +310,109 @@ def create_division(data: dict, session=Depends(require_auth)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
if not can_manage_club_org(cur, profile_id, int(club_id), role):
|
||||
raise HTTPException(403, "Keine Berechtigung, Sparten in diesem Verein anzulegen")
|
||||
|
||||
# Check club exists
|
||||
cur.execute("SELECT id FROM clubs WHERE id = %s", (club_id,))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Verein nicht gefunden")
|
||||
|
||||
# Insert
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO divisions (club_id, name, focus_area)
|
||||
VALUES (%s, %s, %s)
|
||||
RETURNING id
|
||||
""", (
|
||||
club_id,
|
||||
name,
|
||||
data.get('focus_area')
|
||||
))
|
||||
""",
|
||||
(
|
||||
club_id,
|
||||
name,
|
||||
data.get("focus_area"),
|
||||
),
|
||||
)
|
||||
|
||||
division_id = cur.fetchone()['id']
|
||||
division_id = cur.fetchone()["id"]
|
||||
conn.commit()
|
||||
|
||||
# Return created division
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT d.*, c.name as club_name
|
||||
FROM divisions d
|
||||
LEFT JOIN clubs c ON d.club_id = c.id
|
||||
WHERE d.id = %s
|
||||
""", (division_id,))
|
||||
""",
|
||||
(division_id,),
|
||||
)
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
# ── Update Division ───────────────────────────────────────────────────
|
||||
@router.put("/divisions/{division_id}")
|
||||
def update_division(division_id: int, data: dict, session=Depends(require_auth)):
|
||||
"""Update division (admin only)."""
|
||||
role = session.get('role')
|
||||
if role not in ['admin', 'superadmin']:
|
||||
raise HTTPException(403, "Nur Admins dürfen Sparten bearbeiten")
|
||||
"""Update division – Vereinsadmin / Plattform-Admin."""
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check existence
|
||||
cur.execute("SELECT id FROM divisions WHERE id = %s", (division_id,))
|
||||
if not cur.fetchone():
|
||||
cur.execute("SELECT id, club_id FROM divisions WHERE id = %s", (division_id,))
|
||||
div = cur.fetchone()
|
||||
if not div:
|
||||
raise HTTPException(404, "Sparte nicht gefunden")
|
||||
|
||||
# Update
|
||||
cur.execute("""
|
||||
if not can_manage_club_org(cur, profile_id, div["club_id"], role):
|
||||
raise HTTPException(403, "Keine Berechtigung")
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE divisions SET
|
||||
name = %s,
|
||||
focus_area = %s,
|
||||
updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""", (
|
||||
data.get('name'),
|
||||
data.get('focus_area'),
|
||||
division_id
|
||||
))
|
||||
""",
|
||||
(
|
||||
data.get("name"),
|
||||
data.get("focus_area"),
|
||||
division_id,
|
||||
),
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
|
||||
# Return updated division
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT d.*, c.name as club_name
|
||||
FROM divisions d
|
||||
LEFT JOIN clubs c ON d.club_id = c.id
|
||||
WHERE d.id = %s
|
||||
""", (division_id,))
|
||||
""",
|
||||
(division_id,),
|
||||
)
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
# ── Delete Division ───────────────────────────────────────────────────
|
||||
@router.delete("/divisions/{division_id}")
|
||||
def delete_division(division_id: int, session=Depends(require_auth)):
|
||||
"""Delete division (admin only)."""
|
||||
role = session.get('role')
|
||||
if role not in ['admin', 'superadmin']:
|
||||
raise HTTPException(403, "Nur Admins dürfen Sparten löschen")
|
||||
"""Delete division – Vereinsadmin / Plattform-Admin."""
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check existence
|
||||
cur.execute("SELECT id FROM divisions WHERE id = %s", (division_id,))
|
||||
if not cur.fetchone():
|
||||
cur.execute("SELECT id, club_id FROM divisions WHERE id = %s", (division_id,))
|
||||
div = cur.fetchone()
|
||||
if not div:
|
||||
raise HTTPException(404, "Sparte nicht gefunden")
|
||||
|
||||
# Delete
|
||||
if not can_manage_club_org(cur, profile_id, div["club_id"], role):
|
||||
raise HTTPException(403, "Keine Berechtigung")
|
||||
|
||||
cur.execute("DELETE FROM divisions WHERE id = %s", (division_id,))
|
||||
conn.commit()
|
||||
|
||||
@@ -316,19 +425,21 @@ def list_training_groups(
|
||||
club_id: Optional[int] = Query(default=None),
|
||||
division_id: Optional[int] = Query(default=None),
|
||||
status: Optional[str] = Query(default=None),
|
||||
session=Depends(require_auth)
|
||||
session=Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
List training groups with optional filters.
|
||||
|
||||
Filters:
|
||||
- club_id: Filter by club
|
||||
- division_id: Filter by division
|
||||
- status: active, inactive
|
||||
Trainingsgruppen – ohne Plattform-Admin nur in eigenen Vereinen.
|
||||
"""
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
mine = club_ids_for_profile(cur, profile_id)
|
||||
if not is_platform_admin(role) and not mine:
|
||||
return []
|
||||
|
||||
query = """
|
||||
SELECT g.*,
|
||||
c.name as club_name,
|
||||
@@ -343,11 +454,13 @@ def list_training_groups(
|
||||
where = []
|
||||
params = []
|
||||
|
||||
if club_id:
|
||||
if club_id is not None:
|
||||
where.append("g.club_id = %s")
|
||||
params.append(club_id)
|
||||
if not is_platform_admin(role) and club_id not in mine:
|
||||
return []
|
||||
|
||||
if division_id:
|
||||
if division_id is not None:
|
||||
where.append("g.division_id = %s")
|
||||
params.append(division_id)
|
||||
|
||||
@@ -355,6 +468,10 @@ def list_training_groups(
|
||||
where.append("g.status = %s")
|
||||
params.append(status)
|
||||
|
||||
if not is_platform_admin(role):
|
||||
where.append("g.club_id IN (" + ",".join(["%s"] * len(mine)) + ")")
|
||||
params.extend(sorted(mine))
|
||||
|
||||
if where:
|
||||
query += " WHERE " + " AND ".join(where)
|
||||
|
||||
@@ -368,11 +485,14 @@ def list_training_groups(
|
||||
# ── Get Training Group ────────────────────────────────────────────────
|
||||
@router.get("/groups/{group_id}")
|
||||
def get_training_group(group_id: int, session=Depends(require_auth)):
|
||||
"""Get training group by ID."""
|
||||
"""Trainingsgruppe – nur mit Vereinszugriff."""
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT g.*,
|
||||
c.name as club_name,
|
||||
d.name as division_name,
|
||||
@@ -382,45 +502,55 @@ def get_training_group(group_id: int, session=Depends(require_auth)):
|
||||
LEFT JOIN divisions d ON g.division_id = d.id
|
||||
LEFT JOIN profiles p ON g.trainer_id = p.id
|
||||
WHERE g.id = %s
|
||||
""", (group_id,))
|
||||
""",
|
||||
(group_id,),
|
||||
)
|
||||
|
||||
group = cur.fetchone()
|
||||
|
||||
if not group:
|
||||
raise HTTPException(404, "Trainingsgruppe nicht gefunden")
|
||||
|
||||
cid = group["club_id"]
|
||||
if not is_platform_admin(role):
|
||||
assert_club_member(cur, profile_id, cid)
|
||||
|
||||
return r2d(group)
|
||||
|
||||
|
||||
# ── Create Training Group ─────────────────────────────────────────────
|
||||
@router.post("/groups")
|
||||
def create_training_group(data: dict, session=Depends(require_auth)):
|
||||
"""Create new training group (admin, trainer oder normaler Nutzer mit Vereinsbezug)."""
|
||||
"""Trainingsgruppe anlegen – Mitglied mit Planungs-/Admin-Rolle im Verein."""
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get('role')
|
||||
if role not in ['admin', 'superadmin', 'trainer', 'user']:
|
||||
role = session.get("role")
|
||||
if role not in ["admin", "superadmin", "trainer", "user"]:
|
||||
raise HTTPException(403, "Keine Berechtigung, Trainingsgruppen anzulegen")
|
||||
|
||||
club_id = data.get('club_id')
|
||||
name = data.get('name')
|
||||
club_id = data.get("club_id")
|
||||
name = data.get("name")
|
||||
|
||||
if not club_id or not name:
|
||||
raise HTTPException(400, "club_id und name sind Pflichtfelder")
|
||||
|
||||
trainer_id = data.get('trainer_id')
|
||||
trainer_id = data.get("trainer_id")
|
||||
if trainer_id in (None, "", 0) and role in ("trainer", "user"):
|
||||
trainer_id = profile_id
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
if not can_plan_in_club(cur, profile_id, int(club_id), role):
|
||||
raise HTTPException(403, "Keine Berechtigung für diesen Verein")
|
||||
|
||||
# Check club exists
|
||||
cur.execute("SELECT id FROM clubs WHERE id = %s", (club_id,))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Verein nicht gefunden")
|
||||
|
||||
# Insert
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO training_groups (
|
||||
club_id, division_id, name, focus, level, age_group,
|
||||
weekday, time_start, time_end, location,
|
||||
@@ -430,23 +560,25 @@ def create_training_group(data: dict, session=Depends(require_auth)):
|
||||
%s, %s, %s, %s,
|
||||
%s, %s, %s
|
||||
) RETURNING id
|
||||
""", (
|
||||
club_id,
|
||||
data.get('division_id'),
|
||||
name,
|
||||
data.get('focus'),
|
||||
data.get('level'),
|
||||
data.get('age_group'),
|
||||
data.get('weekday'),
|
||||
data.get('time_start'),
|
||||
data.get('time_end'),
|
||||
data.get('location'),
|
||||
trainer_id,
|
||||
data.get('co_trainer_ids'),
|
||||
data.get('status', 'active')
|
||||
))
|
||||
""",
|
||||
(
|
||||
club_id,
|
||||
data.get("division_id"),
|
||||
name,
|
||||
data.get("focus"),
|
||||
data.get("level"),
|
||||
data.get("age_group"),
|
||||
data.get("weekday"),
|
||||
data.get("time_start"),
|
||||
data.get("time_end"),
|
||||
data.get("location"),
|
||||
trainer_id,
|
||||
data.get("co_trainer_ids"),
|
||||
data.get("status", "active"),
|
||||
),
|
||||
)
|
||||
|
||||
group_id = cur.fetchone()['id']
|
||||
group_id = cur.fetchone()["id"]
|
||||
conn.commit()
|
||||
|
||||
return get_training_group(group_id, session)
|
||||
@@ -455,25 +587,35 @@ def create_training_group(data: dict, session=Depends(require_auth)):
|
||||
# ── Update Training Group ─────────────────────────────────────────────
|
||||
@router.put("/groups/{group_id}")
|
||||
def update_training_group(group_id: int, data: dict, session=Depends(require_auth)):
|
||||
"""Update training group (admin or assigned trainer)."""
|
||||
profile_id = session['profile_id']
|
||||
role = session.get('role')
|
||||
"""Update training group – Vereinsadmin, Plattform-Admin oder zugewiesene Trainer."""
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check existence and ownership
|
||||
cur.execute("SELECT trainer_id FROM training_groups WHERE id = %s", (group_id,))
|
||||
cur.execute(
|
||||
"SELECT trainer_id, co_trainer_ids, club_id FROM training_groups WHERE id = %s",
|
||||
(group_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Trainingsgruppe nicht gefunden")
|
||||
|
||||
# Only admin or assigned trainer can update
|
||||
if role not in ['admin', 'superadmin'] and row['trainer_id'] != profile_id:
|
||||
co_trainers = row["co_trainer_ids"] or []
|
||||
club_id = row["club_id"]
|
||||
|
||||
allowed = role in ["admin", "superadmin"]
|
||||
if not allowed:
|
||||
allowed = can_manage_club_org(cur, profile_id, club_id, role)
|
||||
if not allowed:
|
||||
allowed = row["trainer_id"] == profile_id or profile_id in co_trainers
|
||||
|
||||
if not allowed:
|
||||
raise HTTPException(403, "Keine Berechtigung")
|
||||
|
||||
# Update
|
||||
cur.execute("""
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE training_groups SET
|
||||
name = %s,
|
||||
division_id = %s,
|
||||
@@ -489,21 +631,23 @@ def update_training_group(group_id: int, data: dict, session=Depends(require_aut
|
||||
status = %s,
|
||||
updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""", (
|
||||
data.get('name'),
|
||||
data.get('division_id'),
|
||||
data.get('focus'),
|
||||
data.get('level'),
|
||||
data.get('age_group'),
|
||||
data.get('weekday'),
|
||||
data.get('time_start'),
|
||||
data.get('time_end'),
|
||||
data.get('location'),
|
||||
data.get('trainer_id'),
|
||||
data.get('co_trainer_ids'),
|
||||
data.get('status'),
|
||||
group_id
|
||||
))
|
||||
""",
|
||||
(
|
||||
data.get("name"),
|
||||
data.get("division_id"),
|
||||
data.get("focus"),
|
||||
data.get("level"),
|
||||
data.get("age_group"),
|
||||
data.get("weekday"),
|
||||
data.get("time_start"),
|
||||
data.get("time_end"),
|
||||
data.get("location"),
|
||||
data.get("trainer_id"),
|
||||
data.get("co_trainer_ids"),
|
||||
data.get("status"),
|
||||
group_id,
|
||||
),
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
|
||||
@@ -513,20 +657,21 @@ def update_training_group(group_id: int, data: dict, session=Depends(require_aut
|
||||
# ── Delete Training Group ─────────────────────────────────────────────
|
||||
@router.delete("/groups/{group_id}")
|
||||
def delete_training_group(group_id: int, session=Depends(require_auth)):
|
||||
"""Delete training group (admin only)."""
|
||||
role = session.get('role')
|
||||
if role not in ['admin', 'superadmin']:
|
||||
raise HTTPException(403, "Nur Admins dürfen Gruppen löschen")
|
||||
"""Delete training group – Vereinsadmin oder Plattform-Admin."""
|
||||
profile_id = session["profile_id"]
|
||||
role = session.get("role")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
# Check existence
|
||||
cur.execute("SELECT id FROM training_groups WHERE id = %s", (group_id,))
|
||||
if not cur.fetchone():
|
||||
cur.execute("SELECT id, club_id FROM training_groups WHERE id = %s", (group_id,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Trainingsgruppe nicht gefunden")
|
||||
|
||||
# Delete
|
||||
if not can_manage_club_org(cur, profile_id, row["club_id"], role):
|
||||
raise HTTPException(403, "Keine Berechtigung")
|
||||
|
||||
cur.execute("DELETE FROM training_groups WHERE id = %s", (group_id,))
|
||||
conn.commit()
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth
|
||||
from club_tenancy import exercise_visible_to_profile, is_platform_admin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -592,9 +593,24 @@ def list_exercises(
|
||||
where = ["1=1"]
|
||||
params = []
|
||||
|
||||
# Visibility Filter (private nur für Owner)
|
||||
where.append("(e.visibility = 'official' OR e.visibility = 'club' OR e.created_by = %s)")
|
||||
params.append(profile_id)
|
||||
# Mandanten-Sichtbarkeit: official / eigene private / club nur eigene Vereine (Plattform-Admin: alles)
|
||||
role = session.get("role")
|
||||
if not is_platform_admin(role):
|
||||
where.append(
|
||||
"""(
|
||||
e.visibility = 'official'
|
||||
OR (e.visibility = 'private' AND e.created_by = %s)
|
||||
OR (
|
||||
e.visibility = 'club'
|
||||
AND e.club_id IS NOT NULL
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM club_members cm
|
||||
WHERE cm.profile_id = %s AND cm.club_id = e.club_id AND cm.status = 'active'
|
||||
)
|
||||
)
|
||||
)"""
|
||||
)
|
||||
params.extend([profile_id, profile_id])
|
||||
|
||||
vis_list = _merge_str_any(visibility_any, visibility)
|
||||
if vis_list:
|
||||
@@ -754,12 +770,18 @@ def get_exercise(
|
||||
cur = get_cursor(conn)
|
||||
exercise = enrich_exercise_detail(exercise_id, cur)
|
||||
|
||||
if not exercise:
|
||||
raise HTTPException(status_code=404, detail="Übung nicht gefunden")
|
||||
if not exercise:
|
||||
raise HTTPException(status_code=404, detail="Übung nicht gefunden")
|
||||
|
||||
# Permission Check (private nur für Owner)
|
||||
if exercise["visibility"] == "private" and exercise["created_by"] != profile_id:
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für diese Übung")
|
||||
if not exercise_visible_to_profile(
|
||||
cur,
|
||||
profile_id,
|
||||
exercise["visibility"],
|
||||
exercise.get("club_id"),
|
||||
exercise.get("created_by"),
|
||||
session.get("role"),
|
||||
):
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung für diese Übung")
|
||||
|
||||
return exercise
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ from fastapi import APIRouter, HTTPException, Header, Depends
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth
|
||||
from club_tenancy import assert_club_member, memberships_with_roles
|
||||
from models import ProfileCreate, ProfileUpdate
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["profiles"])
|
||||
@@ -40,7 +41,10 @@ def get_current_profile(session=Depends(require_auth)):
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Profil nicht gefunden")
|
||||
return r2d(row)
|
||||
data = r2d(row)
|
||||
data.pop("pin_hash", None)
|
||||
data["clubs"] = memberships_with_roles(cur, profile_id)
|
||||
return data
|
||||
|
||||
|
||||
# ── Admin Profile Management ──────────────────────────────────────────────────
|
||||
@@ -127,10 +131,24 @@ def update_profile(pid: str, p: ProfileUpdate, session=Depends(require_auth)):
|
||||
data["verification_token"] = None
|
||||
data["verification_expires"] = None
|
||||
|
||||
if "active_club_id" in patch:
|
||||
ac = patch["active_club_id"]
|
||||
if ac is None:
|
||||
data["active_club_id"] = None
|
||||
else:
|
||||
try:
|
||||
cid = int(ac)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(400, "active_club_id ungültig")
|
||||
assert_club_member(cur, int(pid), cid)
|
||||
data["active_club_id"] = cid
|
||||
|
||||
nullable_keys = {"goal_weight", "goal_bf_pct", "dob"}
|
||||
for k, v in patch.items():
|
||||
if k == "email":
|
||||
continue
|
||||
if k == "active_club_id":
|
||||
continue
|
||||
if v is None and k in nullable_keys:
|
||||
data[k] = None
|
||||
elif v is not None:
|
||||
|
||||
Reference in new issue
Block a user