feat: Introduce admin reference value types management in API and UI
- Added new routes and API endpoints for managing reference value types in the admin section. - Updated the frontend to include navigation and components for reference value types management. - Enhanced the backend to support the new reference value types in the data layer and versioning.
This commit is contained in:
1 parent
f0e6fd04fb
commit
ab616ba044
7 files changed
+570
-1
No files matched your search
@@ -0,0 +1,192 @@
|
||||
"""
|
||||
Admin: Referenzwert-Typen (Katalog für persönliche Referenzwerte).
|
||||
|
||||
Nur Admins; Nutzer sehen nur aktive Typen über /api/reference-value-types.
|
||||
"""
|
||||
import re
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from psycopg2 import errors as pg_errors
|
||||
from psycopg2.extras import Json
|
||||
|
||||
from auth import require_admin
|
||||
from db import get_db, get_cursor, r2d
|
||||
|
||||
router = APIRouter(prefix="/api/admin/reference-value-types", tags=["admin", "reference-value-types"])
|
||||
|
||||
KEY_PATTERN = re.compile(r"^[a-z][a-z0-9_]{0,62}$")
|
||||
|
||||
|
||||
def _serialize_type(row: dict[str, Any]) -> dict[str, Any]:
|
||||
if not row:
|
||||
return row
|
||||
out = dict(row)
|
||||
ca = out.get("created_at")
|
||||
if ca is not None and hasattr(ca, "isoformat"):
|
||||
out["created_at"] = ca.isoformat()
|
||||
return out
|
||||
|
||||
|
||||
class ReferenceValueTypeAdminCreate(BaseModel):
|
||||
key: str = Field(..., min_length=1, max_length=64)
|
||||
label: str = Field(..., min_length=1, max_length=200)
|
||||
description: Optional[str] = None
|
||||
default_unit: Optional[str] = Field(None, max_length=32)
|
||||
sort_order: int = 0
|
||||
active: bool = True
|
||||
metadata: Optional[dict] = None
|
||||
|
||||
|
||||
class ReferenceValueTypeAdminUpdate(BaseModel):
|
||||
label: Optional[str] = Field(None, min_length=1, max_length=200)
|
||||
description: Optional[str] = None
|
||||
default_unit: Optional[str] = Field(None, max_length=32)
|
||||
sort_order: Optional[int] = None
|
||||
active: Optional[bool] = None
|
||||
metadata: Optional[dict] = None
|
||||
|
||||
|
||||
def _normalize_key(key: str) -> str:
|
||||
k = key.strip().lower()
|
||||
if not KEY_PATTERN.match(k):
|
||||
raise HTTPException(
|
||||
400,
|
||||
"Ungültiger Schlüssel: nur Kleinbuchstaben, Ziffern, Unterstriche; muss mit Buchstabe beginnen.",
|
||||
)
|
||||
return k
|
||||
|
||||
|
||||
def _unit_or_none(u: Optional[str]) -> Optional[str]:
|
||||
if u is None:
|
||||
return None
|
||||
s = u.strip()
|
||||
return s if s else None
|
||||
|
||||
|
||||
@router.get("")
|
||||
def admin_list_reference_value_types(session: dict = Depends(require_admin)):
|
||||
"""Alle Typen inkl. inaktiver (Admin-Übersicht)."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, key, label, description, default_unit, sort_order, active, metadata, created_at
|
||||
FROM reference_value_types
|
||||
ORDER BY sort_order ASC, id ASC
|
||||
"""
|
||||
)
|
||||
return [_serialize_type(r2d(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.get("/{type_id}")
|
||||
def admin_get_reference_value_type(type_id: int, session: dict = Depends(require_admin)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, key, label, description, default_unit, sort_order, active, metadata, created_at
|
||||
FROM reference_value_types WHERE id = %s
|
||||
""",
|
||||
(type_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Typ nicht gefunden")
|
||||
return _serialize_type(r2d(row))
|
||||
|
||||
|
||||
@router.post("")
|
||||
def admin_create_reference_value_type(
|
||||
body: ReferenceValueTypeAdminCreate,
|
||||
session: dict = Depends(require_admin),
|
||||
):
|
||||
key = _normalize_key(body.key)
|
||||
meta = body.metadata if body.metadata is not None else {}
|
||||
du = _unit_or_none(body.default_unit)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO reference_value_types
|
||||
(key, label, description, default_unit, sort_order, active, metadata)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id, key, label, description, default_unit, sort_order, active, metadata, created_at
|
||||
""",
|
||||
(
|
||||
key,
|
||||
body.label.strip(),
|
||||
body.description.strip() if body.description else None,
|
||||
du,
|
||||
body.sort_order,
|
||||
body.active,
|
||||
Json(meta),
|
||||
),
|
||||
)
|
||||
return _serialize_type(r2d(cur.fetchone()))
|
||||
except pg_errors.UniqueViolation:
|
||||
raise HTTPException(409, "Ein Typ mit diesem Schlüssel existiert bereits.")
|
||||
|
||||
|
||||
@router.put("/{type_id}")
|
||||
def admin_update_reference_value_type(
|
||||
type_id: int,
|
||||
body: ReferenceValueTypeAdminUpdate,
|
||||
session: dict = Depends(require_admin),
|
||||
):
|
||||
patch = body.model_dump(exclude_unset=True)
|
||||
if not patch:
|
||||
raise HTTPException(400, "Keine Felder zum Aktualisieren")
|
||||
|
||||
if "default_unit" in patch:
|
||||
patch["default_unit"] = _unit_or_none(patch.get("default_unit"))
|
||||
if "description" in patch and patch["description"] is not None:
|
||||
patch["description"] = patch["description"].strip() or None
|
||||
if "metadata" in patch:
|
||||
patch["metadata"] = Json(patch["metadata"] if patch["metadata"] is not None else {})
|
||||
|
||||
cols = []
|
||||
vals = []
|
||||
for k, v in patch.items():
|
||||
cols.append(f"{k} = %s")
|
||||
vals.append(v)
|
||||
vals.append(type_id)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE reference_value_types SET {", ".join(cols)}
|
||||
WHERE id = %s
|
||||
RETURNING id, key, label, description, default_unit, sort_order, active, metadata, created_at
|
||||
""",
|
||||
tuple(vals),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Typ nicht gefunden")
|
||||
return _serialize_type(r2d(row))
|
||||
|
||||
|
||||
@router.delete("/{type_id}")
|
||||
def admin_delete_reference_value_type(type_id: int, session: dict = Depends(require_admin)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT COUNT(*) AS c FROM profile_reference_values WHERE reference_value_type_id = %s",
|
||||
(type_id,),
|
||||
)
|
||||
n = cur.fetchone()["c"]
|
||||
if n > 0:
|
||||
raise HTTPException(
|
||||
409,
|
||||
f"Es gibt noch {n} gespeicherte Referenzwert(e) zu diesem Typ. "
|
||||
"Bitte zuerst löschen oder den Typ deaktivieren (active = aus).",
|
||||
)
|
||||
cur.execute("DELETE FROM reference_value_types WHERE id = %s RETURNING id", (type_id,))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(404, "Typ nicht gefunden")
|
||||
return {"ok": True}
|
||||
Reference in new issue
Block a user