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
@@ -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