feat(A1): Minimum Usability Slice — CadenceInstance, Today-Übung, Gate-Fortschritt
Deploy Development / deploy (push) Successful in 44s
Test Suite / pytest-backend (push) Successful in 4m54s
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 13s
Deploy Development / deploy (push) Successful in 44s
Test Suite / pytest-backend (push) Successful in 4m54s
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 13s
PO No-Go A1 adressieren: Tages-Tracking mit Messnotiz, Work-UI für Übung, Next-Action-Link, Gate-Fortschritt in Kontrolle, Eingang aus A1-Nav entfernt. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
0baa5952bc
commit
b7d88ce24a
25 files changed
+936
-31
No files matched your search
@@ -124,7 +124,7 @@ INITIATIVE_UI_PROFILES: dict[str, dict[str, Any]] = {
|
||||
"planDefaultRoute": "/plan/gates",
|
||||
"workDefaultRoute": "/work/today",
|
||||
"controlDefaultRoute": "/control/status",
|
||||
"planOutlineKeys": ["profile", "gates", "inbox", "work"],
|
||||
"planOutlineKeys": ["profile", "gates", "work"],
|
||||
"workNavKeys": ["today", "mine", "sprint"],
|
||||
"dataSlices": [
|
||||
"actions",
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
-- AP A1.1 — CadenceInstance (minimal): eine offene Instanz pro Recurring, Tages-Tracking
|
||||
|
||||
CREATE TABLE cadence_instances (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
recurring_element_id UUID NOT NULL REFERENCES recurring_elements(id) ON DELETE CASCADE,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'open'
|
||||
CHECK (status IN ('open', 'completed')),
|
||||
due_at TIMESTAMPTZ NOT NULL,
|
||||
completed_at TIMESTAMPTZ NULL,
|
||||
measurement_note TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_cadence_instances_tenant_recurring
|
||||
ON cadence_instances(tenant_id, recurring_element_id);
|
||||
|
||||
CREATE INDEX idx_cadence_instances_open_due
|
||||
ON cadence_instances(tenant_id, due_at)
|
||||
WHERE status = 'open';
|
||||
|
||||
CREATE UNIQUE INDEX idx_cadence_instances_one_open_per_recurring
|
||||
ON cadence_instances(recurring_element_id)
|
||||
WHERE status = 'open';
|
||||
@@ -24,6 +24,10 @@ class RecurringUpdateRequest(BaseModel):
|
||||
clear_next_due_at: bool = False
|
||||
|
||||
|
||||
class RecurringCompleteRequest(BaseModel):
|
||||
measurement_note: Optional[str] = Field(default=None, max_length=2000)
|
||||
|
||||
|
||||
def _parse_datetime(value: Optional[str]) -> Optional[datetime]:
|
||||
if value is None:
|
||||
return None
|
||||
@@ -73,6 +77,29 @@ def update_recurring_element(
|
||||
return item
|
||||
|
||||
|
||||
@router.post("/{recurring_id}/complete")
|
||||
def complete_recurring_practice(
|
||||
recurring_id: str,
|
||||
body: RecurringCompleteRequest,
|
||||
ctx: TenantContext = Depends(require_capability("kairo.recurring.manage")),
|
||||
):
|
||||
from services.cadence_instance import complete_open_instance
|
||||
|
||||
try:
|
||||
result = complete_open_instance(
|
||||
tenant_id=ctx.tenant_id,
|
||||
recurring_element_id=recurring_id,
|
||||
user_id=ctx.user_id or None,
|
||||
measurement_note=body.measurement_note or "",
|
||||
)
|
||||
except ValueError as exc:
|
||||
detail = str(exc)
|
||||
if detail == "Recurring-Element nicht gefunden":
|
||||
raise HTTPException(status_code=404, detail=detail) from exc
|
||||
raise HTTPException(status_code=400, detail=detail) from exc
|
||||
return result
|
||||
|
||||
|
||||
@router.delete("/{recurring_id}", status_code=204)
|
||||
def delete_recurring_element(
|
||||
recurring_id: str,
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
"""CadenceInstance service — AP A1.1 minimal daily practice tracking."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from services.audit import log_audit
|
||||
|
||||
CadenceStatus = Literal["open", "completed"]
|
||||
|
||||
_CADENCE_COLUMNS = """
|
||||
id, tenant_id, recurring_element_id, status, due_at,
|
||||
completed_at, measurement_note, created_at, updated_at
|
||||
"""
|
||||
|
||||
|
||||
def _serialize_row(row: dict[str, Any]) -> dict[str, Any]:
|
||||
result = dict(row)
|
||||
for key in ("id", "tenant_id", "recurring_element_id"):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
for ts_key in ("due_at", "completed_at", "created_at", "updated_at"):
|
||||
if result.get(ts_key):
|
||||
result[ts_key] = result[ts_key].isoformat()
|
||||
return result
|
||||
|
||||
|
||||
def get_open_instance(
|
||||
*, tenant_id: str, recurring_element_id: str
|
||||
) -> Optional[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT {_CADENCE_COLUMNS}
|
||||
FROM cadence_instances
|
||||
WHERE tenant_id = %s
|
||||
AND recurring_element_id = %s
|
||||
AND status = 'open'
|
||||
LIMIT 1
|
||||
""",
|
||||
(tenant_id, recurring_element_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _serialize_row(dict(row)) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def ensure_open_instance(
|
||||
*,
|
||||
tenant_id: str,
|
||||
recurring_element_id: str,
|
||||
due_at: Optional[datetime] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Ensure exactly one open CadenceInstance (idempotent)."""
|
||||
existing = get_open_instance(
|
||||
tenant_id=tenant_id, recurring_element_id=recurring_element_id
|
||||
)
|
||||
if existing:
|
||||
return existing
|
||||
|
||||
due = due_at or datetime.now(timezone.utc)
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
INSERT INTO cadence_instances (
|
||||
tenant_id, recurring_element_id, status, due_at
|
||||
)
|
||||
VALUES (%s, %s, 'open', %s)
|
||||
RETURNING {_CADENCE_COLUMNS}
|
||||
""",
|
||||
(tenant_id, recurring_element_id, due),
|
||||
)
|
||||
row = _serialize_row(dict(cur.fetchone()))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return row
|
||||
|
||||
|
||||
def complete_open_instance(
|
||||
*,
|
||||
tenant_id: str,
|
||||
recurring_element_id: str,
|
||||
user_id: Optional[str] = None,
|
||||
measurement_note: str = "",
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Close open instance, advance recurring next_due_at, open next instance.
|
||||
Returns { completed, recurring, next_instance }.
|
||||
"""
|
||||
from services.recurring import get_recurring_element, update_recurring_element
|
||||
|
||||
recurring = get_recurring_element(
|
||||
tenant_id=tenant_id, recurring_id=recurring_element_id
|
||||
)
|
||||
if not recurring:
|
||||
raise ValueError("Recurring-Element nicht gefunden")
|
||||
if recurring["status"] != "active":
|
||||
raise ValueError("Recurring-Element ist nicht aktiv")
|
||||
|
||||
open_inst = get_open_instance(
|
||||
tenant_id=tenant_id, recurring_element_id=recurring_element_id
|
||||
)
|
||||
if not open_inst:
|
||||
open_inst = ensure_open_instance(
|
||||
tenant_id=tenant_id,
|
||||
recurring_element_id=recurring_element_id,
|
||||
due_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
note = (measurement_note or "").strip()
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
UPDATE cadence_instances
|
||||
SET status = 'completed',
|
||||
completed_at = %s,
|
||||
measurement_note = %s,
|
||||
updated_at = NOW()
|
||||
WHERE id = %s AND tenant_id = %s AND status = 'open'
|
||||
RETURNING {_CADENCE_COLUMNS}
|
||||
""",
|
||||
(now, note, open_inst["id"], tenant_id),
|
||||
)
|
||||
completed_row = cur.fetchone()
|
||||
if not completed_row:
|
||||
raise ValueError("Keine offene Cadence-Instanz")
|
||||
completed = _serialize_row(dict(completed_row))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
interval = recurring.get("interval_days") or 1
|
||||
next_due = now + timedelta(days=int(interval))
|
||||
|
||||
update_recurring_element(
|
||||
tenant_id=tenant_id,
|
||||
recurring_id=recurring_element_id,
|
||||
user_id=user_id,
|
||||
next_due_at=next_due,
|
||||
)
|
||||
|
||||
next_instance = ensure_open_instance(
|
||||
tenant_id=tenant_id,
|
||||
recurring_element_id=recurring_element_id,
|
||||
due_at=next_due,
|
||||
)
|
||||
|
||||
log_audit(
|
||||
"cadence_instance.completed",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={
|
||||
"cadence_instance_id": completed["id"],
|
||||
"recurring_id": recurring_element_id,
|
||||
"measurement_note": note[:200] if note else "",
|
||||
},
|
||||
)
|
||||
|
||||
updated_recurring = get_recurring_element(
|
||||
tenant_id=tenant_id, recurring_id=recurring_element_id
|
||||
)
|
||||
return {
|
||||
"completed_instance": completed,
|
||||
"next_instance": next_instance,
|
||||
"recurring": updated_recurring,
|
||||
}
|
||||
|
||||
|
||||
def attach_open_instances_to_recurring_list(
|
||||
items: list[dict[str, Any]], *, tenant_id: str
|
||||
) -> list[dict[str, Any]]:
|
||||
if not items:
|
||||
return items
|
||||
ids = [item["id"] for item in items]
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT {_CADENCE_COLUMNS}
|
||||
FROM cadence_instances
|
||||
WHERE tenant_id = %s
|
||||
AND recurring_element_id = ANY(%s::uuid[])
|
||||
AND status = 'open'
|
||||
""",
|
||||
(tenant_id, ids),
|
||||
)
|
||||
by_recurring = {
|
||||
str(row["recurring_element_id"]): _serialize_row(dict(row))
|
||||
for row in cur.fetchall()
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
enriched = []
|
||||
for item in items:
|
||||
copy = dict(item)
|
||||
open_inst = by_recurring.get(item["id"])
|
||||
if not open_inst and item.get("status") == "active":
|
||||
open_inst = ensure_open_instance(
|
||||
tenant_id=tenant_id,
|
||||
recurring_element_id=item["id"],
|
||||
)
|
||||
copy["open_cadence_instance"] = open_inst
|
||||
enriched.append(copy)
|
||||
return enriched
|
||||
@@ -90,6 +90,16 @@ def create_recurring_element(
|
||||
tenant_id=tenant_id,
|
||||
details={"recurring_id": row["id"], "initiative_id": initiative_id},
|
||||
)
|
||||
|
||||
from services.cadence_instance import ensure_open_instance
|
||||
|
||||
due = next_due_at or datetime.now(timezone.utc)
|
||||
open_inst = ensure_open_instance(
|
||||
tenant_id=tenant_id,
|
||||
recurring_element_id=row["id"],
|
||||
due_at=due,
|
||||
)
|
||||
row["open_cadence_instance"] = open_inst
|
||||
return row
|
||||
|
||||
|
||||
@@ -111,10 +121,14 @@ def list_recurring_for_initiative(
|
||||
""",
|
||||
(tenant_id, initiative_id),
|
||||
)
|
||||
return [_serialize_row(dict(r)) for r in cur.fetchall()]
|
||||
rows = [_serialize_row(dict(r)) for r in cur.fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
from services.cadence_instance import attach_open_instances_to_recurring_list
|
||||
|
||||
return attach_open_instances_to_recurring_list(rows, tenant_id=tenant_id)
|
||||
|
||||
|
||||
def get_recurring_element(
|
||||
*, tenant_id: str, recurring_id: str
|
||||
|
||||
@@ -22,10 +22,11 @@ def recurring_due_candidates(
|
||||
re.title AS title,
|
||||
'Wiederkehrendes Element fällig' AS summary,
|
||||
re.initiative_id,
|
||||
re.id AS recurring_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS backlog_item_id,
|
||||
'recurring_due' AS reason_code,
|
||||
'Rhythmus-Element bearbeiten' AS recommended_action
|
||||
'Übung heute erledigen' AS recommended_action
|
||||
FROM recurring_elements re
|
||||
WHERE re.tenant_id = %s AND re.initiative_id = %s
|
||||
AND re.status = 'active'
|
||||
@@ -40,6 +41,8 @@ def recurring_due_candidates(
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
if item.get("recurring_id"):
|
||||
item["recurring_id"] = str(item["recurring_id"])
|
||||
items.append(item)
|
||||
return items
|
||||
finally:
|
||||
@@ -60,10 +63,11 @@ def active_recurring_candidates(
|
||||
re.title AS title,
|
||||
'Heutige Übung / Routine' AS summary,
|
||||
re.initiative_id,
|
||||
re.id AS recurring_id,
|
||||
NULL::uuid AS action_id,
|
||||
NULL::uuid AS backlog_item_id,
|
||||
'recurring_active' AS reason_code,
|
||||
'Routine ausführen' AS recommended_action
|
||||
'Übung heute erledigen' AS recommended_action
|
||||
FROM recurring_elements re
|
||||
WHERE re.tenant_id = %s AND re.initiative_id = %s
|
||||
AND re.status = 'active'
|
||||
@@ -76,6 +80,8 @@ def active_recurring_candidates(
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["initiative_id"] = str(item["initiative_id"])
|
||||
if item.get("recurring_id"):
|
||||
item["recurring_id"] = str(item["recurring_id"])
|
||||
items.append(item)
|
||||
return items
|
||||
finally:
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""AP A1.1 — CadenceInstance complete practice flow."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.factories import provision_user_in_tenant
|
||||
from tests.test_initiatives_actions import _auth, _create_initiative, _login
|
||||
|
||||
|
||||
def test_complete_daily_practice_advances_cadence(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
|
||||
created = _create_initiative(
|
||||
client,
|
||||
token,
|
||||
title="Spagat Cadence",
|
||||
archetype_key="initiative.maturity_journey",
|
||||
)
|
||||
initiative_id = created.json()["id"]
|
||||
|
||||
recurring = client.get(
|
||||
f"/api/initiatives/{initiative_id}/recurring",
|
||||
headers=_auth(token),
|
||||
).json()
|
||||
assert recurring
|
||||
item = recurring[0]
|
||||
assert item.get("open_cadence_instance")
|
||||
assert item["open_cadence_instance"]["status"] == "open"
|
||||
recurring_id = item["id"]
|
||||
|
||||
completed = client.post(
|
||||
f"/api/recurring/{recurring_id}/complete",
|
||||
json={"measurement_note": "45° Spagat gehalten"},
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert completed.status_code == 200
|
||||
body = completed.json()
|
||||
assert body["completed_instance"]["status"] == "completed"
|
||||
assert body["completed_instance"]["measurement_note"] == "45° Spagat gehalten"
|
||||
assert body["next_instance"]["status"] == "open"
|
||||
assert body["recurring"]["next_due_at"]
|
||||
|
||||
refreshed = client.get(
|
||||
f"/api/initiatives/{initiative_id}/recurring",
|
||||
headers=_auth(token),
|
||||
).json()
|
||||
assert refreshed[0]["open_cadence_instance"]["id"] == body["next_instance"]["id"]
|
||||
|
||||
|
||||
def test_steering_next_action_includes_recurring_id(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
token = _login(client, user)
|
||||
|
||||
created = _create_initiative(
|
||||
client,
|
||||
token,
|
||||
title="Spagat Next",
|
||||
archetype_key="initiative.maturity_journey",
|
||||
)
|
||||
initiative_id = created.json()["id"]
|
||||
|
||||
snap = client.get(
|
||||
f"/api/initiatives/{initiative_id}/steering-snapshot",
|
||||
headers=_auth(token),
|
||||
)
|
||||
assert snap.status_code == 200
|
||||
next_actions = snap.json().get("next_actions") or []
|
||||
recurring_items = [a for a in next_actions if a.get("kind") == "recurring_due"]
|
||||
assert recurring_items
|
||||
assert recurring_items[0].get("recurring_id")
|
||||
@@ -82,6 +82,8 @@ def test_operating_context_maturity(client):
|
||||
body = res.json()
|
||||
assert body["method_key"] == "maturity_progression"
|
||||
assert any(s["key"] == "journey" for s in body["ui_profile"]["processSteps"])
|
||||
assert "inbox" not in (body["ui_profile"].get("planOutlineKeys") or [])
|
||||
assert body["ui_profile"]["planOutlineKeys"] == ["profile", "gates", "work"]
|
||||
|
||||
|
||||
def test_operating_context_program(client):
|
||||
|
||||
Reference in new issue
Block a user