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,418 @@
|
||||
"""Attention and NextAction read-models — regelbasiert, tenant-scoped (AP0.8a)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from tenant_context import TenantContext
|
||||
|
||||
AttentionKind = Literal[
|
||||
"blocked_action",
|
||||
"open_blocker",
|
||||
"high_priority_action",
|
||||
"unassigned_action",
|
||||
"initiative_without_next_action",
|
||||
"stale_initiative",
|
||||
"milestone_at_risk",
|
||||
]
|
||||
|
||||
NextActionKind = Literal[
|
||||
"assign_action",
|
||||
"resolve_blocker",
|
||||
"create_action",
|
||||
"convert_backlog",
|
||||
"review_milestone",
|
||||
]
|
||||
|
||||
Severity = Literal["info", "warning", "critical"]
|
||||
|
||||
_SEVERITY_ORDER = {"critical": 0, "warning": 1, "info": 2}
|
||||
|
||||
OPEN_BLOCKER_STATUSES = ("open", "in_progress")
|
||||
OPEN_ACTION_STATUSES = ("open", "in_progress", "blocked")
|
||||
ACTIVE_INITIATIVE_STATUSES = ("active", "paused")
|
||||
|
||||
|
||||
def _serialize_attention(row: dict[str, Any]) -> dict[str, Any]:
|
||||
item = dict(row)
|
||||
for key in ("scope_id", "initiative_id", "action_id", "blocker_id", "milestone_id"):
|
||||
if item.get(key):
|
||||
item[key] = str(item[key])
|
||||
return item
|
||||
|
||||
|
||||
def _blocked_actions(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'blocked_action' AS kind,
|
||||
'critical' AS severity,
|
||||
a.title AS title,
|
||||
'Maßnahme ist blockiert' AS summary,
|
||||
'action' AS scope_type,
|
||||
a.id AS scope_id,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'action_blocked' AS reason_code,
|
||||
'actions' AS data_source
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s AND a.status = 'blocked'
|
||||
ORDER BY a.updated_at DESC
|
||||
LIMIT 50
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _open_blockers(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'open_blocker' AS kind,
|
||||
'warning' AS severity,
|
||||
b.title AS title,
|
||||
'Offener Blocker im Vorhaben' AS summary,
|
||||
'blocker' AS scope_type,
|
||||
b.id AS scope_id,
|
||||
b.initiative_id,
|
||||
b.action_id,
|
||||
b.id AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'blocker_open' AS reason_code,
|
||||
'blockers' AS data_source
|
||||
FROM blockers b
|
||||
WHERE b.tenant_id = %s AND b.status IN ('open', 'in_progress')
|
||||
ORDER BY b.updated_at DESC
|
||||
LIMIT 50
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
items = []
|
||||
for row in cur.fetchall():
|
||||
item = _serialize_attention(dict(row))
|
||||
if item.get("action_id"):
|
||||
item["action_id"] = str(item["action_id"])
|
||||
items.append(item)
|
||||
return items
|
||||
|
||||
|
||||
def _high_priority_actions(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
actor_filter = ""
|
||||
params: list[Any] = [ctx.tenant_id]
|
||||
if ctx.actor_id:
|
||||
actor_filter = """
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM action_assignments aa
|
||||
WHERE aa.action_id = a.id
|
||||
AND aa.tenant_id = a.tenant_id
|
||||
AND aa.actor_id = %s
|
||||
)
|
||||
"""
|
||||
params.append(ctx.actor_id)
|
||||
else:
|
||||
return []
|
||||
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT
|
||||
'high_priority_action' AS kind,
|
||||
'warning' AS severity,
|
||||
a.title AS title,
|
||||
'High-Priority Maßnahme offen' AS summary,
|
||||
'action' AS scope_type,
|
||||
a.id AS scope_id,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'action_high_priority_open' AS reason_code,
|
||||
'actions' AS data_source
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s
|
||||
AND a.priority = 'high'
|
||||
AND a.status IN ('open', 'in_progress')
|
||||
{actor_filter}
|
||||
ORDER BY a.updated_at DESC
|
||||
LIMIT 30
|
||||
""",
|
||||
tuple(params),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _unassigned_actions(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'unassigned_action' AS kind,
|
||||
'warning' AS severity,
|
||||
a.title AS title,
|
||||
'Maßnahme ohne Zuweisung' AS summary,
|
||||
'action' AS scope_type,
|
||||
a.id AS scope_id,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'action_unassigned' AS reason_code,
|
||||
'actions' AS data_source
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s
|
||||
AND a.status IN ('open', 'in_progress')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM action_assignments aa
|
||||
WHERE aa.action_id = a.id AND aa.tenant_id = a.tenant_id
|
||||
)
|
||||
ORDER BY a.updated_at DESC
|
||||
LIMIT 30
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _initiatives_without_next_action(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'initiative_without_next_action' AS kind,
|
||||
'info' AS severity,
|
||||
i.title AS title,
|
||||
'Keine offene nächste Maßnahme' AS summary,
|
||||
'initiative' AS scope_type,
|
||||
i.id AS scope_id,
|
||||
i.id AS initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'initiative_no_open_action' AS reason_code,
|
||||
'initiatives' AS data_source
|
||||
FROM initiatives i
|
||||
WHERE i.tenant_id = %s
|
||||
AND i.status IN ('active', 'paused')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM actions a
|
||||
WHERE a.initiative_id = i.id
|
||||
AND a.tenant_id = i.tenant_id
|
||||
AND a.status IN ('open', 'in_progress', 'blocked')
|
||||
)
|
||||
ORDER BY i.updated_at DESC
|
||||
LIMIT 30
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _stale_initiatives(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'stale_initiative' AS kind,
|
||||
'info' AS severity,
|
||||
i.title AS title,
|
||||
'Vorhaben seit über 14 Tagen unverändert' AS summary,
|
||||
'initiative' AS scope_type,
|
||||
i.id AS scope_id,
|
||||
i.id AS initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
NULL::uuid AS milestone_id,
|
||||
'initiative_stale' AS reason_code,
|
||||
'initiatives' AS data_source
|
||||
FROM initiatives i
|
||||
WHERE i.tenant_id = %s
|
||||
AND i.status = 'active'
|
||||
AND i.updated_at < NOW() - INTERVAL '14 days'
|
||||
ORDER BY i.updated_at ASC
|
||||
LIMIT 20
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def _milestones_at_risk(cur, ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'milestone_at_risk' AS kind,
|
||||
'warning' AS severity,
|
||||
m.title AS title,
|
||||
'Meilenstein als gefährdet markiert' AS summary,
|
||||
'milestone' AS scope_type,
|
||||
m.id AS scope_id,
|
||||
m.initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS blocker_id,
|
||||
m.id AS milestone_id,
|
||||
'milestone_at_risk' AS reason_code,
|
||||
'milestones' AS data_source
|
||||
FROM milestones m
|
||||
WHERE m.tenant_id = %s AND m.status = 'at_risk'
|
||||
ORDER BY m.updated_at DESC
|
||||
LIMIT 20
|
||||
""",
|
||||
(ctx.tenant_id,),
|
||||
)
|
||||
return [_serialize_attention(dict(r)) for r in cur.fetchall()]
|
||||
|
||||
|
||||
def get_attention_items(ctx: TenantContext) -> list[dict[str, Any]]:
|
||||
"""Regelbasierte Attention Items — tenant-scoped, erklärbar."""
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
items: list[dict[str, Any]] = []
|
||||
items.extend(_blocked_actions(cur, ctx))
|
||||
items.extend(_open_blockers(cur, ctx))
|
||||
items.extend(_high_priority_actions(cur, ctx))
|
||||
items.extend(_unassigned_actions(cur, ctx))
|
||||
items.extend(_initiatives_without_next_action(cur, ctx))
|
||||
items.extend(_stale_initiatives(cur, ctx))
|
||||
items.extend(_milestones_at_risk(cur, ctx))
|
||||
|
||||
items.sort(key=lambda x: _SEVERITY_ORDER.get(x["severity"], 99))
|
||||
return items
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_next_action_candidates(
|
||||
ctx: TenantContext, *, limit: int = 10
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Regelbasierte NextActionCandidates — limitiert, tenant-scoped."""
|
||||
if limit < 1:
|
||||
limit = 1
|
||||
if limit > 50:
|
||||
limit = 50
|
||||
|
||||
conn = get_connection()
|
||||
candidates: list[dict[str, Any]] = []
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'resolve_blocker' AS kind,
|
||||
b.title AS title,
|
||||
'Blocker klären oder Status aktualisieren' AS summary,
|
||||
b.initiative_id,
|
||||
b.action_id,
|
||||
NULL::uuid AS backlog_item_id,
|
||||
'blocker_open' AS reason_code,
|
||||
'Blocker bearbeiten' AS recommended_action
|
||||
FROM blockers b
|
||||
WHERE b.tenant_id = %s AND b.status IN ('open', 'in_progress')
|
||||
ORDER BY b.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, limit),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
if item.get("action_id"):
|
||||
item["action_id"] = str(item["action_id"])
|
||||
candidates.append(item)
|
||||
|
||||
remaining = limit - len(candidates)
|
||||
if remaining > 0:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'assign_action' AS kind,
|
||||
a.title AS title,
|
||||
'Actor zuweisen' AS summary,
|
||||
a.initiative_id,
|
||||
a.id AS action_id,
|
||||
NULL::uuid AS backlog_item_id,
|
||||
'action_unassigned' AS reason_code,
|
||||
'Maßnahme zuweisen' AS recommended_action
|
||||
FROM actions a
|
||||
WHERE a.tenant_id = %s
|
||||
AND a.status IN ('open', 'in_progress')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM action_assignments aa
|
||||
WHERE aa.action_id = a.id AND aa.tenant_id = a.tenant_id
|
||||
)
|
||||
ORDER BY a.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, remaining),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
item["action_id"] = str(item["action_id"])
|
||||
candidates.append(item)
|
||||
|
||||
remaining = limit - len(candidates)
|
||||
if remaining > 0:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'convert_backlog' AS kind,
|
||||
bi.title AS title,
|
||||
'Freigegebenes Backlog-Item in Maßnahme umwandeln' AS summary,
|
||||
bi.initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
bi.id AS backlog_item_id,
|
||||
'backlog_accepted_not_converted' AS reason_code,
|
||||
'In Maßnahme umwandeln' AS recommended_action
|
||||
FROM backlog_items bi
|
||||
WHERE bi.tenant_id = %s
|
||||
AND bi.status = 'accepted'
|
||||
AND bi.converted_action_id IS NULL
|
||||
ORDER BY bi.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, remaining),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
item["backlog_item_id"] = str(item["backlog_item_id"])
|
||||
candidates.append(item)
|
||||
|
||||
remaining = limit - len(candidates)
|
||||
if remaining > 0:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
'create_action' AS kind,
|
||||
i.title AS title,
|
||||
'Nächste Maßnahme für Vorhaben anlegen' AS summary,
|
||||
i.id AS initiative_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS backlog_item_id,
|
||||
'initiative_no_open_action' AS reason_code,
|
||||
'Maßnahme anlegen' AS recommended_action
|
||||
FROM initiatives i
|
||||
WHERE i.tenant_id = %s
|
||||
AND i.status IN ('active', 'paused')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM actions a
|
||||
WHERE a.initiative_id = i.id
|
||||
AND a.tenant_id = i.tenant_id
|
||||
AND a.status IN ('open', 'in_progress', 'blocked')
|
||||
)
|
||||
ORDER BY i.updated_at DESC
|
||||
LIMIT %s
|
||||
""",
|
||||
(ctx.tenant_id, remaining),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
candidates.append(item)
|
||||
|
||||
return candidates[:limit]
|
||||
finally:
|
||||
conn.close()
|
||||
+17
-1
@@ -53,7 +53,20 @@ app.add_middleware(
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
from routers import actions, actors, auth, config, features, initiatives, me, prompts, workspace # noqa: E402
|
||||
from routers import ( # noqa: E402
|
||||
actions,
|
||||
actors,
|
||||
auth,
|
||||
backlog,
|
||||
blockers,
|
||||
config,
|
||||
features,
|
||||
initiatives,
|
||||
me,
|
||||
milestones,
|
||||
prompts,
|
||||
workspace,
|
||||
)
|
||||
|
||||
app.include_router(auth.router)
|
||||
app.include_router(me.router)
|
||||
@@ -62,6 +75,9 @@ app.include_router(prompts.router)
|
||||
app.include_router(config.router)
|
||||
app.include_router(initiatives.router)
|
||||
app.include_router(actions.router)
|
||||
app.include_router(blockers.router)
|
||||
app.include_router(backlog.router)
|
||||
app.include_router(milestones.router)
|
||||
app.include_router(actors.router)
|
||||
app.include_router(workspace.router)
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
-- AP0.8: Operating Model Extension I — blockers, backlog_items, milestones
|
||||
|
||||
CREATE TABLE blockers (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||
action_id UUID NULL REFERENCES actions(id) ON DELETE SET NULL,
|
||||
title VARCHAR(255) NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'open'
|
||||
CHECK (status IN ('open', 'in_progress', 'resolved', 'accepted_risk', 'dismissed')),
|
||||
reported_by_actor_id UUID NULL REFERENCES actors(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_blockers_tenant_initiative ON blockers(tenant_id, initiative_id);
|
||||
CREATE INDEX idx_blockers_tenant_status ON blockers(tenant_id, status);
|
||||
|
||||
CREATE TABLE backlog_items (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||
title VARCHAR(255) NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'new'
|
||||
CHECK (status IN ('new', 'triaged', 'accepted', 'rejected', 'converted')),
|
||||
priority VARCHAR(16) NOT NULL DEFAULT 'normal'
|
||||
CHECK (priority IN ('low', 'normal', 'high')),
|
||||
converted_action_id UUID NULL REFERENCES actions(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_backlog_items_tenant_initiative ON backlog_items(tenant_id, initiative_id);
|
||||
CREATE INDEX idx_backlog_items_tenant_status ON backlog_items(tenant_id, status);
|
||||
|
||||
CREATE TABLE milestones (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
initiative_id UUID NOT NULL REFERENCES initiatives(id) ON DELETE CASCADE,
|
||||
title VARCHAR(255) NOT NULL,
|
||||
goal_description TEXT NOT NULL DEFAULT '',
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'planned'
|
||||
CHECK (status IN ('planned', 'active', 'at_risk', 'reached', 'moved', 'discarded')),
|
||||
target_date DATE NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_milestones_tenant_initiative ON milestones(tenant_id, initiative_id);
|
||||
CREATE INDEX idx_milestones_tenant_status ON milestones(tenant_id, status);
|
||||
@@ -1,5 +1,19 @@
|
||||
"""Import all module registrations — side effect registers capabilities."""
|
||||
|
||||
from . import initiative_ops, platform, registry_ops, tenant_ops, workspace_ops # noqa: F401
|
||||
from . import ( # noqa: F401
|
||||
initiative_ops,
|
||||
operating_model_ops,
|
||||
platform,
|
||||
registry_ops,
|
||||
tenant_ops,
|
||||
workspace_ops,
|
||||
)
|
||||
|
||||
__all__ = ["initiative_ops", "platform", "registry_ops", "tenant_ops", "workspace_ops"]
|
||||
__all__ = [
|
||||
"initiative_ops",
|
||||
"operating_model_ops",
|
||||
"platform",
|
||||
"registry_ops",
|
||||
"tenant_ops",
|
||||
"workspace_ops",
|
||||
]
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Operating model capabilities (AP0.8)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from rights_registry import CapabilityRegistration, register_capability
|
||||
|
||||
_MEMBER_READ = (
|
||||
("portal", "admin"),
|
||||
("portal", "user"),
|
||||
("tenant", "owner"),
|
||||
("tenant", "admin"),
|
||||
("tenant", "member"),
|
||||
)
|
||||
|
||||
_MEMBER_MANAGE = (
|
||||
("portal", "admin"),
|
||||
("tenant", "owner"),
|
||||
("tenant", "admin"),
|
||||
("tenant", "member"),
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.attention.read",
|
||||
module="attention",
|
||||
description="Attention- und NextAction-Sichten lesen",
|
||||
default_grants=_MEMBER_READ,
|
||||
)
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.blocker.read",
|
||||
module="blocker",
|
||||
description="Blocker im aktiven Tenant lesen",
|
||||
default_grants=_MEMBER_READ,
|
||||
)
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.blocker.manage",
|
||||
module="blocker",
|
||||
description="Blocker anlegen und bearbeiten",
|
||||
default_grants=_MEMBER_MANAGE,
|
||||
)
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.backlog.read",
|
||||
module="backlog",
|
||||
description="Backlog-Items im aktiven Tenant lesen",
|
||||
default_grants=_MEMBER_READ,
|
||||
)
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.backlog.manage",
|
||||
module="backlog",
|
||||
description="Backlog-Items anlegen, bearbeiten und konvertieren",
|
||||
default_grants=_MEMBER_MANAGE,
|
||||
)
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.milestone.read",
|
||||
module="milestone",
|
||||
description="Meilensteine im aktiven Tenant lesen",
|
||||
default_grants=_MEMBER_READ,
|
||||
)
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.milestone.manage",
|
||||
module="milestone",
|
||||
description="Meilensteine anlegen und bearbeiten",
|
||||
default_grants=_MEMBER_MANAGE,
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,103 @@
|
||||
"""BacklogItem API — AP0.8c."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal, Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from services import backlog as backlog_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/backlog", tags=["backlog"])
|
||||
|
||||
|
||||
class BacklogCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
description: str = ""
|
||||
status: Literal["new", "triaged", "accepted", "rejected"] = "new"
|
||||
priority: Literal["low", "normal", "high"] = "normal"
|
||||
|
||||
|
||||
class BacklogUpdateRequest(BaseModel):
|
||||
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
|
||||
description: Optional[str] = None
|
||||
status: Optional[Literal["new", "triaged", "accepted", "rejected"]] = None
|
||||
priority: Optional[Literal["low", "normal", "high"]] = None
|
||||
|
||||
|
||||
class BacklogConvertRequest(BaseModel):
|
||||
assigned_actor_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
@router.get("/{backlog_item_id}")
|
||||
def get_backlog_item(
|
||||
backlog_item_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.backlog.read")),
|
||||
):
|
||||
item = backlog_service.get_backlog_item(
|
||||
tenant_id=ctx.tenant_id, backlog_item_id=backlog_item_id
|
||||
)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Backlog-Item nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.patch("/{backlog_item_id}")
|
||||
def update_backlog_item(
|
||||
backlog_item_id: str,
|
||||
body: BacklogUpdateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.backlog.manage")),
|
||||
):
|
||||
try:
|
||||
item = backlog_service.update_backlog_item(
|
||||
tenant_id=ctx.tenant_id,
|
||||
backlog_item_id=backlog_item_id,
|
||||
user_id=ctx.user_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
priority=body.priority,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Backlog-Item nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.delete("/{backlog_item_id}", status_code=204)
|
||||
def delete_backlog_item(
|
||||
backlog_item_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.backlog.manage")),
|
||||
):
|
||||
if not backlog_service.delete_backlog_item(
|
||||
tenant_id=ctx.tenant_id,
|
||||
backlog_item_id=backlog_item_id,
|
||||
user_id=ctx.user_id,
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="Backlog-Item nicht gefunden")
|
||||
|
||||
|
||||
@router.post("/{backlog_item_id}/convert-to-action", status_code=201)
|
||||
def convert_backlog_to_action(
|
||||
backlog_item_id: str,
|
||||
body: BacklogConvertRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.backlog.manage")),
|
||||
):
|
||||
assigned = body.assigned_actor_ids
|
||||
if not assigned and ctx.actor_id:
|
||||
assigned = [ctx.actor_id]
|
||||
try:
|
||||
return backlog_service.convert_backlog_to_action(
|
||||
tenant_id=ctx.tenant_id,
|
||||
backlog_item_id=backlog_item_id,
|
||||
user_id=ctx.user_id,
|
||||
assigned_actor_ids=assigned,
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Backlog-Item nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Blocker API — AP0.8b."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal, Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from services import blockers as blocker_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/blockers", tags=["blockers"])
|
||||
|
||||
|
||||
class BlockerCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
description: str = ""
|
||||
status: Literal["open", "in_progress", "resolved", "accepted_risk", "dismissed"] = "open"
|
||||
action_id: Optional[str] = None
|
||||
set_action_blocked: bool = False
|
||||
|
||||
|
||||
class BlockerUpdateRequest(BaseModel):
|
||||
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
|
||||
description: Optional[str] = None
|
||||
status: Optional[
|
||||
Literal["open", "in_progress", "resolved", "accepted_risk", "dismissed"]
|
||||
] = None
|
||||
action_id: Optional[str] = None
|
||||
clear_action_id: bool = False
|
||||
|
||||
|
||||
@router.get("/{blocker_id}")
|
||||
def get_blocker(
|
||||
blocker_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.blocker.read")),
|
||||
):
|
||||
item = blocker_service.get_blocker(tenant_id=ctx.tenant_id, blocker_id=blocker_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Blocker nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.patch("/{blocker_id}")
|
||||
def update_blocker(
|
||||
blocker_id: str,
|
||||
body: BlockerUpdateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.blocker.manage")),
|
||||
):
|
||||
try:
|
||||
item = blocker_service.update_blocker(
|
||||
tenant_id=ctx.tenant_id,
|
||||
blocker_id=blocker_id,
|
||||
user_id=ctx.user_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
action_id=body.action_id,
|
||||
clear_action_id=body.clear_action_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Blocker nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.delete("/{blocker_id}", status_code=204)
|
||||
def delete_blocker(
|
||||
blocker_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.blocker.manage")),
|
||||
):
|
||||
if not blocker_service.delete_blocker(
|
||||
tenant_id=ctx.tenant_id, blocker_id=blocker_id, user_id=ctx.user_id
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="Blocker nicht gefunden")
|
||||
@@ -8,7 +8,10 @@ from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from services import actions as action_service
|
||||
from services import backlog as backlog_service
|
||||
from services import blockers as blocker_service
|
||||
from services import initiatives as initiative_service
|
||||
from services import milestones as milestone_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/initiatives", tags=["initiatives"])
|
||||
@@ -38,6 +41,28 @@ class ActionCreateRequest(BaseModel):
|
||||
assigned_actor_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class BlockerCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
description: str = ""
|
||||
status: Literal["open", "in_progress", "resolved", "accepted_risk", "dismissed"] = "open"
|
||||
action_id: Optional[str] = None
|
||||
set_action_blocked: bool = False
|
||||
|
||||
|
||||
class BacklogCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
description: str = ""
|
||||
status: Literal["new", "triaged", "accepted", "rejected"] = "new"
|
||||
priority: Literal["low", "normal", "high"] = "normal"
|
||||
|
||||
|
||||
class MilestoneCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
goal_description: str = ""
|
||||
status: Literal["planned", "active", "at_risk", "reached", "moved", "discarded"] = "planned"
|
||||
target_date: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_initiatives(
|
||||
ctx: TenantContext = Depends(require_capability("kairo.initiative.read")),
|
||||
@@ -153,3 +178,127 @@ def create_initiative_action(
|
||||
if detail == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
|
||||
|
||||
@router.get("/{initiative_id}/blockers")
|
||||
def list_initiative_blockers(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.blocker.read")),
|
||||
):
|
||||
try:
|
||||
return blocker_service.list_blockers_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
if str(exc) == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/{initiative_id}/blockers", status_code=201)
|
||||
def create_initiative_blocker(
|
||||
initiative_id: str,
|
||||
body: BlockerCreateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.blocker.manage")),
|
||||
):
|
||||
try:
|
||||
return blocker_service.create_blocker(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
action_id=body.action_id,
|
||||
reported_by_actor_id=ctx.actor_id,
|
||||
user_id=ctx.user_id,
|
||||
set_action_blocked=body.set_action_blocked,
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
|
||||
|
||||
@router.get("/{initiative_id}/backlog")
|
||||
def list_initiative_backlog(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.backlog.read")),
|
||||
):
|
||||
try:
|
||||
return backlog_service.list_backlog_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
if str(exc) == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/{initiative_id}/backlog", status_code=201)
|
||||
def create_initiative_backlog_item(
|
||||
initiative_id: str,
|
||||
body: BacklogCreateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.backlog.manage")),
|
||||
):
|
||||
try:
|
||||
return backlog_service.create_backlog_item(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
title=body.title,
|
||||
description=body.description,
|
||||
status=body.status,
|
||||
priority=body.priority,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
|
||||
|
||||
@router.get("/{initiative_id}/milestones")
|
||||
def list_initiative_milestones(
|
||||
initiative_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
|
||||
):
|
||||
try:
|
||||
return milestone_service.list_milestones_for_initiative(
|
||||
tenant_id=ctx.tenant_id, initiative_id=initiative_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
if str(exc) == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/{initiative_id}/milestones", status_code=201)
|
||||
def create_initiative_milestone(
|
||||
initiative_id: str,
|
||||
body: MilestoneCreateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
|
||||
):
|
||||
from datetime import date as date_type
|
||||
|
||||
target_date = None
|
||||
if body.target_date:
|
||||
try:
|
||||
target_date = date_type.fromisoformat(body.target_date)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail="Ungültiges target_date") from exc
|
||||
try:
|
||||
return milestone_service.create_milestone(
|
||||
tenant_id=ctx.tenant_id,
|
||||
initiative_id=initiative_id,
|
||||
title=body.title,
|
||||
goal_description=body.goal_description,
|
||||
status=body.status,
|
||||
target_date=target_date,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Initiative nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Milestone API — AP0.8d."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Literal, Optional
|
||||
|
||||
from capabilities import require_capability
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from services import milestones as milestone_service
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/milestones", tags=["milestones"])
|
||||
|
||||
|
||||
class MilestoneCreateRequest(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=255)
|
||||
goal_description: str = ""
|
||||
status: Literal["planned", "active", "at_risk", "reached", "moved", "discarded"] = "planned"
|
||||
target_date: Optional[date] = None
|
||||
|
||||
|
||||
class MilestoneUpdateRequest(BaseModel):
|
||||
title: Optional[str] = Field(default=None, min_length=1, max_length=255)
|
||||
goal_description: Optional[str] = None
|
||||
status: Optional[
|
||||
Literal["planned", "active", "at_risk", "reached", "moved", "discarded"]
|
||||
] = None
|
||||
target_date: Optional[date] = None
|
||||
clear_target_date: bool = False
|
||||
|
||||
|
||||
@router.get("/{milestone_id}")
|
||||
def get_milestone(
|
||||
milestone_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.read")),
|
||||
):
|
||||
item = milestone_service.get_milestone(tenant_id=ctx.tenant_id, milestone_id=milestone_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Meilenstein nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.patch("/{milestone_id}")
|
||||
def update_milestone(
|
||||
milestone_id: str,
|
||||
body: MilestoneUpdateRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
|
||||
):
|
||||
try:
|
||||
item = milestone_service.update_milestone(
|
||||
tenant_id=ctx.tenant_id,
|
||||
milestone_id=milestone_id,
|
||||
user_id=ctx.user_id,
|
||||
title=body.title,
|
||||
goal_description=body.goal_description,
|
||||
status=body.status,
|
||||
target_date=body.target_date,
|
||||
clear_target_date=body.clear_target_date,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Meilenstein nicht gefunden")
|
||||
return item
|
||||
|
||||
|
||||
@router.delete("/{milestone_id}", status_code=204)
|
||||
def delete_milestone(
|
||||
milestone_id: str,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.milestone.manage")),
|
||||
):
|
||||
if not milestone_service.delete_milestone(
|
||||
tenant_id=ctx.tenant_id, milestone_id=milestone_id, user_id=ctx.user_id
|
||||
):
|
||||
raise HTTPException(status_code=404, detail="Meilenstein nicht gefunden")
|
||||
@@ -7,6 +7,7 @@ from typing import Optional
|
||||
from capabilities import require_capability
|
||||
from data_layer import actions as dl_actions
|
||||
from data_layer import actors as dl_actors
|
||||
from data_layer import attention as dl_attention
|
||||
from data_layer import initiatives as dl_initiatives
|
||||
from data_layer import workspace as dl_workspace
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -61,3 +62,18 @@ def workspace_actor_workload(
|
||||
ctx: TenantContext = Depends(require_capability("kairo.workspace.read")),
|
||||
):
|
||||
return dl_actors.get_actor_workload(ctx)
|
||||
|
||||
|
||||
@router.get("/attention")
|
||||
def workspace_attention(
|
||||
ctx: TenantContext = Depends(require_capability("kairo.attention.read")),
|
||||
):
|
||||
return dl_attention.get_attention_items(ctx)
|
||||
|
||||
|
||||
@router.get("/next-actions")
|
||||
def workspace_next_actions(
|
||||
limit: Optional[int] = Query(default=10, ge=1, le=50),
|
||||
ctx: TenantContext = Depends(require_capability("kairo.attention.read")),
|
||||
):
|
||||
return dl_attention.get_next_action_candidates(ctx, limit=limit or 10)
|
||||
@@ -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
|
||||
@@ -1,4 +1,8 @@
|
||||
"""Shared pytest fixtures for AP0.2 auth tests."""
|
||||
"""Shared pytest fixtures — Integrationstests benötigen PostgreSQL.
|
||||
|
||||
Lokal typischerweise nicht verfügbar: Tests laufen nach Push auf develop/main
|
||||
im Backend-Container auf dem Pi (Gitea workflow test.yml).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -23,6 +27,7 @@ def _db_available() -> bool:
|
||||
dbname=os.getenv("DB_NAME", "kairo_dev"),
|
||||
user=os.getenv("DB_USER", "kairo_dev"),
|
||||
password=os.getenv("DB_PASSWORD", "dev_password"),
|
||||
connect_timeout=3,
|
||||
)
|
||||
conn.close()
|
||||
return True
|
||||
@@ -30,7 +35,18 @@ def _db_available() -> bool:
|
||||
return False
|
||||
|
||||
|
||||
pytestmark = pytest.mark.skipif(not _db_available(), reason="PostgreSQL nicht erreichbar")
|
||||
_REMOTE_HINT = (
|
||||
"PostgreSQL lokal nicht erreichbar. "
|
||||
"Backend-Integrationstests laufen nach Push auf develop/main "
|
||||
"im deployten Backend-Container (Gitea: test.yml auf dem Pi)."
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _require_postgresql():
|
||||
"""Session-weiter Guard — verhindert Migrations-Setup ohne DB (keine ERROR-Spirale)."""
|
||||
if not _db_available():
|
||||
pytest.skip(_REMOTE_HINT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
"""AP0.8 — Operating Model Extension I tests.
|
||||
|
||||
Ausführung: im Backend-Container auf dem Pi nach Deploy (develop/main),
|
||||
siehe .gitea/workflows/test.yml und docs/DEPLOYMENT.md.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.factories import provision_user_in_tenant
|
||||
from tests.test_initiatives_actions import (
|
||||
_auth,
|
||||
_create_action,
|
||||
_create_initiative,
|
||||
_login,
|
||||
)
|
||||
|
||||
|
||||
def _create_blocker(client, token, initiative_id, **kwargs):
|
||||
body = {"title": "Blocker Test", **kwargs}
|
||||
return client.post(
|
||||
f"/api/initiatives/{initiative_id}/blockers",
|
||||
json=body,
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
|
||||
def _create_backlog(client, token, initiative_id, **kwargs):
|
||||
body = {"title": "Backlog Test", **kwargs}
|
||||
return client.post(
|
||||
f"/api/initiatives/{initiative_id}/backlog",
|
||||
json=body,
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
|
||||
def _create_milestone(client, token, initiative_id, **kwargs):
|
||||
body = {"title": "Milestone Test", **kwargs}
|
||||
return client.post(
|
||||
f"/api/initiatives/{initiative_id}/milestones",
|
||||
json=body,
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
|
||||
def test_attention_blocked_action(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
action = _create_action(
|
||||
client, token, initiative_id, assigned_actor_ids=[user["actor_id"]]
|
||||
).json()
|
||||
client.patch(
|
||||
f"/api/actions/{action['id']}",
|
||||
json={"status": "blocked"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
res = client.get("/api/workspace/attention", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
items = res.json()
|
||||
assert any(i["kind"] == "blocked_action" for i in items)
|
||||
blocked = next(i for i in items if i["kind"] == "blocked_action")
|
||||
assert blocked["reason_code"] == "action_blocked"
|
||||
assert blocked["data_source"] == "actions"
|
||||
assert blocked["scope_type"] == "action"
|
||||
|
||||
|
||||
def test_attention_unassigned_action(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
_create_action(client, token, initiative_id, title="Unassigned")
|
||||
|
||||
res = client.get("/api/workspace/attention", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
assert any(i["kind"] == "unassigned_action" for i in res.json())
|
||||
|
||||
|
||||
def test_attention_initiative_without_next_action(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
_create_initiative(client, token, title="Empty Initiative")
|
||||
|
||||
res = client.get("/api/workspace/attention", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
assert any(i["kind"] == "initiative_without_next_action" for i in res.json())
|
||||
|
||||
|
||||
def test_attention_open_blocker(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
_create_blocker(client, token, initiative_id, title="Dependency missing")
|
||||
|
||||
res = client.get("/api/workspace/attention", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
assert any(i["kind"] == "open_blocker" for i in res.json())
|
||||
|
||||
|
||||
def test_attention_milestone_at_risk(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
ms = _create_milestone(client, token, initiative_id).json()
|
||||
client.patch(
|
||||
f"/api/milestones/{ms['id']}",
|
||||
json={"status": "at_risk"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
|
||||
res = client.get("/api/workspace/attention", headers=_auth(token))
|
||||
assert any(i["kind"] == "milestone_at_risk" for i in res.json())
|
||||
|
||||
|
||||
def test_attention_severity_sorting(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
action = _create_action(client, token, initiative_id).json()
|
||||
client.patch(
|
||||
f"/api/actions/{action['id']}",
|
||||
json={"status": "blocked"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
_create_blocker(client, token, initiative_id)
|
||||
|
||||
items = client.get("/api/workspace/attention", headers=_auth(token)).json()
|
||||
severities = [i["severity"] for i in items]
|
||||
order = {"critical": 0, "warning": 1, "info": 2}
|
||||
assert severities == sorted(severities, key=lambda s: order.get(s, 99))
|
||||
|
||||
|
||||
def test_next_action_convert_backlog(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
item = _create_backlog(
|
||||
client, token, initiative_id, status="accepted", title="Convert me"
|
||||
).json()
|
||||
|
||||
res = client.get("/api/workspace/next-actions?limit=10", headers=_auth(token))
|
||||
assert res.status_code == 200
|
||||
assert any(
|
||||
c["kind"] == "convert_backlog" and c["backlog_item_id"] == item["id"]
|
||||
for c in res.json()
|
||||
)
|
||||
|
||||
|
||||
def test_next_action_limit(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
for i in range(5):
|
||||
_create_backlog(
|
||||
client, token, initiative_id, status="accepted", title=f"Item {i}"
|
||||
)
|
||||
|
||||
res = client.get("/api/workspace/next-actions?limit=2", headers=_auth(token))
|
||||
assert len(res.json()) <= 2
|
||||
|
||||
|
||||
def test_blocker_crud(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
action = _create_action(client, token, initiative_id).json()
|
||||
|
||||
created = _create_blocker(
|
||||
client,
|
||||
token,
|
||||
initiative_id,
|
||||
title="API Block",
|
||||
action_id=action["id"],
|
||||
)
|
||||
assert created.status_code == 201
|
||||
blocker = created.json()
|
||||
assert blocker["initiative_id"] == initiative_id
|
||||
|
||||
listed = client.get(
|
||||
f"/api/initiatives/{initiative_id}/blockers", headers=_auth(token)
|
||||
)
|
||||
assert listed.status_code == 200
|
||||
assert any(b["id"] == blocker["id"] for b in listed.json())
|
||||
|
||||
updated = client.patch(
|
||||
f"/api/blockers/{blocker['id']}",
|
||||
json={"status": "resolved"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert updated.status_code == 200
|
||||
assert updated.json()["status"] == "resolved"
|
||||
|
||||
deleted = client.delete(f"/api/blockers/{blocker['id']}", headers=_auth(token))
|
||||
assert deleted.status_code == 204
|
||||
|
||||
|
||||
def test_blocker_cross_tenant(client):
|
||||
user_a = provision_user_in_tenant()
|
||||
user_b = provision_user_in_tenant()
|
||||
token_a = _login(client, user_a)
|
||||
token_b = _login(client, user_b)
|
||||
initiative_id = _create_initiative(client, token_a).json()["id"]
|
||||
blocker = _create_blocker(client, token_a, initiative_id).json()
|
||||
|
||||
assert (
|
||||
client.get(f"/api/blockers/{blocker['id']}", headers=_auth(token_b)).status_code
|
||||
== 404
|
||||
)
|
||||
|
||||
|
||||
def test_backlog_convert_to_action(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
item = _create_backlog(
|
||||
client, token, initiative_id, status="accepted", title="Feature X"
|
||||
).json()
|
||||
|
||||
converted = client.post(
|
||||
f"/api/backlog/{item['id']}/convert-to-action",
|
||||
json={},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert converted.status_code == 201
|
||||
body = converted.json()
|
||||
assert body["backlog_item"]["status"] == "converted"
|
||||
assert body["action"]["title"] == "Feature X"
|
||||
assert body["backlog_item"]["converted_action_id"] == body["action"]["id"]
|
||||
|
||||
|
||||
def test_backlog_crud(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
created = _create_backlog(client, token, initiative_id, status="triaged")
|
||||
assert created.status_code == 201
|
||||
item = created.json()
|
||||
|
||||
patched = client.patch(
|
||||
f"/api/backlog/{item['id']}",
|
||||
json={"status": "accepted"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert patched.status_code == 200
|
||||
|
||||
deleted = client.delete(f"/api/backlog/{item['id']}", headers=_auth(token))
|
||||
assert deleted.status_code == 204
|
||||
|
||||
|
||||
def test_milestone_crud(client):
|
||||
user = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, user)
|
||||
initiative_id = _create_initiative(client, token).json()["id"]
|
||||
created = _create_milestone(
|
||||
client, token, initiative_id, status="active", target_date="2026-12-31"
|
||||
)
|
||||
assert created.status_code == 201
|
||||
ms = created.json()
|
||||
assert ms["target_date"] == "2026-12-31"
|
||||
|
||||
deleted = client.delete(f"/api/milestones/{ms['id']}", headers=_auth(token))
|
||||
assert deleted.status_code == 204
|
||||
|
||||
|
||||
def test_member_has_ap08_capabilities(client):
|
||||
member = provision_user_in_tenant(tenant_role="member")
|
||||
token = _login(client, member)
|
||||
ctx = client.get("/api/me/context", headers=_auth(token)).json()
|
||||
caps = ctx["capabilities"]
|
||||
for key in (
|
||||
"kairo.attention.read",
|
||||
"kairo.blocker.read",
|
||||
"kairo.blocker.manage",
|
||||
"kairo.backlog.read",
|
||||
"kairo.backlog.manage",
|
||||
"kairo.milestone.read",
|
||||
"kairo.milestone.manage",
|
||||
):
|
||||
assert key in caps
|
||||
@@ -37,6 +37,7 @@ def test_migration_runner_finds_migrations():
|
||||
assert "004_capabilities_registry" in names
|
||||
assert "005_prompt_feature_config_registry" in names
|
||||
assert "006_initiatives_actions" in names
|
||||
assert "007_operating_model_extension_i" in names
|
||||
|
||||
|
||||
def test_migration_runner_is_idempotent():
|
||||
@@ -52,6 +53,7 @@ def test_migration_runner_is_idempotent():
|
||||
assert "004_capabilities_registry" in executed
|
||||
assert "005_prompt_feature_config_registry" in executed
|
||||
assert "006_initiatives_actions" in executed
|
||||
assert "007_operating_model_extension_i" in executed
|
||||
|
||||
|
||||
def test_core_table_exists():
|
||||
|
||||
@@ -28,6 +28,13 @@ def test_registry_contains_initial_capabilities():
|
||||
"kairo.action.read",
|
||||
"kairo.action.manage",
|
||||
"kairo.workspace.read",
|
||||
"kairo.attention.read",
|
||||
"kairo.blocker.read",
|
||||
"kairo.blocker.manage",
|
||||
"kairo.backlog.read",
|
||||
"kairo.backlog.manage",
|
||||
"kairo.milestone.read",
|
||||
"kairo.milestone.manage",
|
||||
}
|
||||
|
||||
|
||||
@@ -39,7 +46,7 @@ def test_sync_is_idempotent():
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT COUNT(*) FROM capabilities")
|
||||
assert cur.fetchone()[0] == 18
|
||||
assert cur.fetchone()[0] == 25
|
||||
cur.execute("SELECT COUNT(*) FROM role_capability_grants")
|
||||
assert cur.fetchone()[0] >= 5
|
||||
finally:
|
||||
|
||||
+2
-2
@@ -1,3 +1,3 @@
|
||||
APP_VERSION = "0.7.0-ap0.7"
|
||||
DB_SCHEMA_VERSION = "006"
|
||||
APP_VERSION = "0.8.0-ap0.8"
|
||||
DB_SCHEMA_VERSION = "007"
|
||||
APP_NAME = "jinkendo-kairo"
|
||||
Reference in new issue
Block a user