Some checks failed
Deploy Development / deploy (push) Successful in 33s
Test Suite / pytest-backend (push) Failing after 28s
Test Suite / k6 /api/health Baseline (push) Has been skipped
Test Suite / playwright-smoke (push) Has been skipped
Test Suite / lint-backend (push) Successful in 7s
Test Suite / compose-smoke (push) Has been skipped
399 lines
12 KiB
Python
399 lines
12 KiB
Python
"""Action (Maßnahme) service — tenant-scoped CRUD, assignments, open actions."""
|
|
|
|
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 PRIORITIES, get_initiative
|
|
|
|
ActionStatus = Literal["open", "in_progress", "blocked", "done", "discarded"]
|
|
|
|
ACTION_STATUSES = frozenset({"open", "in_progress", "blocked", "done", "discarded"})
|
|
OPEN_ACTION_STATUSES = frozenset({"open", "in_progress", "blocked"})
|
|
|
|
|
|
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
|
result = dict(row)
|
|
for key in ("id", "tenant_id", "initiative_id", "owner_actor_id"):
|
|
if result.get(key):
|
|
result[key] = str(result[key])
|
|
if result.get("created_at"):
|
|
result["created_at"] = result["created_at"].isoformat()
|
|
if result.get("updated_at"):
|
|
result["updated_at"] = result["updated_at"].isoformat()
|
|
return result
|
|
|
|
|
|
def _validate_action_status(status: str) -> None:
|
|
if status not in ACTION_STATUSES:
|
|
raise ValueError(f"Ungültiger Action-Status: {status}")
|
|
|
|
|
|
def _validate_priority(priority: str) -> None:
|
|
if priority not in PRIORITIES:
|
|
raise ValueError(f"Ungültige Priorität: {priority}")
|
|
|
|
|
|
def _load_assignments(*, tenant_id: str, action_ids: list[str]) -> dict[str, list[str]]:
|
|
if not action_ids:
|
|
return {}
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
cur.execute(
|
|
"""
|
|
SELECT action_id, actor_id
|
|
FROM action_assignments
|
|
WHERE tenant_id = %s AND action_id = ANY(%s::uuid[])
|
|
ORDER BY created_at
|
|
""",
|
|
(tenant_id, action_ids),
|
|
)
|
|
result: dict[str, list[str]] = {aid: [] for aid in action_ids}
|
|
for row in cur.fetchall():
|
|
result[str(row["action_id"])].append(str(row["actor_id"]))
|
|
return result
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def _attach_assignments(
|
|
actions: list[dict[str, Any]], *, tenant_id: str
|
|
) -> list[dict[str, Any]]:
|
|
if not actions:
|
|
return actions
|
|
action_ids = [a["id"] for a in actions]
|
|
assignments = _load_assignments(tenant_id=tenant_id, action_ids=action_ids)
|
|
for action in actions:
|
|
action["assigned_actor_ids"] = assignments.get(action["id"], [])
|
|
return actions
|
|
|
|
|
|
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_action(
|
|
*,
|
|
tenant_id: str,
|
|
initiative_id: str,
|
|
title: str,
|
|
description: str = "",
|
|
status: ActionStatus = "open",
|
|
priority: str = "normal",
|
|
assigned_actor_ids: Optional[list[str]] = None,
|
|
user_id: Optional[str] = None,
|
|
) -> dict[str, Any]:
|
|
title = title.strip()
|
|
if not title:
|
|
raise ValueError("Titel ist erforderlich")
|
|
_validate_action_status(status)
|
|
_validate_priority(priority)
|
|
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
|
raise ValueError("Initiative nicht gefunden")
|
|
|
|
assigned_actor_ids = assigned_actor_ids or []
|
|
for actor_id in assigned_actor_ids:
|
|
if not _actor_in_tenant(tenant_id=tenant_id, actor_id=actor_id):
|
|
raise ValueError(f"Actor {actor_id} gehört nicht zum Tenant")
|
|
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO actions (
|
|
tenant_id, initiative_id, title, description, status, priority
|
|
)
|
|
VALUES (%s, %s, %s, %s, %s, %s)
|
|
RETURNING id, tenant_id, initiative_id, title, description,
|
|
status, priority, created_at, updated_at
|
|
""",
|
|
(tenant_id, initiative_id, title, description, status, priority),
|
|
)
|
|
row = _serialize_row(dict(cur.fetchone()))
|
|
for actor_id in assigned_actor_ids:
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO action_assignments (tenant_id, action_id, actor_id)
|
|
VALUES (%s, %s, %s)
|
|
""",
|
|
(tenant_id, row["id"], actor_id),
|
|
)
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
row["assigned_actor_ids"] = assigned_actor_ids
|
|
log_audit(
|
|
"action.created",
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
details={
|
|
"action_id": row["id"],
|
|
"initiative_id": initiative_id,
|
|
"title": title,
|
|
"status": status,
|
|
"assigned_actor_ids": assigned_actor_ids,
|
|
},
|
|
)
|
|
return row
|
|
|
|
|
|
def list_actions_for_initiative(
|
|
*, tenant_id: str, initiative_id: str
|
|
) -> list[dict[str, Any]]:
|
|
if not get_initiative(tenant_id=tenant_id, initiative_id=initiative_id):
|
|
return []
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
cur.execute(
|
|
"""
|
|
SELECT id, tenant_id, initiative_id, title, description,
|
|
status, priority, created_at, updated_at
|
|
FROM actions
|
|
WHERE tenant_id = %s AND initiative_id = %s
|
|
ORDER BY updated_at DESC, title
|
|
""",
|
|
(tenant_id, initiative_id),
|
|
)
|
|
actions = [_serialize_row(dict(row)) for row in cur.fetchall()]
|
|
finally:
|
|
conn.close()
|
|
return _attach_assignments(actions, tenant_id=tenant_id)
|
|
|
|
|
|
def get_action(*, tenant_id: str, action_id: str) -> Optional[dict[str, Any]]:
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
cur.execute(
|
|
"""
|
|
SELECT id, tenant_id, initiative_id, title, description,
|
|
status, priority, created_at, updated_at
|
|
FROM actions
|
|
WHERE id = %s AND tenant_id = %s
|
|
""",
|
|
(action_id, tenant_id),
|
|
)
|
|
row = cur.fetchone()
|
|
if not row:
|
|
return None
|
|
action = _serialize_row(dict(row))
|
|
finally:
|
|
conn.close()
|
|
return _attach_assignments([action], tenant_id=tenant_id)[0]
|
|
|
|
|
|
def update_action(
|
|
*,
|
|
tenant_id: str,
|
|
action_id: str,
|
|
user_id: Optional[str] = None,
|
|
title: Optional[str] = None,
|
|
description: Optional[str] = None,
|
|
status: Optional[ActionStatus] = None,
|
|
priority: Optional[str] = None,
|
|
) -> Optional[dict[str, Any]]:
|
|
existing = get_action(tenant_id=tenant_id, action_id=action_id)
|
|
if not existing:
|
|
return None
|
|
|
|
updates: list[str] = []
|
|
params: list[Any] = []
|
|
old_status = existing["status"]
|
|
|
|
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_action_status(status)
|
|
updates.append("status = %s")
|
|
params.append(status)
|
|
if priority is not None:
|
|
_validate_priority(priority)
|
|
updates.append("priority = %s")
|
|
params.append(priority)
|
|
|
|
if not updates:
|
|
return existing
|
|
|
|
updates.append("updated_at = NOW()")
|
|
params.extend([action_id, tenant_id])
|
|
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
cur.execute(
|
|
f"""
|
|
UPDATE actions
|
|
SET {", ".join(updates)}
|
|
WHERE id = %s AND tenant_id = %s
|
|
RETURNING id, tenant_id, initiative_id, title, description,
|
|
status, priority, created_at, updated_at
|
|
""",
|
|
params,
|
|
)
|
|
row = cur.fetchone()
|
|
if not row:
|
|
return None
|
|
result = _serialize_row(dict(row))
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
result = get_action(tenant_id=tenant_id, action_id=action_id)
|
|
assert result is not None
|
|
|
|
log_audit(
|
|
"action.updated",
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
details={"action_id": action_id, "fields": updates},
|
|
)
|
|
if status is not None and status != old_status:
|
|
log_audit(
|
|
"action.status_changed",
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
details={
|
|
"action_id": action_id,
|
|
"from_status": old_status,
|
|
"to_status": status,
|
|
},
|
|
)
|
|
return result
|
|
|
|
|
|
def set_action_assignments(
|
|
*,
|
|
tenant_id: str,
|
|
action_id: str,
|
|
actor_ids: list[str],
|
|
user_id: Optional[str] = None,
|
|
) -> Optional[dict[str, Any]]:
|
|
existing = get_action(tenant_id=tenant_id, action_id=action_id)
|
|
if not existing:
|
|
return None
|
|
|
|
unique_actor_ids = list(dict.fromkeys(actor_ids))
|
|
for actor_id in unique_actor_ids:
|
|
if not _actor_in_tenant(tenant_id=tenant_id, actor_id=actor_id):
|
|
raise ValueError(f"Actor {actor_id} gehört nicht zum Tenant")
|
|
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute(
|
|
"DELETE FROM action_assignments WHERE action_id = %s AND tenant_id = %s",
|
|
(action_id, tenant_id),
|
|
)
|
|
for actor_id in unique_actor_ids:
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO action_assignments (tenant_id, action_id, actor_id)
|
|
VALUES (%s, %s, %s)
|
|
""",
|
|
(tenant_id, action_id, actor_id),
|
|
)
|
|
cur.execute(
|
|
"UPDATE actions SET updated_at = NOW() WHERE id = %s AND tenant_id = %s",
|
|
(action_id, tenant_id),
|
|
)
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
log_audit(
|
|
"action.assigned",
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
details={
|
|
"action_id": action_id,
|
|
"actor_ids": unique_actor_ids,
|
|
"previous_actor_ids": existing.get("assigned_actor_ids", []),
|
|
},
|
|
)
|
|
return get_action(tenant_id=tenant_id, action_id=action_id)
|
|
|
|
|
|
def delete_action(
|
|
*,
|
|
tenant_id: str,
|
|
action_id: str,
|
|
user_id: Optional[str] = None,
|
|
) -> bool:
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute(
|
|
"DELETE FROM actions WHERE id = %s AND tenant_id = %s RETURNING id",
|
|
(action_id, tenant_id),
|
|
)
|
|
deleted = cur.fetchone() is not None
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
if deleted:
|
|
log_audit(
|
|
"action.deleted",
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
details={"action_id": action_id},
|
|
)
|
|
return deleted
|
|
|
|
|
|
def list_open_actions_for_actor(
|
|
*, tenant_id: str, actor_id: str
|
|
) -> list[dict[str, Any]]:
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
cur.execute(
|
|
"""
|
|
SELECT a.id, a.tenant_id, a.initiative_id, a.title, a.description,
|
|
a.status, a.priority, a.created_at, a.updated_at,
|
|
i.title AS initiative_title
|
|
FROM actions a
|
|
JOIN action_assignments aa ON aa.action_id = a.id AND aa.tenant_id = a.tenant_id
|
|
JOIN initiatives i ON i.id = a.initiative_id AND i.tenant_id = a.tenant_id
|
|
WHERE a.tenant_id = %s
|
|
AND aa.actor_id = %s
|
|
AND a.status = ANY(%s)
|
|
ORDER BY
|
|
CASE a.priority
|
|
WHEN 'high' THEN 0
|
|
WHEN 'normal' THEN 1
|
|
WHEN 'low' THEN 2
|
|
END,
|
|
a.updated_at DESC
|
|
""",
|
|
(tenant_id, actor_id, list(OPEN_ACTION_STATUSES)),
|
|
)
|
|
actions = [_serialize_row(dict(row)) for row in cur.fetchall()]
|
|
finally:
|
|
conn.close()
|
|
return _attach_assignments(actions, tenant_id=tenant_id)
|