All checks were successful
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Successful in 1m6s
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 21s
Test Suite / playwright-smoke (push) Successful in 14s
Schließt den zweiten OM-Slice entlang der Roadmap: neue Entitäten parallel im Vorhaben, erweiterte Action-Status/Fälligkeit und Attention-Regeln 7–9. Co-authored-by: Cursor <cursoragent@cursor.com>
266 lines
7.7 KiB
Python
266 lines
7.7 KiB
Python
"""Decision service — tenant-scoped CRUD (AP0.9c)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any, Literal, Optional
|
|
|
|
from psycopg2.extras import RealDictCursor
|
|
|
|
from db import get_connection
|
|
from services.audit import log_audit
|
|
from services.initiatives import get_initiative
|
|
|
|
DecisionStatus = Literal["proposed", "decided", "superseded"]
|
|
|
|
DECISION_STATUSES = frozenset({"proposed", "decided", "superseded"})
|
|
|
|
_DECISION_COLUMNS = """
|
|
id, tenant_id, initiative_id, title, description, status, outcome,
|
|
decided_by_actor_id, created_at, updated_at
|
|
"""
|
|
|
|
|
|
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
|
result = dict(row)
|
|
for key in ("id", "tenant_id", "initiative_id", "decided_by_actor_id"):
|
|
if result.get(key):
|
|
result[key] = str(result[key])
|
|
for ts_key in ("created_at", "updated_at"):
|
|
if result.get(ts_key):
|
|
result[ts_key] = result[ts_key].isoformat()
|
|
return result
|
|
|
|
|
|
def _validate_status(status: str) -> None:
|
|
if status not in DECISION_STATUSES:
|
|
raise ValueError(f"Ungültiger Decision-Status: {status}")
|
|
|
|
|
|
def _actor_in_tenant(*, tenant_id: str, actor_id: str) -> bool:
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute(
|
|
"SELECT 1 FROM actors WHERE id = %s AND tenant_id = %s AND is_active = TRUE",
|
|
(actor_id, tenant_id),
|
|
)
|
|
return cur.fetchone() is not None
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def create_decision(
|
|
*,
|
|
tenant_id: str,
|
|
initiative_id: str,
|
|
title: str,
|
|
description: str = "",
|
|
status: DecisionStatus = "proposed",
|
|
outcome: str = "",
|
|
decided_by_actor_id: Optional[str] = None,
|
|
user_id: Optional[str] = None,
|
|
) -> dict[str, Any]:
|
|
title = title.strip()
|
|
if not title:
|
|
raise ValueError("Titel ist erforderlich")
|
|
_validate_status(status)
|
|
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
|
raise ValueError("Initiative nicht gefunden")
|
|
if decided_by_actor_id and not _actor_in_tenant(
|
|
tenant_id=tenant_id, actor_id=decided_by_actor_id
|
|
):
|
|
raise ValueError("Actor gehört nicht zum Tenant")
|
|
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
cur.execute(
|
|
f"""
|
|
INSERT INTO decisions (
|
|
tenant_id, initiative_id, title, description, status, outcome,
|
|
decided_by_actor_id
|
|
)
|
|
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
|
RETURNING {_DECISION_COLUMNS}
|
|
""",
|
|
(
|
|
tenant_id,
|
|
initiative_id,
|
|
title,
|
|
description,
|
|
status,
|
|
outcome,
|
|
decided_by_actor_id,
|
|
),
|
|
)
|
|
row = _serialize_row(dict(cur.fetchone()))
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
log_audit(
|
|
"decision.created",
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
details={"decision_id": row["id"], "initiative_id": initiative_id},
|
|
)
|
|
return row
|
|
|
|
|
|
def list_decisions_for_initiative(
|
|
*, tenant_id: str, initiative_id: str
|
|
) -> list[dict[str, Any]]:
|
|
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
|
raise ValueError("Initiative nicht gefunden")
|
|
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
cur.execute(
|
|
f"""
|
|
SELECT {_DECISION_COLUMNS}
|
|
FROM decisions
|
|
WHERE tenant_id = %s AND initiative_id = %s
|
|
ORDER BY updated_at DESC, title
|
|
""",
|
|
(tenant_id, initiative_id),
|
|
)
|
|
return [_serialize_row(dict(r)) for r in cur.fetchall()]
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def get_decision(*, tenant_id: str, decision_id: str) -> Optional[dict[str, Any]]:
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
cur.execute(
|
|
f"""
|
|
SELECT {_DECISION_COLUMNS}
|
|
FROM decisions
|
|
WHERE id = %s AND tenant_id = %s
|
|
""",
|
|
(decision_id, tenant_id),
|
|
)
|
|
row = cur.fetchone()
|
|
return _serialize_row(dict(row)) if row else None
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def update_decision(
|
|
*,
|
|
tenant_id: str,
|
|
decision_id: str,
|
|
user_id: Optional[str] = None,
|
|
title: Optional[str] = None,
|
|
description: Optional[str] = None,
|
|
status: Optional[DecisionStatus] = None,
|
|
outcome: Optional[str] = None,
|
|
decided_by_actor_id: Optional[str] = None,
|
|
) -> Optional[dict[str, Any]]:
|
|
existing = get_decision(tenant_id=tenant_id, decision_id=decision_id)
|
|
if not existing:
|
|
return None
|
|
|
|
old_status = existing["status"]
|
|
updates: list[str] = []
|
|
params: list[Any] = []
|
|
|
|
if title is not None:
|
|
title = title.strip()
|
|
if not title:
|
|
raise ValueError("Titel ist erforderlich")
|
|
updates.append("title = %s")
|
|
params.append(title)
|
|
if description is not None:
|
|
updates.append("description = %s")
|
|
params.append(description)
|
|
if status is not None:
|
|
_validate_status(status)
|
|
updates.append("status = %s")
|
|
params.append(status)
|
|
if outcome is not None:
|
|
updates.append("outcome = %s")
|
|
params.append(outcome)
|
|
if decided_by_actor_id is not None:
|
|
if decided_by_actor_id and not _actor_in_tenant(
|
|
tenant_id=tenant_id, actor_id=decided_by_actor_id
|
|
):
|
|
raise ValueError("Actor gehört nicht zum Tenant")
|
|
updates.append("decided_by_actor_id = %s")
|
|
params.append(decided_by_actor_id or None)
|
|
|
|
if not updates:
|
|
return existing
|
|
|
|
updates.append("updated_at = NOW()")
|
|
params.extend([decision_id, tenant_id])
|
|
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
cur.execute(
|
|
f"""
|
|
UPDATE decisions
|
|
SET {", ".join(updates)}
|
|
WHERE id = %s AND tenant_id = %s
|
|
RETURNING {_DECISION_COLUMNS}
|
|
""",
|
|
params,
|
|
)
|
|
row = cur.fetchone()
|
|
if not row:
|
|
return None
|
|
result = _serialize_row(dict(row))
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
log_audit(
|
|
"decision.updated",
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
details={"decision_id": decision_id},
|
|
)
|
|
if status is not None and status != old_status:
|
|
log_audit(
|
|
"decision.status_changed",
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
details={
|
|
"decision_id": decision_id,
|
|
"from_status": old_status,
|
|
"to_status": status,
|
|
},
|
|
)
|
|
return result
|
|
|
|
|
|
def delete_decision(
|
|
*,
|
|
tenant_id: str,
|
|
decision_id: str,
|
|
user_id: Optional[str] = None,
|
|
) -> bool:
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute(
|
|
"DELETE FROM decisions WHERE id = %s AND tenant_id = %s RETURNING id",
|
|
(decision_id, tenant_id),
|
|
)
|
|
deleted = cur.fetchone() is not None
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
if deleted:
|
|
log_audit(
|
|
"decision.deleted",
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
details={"decision_id": decision_id},
|
|
)
|
|
return deleted
|