feat(sprint7.7): версионирование графа шагов в БД + UI переключения

Хранить старый 6-шаговый сценарий new_booking параллельно с новым 4-шаговым,
чтобы оператор мог откатиться или сравнить варианты. Активный граф ровно один,
переключение через UI «Настройки → Шаги».

Модель и миграция:
- Таблица intent_step_graphs (id, intent_id, version, name, is_active, created_at).
- intent_steps.graph_id FK + UNIQUE сменён с (intent_id, code) на (graph_id, code).
- Alembic-миграция j6d8c4b56g23 (batch_alter_table для SQLite).

Сервис и сидинг (services/intent_step_graph_service.py):
- ensure_seed_graphs идемпотентен: создаёт активный граф для каждой ветки,
  привязывает существующие шаги (graph_id IS NULL), для new_booking
  восстанавливает архивный v1 из _archived_v1/*.md и _PRE_SPRINT_7_6_ALLOWED_NEXT.
- Активный граф new_booking сжат до 4 шагов: deprecated present/offer_time
  удаляются из активного, остаются только в архивном v1.
- list_graphs / get_active_graph / set_active_graph.

API:
- GET /intents/{code}/step-graphs — список с steps_count и is_active.
- POST /intents/{code}/step-graphs/{graph_id}/activate.
- list_steps_for_intent / get_step_by_code / get_first_step фильтруют
  по активному графу через _active_graph_filter (join с intent_step_graphs).
- ensure_seed_guards и migrate_new_booking_allowed_next_v2 защищены: не
  трогают шаги архивных графов.

UI (static/settings.html):
- Во вкладке «Шаги» вверху блок «Версии графа шагов»: карточки с именем,
  кол-вом шагов, бейджем «активная» или кнопкой «Активировать». При
  переключении заголовок меняется «Шаги (4)» ↔ «Шаги (6)».
- Раздел «Тест-вопрос от пациента» сделан сворачиваемым (details/summary
  в стиле prompt-block).

Промпты архивного графа восстановлены из коммита 60f8a7b^ в
prompts/intents/new_booking/steps/_archived_v1/*.md.

SPRINTS.md: Спринт 7.7 →  Закрыт.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
AR 15 M4
2026-05-02 14:29:07 +05:00
parent 60f8a7b398
commit a79b6f9d05
18 changed files with 799 additions and 65 deletions
+56 -2
View File
@@ -3,7 +3,7 @@ import logging
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from db.models import Intent, IntentStep
from db.models import Intent, IntentStep, IntentStepGraph
from db.session import get_session
from models.requests import (
IntentDocumentsUpdateRequest,
@@ -14,10 +14,18 @@ from models.responses import (
IntentDocumentsResponse,
IntentInfo,
IntentListResponse,
IntentStepGraphInfo,
IntentStepGraphListResponse,
IntentStepInfo,
IntentStepListResponse,
)
from services import config_service, intent_document_service, intent_service, intent_step_service
from services import (
config_service,
intent_document_service,
intent_service,
intent_step_graph_service,
intent_step_service,
)
logger = logging.getLogger(__name__)
@@ -93,6 +101,52 @@ async def list_intent_steps(code: str, session: AsyncSession = Depends(get_sessi
)
def _graph_to_info(graph: IntentStepGraph, intent_code: str, steps_count: int) -> IntentStepGraphInfo:
return IntentStepGraphInfo(
id=graph.id,
intent_code=intent_code,
version=graph.version,
name=graph.name,
is_active=graph.is_active,
steps_count=steps_count,
created_at=graph.created_at.isoformat(),
)
@router.get("/{code}/step-graphs", response_model=IntentStepGraphListResponse)
async def list_intent_step_graphs(code: str, session: AsyncSession = Depends(get_session)):
intent = await intent_service.get_intent_by_code(session, code)
if intent is None:
raise HTTPException(status_code=404, detail="Intent not found")
pairs = await intent_step_graph_service.list_graphs(session, intent.id)
active_id = next((g.id for g, _ in pairs if g.is_active), None)
return IntentStepGraphListResponse(
intent_code=intent.code,
graphs=[_graph_to_info(g, intent.code, c) for g, c in pairs],
active_graph_id=active_id,
total=len(pairs),
)
@router.post("/{code}/step-graphs/{graph_id}/activate", response_model=IntentStepGraphListResponse)
async def activate_intent_step_graph(
code: str, graph_id: int, session: AsyncSession = Depends(get_session)
):
intent = await intent_service.get_intent_by_code(session, code)
if intent is None:
raise HTTPException(status_code=404, detail="Intent not found")
target = await intent_step_graph_service.set_active_graph(session, intent.id, graph_id)
if target is None:
raise HTTPException(status_code=404, detail="Step graph not found")
pairs = await intent_step_graph_service.list_graphs(session, intent.id)
return IntentStepGraphListResponse(
intent_code=intent.code,
graphs=[_graph_to_info(g, intent.code, c) for g, c in pairs],
active_graph_id=target.id,
total=len(pairs),
)
@router.patch("/{code}/steps/{step_code}", response_model=IntentStepInfo)
async def update_intent_step(
code: str,