feat: Enhance reference value types management with validation rules and metadata
- Updated the backend to include new fields for validation rules and metadata in reference value types. - Enhanced the AdminReferenceValueTypesPage to support new validation rules for different data types. - Improved the ProfileReferenceValuesPage to handle validation and metadata for profile reference values. - Added API endpoint for fetching reference value metadata enums to support frontend validation. - Refactored frontend forms to incorporate new fields and validation logic for a better user experience.
This commit is contained in:
1 parent
f04318f76a
commit
45e4e64f15
9 files changed
+864
-137
No files matched your search
@@ -13,6 +13,7 @@ from psycopg2.extras import Json
|
||||
|
||||
from auth import require_admin
|
||||
from db import get_db, get_cursor, r2d
|
||||
from reference_value_validation import VALUE_DATA_TYPES
|
||||
|
||||
router = APIRouter(prefix="/api/admin/reference-value-types", tags=["admin", "reference-value-types"])
|
||||
|
||||
@@ -29,11 +30,24 @@ def _serialize_type(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return out
|
||||
|
||||
|
||||
def _normalize_value_data_type(v: str) -> str:
|
||||
s = (v or "decimal").strip().lower()
|
||||
if s not in VALUE_DATA_TYPES:
|
||||
raise HTTPException(
|
||||
400,
|
||||
f"Ungültiger Datentyp: {s}. Erlaubt: {', '.join(sorted(VALUE_DATA_TYPES))}",
|
||||
)
|
||||
return s
|
||||
|
||||
|
||||
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
|
||||
category: Optional[str] = None
|
||||
default_unit: Optional[str] = Field(None, max_length=32)
|
||||
value_data_type: str = "decimal"
|
||||
validation_rules: Optional[dict] = None
|
||||
sort_order: int = 0
|
||||
active: bool = True
|
||||
metadata: Optional[dict] = None
|
||||
@@ -42,7 +56,10 @@ class ReferenceValueTypeAdminCreate(BaseModel):
|
||||
class ReferenceValueTypeAdminUpdate(BaseModel):
|
||||
label: Optional[str] = Field(None, min_length=1, max_length=200)
|
||||
description: Optional[str] = None
|
||||
category: Optional[str] = None
|
||||
default_unit: Optional[str] = Field(None, max_length=32)
|
||||
value_data_type: Optional[str] = None
|
||||
validation_rules: Optional[dict] = None
|
||||
sort_order: Optional[int] = None
|
||||
active: Optional[bool] = None
|
||||
metadata: Optional[dict] = None
|
||||
@@ -65,6 +82,13 @@ def _unit_or_none(u: Optional[str]) -> Optional[str]:
|
||||
return s if s else None
|
||||
|
||||
|
||||
def _cat_or_none(c: Optional[str]) -> Optional[str]:
|
||||
if c is None:
|
||||
return None
|
||||
s = c.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)."""
|
||||
@@ -72,7 +96,9 @@ def admin_list_reference_value_types(session: dict = Depends(require_admin)):
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, key, label, description, default_unit, sort_order, active, metadata, created_at
|
||||
SELECT
|
||||
id, key, label, description, category, default_unit, value_data_type,
|
||||
validation_rules, sort_order, active, metadata, created_at
|
||||
FROM reference_value_types
|
||||
ORDER BY sort_order ASC, id ASC
|
||||
"""
|
||||
@@ -86,7 +112,9 @@ def admin_get_reference_value_type(type_id: int, session: dict = Depends(require
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, key, label, description, default_unit, sort_order, active, metadata, created_at
|
||||
SELECT
|
||||
id, key, label, description, category, default_unit, value_data_type,
|
||||
validation_rules, sort_order, active, metadata, created_at
|
||||
FROM reference_value_types WHERE id = %s
|
||||
""",
|
||||
(type_id,),
|
||||
@@ -103,7 +131,18 @@ def admin_create_reference_value_type(
|
||||
session: dict = Depends(require_admin),
|
||||
):
|
||||
key = _normalize_key(body.key)
|
||||
vdt = _normalize_value_data_type(body.value_data_type)
|
||||
if not _unit_or_none(body.default_unit):
|
||||
raise HTTPException(400, "Standard-Einheit ist erforderlich (wird bei der Erfassung fix verwendet).")
|
||||
meta = body.metadata if body.metadata is not None else {}
|
||||
rules = body.validation_rules if body.validation_rules is not None else {}
|
||||
if vdt == "enum":
|
||||
av = rules.get("allowed_values") if isinstance(rules, dict) else []
|
||||
if not isinstance(av, list) or not [x for x in av if str(x).strip()]:
|
||||
raise HTTPException(
|
||||
400,
|
||||
"Datentyp ENUM erfordert unter Plausibilisierung eine nicht-leere Liste „Erlaubte Werte“.",
|
||||
)
|
||||
du = _unit_or_none(body.default_unit)
|
||||
|
||||
with get_db() as conn:
|
||||
@@ -112,15 +151,21 @@ def admin_create_reference_value_type(
|
||||
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, label, description, category, default_unit, value_data_type,
|
||||
validation_rules, sort_order, active, metadata)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING
|
||||
id, key, label, description, category, default_unit, value_data_type,
|
||||
validation_rules, sort_order, active, metadata, created_at
|
||||
""",
|
||||
(
|
||||
key,
|
||||
body.label.strip(),
|
||||
body.description.strip() if body.description else None,
|
||||
_cat_or_none(body.category),
|
||||
du,
|
||||
vdt,
|
||||
Json(rules),
|
||||
body.sort_order,
|
||||
body.active,
|
||||
Json(meta),
|
||||
@@ -141,12 +186,20 @@ def admin_update_reference_value_type(
|
||||
if not patch:
|
||||
raise HTTPException(400, "Keine Felder zum Aktualisieren")
|
||||
|
||||
if "value_data_type" in patch and patch["value_data_type"] is not None:
|
||||
patch["value_data_type"] = _normalize_value_data_type(patch["value_data_type"])
|
||||
if "default_unit" in patch:
|
||||
patch["default_unit"] = _unit_or_none(patch.get("default_unit"))
|
||||
if patch["default_unit"] is None:
|
||||
raise HTTPException(400, "Standard-Einheit darf nicht leer werden.")
|
||||
if "description" in patch and patch["description"] is not None:
|
||||
patch["description"] = patch["description"].strip() or None
|
||||
if "category" in patch:
|
||||
patch["category"] = _cat_or_none(patch.get("category"))
|
||||
if "metadata" in patch:
|
||||
patch["metadata"] = Json(patch["metadata"] if patch["metadata"] is not None else {})
|
||||
if "validation_rules" in patch:
|
||||
patch["validation_rules"] = Json(patch["validation_rules"] if patch["validation_rules"] is not None else {})
|
||||
|
||||
cols = []
|
||||
vals = []
|
||||
@@ -161,7 +214,9 @@ def admin_update_reference_value_type(
|
||||
f"""
|
||||
UPDATE reference_value_types SET {", ".join(cols)}
|
||||
WHERE id = %s
|
||||
RETURNING id, key, label, description, default_unit, sort_order, active, metadata, created_at
|
||||
RETURNING
|
||||
id, key, label, description, category, default_unit, value_data_type,
|
||||
validation_rules, sort_order, active, metadata, created_at
|
||||
""",
|
||||
tuple(vals),
|
||||
)
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""
|
||||
Persönliche Referenzwerte (profilorientiert)
|
||||
|
||||
Typkatalog system-seeded; Nutzer pflegt historische Werte pro aktivem Profil.
|
||||
Typkatalog system-seeded; Nutzer pflegt historische Einträge pro aktivem Profil.
|
||||
Einheit immer aus dem Typ; Wert je value_data_type validiert.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -10,11 +11,21 @@ from decimal import Decimal
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Query
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
from pydantic import BaseModel, Field
|
||||
from psycopg2.extras import Json
|
||||
|
||||
from auth import require_auth
|
||||
from db import get_db, get_cursor, r2d
|
||||
from reference_value_validation import (
|
||||
REF_VALUE_CONFIDENCE,
|
||||
REF_VALUE_METHODS,
|
||||
REF_VALUE_SOURCES,
|
||||
validate_meta_confidence,
|
||||
validate_meta_method,
|
||||
validate_meta_source,
|
||||
validate_value_for_data_type,
|
||||
resolve_unit_from_type,
|
||||
)
|
||||
from routers.profiles import get_pid
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["reference-values"])
|
||||
@@ -36,15 +47,14 @@ def _row_to_api(d: dict[str, Any]) -> dict[str, Any]:
|
||||
vn = out.get("value_numeric")
|
||||
if vn is not None and isinstance(vn, Decimal):
|
||||
out["value_numeric"] = float(vn)
|
||||
conf = out.get("confidence")
|
||||
if conf is not None and isinstance(conf, Decimal):
|
||||
out["confidence"] = float(conf)
|
||||
return out
|
||||
|
||||
|
||||
def _get_type_by_key(cur, key: str, require_active: bool = True) -> dict:
|
||||
q = (
|
||||
"SELECT id, key, label, default_unit, active FROM reference_value_types WHERE key = %s "
|
||||
"SELECT id, key, label, description, default_unit, active, category, "
|
||||
"value_data_type, validation_rules, metadata "
|
||||
"FROM reference_value_types WHERE key = %s "
|
||||
)
|
||||
if require_active:
|
||||
q += "AND active = TRUE "
|
||||
@@ -60,42 +70,34 @@ class ProfileReferenceValueCreate(BaseModel):
|
||||
effective_date: str
|
||||
value_numeric: Optional[float] = None
|
||||
value_text: Optional[str] = None
|
||||
unit: Optional[str] = Field(None, max_length=32)
|
||||
source: Optional[str] = None
|
||||
confidence: Optional[float] = Field(None, ge=0, le=100)
|
||||
method: Optional[str] = None
|
||||
source: str = Field(..., min_length=1)
|
||||
method: str = Field(..., min_length=1)
|
||||
confidence: str = Field(..., min_length=1)
|
||||
notes: Optional[str] = None
|
||||
extra: Optional[dict] = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _value_present(self):
|
||||
has_num = self.value_numeric is not None
|
||||
has_txt = self.value_text is not None and str(self.value_text).strip() != ""
|
||||
if not has_num and not has_txt:
|
||||
raise ValueError("Mindestens value_numeric oder value_text erforderlich")
|
||||
return self
|
||||
|
||||
|
||||
class ProfileReferenceValueUpdate(BaseModel):
|
||||
effective_date: Optional[str] = None
|
||||
value_numeric: Optional[float] = None
|
||||
value_text: Optional[str] = None
|
||||
unit: Optional[str] = Field(None, max_length=32)
|
||||
source: Optional[str] = None
|
||||
confidence: Optional[float] = Field(None, ge=0, le=100)
|
||||
method: Optional[str] = None
|
||||
confidence: Optional[str] = None
|
||||
notes: Optional[str] = None
|
||||
extra: Optional[dict] = None
|
||||
|
||||
|
||||
@router.get("/reference-value-types")
|
||||
def list_reference_value_types(session: dict = Depends(require_auth)):
|
||||
"""Alle aktiven Referenztyp-Definitionen (für dynamische UI)."""
|
||||
"""Alle aktiven Referenztyp-Definitionen (dynamische UI inkl. Validierungsmetadaten)."""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, key, label, description, default_unit, sort_order, active, metadata, created_at
|
||||
SELECT
|
||||
id, key, label, description, default_unit, sort_order, active,
|
||||
category, value_data_type, validation_rules, metadata, created_at
|
||||
FROM reference_value_types
|
||||
WHERE active = TRUE
|
||||
ORDER BY sort_order ASC, id ASC
|
||||
@@ -104,6 +106,16 @@ def list_reference_value_types(session: dict = Depends(require_auth)):
|
||||
return [_row_to_api(r2d(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
@router.get("/reference-value-meta/enums")
|
||||
def list_reference_value_meta_enums(session: dict = Depends(require_auth)):
|
||||
"""Erlaubte Werte für Quelle, Methode, Vertrauensgrad (Erfassungsdialog)."""
|
||||
return {
|
||||
"sources": sorted(REF_VALUE_SOURCES),
|
||||
"methods": sorted(REF_VALUE_METHODS),
|
||||
"confidence_levels": sorted(REF_VALUE_CONFIDENCE),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/profile-reference-values")
|
||||
def list_profile_reference_values(
|
||||
type_key: str = Query(..., description="Schlüssel aus reference_value_types.key"),
|
||||
@@ -156,18 +168,17 @@ def create_profile_reference_value(
|
||||
except ValueError:
|
||||
raise HTTPException(400, "Ungültiges Datum. Format: YYYY-MM-DD")
|
||||
|
||||
src = validate_meta_source(body.source)
|
||||
meth = validate_meta_method(body.method)
|
||||
conf = validate_meta_confidence(body.confidence)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
t = _get_type_by_key(cur, body.reference_value_type_key.strip(), require_active=True)
|
||||
unit = (body.unit or "").strip() or (t.get("default_unit") or "").strip()
|
||||
if not unit:
|
||||
raise HTTPException(400, "Bitte eine Einheit angeben (kein Standard für diesen Typ definiert).")
|
||||
|
||||
vnum = body.value_numeric
|
||||
vtxt = (body.value_text.strip() if body.value_text is not None else None) or None
|
||||
if vnum is None and not vtxt:
|
||||
raise HTTPException(400, "Mindestens value_numeric oder value_text erforderlich.")
|
||||
|
||||
vdt = (t.get("value_data_type") or "decimal").strip().lower()
|
||||
rules = t.get("validation_rules") or {}
|
||||
vnum, vtxt = validate_value_for_data_type(vdt, rules, body.value_numeric, body.value_text)
|
||||
unit = resolve_unit_from_type(t.get("default_unit"))
|
||||
extra = body.extra if body.extra is not None else {}
|
||||
|
||||
cur.execute(
|
||||
@@ -186,9 +197,9 @@ def create_profile_reference_value(
|
||||
vnum,
|
||||
vtxt,
|
||||
unit,
|
||||
body.source,
|
||||
body.confidence,
|
||||
body.method,
|
||||
src,
|
||||
conf,
|
||||
meth,
|
||||
body.notes,
|
||||
Json(extra),
|
||||
),
|
||||
@@ -245,7 +256,7 @@ def update_profile_reference_value(
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT v.*, rt.default_unit
|
||||
SELECT v.*, rt.default_unit, rt.value_data_type, rt.validation_rules
|
||||
FROM profile_reference_values v
|
||||
JOIN reference_value_types rt ON rt.id = v.reference_value_type_id
|
||||
WHERE v.id = %s AND v.profile_id = %s
|
||||
@@ -257,43 +268,44 @@ def update_profile_reference_value(
|
||||
raise HTTPException(404, "Eintrag nicht gefunden")
|
||||
cur_row = r2d(row)
|
||||
|
||||
vdt = (cur_row.get("value_data_type") or "decimal").strip().lower()
|
||||
rules = cur_row.get("validation_rules") or {}
|
||||
|
||||
new_ed = patch.get("effective_date", cur_row["effective_date"])
|
||||
if hasattr(new_ed, "isoformat"):
|
||||
new_ed = new_ed.isoformat()
|
||||
|
||||
new_num = patch["value_numeric"] if "value_numeric" in patch else cur_row.get("value_numeric")
|
||||
new_txt_raw = patch["value_text"] if "value_text" in patch else cur_row.get("value_text")
|
||||
new_txt = (new_txt_raw.strip() if isinstance(new_txt_raw, str) else new_txt_raw) or None
|
||||
if new_num is not None and isinstance(new_num, Decimal):
|
||||
new_num = float(new_num)
|
||||
vn = patch["value_numeric"] if "value_numeric" in patch else cur_row.get("value_numeric")
|
||||
vt_raw = patch["value_text"] if "value_text" in patch else cur_row.get("value_text")
|
||||
if vn is not None and isinstance(vn, Decimal):
|
||||
vn = float(vn)
|
||||
|
||||
if new_num is None and not new_txt:
|
||||
raise HTTPException(400, "Mindestens value_numeric oder value_text erforderlich.")
|
||||
vnum, vtxt = validate_value_for_data_type(vdt, rules, vn, vt_raw)
|
||||
|
||||
if "unit" in patch:
|
||||
new_unit = str(patch["unit"]).strip()
|
||||
if new_unit == "":
|
||||
default_u = (cur_row.get("default_unit") or "").strip()
|
||||
nu = default_u or cur_row["unit"]
|
||||
else:
|
||||
nu = new_unit
|
||||
unit = resolve_unit_from_type(cur_row.get("default_unit"))
|
||||
|
||||
if "source" in patch:
|
||||
src = validate_meta_source(patch["source"])
|
||||
else:
|
||||
nu = cur_row["unit"]
|
||||
if not nu:
|
||||
raise HTTPException(400, "Einheit darf nicht leer sein.")
|
||||
src = validate_meta_source(cur_row.get("source"))
|
||||
if "method" in patch:
|
||||
meth = validate_meta_method(patch["method"])
|
||||
else:
|
||||
meth = validate_meta_method(cur_row.get("method"))
|
||||
if "confidence" in patch:
|
||||
conf = validate_meta_confidence(patch["confidence"])
|
||||
else:
|
||||
conf = validate_meta_confidence(cur_row.get("confidence"))
|
||||
|
||||
updates: dict[str, Any] = {
|
||||
"effective_date": new_ed,
|
||||
"value_numeric": new_num,
|
||||
"value_text": new_txt,
|
||||
"unit": nu,
|
||||
"value_numeric": vnum,
|
||||
"value_text": vtxt,
|
||||
"unit": unit,
|
||||
"source": src,
|
||||
"method": meth,
|
||||
"confidence": conf,
|
||||
}
|
||||
if "source" in patch:
|
||||
updates["source"] = patch["source"]
|
||||
if "confidence" in patch:
|
||||
updates["confidence"] = patch["confidence"]
|
||||
if "method" in patch:
|
||||
updates["method"] = patch["method"]
|
||||
if "notes" in patch:
|
||||
updates["notes"] = patch["notes"]
|
||||
if "extra" in patch:
|
||||
|
||||
Reference in new issue
Block a user