Fixed Taiga integration
This commit is contained in:
@@ -6,8 +6,8 @@ from app.config import get_settings
|
||||
from app.integrations.taiga import TaigaClient
|
||||
from app.projects.service import ProjectService
|
||||
|
||||
MAX_PROJECTS_IN_CONTEXT = 8
|
||||
MAX_OPEN_PER_PROJECT = 5
|
||||
MAX_PROJECTS_IN_CONTEXT = 20
|
||||
MAX_OPEN_PER_PROJECT = 8
|
||||
|
||||
|
||||
def get_projects_snapshot(db: Session) -> dict[str, Any]:
|
||||
@@ -21,11 +21,18 @@ def get_projects_snapshot(db: Session) -> dict[str, Any]:
|
||||
if not projects:
|
||||
try:
|
||||
projects = service.sync_taiga_projects()
|
||||
except Exception:
|
||||
projects = []
|
||||
except Exception as exc:
|
||||
return {
|
||||
"configured": True,
|
||||
"projects": [],
|
||||
"open_items": [],
|
||||
"taiga_open": [],
|
||||
"error": str(exc),
|
||||
}
|
||||
|
||||
open_items = service.list_work_items(limit=15, status="open")
|
||||
taiga_open: list[dict[str, Any]] = []
|
||||
fetch_error: str | None = None
|
||||
|
||||
try:
|
||||
client = TaigaClient()
|
||||
@@ -33,8 +40,7 @@ def get_projects_snapshot(db: Session) -> dict[str, Any]:
|
||||
stories = client.list_open_userstories(
|
||||
proj["taiga_id"], limit=MAX_OPEN_PER_PROJECT
|
||||
)
|
||||
if not stories:
|
||||
continue
|
||||
tasks = client.list_open_tasks(proj["taiga_id"], limit=MAX_OPEN_PER_PROJECT)
|
||||
taiga_open.append(
|
||||
{
|
||||
"slug": proj["slug"],
|
||||
@@ -46,16 +52,24 @@ def get_projects_snapshot(db: Session) -> dict[str, Any]:
|
||||
}
|
||||
for s in stories
|
||||
],
|
||||
"tasks": [
|
||||
{
|
||||
"ref": t.get("ref"),
|
||||
"subject": t.get("subject", "")[:120],
|
||||
}
|
||||
for t in tasks
|
||||
],
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as exc:
|
||||
fetch_error = str(exc)
|
||||
|
||||
return {
|
||||
"configured": True,
|
||||
"projects": projects,
|
||||
"open_items": open_items,
|
||||
"taiga_open": taiga_open,
|
||||
"error": fetch_error,
|
||||
}
|
||||
|
||||
|
||||
@@ -63,13 +77,16 @@ def format_projects_context(snapshot: dict[str, Any]) -> str:
|
||||
if not snapshot.get("configured"):
|
||||
return "[Taiga/Gitea]\nНе настроено (нет TAIGA_USERNAME/PASSWORD в .env)."
|
||||
|
||||
lines = ["[Проекты и задачи — актуальный снимок для контекста]"]
|
||||
lines = ["[Проекты и задачи — снимок на начало ответа]"]
|
||||
|
||||
if snapshot.get("error"):
|
||||
lines.append(f"⚠ Ошибка загрузки задач из Taiga: {snapshot['error']}")
|
||||
|
||||
projects = snapshot.get("projects") or []
|
||||
if not projects:
|
||||
lines.append("Проекты Taiga: кэш пуст. Попроси sync_taiga_projects или проверь подключение.")
|
||||
lines.append("Проекты Taiga: кэш пуст. Вызови sync_taiga_projects.")
|
||||
else:
|
||||
lines.append("Проекты Taiga:")
|
||||
lines.append(f"Проекты Taiga ({len(projects)}):")
|
||||
for p in projects[:MAX_PROJECTS_IN_CONTEXT]:
|
||||
gitea = (
|
||||
f"{p.get('gitea_owner')}/{p.get('gitea_repo')}"
|
||||
@@ -78,32 +95,39 @@ def format_projects_context(snapshot: dict[str, Any]) -> str:
|
||||
)
|
||||
lines.append(f"- `{p.get('slug')}`: {p.get('name')} · {gitea}")
|
||||
|
||||
open_items = snapshot.get("open_items") or []
|
||||
if open_items:
|
||||
lines.append("")
|
||||
lines.append("Локальные work items (созданные ассистентом, открытые):")
|
||||
for item in open_items[:10]:
|
||||
gitea_part = f", gitea #{item.get('gitea_issue')}" if item.get("gitea_issue") else ""
|
||||
lines.append(
|
||||
f"- taiga #{item.get('taiga_ref')} {item.get('title')} "
|
||||
f"({item.get('taiga_slug')}{gitea_part})"
|
||||
)
|
||||
|
||||
taiga_open = snapshot.get("taiga_open") or []
|
||||
if taiga_open:
|
||||
lines.append("")
|
||||
lines.append("Открытые user stories в Taiga:")
|
||||
lines.append("Открытые задачи в Taiga (live):")
|
||||
for block in taiga_open:
|
||||
lines.append(f" [{block.get('slug')}]")
|
||||
for story in block.get("stories", []):
|
||||
lines.append(f" - #{story.get('ref')} {story.get('subject')}")
|
||||
elif projects:
|
||||
stories = block.get("stories") or []
|
||||
tasks = block.get("tasks") or []
|
||||
if not stories and not tasks:
|
||||
lines.append(f" `{block.get('slug')}`: нет открытых")
|
||||
continue
|
||||
lines.append(f" `{block.get('slug')}`:")
|
||||
for story in stories:
|
||||
lines.append(f" story #{story.get('ref')} {story.get('subject')}")
|
||||
for task in tasks:
|
||||
lines.append(f" task #{task.get('ref')} {task.get('subject')}")
|
||||
|
||||
open_items = snapshot.get("open_items") or []
|
||||
if open_items:
|
||||
lines.append("")
|
||||
lines.append("Открытые user stories в Taiga: нет или не удалось загрузить.")
|
||||
lines.append("Work items созданные ассистентом (локальная БД):")
|
||||
for item in open_items[:10]:
|
||||
gitea_part = f", gitea #{item.get('gitea_issue')}" if item.get("gitea_issue") else ""
|
||||
lines.append(
|
||||
f"- #{item.get('taiga_ref')} {item.get('title')} "
|
||||
f"({item.get('taiga_slug')}{gitea_part})"
|
||||
)
|
||||
|
||||
lines.append("")
|
||||
lines.append(
|
||||
"Для создания фичи/бага из вольного текста используй create_work_item. "
|
||||
"Не выдумывай номера задач — опирайся на список выше."
|
||||
"Правила: "
|
||||
"«какие задачи» → list_taiga_tasks (Taiga API), НЕ list_work_items. "
|
||||
"list_work_items — только созданные через ассистента. "
|
||||
"Не пиши «ожидаю систему» — сразу вызывай tool или отвечай из снимка выше. "
|
||||
"create_work_item — для новых фич/багов из вольного текста."
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
@@ -366,6 +366,63 @@ class ProjectService:
|
||||
item.status = "closed"
|
||||
item.closed_at = datetime.now(timezone.utc)
|
||||
|
||||
def list_taiga_open_tasks(
|
||||
self,
|
||||
project_slug: str | None = None,
|
||||
limit: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
if not self.settings.taiga_configured:
|
||||
raise ValueError("Taiga не настроена")
|
||||
|
||||
projects = self.list_projects()
|
||||
if not projects:
|
||||
projects = self.sync_taiga_projects()
|
||||
|
||||
if project_slug:
|
||||
projects = [p for p in projects if p["slug"] == project_slug]
|
||||
if not projects:
|
||||
raise ValueError(
|
||||
f"Проект '{project_slug}' не найден. Вызови sync_taiga_projects."
|
||||
)
|
||||
|
||||
client = TaigaClient()
|
||||
blocks: list[dict[str, Any]] = []
|
||||
|
||||
for proj in projects:
|
||||
stories = client.list_open_userstories(proj["taiga_id"], limit=limit)
|
||||
tasks = client.list_open_tasks(proj["taiga_id"], limit=limit)
|
||||
blocks.append(
|
||||
{
|
||||
"slug": proj["slug"],
|
||||
"name": proj["name"],
|
||||
"taiga_id": proj["taiga_id"],
|
||||
"stories": [
|
||||
{
|
||||
"ref": s.get("ref"),
|
||||
"subject": s.get("subject", ""),
|
||||
"url": client.story_url(proj["taiga_id"], s.get("ref", 0)),
|
||||
}
|
||||
for s in stories
|
||||
],
|
||||
"tasks": [
|
||||
{
|
||||
"ref": t.get("ref"),
|
||||
"subject": t.get("subject", ""),
|
||||
"user_story": t.get("user_story"),
|
||||
}
|
||||
for t in tasks
|
||||
],
|
||||
}
|
||||
)
|
||||
|
||||
total_stories = sum(len(b["stories"]) for b in blocks)
|
||||
total_tasks = sum(len(b["tasks"]) for b in blocks)
|
||||
return {
|
||||
"projects": blocks,
|
||||
"total_stories": total_stories,
|
||||
"total_tasks": total_tasks,
|
||||
}
|
||||
|
||||
def list_work_items(self, limit: int = 30, status: str | None = None) -> list[dict[str, Any]]:
|
||||
stmt = select(WorkItem).order_by(WorkItem.created_at.desc()).limit(limit)
|
||||
if status:
|
||||
|
||||
Reference in New Issue
Block a user