AP0.8: Operating Model Extension I (Attention, Blocker, Backlog, Milestone)
Deploy Development / deploy (push) Successful in 45s
Test Suite / pytest-backend (push) Successful in 58s
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 18s
Test Suite / playwright-smoke (push) Successful in 12s
Deploy Development / deploy (push) Successful in 45s
Test Suite / pytest-backend (push) Successful in 58s
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 18s
Test Suite / playwright-smoke (push) Successful in 12s
Schema 007, regelbasierte Attention/NextAction im Data Layer, CRUD fuer Blocker/Backlog/Meilensteine, Workspace-Widget und Initiative-Detail-Sektionen. 25 Capabilities. Tests fuer Remote-Pytest auf Pi angepasst (conftest Session-Guard). Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
6dd9dd4f62
commit
fe3bc4f057
39 files changed
+4333
-22
No files matched your search
@@ -0,0 +1,296 @@
|
||||
"""BacklogItem service — tenant-scoped CRUD + convert (AP0.8c)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from services.actions import create_action
|
||||
from services.audit import log_audit
|
||||
from services.initiatives import PRIORITIES, get_initiative
|
||||
|
||||
BacklogStatus = Literal["new", "triaged", "accepted", "rejected", "converted"]
|
||||
|
||||
BACKLOG_STATUSES = frozenset({"new", "triaged", "accepted", "rejected", "converted"})
|
||||
|
||||
|
||||
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in ("id", "tenant_id", "initiative_id", "converted_action_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_status(status: str) -> None:
|
||||
if status not in BACKLOG_STATUSES:
|
||||
raise ValueError(f"Ungültiger Backlog-Status: {status}")
|
||||
|
||||
|
||||
def _validate_priority(priority: str) -> None:
|
||||
if priority not in PRIORITIES:
|
||||
raise ValueError(f"Ungültige Priorität: {priority}")
|
||||
|
||||
|
||||
def create_backlog_item(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
title: str,
|
||||
description: str = "",
|
||||
status: BacklogStatus = "new",
|
||||
priority: str = "normal",
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
title = title.strip()
|
||||
if not title:
|
||||
raise ValueError("Titel ist erforderlich")
|
||||
_validate_status(status)
|
||||
_validate_priority(priority)
|
||||
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(
|
||||
"""
|
||||
INSERT INTO backlog_items (
|
||||
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, converted_action_id, created_at, updated_at
|
||||
""",
|
||||
(tenant_id, initiative_id, title, description, status, priority),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"backlog.created",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"backlog_item_id": row["id"], "initiative_id": initiative_id, "title": title},
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def list_backlog_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(
|
||||
"""
|
||||
SELECT id, tenant_id, initiative_id, title, description, status,
|
||||
priority, converted_action_id, created_at, updated_at
|
||||
FROM backlog_items
|
||||
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_backlog_item(*, tenant_id: str, backlog_item_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, converted_action_id, created_at, updated_at
|
||||
FROM backlog_items
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(backlog_item_id, tenant_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _serialize_row(dict(row)) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_backlog_item(
|
||||
*,
|
||||
tenant_id: str,
|
||||
backlog_item_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
description: Optional[str] = None,
|
||||
status: Optional[BacklogStatus] = None,
|
||||
priority: Optional[str] = None,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_backlog_item(tenant_id=tenant_id, backlog_item_id=backlog_item_id)
|
||||
if not existing:
|
||||
return None
|
||||
if existing["status"] == "converted":
|
||||
raise ValueError("Konvertiertes Backlog-Item kann nicht bearbeitet werden")
|
||||
|
||||
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 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([backlog_item_id, tenant_id])
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE backlog_items
|
||||
SET {", ".join(updates)}
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING id, tenant_id, initiative_id, title, description, status,
|
||||
priority, converted_action_id, created_at, updated_at
|
||||
""",
|
||||
params,
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
result = _serialize_row(dict(row))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"backlog.updated",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"backlog_item_id": backlog_item_id},
|
||||
)
|
||||
if status is not None and status != old_status:
|
||||
log_audit(
|
||||
"backlog.status_changed",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"backlog_item_id": backlog_item_id,
|
||||
"from_status": old_status,
|
||||
"to_status": status,
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def delete_backlog_item(
|
||||
*,
|
||||
tenant_id: str,
|
||||
backlog_item_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"DELETE FROM backlog_items WHERE id = %s AND tenant_id = %s RETURNING id",
|
||||
(backlog_item_id, tenant_id),
|
||||
)
|
||||
deleted = cur.fetchone() is not None
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if deleted:
|
||||
log_audit(
|
||||
"backlog.deleted",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"backlog_item_id": backlog_item_id},
|
||||
)
|
||||
return deleted
|
||||
|
||||
|
||||
def convert_backlog_to_action(
|
||||
*,
|
||||
tenant_id: str,
|
||||
backlog_item_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
assigned_actor_ids: Optional[list[str]] = None,
|
||||
) -> dict[str, Any]:
|
||||
existing = get_backlog_item(tenant_id=tenant_id, backlog_item_id=backlog_item_id)
|
||||
if not existing:
|
||||
raise ValueError("Backlog-Item nicht gefunden")
|
||||
if existing["status"] == "converted":
|
||||
raise ValueError("Backlog-Item wurde bereits konvertiert")
|
||||
if existing["status"] not in ("accepted", "triaged", "new"):
|
||||
raise ValueError("Backlog-Item kann in diesem Status nicht konvertiert werden")
|
||||
|
||||
action = create_action(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=existing["initiative_id"],
|
||||
title=existing["title"],
|
||||
description=existing["description"] or "",
|
||||
priority=existing["priority"],
|
||||
assigned_actor_ids=assigned_actor_ids or [],
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE backlog_items
|
||||
SET status = 'converted',
|
||||
converted_action_id = %s,
|
||||
updated_at = NOW()
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING id, tenant_id, initiative_id, title, description, status,
|
||||
priority, converted_action_id, created_at, updated_at
|
||||
""",
|
||||
(action["id"], backlog_item_id, tenant_id),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"backlog.converted_to_action",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"backlog_item_id": backlog_item_id,
|
||||
"action_id": action["id"],
|
||||
"initiative_id": existing["initiative_id"],
|
||||
},
|
||||
)
|
||||
return {"backlog_item": row, "action": action}
|
||||
@@ -0,0 +1,295 @@
|
||||
"""Blocker service — tenant-scoped CRUD (AP0.8b)."""
|
||||
|
||||
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
|
||||
|
||||
BlockerStatus = Literal["open", "in_progress", "resolved", "accepted_risk", "dismissed"]
|
||||
|
||||
BLOCKER_STATUSES = frozenset(
|
||||
{"open", "in_progress", "resolved", "accepted_risk", "dismissed"}
|
||||
)
|
||||
|
||||
|
||||
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in ("id", "tenant_id", "initiative_id", "action_id", "reported_by_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_status(status: str) -> None:
|
||||
if status not in BLOCKER_STATUSES:
|
||||
raise ValueError(f"Ungültiger Blocker-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 _action_in_initiative(*, tenant_id: str, initiative_id: str, action_id: str) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT 1 FROM actions
|
||||
WHERE id = %s AND tenant_id = %s AND initiative_id = %s
|
||||
""",
|
||||
(action_id, tenant_id, initiative_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def create_blocker(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
title: str,
|
||||
description: str = "",
|
||||
status: BlockerStatus = "open",
|
||||
action_id: Optional[str] = None,
|
||||
reported_by_actor_id: Optional[str] = None,
|
||||
user_id: Optional[str] = None,
|
||||
set_action_blocked: bool = False,
|
||||
) -> 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 action_id and not _action_in_initiative(
|
||||
tenant_id=tenant_id, initiative_id=initiative_id, action_id=action_id
|
||||
):
|
||||
raise ValueError("Maßnahme gehört nicht zum Vorhaben")
|
||||
if reported_by_actor_id and not _actor_in_tenant(
|
||||
tenant_id=tenant_id, actor_id=reported_by_actor_id
|
||||
):
|
||||
raise ValueError("Reporter-Actor gehört nicht zum Tenant")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO blockers (
|
||||
tenant_id, initiative_id, action_id, title, description,
|
||||
status, reported_by_actor_id
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id, tenant_id, initiative_id, action_id, title, description,
|
||||
status, reported_by_actor_id, created_at, updated_at
|
||||
""",
|
||||
(
|
||||
tenant_id,
|
||||
initiative_id,
|
||||
action_id,
|
||||
title,
|
||||
description,
|
||||
status,
|
||||
reported_by_actor_id,
|
||||
),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
if set_action_blocked and action_id:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE actions SET status = 'blocked', updated_at = NOW()
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(action_id, tenant_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"blocker.created",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"blocker_id": row["id"], "initiative_id": initiative_id, "title": title},
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def list_blockers_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(
|
||||
"""
|
||||
SELECT id, tenant_id, initiative_id, action_id, title, description,
|
||||
status, reported_by_actor_id, created_at, updated_at
|
||||
FROM blockers
|
||||
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_blocker(*, tenant_id: str, blocker_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, action_id, title, description,
|
||||
status, reported_by_actor_id, created_at, updated_at
|
||||
FROM blockers
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(blocker_id, tenant_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _serialize_row(dict(row)) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_blocker(
|
||||
*,
|
||||
tenant_id: str,
|
||||
blocker_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
description: Optional[str] = None,
|
||||
status: Optional[BlockerStatus] = None,
|
||||
action_id: Optional[str] = None,
|
||||
clear_action_id: bool = False,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_blocker(tenant_id=tenant_id, blocker_id=blocker_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 clear_action_id:
|
||||
updates.append("action_id = NULL")
|
||||
elif action_id is not None:
|
||||
if not _action_in_initiative(
|
||||
tenant_id=tenant_id,
|
||||
initiative_id=existing["initiative_id"],
|
||||
action_id=action_id,
|
||||
):
|
||||
raise ValueError("Maßnahme gehört nicht zum Vorhaben")
|
||||
updates.append("action_id = %s")
|
||||
params.append(action_id)
|
||||
|
||||
if not updates:
|
||||
return existing
|
||||
|
||||
updates.append("updated_at = NOW()")
|
||||
params.extend([blocker_id, tenant_id])
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE blockers
|
||||
SET {", ".join(updates)}
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING id, tenant_id, initiative_id, action_id, title, description,
|
||||
status, reported_by_actor_id, created_at, updated_at
|
||||
""",
|
||||
params,
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
result = _serialize_row(dict(row))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"blocker.updated",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"blocker_id": blocker_id},
|
||||
)
|
||||
if status is not None and status != old_status:
|
||||
log_audit(
|
||||
"blocker.status_changed",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"blocker_id": blocker_id,
|
||||
"from_status": old_status,
|
||||
"to_status": status,
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def delete_blocker(
|
||||
*,
|
||||
tenant_id: str,
|
||||
blocker_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"DELETE FROM blockers WHERE id = %s AND tenant_id = %s RETURNING id",
|
||||
(blocker_id, tenant_id),
|
||||
)
|
||||
deleted = cur.fetchone() is not None
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if deleted:
|
||||
log_audit(
|
||||
"blocker.deleted",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"blocker_id": blocker_id},
|
||||
)
|
||||
return deleted
|
||||
@@ -0,0 +1,242 @@
|
||||
"""Milestone service — tenant-scoped CRUD (AP0.8d)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
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
|
||||
|
||||
MilestoneStatus = Literal[
|
||||
"planned", "active", "at_risk", "reached", "moved", "discarded"
|
||||
]
|
||||
|
||||
MILESTONE_STATUSES = frozenset(
|
||||
{"planned", "active", "at_risk", "reached", "moved", "discarded"}
|
||||
)
|
||||
|
||||
|
||||
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in ("id", "tenant_id", "initiative_id"):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
if result.get("target_date"):
|
||||
result["target_date"] = (
|
||||
result["target_date"].isoformat()
|
||||
if hasattr(result["target_date"], "isoformat")
|
||||
else str(result["target_date"])
|
||||
)
|
||||
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_status(status: str) -> None:
|
||||
if status not in MILESTONE_STATUSES:
|
||||
raise ValueError(f"Ungültiger Meilenstein-Status: {status}")
|
||||
|
||||
|
||||
def create_milestone(
|
||||
*,
|
||||
tenant_id: str,
|
||||
initiative_id: str,
|
||||
title: str,
|
||||
goal_description: str = "",
|
||||
status: MilestoneStatus = "planned",
|
||||
target_date: Optional[date] = 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")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO milestones (
|
||||
tenant_id, initiative_id, title, goal_description, status, target_date
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
RETURNING id, tenant_id, initiative_id, title, goal_description, status,
|
||||
target_date, created_at, updated_at
|
||||
""",
|
||||
(tenant_id, initiative_id, title, goal_description, status, target_date),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"milestone.created",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"milestone_id": row["id"], "initiative_id": initiative_id, "title": title},
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def list_milestones_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(
|
||||
"""
|
||||
SELECT id, tenant_id, initiative_id, title, goal_description, status,
|
||||
target_date, created_at, updated_at
|
||||
FROM milestones
|
||||
WHERE tenant_id = %s AND initiative_id = %s
|
||||
ORDER BY target_date NULLS LAST, updated_at DESC, title
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
return [_serialize_row(dict(r)) for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_milestone(*, tenant_id: str, milestone_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, goal_description, status,
|
||||
target_date, created_at, updated_at
|
||||
FROM milestones
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
""",
|
||||
(milestone_id, tenant_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _serialize_row(dict(row)) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_milestone(
|
||||
*,
|
||||
tenant_id: str,
|
||||
milestone_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
goal_description: Optional[str] = None,
|
||||
status: Optional[MilestoneStatus] = None,
|
||||
target_date: Optional[date] = None,
|
||||
clear_target_date: bool = False,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
existing = get_milestone(tenant_id=tenant_id, milestone_id=milestone_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 goal_description is not None:
|
||||
updates.append("goal_description = %s")
|
||||
params.append(goal_description)
|
||||
if status is not None:
|
||||
_validate_status(status)
|
||||
updates.append("status = %s")
|
||||
params.append(status)
|
||||
if clear_target_date:
|
||||
updates.append("target_date = NULL")
|
||||
elif target_date is not None:
|
||||
updates.append("target_date = %s")
|
||||
params.append(target_date)
|
||||
|
||||
if not updates:
|
||||
return existing
|
||||
|
||||
updates.append("updated_at = NOW()")
|
||||
params.extend([milestone_id, tenant_id])
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE milestones
|
||||
SET {", ".join(updates)}
|
||||
WHERE id = %s AND tenant_id = %s
|
||||
RETURNING id, tenant_id, initiative_id, title, goal_description, status,
|
||||
target_date, created_at, updated_at
|
||||
""",
|
||||
params,
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
result = _serialize_row(dict(row))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"milestone.updated",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"milestone_id": milestone_id},
|
||||
)
|
||||
if status is not None and status != old_status:
|
||||
log_audit(
|
||||
"milestone.status_changed",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"milestone_id": milestone_id,
|
||||
"from_status": old_status,
|
||||
"to_status": status,
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def delete_milestone(
|
||||
*,
|
||||
tenant_id: str,
|
||||
milestone_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"DELETE FROM milestones WHERE id = %s AND tenant_id = %s RETURNING id",
|
||||
(milestone_id, tenant_id),
|
||||
)
|
||||
deleted = cur.fetchone() is not None
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if deleted:
|
||||
log_audit(
|
||||
"milestone.deleted",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"milestone_id": milestone_id},
|
||||
)
|
||||
return deleted
|
||||
Reference in new issue
Block a user