All checks were successful
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>
243 lines
7.3 KiB
Python
243 lines
7.3 KiB
Python
"""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
|