All checks were successful
Deploy Development / deploy (push) Successful in 44s
Test Suite / pytest-backend (push) Successful in 1m39s
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 013; Projekte/Arbeitspakete/Aufgaben pflegbar; Tab Zielzustände vs Ausführung. Co-authored-by: Cursor <cursoragent@cursor.com>
284 lines
8.5 KiB
Python
284 lines
8.5 KiB
Python
"""Project service — operative Struktur unter Initiative (AP1.5)."""
|
|
|
|
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
|
|
|
|
ProjectStatus = Literal["active", "paused", "completed", "archived"]
|
|
PROJECT_STATUSES = frozenset({"active", "paused", "completed", "archived"})
|
|
|
|
_PROJECT_COLUMNS = """
|
|
id, tenant_id, initiative_id, title, description, status,
|
|
roadmap_item_id, sort_order, target_date, 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", "roadmap_item_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"])
|
|
)
|
|
for ts in ("created_at", "updated_at"):
|
|
if result.get(ts):
|
|
result[ts] = result[ts].isoformat()
|
|
return result
|
|
|
|
|
|
def _validate_status(status: str) -> None:
|
|
if status not in PROJECT_STATUSES:
|
|
raise ValueError(f"Ungültiger Project-Status: {status}")
|
|
|
|
|
|
def _validate_roadmap_item(
|
|
cur, *, tenant_id: str, initiative_id: str, roadmap_item_id: Optional[str]
|
|
) -> None:
|
|
if not roadmap_item_id:
|
|
return
|
|
cur.execute(
|
|
"""
|
|
SELECT 1 FROM roadmap_items ri
|
|
JOIN roadmaps r ON r.id = ri.roadmap_id AND r.tenant_id = ri.tenant_id
|
|
WHERE ri.id = %s AND ri.tenant_id = %s AND r.initiative_id = %s
|
|
""",
|
|
(roadmap_item_id, tenant_id, initiative_id),
|
|
)
|
|
if not cur.fetchone():
|
|
raise ValueError("Gate/Plan-Element gehört nicht zu diesem Vorhaben")
|
|
|
|
|
|
def create_project(
|
|
*,
|
|
tenant_id: str,
|
|
initiative_id: str,
|
|
title: str,
|
|
description: str = "",
|
|
status: ProjectStatus = "active",
|
|
roadmap_item_id: Optional[str] = None,
|
|
sort_order: int = 0,
|
|
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:
|
|
_validate_roadmap_item(
|
|
cur,
|
|
tenant_id=tenant_id,
|
|
initiative_id=initiative_id,
|
|
roadmap_item_id=roadmap_item_id,
|
|
)
|
|
cur.execute(
|
|
f"""
|
|
INSERT INTO projects (
|
|
tenant_id, initiative_id, title, description, status,
|
|
roadmap_item_id, sort_order, target_date
|
|
)
|
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
|
RETURNING {_PROJECT_COLUMNS}
|
|
""",
|
|
(
|
|
tenant_id,
|
|
initiative_id,
|
|
title,
|
|
description,
|
|
status,
|
|
roadmap_item_id,
|
|
sort_order,
|
|
target_date,
|
|
),
|
|
)
|
|
row = _serialize_row(dict(cur.fetchone()))
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
log_audit(
|
|
"project.created",
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
details={"project_id": row["id"], "initiative_id": initiative_id, "title": title},
|
|
)
|
|
return row
|
|
|
|
|
|
def list_projects_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 {_PROJECT_COLUMNS}
|
|
FROM projects
|
|
WHERE tenant_id = %s AND initiative_id = %s
|
|
ORDER BY sort_order ASC, updated_at DESC, title
|
|
""",
|
|
(tenant_id, initiative_id),
|
|
)
|
|
return [_serialize_row(dict(r)) for r in cur.fetchall()]
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def get_project(*, tenant_id: str, project_id: str) -> Optional[dict[str, Any]]:
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
cur.execute(
|
|
f"""
|
|
SELECT {_PROJECT_COLUMNS}
|
|
FROM projects WHERE id = %s AND tenant_id = %s
|
|
""",
|
|
(project_id, tenant_id),
|
|
)
|
|
row = cur.fetchone()
|
|
return _serialize_row(dict(row)) if row else None
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def update_project(
|
|
*,
|
|
tenant_id: str,
|
|
project_id: str,
|
|
user_id: Optional[str] = None,
|
|
title: Optional[str] = None,
|
|
description: Optional[str] = None,
|
|
status: Optional[ProjectStatus] = None,
|
|
roadmap_item_id: Optional[str] = None,
|
|
clear_roadmap_item: bool = False,
|
|
sort_order: Optional[int] = None,
|
|
target_date: Optional[date] = None,
|
|
clear_target_date: bool = False,
|
|
) -> Optional[dict[str, Any]]:
|
|
existing = get_project(tenant_id=tenant_id, project_id=project_id)
|
|
if not existing:
|
|
return None
|
|
|
|
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_roadmap_item:
|
|
updates.append("roadmap_item_id = NULL")
|
|
elif roadmap_item_id is not None:
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
_validate_roadmap_item(
|
|
cur,
|
|
tenant_id=tenant_id,
|
|
initiative_id=existing["initiative_id"],
|
|
roadmap_item_id=roadmap_item_id,
|
|
)
|
|
finally:
|
|
conn.close()
|
|
updates.append("roadmap_item_id = %s")
|
|
params.append(roadmap_item_id)
|
|
if sort_order is not None:
|
|
updates.append("sort_order = %s")
|
|
params.append(sort_order)
|
|
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([project_id, tenant_id])
|
|
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
cur.execute(
|
|
f"""
|
|
UPDATE projects SET {", ".join(updates)}
|
|
WHERE id = %s AND tenant_id = %s
|
|
RETURNING {_PROJECT_COLUMNS}
|
|
""",
|
|
params,
|
|
)
|
|
row = cur.fetchone()
|
|
if not row:
|
|
return None
|
|
result = _serialize_row(dict(row))
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
log_audit(
|
|
"project.updated",
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
details={"project_id": project_id},
|
|
)
|
|
return result
|
|
|
|
|
|
def delete_project(
|
|
*, tenant_id: str, project_id: str, user_id: Optional[str] = None
|
|
) -> bool:
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute(
|
|
"UPDATE actions SET project_id = NULL WHERE project_id = %s AND tenant_id = %s",
|
|
(project_id, tenant_id),
|
|
)
|
|
cur.execute(
|
|
"DELETE FROM projects WHERE id = %s AND tenant_id = %s RETURNING id",
|
|
(project_id, tenant_id),
|
|
)
|
|
deleted = cur.fetchone() is not None
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
if deleted:
|
|
log_audit(
|
|
"project.deleted",
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
details={"project_id": project_id},
|
|
)
|
|
return deleted
|