AP1.10b/10c: Entity Field System mit dynamischen Vorhaben-Zusatzfeldern.
Deploy Development / deploy (push) Successful in 44s
Test Suite / pytest-backend (push) Successful in 1m54s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Test Suite / playwright-smoke (push) Successful in 15s
Deploy Development / deploy (push) Successful in 44s
Test Suite / pytest-backend (push) Successful in 1m54s
Test Suite / lint-backend (push) Successful in 2s
Test Suite / compose-smoke (push) Has been skipped
Test Suite / k6 /api/health Baseline (push) Successful in 19s
Test Suite / playwright-smoke (push) Successful in 15s
EFS-Tabellen, Registry-Sync und Fields-API ermöglichen archetyp-spezifische Felder; Frontend rendert sie im Profil-Modal per FieldRenderer. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
408050bcb8
commit
a6fc86025c
23 files changed
+1107
-20
No files matched your search
@@ -0,0 +1,20 @@
|
||||
from entity_fields.definitions import FIELD_DEFINITIONS
|
||||
from entity_fields.service import (
|
||||
get_entity_field_values,
|
||||
get_initiative_archetype_key,
|
||||
list_field_definitions,
|
||||
patch_entity_field_values,
|
||||
)
|
||||
from entity_fields.sync import sync_entity_field_registry_to_db
|
||||
from entity_fields.validation import normalize_field_value, validate_required_fields
|
||||
|
||||
__all__ = [
|
||||
"FIELD_DEFINITIONS",
|
||||
"get_entity_field_values",
|
||||
"get_initiative_archetype_key",
|
||||
"list_field_definitions",
|
||||
"normalize_field_value",
|
||||
"patch_entity_field_values",
|
||||
"sync_entity_field_registry_to_db",
|
||||
"validate_required_fields",
|
||||
]
|
||||
@@ -0,0 +1,48 @@
|
||||
"""System-Felddefinitionen (Seed) — AP1.10b."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
FIELD_DEFINITIONS: tuple[dict[str, Any], ...] = (
|
||||
{
|
||||
"archetype_key": "initiative.program",
|
||||
"field_key": "stakeholder_map",
|
||||
"field_type": "longtext",
|
||||
"label": "Stakeholder-Übersicht",
|
||||
"required": False,
|
||||
"searchable": True,
|
||||
"sort_order": 10,
|
||||
"validation_json": {},
|
||||
},
|
||||
{
|
||||
"archetype_key": "initiative.program",
|
||||
"field_key": "success_criteria",
|
||||
"field_type": "longtext",
|
||||
"label": "Erfolgskriterien",
|
||||
"required": False,
|
||||
"searchable": True,
|
||||
"sort_order": 20,
|
||||
"validation_json": {},
|
||||
},
|
||||
{
|
||||
"archetype_key": "initiative.product",
|
||||
"field_key": "release_theme",
|
||||
"field_type": "text",
|
||||
"label": "Release-Thema",
|
||||
"required": False,
|
||||
"searchable": True,
|
||||
"sort_order": 10,
|
||||
"validation_json": {},
|
||||
},
|
||||
{
|
||||
"archetype_key": "initiative.product",
|
||||
"field_key": "metrics",
|
||||
"field_type": "longtext",
|
||||
"label": "Metriken / KPIs",
|
||||
"required": False,
|
||||
"searchable": True,
|
||||
"sort_order": 20,
|
||||
"validation_json": {},
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,206 @@
|
||||
"""Entity Field System — Lesen/Schreiben dynamischer Feldwerte — AP1.10b/10c."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from psycopg2.extras import Json, RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from entity_fields.validation import normalize_field_value, validate_required_fields
|
||||
|
||||
|
||||
def _serialize_definition(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
if result.get("id"):
|
||||
result["id"] = str(result["id"])
|
||||
validation = result.get("validation_json")
|
||||
if validation is None:
|
||||
result["validation_json"] = {}
|
||||
return result
|
||||
|
||||
|
||||
def _api_value_from_row(row: dict[str, Any], field_type: str) -> Any:
|
||||
if field_type == "number":
|
||||
if row.get("value_number") is not None:
|
||||
return float(row["value_number"])
|
||||
return None
|
||||
if field_type == "boolean":
|
||||
if row.get("value_boolean") is not None:
|
||||
return bool(row["value_boolean"])
|
||||
return False
|
||||
if field_type == "date":
|
||||
value_date = row.get("value_date")
|
||||
if value_date is not None:
|
||||
return value_date.isoformat()
|
||||
return None
|
||||
text = row.get("value_text") or ""
|
||||
return text
|
||||
|
||||
|
||||
def list_field_definitions(
|
||||
*,
|
||||
archetype_key: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, archetype_key, field_key, field_type, label,
|
||||
required, searchable, sort_order, validation_json
|
||||
FROM field_definitions
|
||||
WHERE archetype_key = %s
|
||||
ORDER BY sort_order ASC, field_key ASC
|
||||
""",
|
||||
(archetype_key,),
|
||||
)
|
||||
return [_serialize_definition(dict(row)) for row in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_entity_field_values(
|
||||
*,
|
||||
tenant_id: str,
|
||||
entity_type: str,
|
||||
entity_id: str,
|
||||
definitions: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
if not definitions:
|
||||
return {}
|
||||
|
||||
field_keys = [item["field_key"] for item in definitions]
|
||||
type_by_key = {item["field_key"]: item["field_type"] for item in definitions}
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT field_key, value_text, value_number, value_boolean, value_date
|
||||
FROM field_values
|
||||
WHERE tenant_id = %s
|
||||
AND entity_type = %s
|
||||
AND entity_id = %s
|
||||
AND field_key = ANY(%s)
|
||||
""",
|
||||
(tenant_id, entity_type, entity_id, field_keys),
|
||||
)
|
||||
rows = {row["field_key"]: dict(row) for row in cur.fetchall()}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
result: dict[str, Any] = {}
|
||||
for field_key in field_keys:
|
||||
row = rows.get(field_key)
|
||||
if row is None:
|
||||
field_type = type_by_key[field_key]
|
||||
if field_type == "boolean":
|
||||
result[field_key] = False
|
||||
else:
|
||||
result[field_key] = None if field_type in {"number", "date"} else ""
|
||||
else:
|
||||
result[field_key] = _api_value_from_row(row, type_by_key[field_key])
|
||||
return result
|
||||
|
||||
|
||||
def patch_entity_field_values(
|
||||
*,
|
||||
tenant_id: str,
|
||||
entity_type: str,
|
||||
entity_id: str,
|
||||
definitions: list[dict[str, Any]],
|
||||
values: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
if not values:
|
||||
return get_entity_field_values(
|
||||
tenant_id=tenant_id,
|
||||
entity_type=entity_type,
|
||||
entity_id=entity_id,
|
||||
definitions=definitions,
|
||||
)
|
||||
|
||||
allowed_keys = {item["field_key"] for item in definitions}
|
||||
unknown = sorted(set(values.keys()) - allowed_keys)
|
||||
if unknown:
|
||||
raise ValueError(f"Unbekannte Felder: {', '.join(unknown)}")
|
||||
|
||||
definition_by_key = {item["field_key"]: item for item in definitions}
|
||||
merged = get_entity_field_values(
|
||||
tenant_id=tenant_id,
|
||||
entity_type=entity_type,
|
||||
entity_id=entity_id,
|
||||
definitions=definitions,
|
||||
)
|
||||
merged.update(values)
|
||||
validate_required_fields(definitions=definitions, values=merged)
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
for field_key, raw_value in values.items():
|
||||
definition = definition_by_key[field_key]
|
||||
normalized = normalize_field_value(
|
||||
field_type=definition["field_type"],
|
||||
raw_value=raw_value,
|
||||
validation_json=definition.get("validation_json"),
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO field_values (
|
||||
tenant_id, entity_type, entity_id, field_key,
|
||||
value_json, value_text, value_number, value_boolean, value_date
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
ON CONFLICT (tenant_id, entity_type, entity_id, field_key) DO UPDATE SET
|
||||
value_json = EXCLUDED.value_json,
|
||||
value_text = EXCLUDED.value_text,
|
||||
value_number = EXCLUDED.value_number,
|
||||
value_boolean = EXCLUDED.value_boolean,
|
||||
value_date = EXCLUDED.value_date,
|
||||
updated_at = NOW()
|
||||
""",
|
||||
(
|
||||
tenant_id,
|
||||
entity_type,
|
||||
entity_id,
|
||||
field_key,
|
||||
Json(normalized["value_json"]) if normalized["value_json"] is not None else None,
|
||||
normalized["value_text"],
|
||||
normalized["value_number"],
|
||||
normalized["value_boolean"],
|
||||
normalized["value_date"],
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
return get_entity_field_values(
|
||||
tenant_id=tenant_id,
|
||||
entity_type=entity_type,
|
||||
entity_id=entity_id,
|
||||
definitions=definitions,
|
||||
)
|
||||
|
||||
|
||||
def get_initiative_archetype_key(*, tenant_id: str, initiative_id: str) -> Optional[str]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT archetype_key
|
||||
FROM initiatives
|
||||
WHERE tenant_id = %s AND id = %s
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return row[0] if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Sync Entity-Archetypen und Felddefinitionen in PostgreSQL — AP1.10b."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from db import get_connection
|
||||
from entity_archetypes.registry import INITIATIVE_ARCHETYPES
|
||||
from entity_fields.definitions import FIELD_DEFINITIONS
|
||||
|
||||
|
||||
def sync_entity_field_registry_to_db() -> int:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
for archetype in INITIATIVE_ARCHETYPES:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO entity_archetypes (
|
||||
archetype_key, entity_type, label, description, is_system
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
ON CONFLICT (archetype_key) DO UPDATE SET
|
||||
entity_type = EXCLUDED.entity_type,
|
||||
label = EXCLUDED.label,
|
||||
description = EXCLUDED.description,
|
||||
is_system = EXCLUDED.is_system,
|
||||
updated_at = NOW()
|
||||
""",
|
||||
(
|
||||
archetype["key"],
|
||||
archetype["entity_type"],
|
||||
archetype["label"],
|
||||
archetype["description"],
|
||||
archetype["is_system"],
|
||||
),
|
||||
)
|
||||
|
||||
for field_def in FIELD_DEFINITIONS:
|
||||
validation_json = field_def.get("validation_json") or {}
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO field_definitions (
|
||||
archetype_key, field_key, field_type, label,
|
||||
required, searchable, sort_order, validation_json
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s::jsonb)
|
||||
ON CONFLICT (archetype_key, field_key) DO UPDATE SET
|
||||
field_type = EXCLUDED.field_type,
|
||||
label = EXCLUDED.label,
|
||||
required = EXCLUDED.required,
|
||||
searchable = EXCLUDED.searchable,
|
||||
sort_order = EXCLUDED.sort_order,
|
||||
validation_json = EXCLUDED.validation_json,
|
||||
updated_at = NOW()
|
||||
""",
|
||||
(
|
||||
field_def["archetype_key"],
|
||||
field_def["field_key"],
|
||||
field_def["field_type"],
|
||||
field_def["label"],
|
||||
field_def["required"],
|
||||
field_def["searchable"],
|
||||
field_def["sort_order"],
|
||||
json.dumps(validation_json),
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
print(
|
||||
"[entity_fields] Sync OK — "
|
||||
f"{len(INITIATIVE_ARCHETYPES)} Archetyp(en), "
|
||||
f"{len(FIELD_DEFINITIONS)} Felddefinition(en)"
|
||||
)
|
||||
return 0
|
||||
except Exception as exc:
|
||||
conn.rollback()
|
||||
print(f"[entity_fields] Sync FAIL: {exc}")
|
||||
return 1
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Validierung dynamischer Feldwerte gegen Definitionen — AP1.10b/10c."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import date, datetime
|
||||
from typing import Any, Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
VALID_FIELD_TYPES = frozenset(
|
||||
{"text", "longtext", "number", "boolean", "date", "enum", "actor_ref", "url"}
|
||||
)
|
||||
|
||||
_URL_SCHEME_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9+.-]*:")
|
||||
|
||||
|
||||
def _parse_date(value: str) -> date:
|
||||
try:
|
||||
return date.fromisoformat(value)
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"Ungültiges Datum: {value}") from exc
|
||||
|
||||
|
||||
def _validate_url(value: str) -> None:
|
||||
if not value.strip():
|
||||
return
|
||||
parsed = urlparse(value.strip())
|
||||
if parsed.scheme and parsed.netloc:
|
||||
return
|
||||
if _URL_SCHEME_RE.match(value.strip()):
|
||||
return
|
||||
raise ValueError(f"Ungültige URL: {value}")
|
||||
|
||||
|
||||
def normalize_field_value(
|
||||
*,
|
||||
field_type: str,
|
||||
raw_value: Any,
|
||||
validation_json: Optional[dict[str, Any]] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Wert normalisieren und in DB-Spalten aufteilen."""
|
||||
validation_json = validation_json or {}
|
||||
|
||||
if field_type in {"text", "longtext", "url", "actor_ref", "enum"}:
|
||||
if raw_value is None:
|
||||
text = ""
|
||||
elif not isinstance(raw_value, str):
|
||||
raise ValueError(f"Feld erwartet Text, erhalten: {type(raw_value).__name__}")
|
||||
else:
|
||||
text = raw_value.strip()
|
||||
if field_type == "url" and text:
|
||||
_validate_url(text)
|
||||
if field_type == "enum" and text:
|
||||
options = validation_json.get("options") or []
|
||||
if options and text not in options:
|
||||
raise ValueError(f"Ungültiger Enum-Wert: {text}")
|
||||
return {
|
||||
"value_json": None,
|
||||
"value_text": text,
|
||||
"value_number": None,
|
||||
"value_boolean": None,
|
||||
"value_date": None,
|
||||
"api_value": text,
|
||||
}
|
||||
|
||||
if field_type == "number":
|
||||
if raw_value is None or raw_value == "":
|
||||
return {
|
||||
"value_json": None,
|
||||
"value_text": "",
|
||||
"value_number": None,
|
||||
"value_boolean": None,
|
||||
"value_date": None,
|
||||
"api_value": None,
|
||||
}
|
||||
try:
|
||||
number = float(raw_value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError(f"Ungültige Zahl: {raw_value}") from exc
|
||||
return {
|
||||
"value_json": None,
|
||||
"value_text": str(number),
|
||||
"value_number": number,
|
||||
"value_boolean": None,
|
||||
"value_date": None,
|
||||
"api_value": number,
|
||||
}
|
||||
|
||||
if field_type == "boolean":
|
||||
if raw_value is None:
|
||||
bool_val = False
|
||||
elif isinstance(raw_value, bool):
|
||||
bool_val = raw_value
|
||||
elif isinstance(raw_value, str):
|
||||
lowered = raw_value.strip().lower()
|
||||
if lowered in {"true", "1", "yes", "on"}:
|
||||
bool_val = True
|
||||
elif lowered in {"false", "0", "no", "off", ""}:
|
||||
bool_val = False
|
||||
else:
|
||||
raise ValueError(f"Ungültiger Boolean-Wert: {raw_value}")
|
||||
else:
|
||||
bool_val = bool(raw_value)
|
||||
return {
|
||||
"value_json": None,
|
||||
"value_text": "true" if bool_val else "false",
|
||||
"value_number": None,
|
||||
"value_boolean": bool_val,
|
||||
"value_date": None,
|
||||
"api_value": bool_val,
|
||||
}
|
||||
|
||||
if field_type == "date":
|
||||
if raw_value is None or raw_value == "":
|
||||
return {
|
||||
"value_json": None,
|
||||
"value_text": "",
|
||||
"value_number": None,
|
||||
"value_boolean": None,
|
||||
"value_date": None,
|
||||
"api_value": None,
|
||||
}
|
||||
if isinstance(raw_value, date) and not isinstance(raw_value, datetime):
|
||||
parsed = raw_value
|
||||
elif isinstance(raw_value, str):
|
||||
parsed = _parse_date(raw_value)
|
||||
else:
|
||||
raise ValueError(f"Ungültiges Datum: {raw_value}")
|
||||
iso = parsed.isoformat()
|
||||
return {
|
||||
"value_json": None,
|
||||
"value_text": iso,
|
||||
"value_number": None,
|
||||
"value_boolean": None,
|
||||
"value_date": parsed,
|
||||
"api_value": iso,
|
||||
}
|
||||
|
||||
raise ValueError(f"Unbekannter Feldtyp: {field_type}")
|
||||
|
||||
|
||||
def validate_required_fields(
|
||||
*,
|
||||
definitions: list[dict[str, Any]],
|
||||
values: dict[str, Any],
|
||||
) -> None:
|
||||
for definition in definitions:
|
||||
if not definition.get("required"):
|
||||
continue
|
||||
key = definition["field_key"]
|
||||
raw = values.get(key)
|
||||
if raw is None or (isinstance(raw, str) and not raw.strip()):
|
||||
raise ValueError(f"Pflichtfeld fehlt: {definition.get('label') or key}")
|
||||
Reference in new issue
Block a user