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>
274 lines
8.1 KiB
Python
274 lines
8.1 KiB
Python
"""Task service — kleinste Einheit unter Action (AP1.5)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from typing import Any, Literal, Optional
|
|
|
|
from psycopg2.extras import RealDictCursor
|
|
|
|
from db import get_connection
|
|
from services.actions import get_action
|
|
from services.audit import log_audit
|
|
|
|
TaskStatus = Literal["open", "in_progress", "done", "discarded"]
|
|
TASK_STATUSES = frozenset({"open", "in_progress", "done", "discarded"})
|
|
|
|
_TASK_COLUMNS = """
|
|
id, tenant_id, action_id, title, description, status,
|
|
roadmap_item_id, sort_order, due_at, created_at, updated_at
|
|
"""
|
|
|
|
|
|
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
|
result = dict(row)
|
|
for key in ("id", "tenant_id", "action_id", "roadmap_item_id"):
|
|
if result.get(key):
|
|
result[key] = str(result[key])
|
|
if result.get("due_at"):
|
|
result["due_at"] = result["due_at"].isoformat()
|
|
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 TASK_STATUSES:
|
|
raise ValueError(f"Ungültiger Task-Status: {status}")
|
|
|
|
|
|
def _get_action_or_raise(*, tenant_id: str, action_id: str) -> dict[str, Any]:
|
|
action = get_action(tenant_id=tenant_id, action_id=action_id)
|
|
if not action:
|
|
raise ValueError("Arbeitspaket nicht gefunden")
|
|
return action
|
|
|
|
|
|
def _validate_roadmap_item_for_action(
|
|
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 gehört nicht zum Vorhaben des Arbeitspakets")
|
|
|
|
|
|
def create_task(
|
|
*,
|
|
tenant_id: str,
|
|
action_id: str,
|
|
title: str,
|
|
description: str = "",
|
|
status: TaskStatus = "open",
|
|
roadmap_item_id: Optional[str] = None,
|
|
sort_order: int = 0,
|
|
due_at: Optional[datetime] = None,
|
|
user_id: Optional[str] = None,
|
|
) -> dict[str, Any]:
|
|
title = title.strip()
|
|
if not title:
|
|
raise ValueError("Titel ist erforderlich")
|
|
_validate_status(status)
|
|
action = _get_action_or_raise(tenant_id=tenant_id, action_id=action_id)
|
|
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
_validate_roadmap_item_for_action(
|
|
cur,
|
|
tenant_id=tenant_id,
|
|
initiative_id=action["initiative_id"],
|
|
roadmap_item_id=roadmap_item_id,
|
|
)
|
|
cur.execute(
|
|
f"""
|
|
INSERT INTO tasks (
|
|
tenant_id, action_id, title, description, status,
|
|
roadmap_item_id, sort_order, due_at
|
|
)
|
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
|
RETURNING {_TASK_COLUMNS}
|
|
""",
|
|
(
|
|
tenant_id,
|
|
action_id,
|
|
title,
|
|
description,
|
|
status,
|
|
roadmap_item_id,
|
|
sort_order,
|
|
due_at,
|
|
),
|
|
)
|
|
row = _serialize_row(dict(cur.fetchone()))
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
log_audit(
|
|
"task.created",
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
details={"task_id": row["id"], "action_id": action_id, "title": title},
|
|
)
|
|
return row
|
|
|
|
|
|
def list_tasks_for_action(*, tenant_id: str, action_id: str) -> list[dict[str, Any]]:
|
|
_get_action_or_raise(tenant_id=tenant_id, action_id=action_id)
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
cur.execute(
|
|
f"""
|
|
SELECT {_TASK_COLUMNS}
|
|
FROM tasks
|
|
WHERE tenant_id = %s AND action_id = %s
|
|
ORDER BY sort_order ASC, created_at ASC
|
|
""",
|
|
(tenant_id, action_id),
|
|
)
|
|
return [_serialize_row(dict(r)) for r in cur.fetchall()]
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def get_task(*, tenant_id: str, task_id: str) -> Optional[dict[str, Any]]:
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
cur.execute(
|
|
f"SELECT {_TASK_COLUMNS} FROM tasks WHERE id = %s AND tenant_id = %s",
|
|
(task_id, tenant_id),
|
|
)
|
|
row = cur.fetchone()
|
|
return _serialize_row(dict(row)) if row else None
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def update_task(
|
|
*,
|
|
tenant_id: str,
|
|
task_id: str,
|
|
user_id: Optional[str] = None,
|
|
title: Optional[str] = None,
|
|
description: Optional[str] = None,
|
|
status: Optional[TaskStatus] = None,
|
|
roadmap_item_id: Optional[str] = None,
|
|
clear_roadmap_item: bool = False,
|
|
sort_order: Optional[int] = None,
|
|
due_at: Optional[datetime] = None,
|
|
clear_due_at: bool = False,
|
|
) -> Optional[dict[str, Any]]:
|
|
existing = get_task(tenant_id=tenant_id, task_id=task_id)
|
|
if not existing:
|
|
return None
|
|
|
|
action = _get_action_or_raise(tenant_id=tenant_id, action_id=existing["action_id"])
|
|
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_for_action(
|
|
cur,
|
|
tenant_id=tenant_id,
|
|
initiative_id=action["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_due_at:
|
|
updates.append("due_at = NULL")
|
|
elif due_at is not None:
|
|
updates.append("due_at = %s")
|
|
params.append(due_at)
|
|
|
|
if not updates:
|
|
return existing
|
|
|
|
updates.append("updated_at = NOW()")
|
|
params.extend([task_id, tenant_id])
|
|
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|
cur.execute(
|
|
f"""
|
|
UPDATE tasks SET {", ".join(updates)}
|
|
WHERE id = %s AND tenant_id = %s
|
|
RETURNING {_TASK_COLUMNS}
|
|
""",
|
|
params,
|
|
)
|
|
row = cur.fetchone()
|
|
if not row:
|
|
return None
|
|
result = _serialize_row(dict(row))
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
log_audit(
|
|
"task.updated",
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
details={"task_id": task_id},
|
|
)
|
|
return result
|
|
|
|
|
|
def delete_task(*, tenant_id: str, task_id: str, user_id: Optional[str] = None) -> bool:
|
|
conn = get_connection()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute(
|
|
"DELETE FROM tasks WHERE id = %s AND tenant_id = %s RETURNING id",
|
|
(task_id, tenant_id),
|
|
)
|
|
deleted = cur.fetchone() is not None
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
if deleted:
|
|
log_audit(
|
|
"task.deleted",
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
details={"task_id": task_id},
|
|
)
|
|
return deleted
|