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}
|
||||
|
||||
|
||||
+137
-35
@@ -5,7 +5,9 @@ Handles CRUD operations for skills and training methods.
|
||||
Read access for all authenticated users.
|
||||
Write access for admins only.
|
||||
"""
|
||||
from typing import Optional
|
||||
import json
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Depends, Query
|
||||
|
||||
from db import get_db, get_cursor, r2d
|
||||
@@ -14,6 +16,17 @@ from auth import require_auth
|
||||
router = APIRouter(prefix="/api", tags=["skills"])
|
||||
|
||||
|
||||
def _main_id_for_category(cur, category_id: Optional[int]) -> Optional[int]:
|
||||
if not category_id:
|
||||
return None
|
||||
cur.execute(
|
||||
"SELECT main_category_id FROM skill_categories WHERE id = %s",
|
||||
(category_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return row["main_category_id"] if row else None
|
||||
|
||||
|
||||
# ── List Skills ───────────────────────────────────────────────────────
|
||||
@router.get("/skills")
|
||||
def list_skills(
|
||||
@@ -56,6 +69,57 @@ def list_skills(
|
||||
return [r2d(r) for r in rows]
|
||||
|
||||
|
||||
# ── Katalog-Ansicht (Hierarchie-Sortierung, Admin) ───────────────────────
|
||||
@router.get("/skills/catalog")
|
||||
def list_skills_catalog(
|
||||
status: Optional[str] = Query(
|
||||
default="active",
|
||||
description="'active', 'inactive' oder 'all' (nur Admin)",
|
||||
),
|
||||
session=Depends(require_auth),
|
||||
):
|
||||
"""
|
||||
Fähigkeiten für Admin-Katalog: sortiert nach Hauptgruppe → Kategorie → Sortierung → Name.
|
||||
status=all nur für admin/superadmin.
|
||||
"""
|
||||
role = session.get("role")
|
||||
admin = role in ("admin", "superadmin")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
q = """
|
||||
SELECT s.*,
|
||||
mc.name AS catalog_main_category_name,
|
||||
mc.sort_order AS catalog_main_sort,
|
||||
mc.slug AS catalog_main_slug,
|
||||
sc.name AS catalog_category_name,
|
||||
sc.sort_order AS catalog_category_sort,
|
||||
sc.slug AS catalog_category_slug
|
||||
FROM skills s
|
||||
LEFT JOIN skill_main_categories mc ON s.main_category_id = mc.id
|
||||
LEFT JOIN skill_categories sc ON s.category_id = sc.id
|
||||
WHERE 1=1
|
||||
"""
|
||||
params: list[Any] = []
|
||||
if status == "all":
|
||||
if not admin:
|
||||
raise HTTPException(403, "Nur Admins dürfen alle Status sehen")
|
||||
elif status:
|
||||
q += " AND s.status = %s"
|
||||
params.append(status)
|
||||
else:
|
||||
q += " AND s.status = %s"
|
||||
params.append("active")
|
||||
q += """
|
||||
ORDER BY mc.sort_order NULLS LAST,
|
||||
sc.sort_order NULLS LAST,
|
||||
s.sort_order NULLS LAST,
|
||||
s.name
|
||||
"""
|
||||
cur.execute(q, params)
|
||||
return [r2d(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
# ── Get Skill ─────────────────────────────────────────────────────────
|
||||
@router.get("/skills/{skill_id}")
|
||||
def get_skill(skill_id: int, session=Depends(require_auth)):
|
||||
@@ -84,24 +148,46 @@ def create_skill(data: dict, session=Depends(require_auth)):
|
||||
if not name:
|
||||
raise HTTPException(400, "Name ist Pflichtfeld")
|
||||
|
||||
cat_id = data.get("category_id")
|
||||
if cat_id is not None:
|
||||
cat_id = int(cat_id)
|
||||
main_id = data.get("main_category_id")
|
||||
if main_id is not None:
|
||||
main_id = int(main_id)
|
||||
|
||||
focus = data.get("focus_areas")
|
||||
if isinstance(focus, (list, dict)):
|
||||
focus = json.dumps(focus)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
if cat_id and main_id is None:
|
||||
main_id = _main_id_for_category(cur, cat_id)
|
||||
|
||||
cur.execute("""
|
||||
INSERT INTO skills (name, category, description, importance, keywords, status)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO skills (
|
||||
name, category, description, importance, keywords, status,
|
||||
category_id, main_category_id, focus_areas, sort_order
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s::jsonb, %s)
|
||||
RETURNING id
|
||||
""", (
|
||||
name,
|
||||
data.get('category'),
|
||||
data.get('description'),
|
||||
data.get('importance'),
|
||||
data.get('keywords'),
|
||||
data.get('status', 'active')
|
||||
))
|
||||
""",
|
||||
(
|
||||
name,
|
||||
data.get("category"),
|
||||
data.get("description"),
|
||||
data.get("importance"),
|
||||
data.get("keywords"),
|
||||
data.get("status", "active"),
|
||||
cat_id,
|
||||
main_id,
|
||||
focus if focus is not None else "[]",
|
||||
data.get("sort_order"),
|
||||
),
|
||||
)
|
||||
|
||||
skill_id = cur.fetchone()['id']
|
||||
conn.commit()
|
||||
skill_id = cur.fetchone()["id"]
|
||||
|
||||
return get_skill(skill_id, session)
|
||||
|
||||
@@ -122,28 +208,44 @@ def update_skill(skill_id: int, data: dict, session=Depends(require_auth)):
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Fähigkeit nicht gefunden")
|
||||
|
||||
# Update
|
||||
cur.execute("""
|
||||
UPDATE skills SET
|
||||
name = %s,
|
||||
category = %s,
|
||||
description = %s,
|
||||
importance = %s,
|
||||
keywords = %s,
|
||||
status = %s,
|
||||
updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""", (
|
||||
data.get('name'),
|
||||
data.get('category'),
|
||||
data.get('description'),
|
||||
data.get('importance'),
|
||||
data.get('keywords'),
|
||||
data.get('status'),
|
||||
skill_id
|
||||
))
|
||||
sets: list = []
|
||||
vals: list = []
|
||||
for key in (
|
||||
"name",
|
||||
"category",
|
||||
"description",
|
||||
"importance",
|
||||
"keywords",
|
||||
"status",
|
||||
"category_id",
|
||||
"main_category_id",
|
||||
"sort_order",
|
||||
):
|
||||
if key in data:
|
||||
sets.append(f"{key} = %s")
|
||||
vals.append(data[key])
|
||||
if "focus_areas" in data:
|
||||
fa = data["focus_areas"]
|
||||
if isinstance(fa, (list, dict)):
|
||||
fa = json.dumps(fa)
|
||||
sets.append("focus_areas = %s::jsonb")
|
||||
vals.append(fa if fa is not None else "[]")
|
||||
|
||||
conn.commit()
|
||||
if sets:
|
||||
sets.append("updated_at = NOW()")
|
||||
vals.append(skill_id)
|
||||
cur.execute(
|
||||
f"UPDATE skills SET {', '.join(sets)} WHERE id = %s",
|
||||
tuple(vals),
|
||||
)
|
||||
|
||||
if "category_id" in data and "main_category_id" not in data:
|
||||
mid = _main_id_for_category(cur, data.get("category_id"))
|
||||
if mid is not None:
|
||||
cur.execute(
|
||||
"UPDATE skills SET main_category_id = %s WHERE id = %s",
|
||||
(mid, skill_id),
|
||||
)
|
||||
|
||||
return get_skill(skill_id, session)
|
||||
|
||||
|
||||
Reference in new issue
Block a user