feat: add skill main categories and enhance skills catalog functionality
- Introduced endpoints for managing skill main categories, including CRUD operations. - Enhanced skills catalog endpoint to support hierarchical sorting by main category and category. - Updated frontend API utility functions to include new skill main category operations. - Improved admin interface for skills management with new layout and styles. - Documented changes in the changelog for better tracking of new features and updates.
This commit is contained in:
1 parent
f1ee1eec7e
commit
e8b7e62832
7 files changed
+2231
-806
No files matched your search
+246
-46
@@ -3,7 +3,9 @@ Catalog Management Endpoints for Shinkan Jinkendo
|
||||
|
||||
Admin-verwaltbare Stammdaten für Übungen, Fokusbereiche, Stile, etc.
|
||||
"""
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Depends, Query
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
@@ -12,6 +14,131 @@ from auth import require_auth
|
||||
router = APIRouter(prefix="/api", tags=["catalogs"])
|
||||
|
||||
|
||||
def _slugify_skill_label(text: str) -> str:
|
||||
t = (text or "").strip().lower()
|
||||
t = re.sub(r"[^a-z0-9äöüß]+", "_", t, flags=re.IGNORECASE)
|
||||
t = re.sub(r"_+", "_", t).strip("_")
|
||||
return (t[:48] or "gruppe")
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════════════════
|
||||
# SKILL MAIN CATEGORIES (Hauptgruppen, z. B. „KARATE Fähigkeiten“)
|
||||
# ════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
@router.get("/skill-main-categories")
|
||||
def list_skill_main_categories(session=Depends(require_auth)):
|
||||
"""Alle Hauptkategorien für den Fähigkeitskatalog (sortiert)."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT * FROM skill_main_categories ORDER BY sort_order NULLS LAST, name"
|
||||
)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.post("/skill-main-categories")
|
||||
def create_skill_main_category(data: dict, session=Depends(require_auth)):
|
||||
role = session.get("role")
|
||||
if role not in ("admin", "superadmin"):
|
||||
raise HTTPException(403, "Nur Admins dürfen Hauptkategorien anlegen")
|
||||
name = (data.get("name") or "").strip()
|
||||
if not name:
|
||||
raise HTTPException(400, "Name ist Pflichtfeld")
|
||||
slug = (data.get("slug") or "").strip() or _slugify_skill_label(name)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO skill_main_categories (name, slug, description, sort_order)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
name,
|
||||
slug,
|
||||
data.get("description"),
|
||||
data.get("sort_order", 99),
|
||||
),
|
||||
)
|
||||
mid = cur.fetchone()["id"]
|
||||
except Exception as e:
|
||||
if "unique" in str(e).lower() or "duplicate" in str(e).lower():
|
||||
raise HTTPException(409, "Name oder Slug bereits vergeben") from e
|
||||
raise
|
||||
cur.execute("SELECT * FROM skill_main_categories WHERE id = %s", (mid,))
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
@router.put("/skill-main-categories/{main_id}")
|
||||
def update_skill_main_category(main_id: int, data: dict, session=Depends(require_auth)):
|
||||
role = session.get("role")
|
||||
if role not in ("admin", "superadmin"):
|
||||
raise HTTPException(403, "Nur Admins dürfen Hauptkategorien bearbeiten")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT id FROM skill_main_categories WHERE id = %s", (main_id,))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Hauptkategorie nicht gefunden")
|
||||
sets = []
|
||||
vals = []
|
||||
for key in ("name", "slug", "description", "sort_order"):
|
||||
if key in data:
|
||||
sets.append(f"{key} = %s")
|
||||
vals.append(data[key])
|
||||
if not sets:
|
||||
cur.execute("SELECT * FROM skill_main_categories WHERE id = %s", (main_id,))
|
||||
return r2d(cur.fetchone())
|
||||
sets.append("updated_at = NOW()")
|
||||
vals.append(main_id)
|
||||
try:
|
||||
cur.execute(
|
||||
f"UPDATE skill_main_categories SET {', '.join(sets)} WHERE id = %s",
|
||||
tuple(vals),
|
||||
)
|
||||
except Exception as e:
|
||||
if "unique" in str(e).lower():
|
||||
raise HTTPException(409, "Name oder Slug bereits vergeben") from e
|
||||
raise
|
||||
cur.execute("SELECT * FROM skill_main_categories WHERE id = %s", (main_id,))
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
@router.delete("/skill-main-categories/{main_id}")
|
||||
def delete_skill_main_category(main_id: int, session=Depends(require_auth)):
|
||||
role = session.get("role")
|
||||
if role != "superadmin":
|
||||
raise HTTPException(403, "Nur Superadmins dürfen Hauptkategorien löschen")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT COUNT(*) AS c FROM skill_categories WHERE main_category_id = %s",
|
||||
(main_id,),
|
||||
)
|
||||
if (cur.fetchone() or {}).get("c", 0) > 0:
|
||||
raise HTTPException(
|
||||
409,
|
||||
"Hauptkategorie hat noch Unterkategorien. Bitte zuerst verschieben oder löschen.",
|
||||
)
|
||||
cur.execute(
|
||||
"SELECT COUNT(*) AS c FROM skills WHERE main_category_id = %s",
|
||||
(main_id,),
|
||||
)
|
||||
if (cur.fetchone() or {}).get("c", 0) > 0:
|
||||
raise HTTPException(
|
||||
409,
|
||||
"Hauptkategorie ist noch Fähigkeiten zugeordnet.",
|
||||
)
|
||||
cur.execute(
|
||||
"DELETE FROM skill_main_categories WHERE id = %s RETURNING id",
|
||||
(main_id,),
|
||||
)
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Hauptkategorie nicht gefunden")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════════════════
|
||||
# FOCUS AREAS
|
||||
# ════════════════════════════════════════════════════════════════════════
|
||||
@@ -526,24 +653,35 @@ def delete_training_type(type_id: int, session=Depends(require_auth)):
|
||||
@router.get("/skill-categories")
|
||||
def list_skill_categories(
|
||||
status: Optional[str] = Query(default='active'),
|
||||
session=Depends(require_auth)
|
||||
main_category_id: Optional[int] = Query(default=None),
|
||||
session=Depends(require_auth),
|
||||
):
|
||||
"""List all skill categories."""
|
||||
"""List all skill categories (mit Hauptkategorie)."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
query = """
|
||||
SELECT sc.*, pc.name as parent_category_name
|
||||
SELECT sc.*, pc.name as parent_category_name,
|
||||
mc.id as main_category_ref_id, mc.name as main_category_name,
|
||||
mc.slug as main_category_slug, mc.sort_order as main_category_sort
|
||||
FROM skill_categories sc
|
||||
LEFT JOIN skill_categories pc ON sc.parent_category_id = pc.id
|
||||
LEFT JOIN skill_main_categories mc ON sc.main_category_id = mc.id
|
||||
"""
|
||||
params = []
|
||||
where = []
|
||||
|
||||
if status:
|
||||
query += " WHERE sc.status = %s"
|
||||
where.append("sc.status = %s")
|
||||
params.append(status)
|
||||
if main_category_id is not None:
|
||||
where.append("sc.main_category_id = %s")
|
||||
params.append(main_category_id)
|
||||
|
||||
query += " ORDER BY sc.sort_order, sc.name"
|
||||
if where:
|
||||
query += " WHERE " + " AND ".join(where)
|
||||
|
||||
query += " ORDER BY mc.sort_order NULLS LAST, sc.sort_order NULLS LAST, sc.name"
|
||||
|
||||
cur.execute(query, params)
|
||||
rows = cur.fetchall()
|
||||
@@ -557,34 +695,56 @@ def create_skill_category(data: dict, session=Depends(require_auth)):
|
||||
if role not in ['admin', 'superadmin']:
|
||||
raise HTTPException(403, "Nur Admins dürfen Fähigkeitsbereiche erstellen")
|
||||
|
||||
name = data.get('name')
|
||||
name = (data.get("name") or "").strip()
|
||||
if not name:
|
||||
raise HTTPException(400, "Name ist Pflichtfeld")
|
||||
|
||||
main_category_id = data.get("main_category_id")
|
||||
if main_category_id is not None:
|
||||
main_category_id = int(main_category_id)
|
||||
|
||||
slug = (data.get("slug") or "").strip() or _slugify_skill_label(name)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
cur.execute("""
|
||||
INSERT INTO skill_categories (name, description, parent_category_id, sort_order, status)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""", (
|
||||
name,
|
||||
data.get('description'),
|
||||
data.get('parent_category_id'),
|
||||
data.get('sort_order', 99),
|
||||
data.get('status', 'active')
|
||||
))
|
||||
try:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO skill_categories (
|
||||
name, slug, description, parent_category_id, main_category_id,
|
||||
sort_order, status
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
name,
|
||||
slug,
|
||||
data.get("description"),
|
||||
data.get("parent_category_id"),
|
||||
main_category_id,
|
||||
data.get("sort_order", 99),
|
||||
data.get("status", "active"),
|
||||
),
|
||||
)
|
||||
cat_id = cur.fetchone()["id"]
|
||||
except Exception as e:
|
||||
if "unique" in str(e).lower() or "duplicate" in str(e).lower():
|
||||
raise HTTPException(409, "Name oder Slug schon vergeben") from e
|
||||
raise
|
||||
|
||||
cat_id = cur.fetchone()['id']
|
||||
conn.commit()
|
||||
|
||||
cur.execute("""
|
||||
SELECT sc.*, pc.name as parent_category_name
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT sc.*, pc.name as parent_category_name,
|
||||
mc.name as main_category_name, mc.slug as main_category_slug
|
||||
FROM skill_categories sc
|
||||
LEFT JOIN skill_categories pc ON sc.parent_category_id = pc.id
|
||||
LEFT JOIN skill_main_categories mc ON sc.main_category_id = mc.id
|
||||
WHERE sc.id = %s
|
||||
""", (cat_id,))
|
||||
""",
|
||||
(cat_id,),
|
||||
)
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
@@ -598,32 +758,59 @@ def update_skill_category(cat_id: int, data: dict, session=Depends(require_auth)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
cur.execute("""
|
||||
UPDATE skill_categories SET
|
||||
name = %s,
|
||||
description = %s,
|
||||
parent_category_id = %s,
|
||||
sort_order = %s,
|
||||
status = %s,
|
||||
updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""", (
|
||||
data.get('name'),
|
||||
data.get('description'),
|
||||
data.get('parent_category_id'),
|
||||
data.get('sort_order'),
|
||||
data.get('status'),
|
||||
cat_id
|
||||
))
|
||||
cur.execute("SELECT id FROM skill_categories WHERE id = %s", (cat_id,))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Kategorie nicht gefunden")
|
||||
|
||||
conn.commit()
|
||||
sets: list = []
|
||||
vals: list = []
|
||||
for key in (
|
||||
"name",
|
||||
"slug",
|
||||
"description",
|
||||
"parent_category_id",
|
||||
"main_category_id",
|
||||
"sort_order",
|
||||
"status",
|
||||
):
|
||||
if key in data:
|
||||
sets.append(f"{key} = %s")
|
||||
vals.append(data[key])
|
||||
if sets:
|
||||
sets.append("updated_at = NOW()")
|
||||
vals.append(cat_id)
|
||||
try:
|
||||
cur.execute(
|
||||
f"UPDATE skill_categories SET {', '.join(sets)} WHERE id = %s",
|
||||
tuple(vals),
|
||||
)
|
||||
except Exception as e:
|
||||
if "unique" in str(e).lower():
|
||||
raise HTTPException(409, "Name oder Slug schon vergeben") from e
|
||||
raise
|
||||
|
||||
cur.execute("""
|
||||
SELECT sc.*, pc.name as parent_category_name
|
||||
cur.execute(
|
||||
"SELECT main_category_id FROM skill_categories WHERE id = %s",
|
||||
(cat_id,),
|
||||
)
|
||||
effective_main = cur.fetchone()["main_category_id"]
|
||||
if effective_main is not None:
|
||||
cur.execute(
|
||||
"UPDATE skills SET main_category_id = %s WHERE category_id = %s",
|
||||
(effective_main, cat_id),
|
||||
)
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT sc.*, pc.name as parent_category_name,
|
||||
mc.name as main_category_name, mc.slug as main_category_slug
|
||||
FROM skill_categories sc
|
||||
LEFT JOIN skill_categories pc ON sc.parent_category_id = pc.id
|
||||
LEFT JOIN skill_main_categories mc ON sc.main_category_id = mc.id
|
||||
WHERE sc.id = %s
|
||||
""", (cat_id,))
|
||||
""",
|
||||
(cat_id,),
|
||||
)
|
||||
return r2d(cur.fetchone())
|
||||
|
||||
|
||||
@@ -636,8 +823,21 @@ def delete_skill_category(cat_id: int, session=Depends(require_auth)):
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("DELETE FROM skill_categories WHERE id = %s", (cat_id,))
|
||||
conn.commit()
|
||||
cur.execute("SELECT COUNT(*) AS c FROM skills WHERE category_id = %s", (cat_id,))
|
||||
if (cur.fetchone() or {}).get("c", 0) > 0:
|
||||
raise HTTPException(
|
||||
409,
|
||||
"Kategorie noch Fähigkeiten zugeordnet – bitte zuerst verschieben oder löschen.",
|
||||
)
|
||||
cur.execute(
|
||||
"SELECT COUNT(*) AS c FROM skill_categories WHERE parent_category_id = %s",
|
||||
(cat_id,),
|
||||
)
|
||||
if (cur.fetchone() or {}).get("c", 0) > 0:
|
||||
raise HTTPException(409, "Kategorie hat Unterkategorien.")
|
||||
cur.execute("DELETE FROM skill_categories WHERE id = %s RETURNING id", (cat_id,))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Kategorie nicht gefunden")
|
||||
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
Reference in new issue
Block a user