Spaces:
Running
Running
Download backend/app/api/playbook.py from axeronis/microfunnel-api: direct link, hf CLI and curl.
- Browser
- Download file 33.3 kB
-
https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/api/playbook.py
- Command line
-
hf download hf://spaces/axeronis/microfunnel-api/backend/app/api/playbook.py
-
curl -L -o playbook.py https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/api/playbook.py
33.3 kB
| from fastapi import APIRouter, Depends, HTTPException, status | |
| from sqlmodel import select | |
| from sqlmodel.ext.asyncio.session import AsyncSession | |
| from pydantic import BaseModel | |
| from typing import List, Optional, Dict | |
| from uuid import UUID | |
| from datetime import datetime | |
| from app.core.database import get_async_session | |
| from app.api.deps import get_current_user | |
| from app.models import User, SalesStage, Tenant | |
| from sqlalchemy.orm.attributes import flag_modified | |
| router = APIRouter(prefix="/playbook", tags=["Playbook"]) | |
| # ============================================================================ | |
| # Sync Helper | |
| # ============================================================================ | |
| async def sync_tenant_qualification_fields(session: AsyncSession, tenant_id: UUID): | |
| """ | |
| Collect all unique exit_criteria from active stages and merge them into | |
| tenant.ai_settings["qualification_fields"]. This ensures AI extraction | |
| uses the same fields defined in the funnel. | |
| """ | |
| # Get all active stages | |
| result = await session.execute( | |
| select(SalesStage) | |
| .where(SalesStage.tenant_id == tenant_id) | |
| .where(SalesStage.is_active == True) | |
| ) | |
| stages = result.scalars().all() | |
| # Collect unique criteria from all stages | |
| all_criteria = set() | |
| for stage in stages: | |
| for criterion in (stage.exit_criteria or []): | |
| if criterion and criterion.strip(): | |
| all_criteria.add(criterion.strip()) | |
| # Get tenant | |
| tenant = await session.get(Tenant, tenant_id) | |
| if not tenant: | |
| return | |
| # Merge with existing qualification_fields (preserve user additions) | |
| ai_settings = tenant.ai_settings or {} | |
| existing_fields = set(ai_settings.get("qualification_fields", [])) | |
| # Combine: all stage criteria + existing fields | |
| merged_fields = list(all_criteria | existing_fields) | |
| # Update tenant | |
| ai_settings["qualification_fields"] = merged_fields | |
| ai_settings["custom_fields"] = merged_fields # Backward compat in ai_settings JSON | |
| tenant.ai_settings = ai_settings | |
| flag_modified(tenant, "ai_settings") | |
| session.add(tenant) | |
| await session.commit() | |
| print(f"✅ Synced {len(merged_fields)} qualification fields for tenant {tenant_id}") | |
| # ============================================================================ | |
| # Schemas | |
| # ============================================================================ | |
| class SalesStageCreate(BaseModel): | |
| name: str | |
| description: Optional[str] = None | |
| ai_goal: str | |
| exit_criteria: List[str] = [] | |
| class SalesStageUpdate(BaseModel): | |
| name: Optional[str] = None | |
| description: Optional[str] = None | |
| ai_goal: Optional[str] = None | |
| exit_criteria: Optional[List[str]] = None | |
| class ReorderRequest(BaseModel): | |
| stage_ids: List[UUID] # New order of stage IDs | |
| class TemplateInfo(BaseModel): | |
| id: str | |
| name: str | |
| class TemplatesResponse(BaseModel): | |
| templates: List[TemplateInfo] | |
| class TemplateType(str): | |
| """Playbook template types.""" | |
| REAL_ESTATE = "real_estate" | |
| B2B_SAAS = "b2b_saas" | |
| CONSULTING = "consulting" | |
| ECOMMERCE = "ecommerce" | |
| FINANCIAL = "financial" | |
| class SalesStageResponse(BaseModel): | |
| id: UUID | |
| tenant_id: UUID | |
| name: str | |
| description: Optional[str] | |
| order_index: int | |
| ai_goal: str | |
| exit_criteria: List[str] | |
| is_active: bool | |
| created_at: datetime | |
| updated_at: datetime | |
| # ============================================================================ | |
| # Endpoints | |
| # ============================================================================ | |
| async def list_stages( | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| List all sales stages for current tenant, ordered by order_index. | |
| """ | |
| result = await session.execute( | |
| select(SalesStage) | |
| .where(SalesStage.tenant_id == current_user.tenant_id) | |
| .where(SalesStage.is_active == True) | |
| .order_by(SalesStage.order_index) | |
| ) | |
| stages = result.scalars().all() | |
| return [ | |
| SalesStageResponse( | |
| id=stage.id, | |
| tenant_id=stage.tenant_id, | |
| name=stage.name, | |
| description=stage.description, | |
| order_index=stage.order_index, | |
| ai_goal=stage.ai_goal, | |
| exit_criteria=stage.exit_criteria or [], | |
| is_active=stage.is_active, | |
| created_at=stage.created_at, | |
| updated_at=stage.updated_at | |
| ) | |
| for stage in stages | |
| ] | |
| async def create_stage( | |
| request: SalesStageCreate, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Create a new sales stage for current tenant. | |
| Automatically assigns next order_index. | |
| """ | |
| # Get max order_index | |
| result = await session.execute( | |
| select(SalesStage) | |
| .where(SalesStage.tenant_id == current_user.tenant_id) | |
| .order_by(SalesStage.order_index.desc()) | |
| ) | |
| last_stage = result.scalars().first() | |
| next_order = (last_stage.order_index + 1) if last_stage else 1 | |
| # Create new stage | |
| new_stage = SalesStage( | |
| tenant_id=current_user.tenant_id, | |
| name=request.name, | |
| description=request.description, | |
| ai_goal=request.ai_goal, | |
| exit_criteria=request.exit_criteria, | |
| order_index=next_order, | |
| is_active=True | |
| ) | |
| session.add(new_stage) | |
| await session.commit() | |
| await session.refresh(new_stage) | |
| # Sync exit criteria to tenant qualification fields | |
| await sync_tenant_qualification_fields(session, current_user.tenant_id) | |
| return SalesStageResponse( | |
| id=new_stage.id, | |
| tenant_id=new_stage.tenant_id, | |
| name=new_stage.name, | |
| description=new_stage.description, | |
| order_index=new_stage.order_index, | |
| ai_goal=new_stage.ai_goal, | |
| exit_criteria=new_stage.exit_criteria or [], | |
| is_active=new_stage.is_active, | |
| created_at=new_stage.created_at, | |
| updated_at=new_stage.updated_at | |
| ) | |
| async def update_stage( | |
| stage_id: UUID, | |
| request: SalesStageUpdate, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Update an existing sales stage. | |
| """ | |
| # Get stage | |
| result = await session.execute( | |
| select(SalesStage) | |
| .where(SalesStage.id == stage_id) | |
| .where(SalesStage.tenant_id == current_user.tenant_id) | |
| ) | |
| stage = result.scalar_one_or_none() | |
| if not stage: | |
| raise HTTPException( | |
| status_code=status.HTTP_404_NOT_FOUND, | |
| detail="Stage not found" | |
| ) | |
| # Update fields | |
| if request.name is not None: | |
| stage.name = request.name | |
| if request.description is not None: | |
| stage.description = request.description | |
| if request.ai_goal is not None: | |
| stage.ai_goal = request.ai_goal | |
| if request.exit_criteria is not None: | |
| stage.exit_criteria = request.exit_criteria | |
| stage.updated_at = datetime.utcnow() | |
| session.add(stage) | |
| await session.commit() | |
| await session.refresh(stage) | |
| # Sync exit criteria to tenant qualification fields | |
| await sync_tenant_qualification_fields(session, current_user.tenant_id) | |
| return SalesStageResponse( | |
| id=stage.id, | |
| tenant_id=stage.tenant_id, | |
| name=stage.name, | |
| description=stage.description, | |
| order_index=stage.order_index, | |
| ai_goal=stage.ai_goal, | |
| exit_criteria=stage.exit_criteria or [], | |
| is_active=stage.is_active, | |
| created_at=stage.created_at, | |
| updated_at=stage.updated_at | |
| ) | |
| async def reorder_stages( | |
| request: ReorderRequest, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Reorder stages by providing list of IDs in new order. | |
| """ | |
| # Verify all stages belong to current tenant | |
| result = await session.execute( | |
| select(SalesStage) | |
| .where(SalesStage.id.in_(request.stage_ids)) | |
| .where(SalesStage.tenant_id == current_user.tenant_id) | |
| ) | |
| stages = result.scalars().all() | |
| if len(stages) != len(request.stage_ids): | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="Some stages not found or not owned by tenant" | |
| ) | |
| # Update order_index for each stage | |
| stage_map = {stage.id: stage for stage in stages} | |
| for new_index, stage_id in enumerate(request.stage_ids, start=1): | |
| stage = stage_map[stage_id] | |
| stage.order_index = new_index | |
| stage.updated_at = datetime.utcnow() | |
| session.add(stage) | |
| await session.commit() | |
| return {"message": "Stages reordered successfully"} | |
| async def delete_stage( | |
| stage_id: UUID, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Soft delete a sales stage (sets is_active=False). | |
| """ | |
| # Get stage | |
| result = await session.execute( | |
| select(SalesStage) | |
| .where(SalesStage.id == stage_id) | |
| .where(SalesStage.tenant_id == current_user.tenant_id) | |
| ) | |
| stage = result.scalar_one_or_none() | |
| if not stage: | |
| raise HTTPException( | |
| status_code=status.HTTP_404_NOT_FOUND, | |
| detail="Stage not found" | |
| ) | |
| # Soft delete | |
| stage.is_active = False | |
| stage.updated_at = datetime.utcnow() | |
| session.add(stage) | |
| await session.commit() | |
| # Sync exit criteria to tenant qualification fields (recalculate) | |
| await sync_tenant_qualification_fields(session, current_user.tenant_id) | |
| return None | |
| # ============================================================================ | |
| # Template Presets | |
| # ============================================================================ | |
| PLAYBOOK_TEMPLATES: Dict[str, List[Dict]] = { | |
| "real_estate": [ | |
| { | |
| "name": "Первый контакт", | |
| "description": "Знакомство с клиентом и выявление интереса", | |
| "ai_goal": "Установить контакт, узнать, что именно ищет клиент (квартира/дом, район, бюджет). Создать доверительную атмосферу.", | |
| "exit_criteria": ["Тип недвижимости", "Район", "Бюджет"] | |
| }, | |
| { | |
| "name": "Квалификация", | |
| "description": "Глубокое понимание потребностей", | |
| "ai_goal": "Выявить критерии выбора (количество комнат, этаж, инфраструктура). Узнать срочность покупки и способ оплаты (ипотека/наличные).", | |
| "exit_criteria": ["Срочность", "Способ оплаты", "Критерии выбора"] | |
| }, | |
| { | |
| "name": "Показ объектов", | |
| "description": "Презентация подходящих вариантов", | |
| "ai_goal": "Согласовать время показа, рассказать о преимуществах объектов. Собрать обратную связь после показа.", | |
| "exit_criteria": ["Дата показа", "Обратная связь"] | |
| }, | |
| { | |
| "name": "Принятие решения", | |
| "description": "Работа с возражениями и сделка", | |
| "ai_goal": "Ответить на вопросы, развеять сомнения. Обсудить условия сделки, помочь с документами.", | |
| "exit_criteria": ["Готовность к сделке"] | |
| } | |
| ], | |
| "b2b_saas": [ | |
| { | |
| "name": "Discovery", | |
| "description": "Выявление потребностей бизнеса", | |
| "ai_goal": "Понять текущие процессы клиента, проблемы, которые он хочет решить. Узнать размер команды и бюджет.", | |
| "exit_criteria": ["Боли клиента", "Размер команды", "Бюджет"] | |
| }, | |
| { | |
| "name": "Demo", | |
| "description": "Демонстрация продукта", | |
| "ai_goal": "Показать, как наш продукт решает конкретные проблемы клиента. Собрать вопросы и возражения.", | |
| "exit_criteria": ["Дата демо", "Заинтересованность"] | |
| }, | |
| { | |
| "name": "Trial", | |
| "description": "Тестовый период", | |
| "ai_goal": "Помочь с onboarding, ответить на вопросы. Узнать feedback и готовность к покупке.", | |
| "exit_criteria": ["Статус триала", "Feedback"] | |
| }, | |
| { | |
| "name": "Negotiation", | |
| "description": "Обсуждение условий", | |
| "ai_goal": "Обсудить тариф, условия оплаты, интеграции. Подготовить договор.", | |
| "exit_criteria": ["Тариф выбран", "Договор согласован"] | |
| } | |
| ], | |
| "consulting": [ | |
| { | |
| "name": "Консультация", | |
| "description": "Первичная встреча", | |
| "ai_goal": "Понять запрос клиента, его текущую ситуацию. Рассказать о нашем опыте в похожих проектах.", | |
| "exit_criteria": ["Запрос клиента", "Бюджет проекта"] | |
| }, | |
| { | |
| "name": "Анализ", | |
| "description": "Глубинный анализ задачи", | |
| "ai_goal": "Собрать дополнительную информацию, провести аудит. Выявить scope of work.", | |
| "exit_criteria": ["Scope проекта", "Сроки"] | |
| }, | |
| { | |
| "name": "Proposal", | |
| "description": "Коммерческое предложение", | |
| "ai_goal": "Представить план работы, стоимость, этапы. Ответить на вопросы.", | |
| "exit_criteria": ["Proposal отправлен", "Feedback получен"] | |
| }, | |
| { | |
| "name": "Договор", | |
| "description": "Подписание контракта", | |
| "ai_goal": "Согласовать условия, подписать договор, запланировать старт проекта.", | |
| "exit_criteria": ["Договор подписан"] | |
| } | |
| ], | |
| "ecommerce": [ | |
| { | |
| "name": "Интерес", | |
| "description": "Клиент заинтересовался товаром", | |
| "ai_goal": "Ответить на вопросы о товаре, характеристиках, доставке. Помочь с выбором.", | |
| "exit_criteria": ["Товар выбран"] | |
| }, | |
| { | |
| "name": "Корзина", | |
| "description": "Добавление в корзину", | |
| "ai_goal": "Предложить сопутствующие товары, рассказать о скидках. Напомнить о товаре, если клиент ушёл.", | |
| "exit_criteria": ["В корзине"] | |
| }, | |
| { | |
| "name": "Оформление", | |
| "description": "Процесс заказа", | |
| "ai_goal": "Помочь с оформлением, ответить на вопросы о доставке и оплате.", | |
| "exit_criteria": ["Адрес указан", "Способ оплаты выбран"] | |
| }, | |
| { | |
| "name": "Оплата", | |
| "description": "Завершение покупки", | |
| "ai_goal": "Подтвердить заказ, сообщить номер отслеживания. Попросить оставить отзыв после получения.", | |
| "exit_criteria": ["Заказ оплачен"] | |
| } | |
| ], | |
| "financial": [ | |
| { | |
| "name": "Знакомство", | |
| "description": "Первый контакт", | |
| "ai_goal": "Понять финансовые цели клиента (накопления, инвестиции, кредит). Оценить его текущую ситуацию.", | |
| "exit_criteria": ["Финансовая цель", "Доход"] | |
| }, | |
| { | |
| "name": "Анализ", | |
| "description": "Финансовый анализ", | |
| "ai_goal": "Собрать данные о доходах, расходах, активах. Оценить риск-профиль.", | |
| "exit_criteria": ["Финансовая ситуация", "Риск-профиль"] | |
| }, | |
| { | |
| "name": "Рекомендации", | |
| "description": "Предложение продуктов", | |
| "ai_goal": "Предложить подходящие финансовые продукты (вклады, инвестиции, страхование). Объяснить условия.", | |
| "exit_criteria": ["Продукт выбран"] | |
| }, | |
| { | |
| "name": "Оформление", | |
| "description": "Заключение договора", | |
| "ai_goal": "Помочь с документами, ответить на юридические вопросы. Оформить продукт.", | |
| "exit_criteria": ["Договор подписан"] | |
| } | |
| ] | |
| } | |
| async def get_template_types(): | |
| """ | |
| Get list of available playbook templates. | |
| """ | |
| return TemplatesResponse( | |
| templates=[ | |
| TemplateInfo(id="real_estate", name="🏠 Недвижимость"), | |
| TemplateInfo(id="b2b_saas", name="💼 B2B SaaS"), | |
| TemplateInfo(id="consulting", name="🎯 Консалтинг"), | |
| TemplateInfo(id="ecommerce", name="🛒 E-commerce"), | |
| TemplateInfo(id="financial", name="💰 Финансы") | |
| ] | |
| ) | |
| async def load_template( | |
| template_type: str, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Load a predefined playbook template. | |
| Deletes existing stages and creates new ones from template. | |
| """ | |
| if template_type not in PLAYBOOK_TEMPLATES: | |
| raise HTTPException( | |
| status_code=status.HTTP_404_NOT_FOUND, | |
| detail=f"Template '{template_type}' not found" | |
| ) | |
| # Delete existing stages (soft delete) | |
| result = await session.execute( | |
| select(SalesStage) | |
| .where(SalesStage.tenant_id == current_user.tenant_id) | |
| ) | |
| existing_stages = result.scalars().all() | |
| for stage in existing_stages: | |
| stage.is_active = False | |
| session.add(stage) | |
| # Create new stages from template | |
| template_stages = PLAYBOOK_TEMPLATES[template_type] | |
| created_stages = [] | |
| for order_index, stage_data in enumerate(template_stages, start=1): | |
| new_stage = SalesStage( | |
| tenant_id=current_user.tenant_id, | |
| name=stage_data["name"], | |
| description=stage_data.get("description"), | |
| ai_goal=stage_data["ai_goal"], | |
| exit_criteria=stage_data["exit_criteria"], | |
| order_index=order_index, | |
| is_active=True | |
| ) | |
| session.add(new_stage) | |
| created_stages.append(new_stage) | |
| await session.commit() | |
| # Refresh to get IDs | |
| for stage in created_stages: | |
| await session.refresh(stage) | |
| # Sync exit criteria to tenant qualification fields | |
| await sync_tenant_qualification_fields(session, current_user.tenant_id) | |
| return { | |
| "message": f"Template '{template_type}' loaded successfully", | |
| "stages_created": len(created_stages), | |
| "stages": [ | |
| SalesStageResponse( | |
| id=stage.id, | |
| tenant_id=stage.tenant_id, | |
| name=stage.name, | |
| description=stage.description, | |
| order_index=stage.order_index, | |
| ai_goal=stage.ai_goal, | |
| exit_criteria=stage.exit_criteria or [], | |
| is_active=stage.is_active, | |
| created_at=stage.created_at, | |
| updated_at=stage.updated_at | |
| ) | |
| for stage in created_stages | |
| ] | |
| } | |
| async def get_custom_fields( | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Get custom_fields from tenant's AI settings. | |
| These are the available fields for exit_criteria. | |
| """ | |
| # Get tenant | |
| result = await session.execute( | |
| select(Tenant).where(Tenant.id == current_user.tenant_id) | |
| ) | |
| tenant = result.scalar_one_or_none() | |
| if not tenant: | |
| raise HTTPException( | |
| status_code=status.HTTP_404_NOT_FOUND, | |
| detail="Tenant not found" | |
| ) | |
| # Extract qualification_fields from ai_settings | |
| default_fields = ["Имя", "Контакт", "Бюджет", "Срочность"] | |
| if tenant.ai_settings and isinstance(tenant.ai_settings, dict): | |
| # We exclusively use qualification_fields now, with fallback to legacy custom_fields | |
| custom_fields = tenant.ai_settings.get("qualification_fields") or tenant.ai_settings.get("custom_fields", default_fields) | |
| else: | |
| custom_fields = default_fields | |
| return custom_fields | |
| # ============================================================================ | |
| # AI Generation Endpoint | |
| # ============================================================================ | |
| class GeneratedStage(BaseModel): | |
| name: str | |
| description: str | |
| ai_goal: str | |
| exit_criteria: List[str] | |
| class GenerateFunnelResponse(BaseModel): | |
| success: bool | |
| stages: List[SalesStageResponse] | |
| message: str | |
| async def generate_funnel_with_ai( | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Generate optimal sales funnel stages using AI. | |
| Analyzes: | |
| - Tenant's business settings (type, description, selling style) | |
| - Knowledge base content | |
| - Products/services | |
| - Custom fields | |
| Returns generated stages tailored to the specific business. | |
| """ | |
| import json | |
| from app.models.knowledge import KnowledgeBase | |
| from app.models.product import Product | |
| # Get tenant | |
| result = await session.execute( | |
| select(Tenant).where(Tenant.id == current_user.tenant_id) | |
| ) | |
| tenant = result.scalar_one_or_none() | |
| if not tenant: | |
| raise HTTPException( | |
| status_code=status.HTTP_404_NOT_FOUND, | |
| detail="Tenant not found" | |
| ) | |
| # Gather business context | |
| business_type = tenant.business_type or "general" | |
| ai_settings = tenant.ai_settings or {} | |
| business_description = ai_settings.get("business_description", "") | |
| selling_style = ai_settings.get("selling_style", "Consultative") | |
| # Use qualification_fields (current) with fallback to custom_fields (legacy) | |
| custom_fields = ai_settings.get("qualification_fields") or ai_settings.get("custom_fields", ["Имя", "Контакт", "Бюджет", "Срочность"]) | |
| # Get knowledge base | |
| kb_result = await session.execute( | |
| select(KnowledgeBase) | |
| .where(KnowledgeBase.tenant_id == tenant.id) | |
| .where(KnowledgeBase.is_active == True) | |
| .limit(20) | |
| ) | |
| kb_items = kb_result.scalars().all() | |
| kb_summary = "\n".join([f"- [{item.category}] {item.content_chunk[:200]}..." for item in kb_items]) if kb_items else "Нет данных" | |
| # Get products/services | |
| prod_result = await session.execute( | |
| select(Product) | |
| .where(Product.tenant_id == tenant.id) | |
| .where(Product.is_active == True) | |
| .limit(10) | |
| ) | |
| products = prod_result.scalars().all() | |
| products_summary = "\n".join([f"- {p.name}: {p.price} {p.currency}" + (f" — {p.description[:100]}" if p.description else "") for p in products]) if products else "Нет товаров/услуг" | |
| # Build AI prompt | |
| prompt = f"""Ты эксперт по построению воронок продаж. Проанализируй бизнес и создай оптимальную воронку продаж. | |
| === ИНФОРМАЦИЯ О БИЗНЕСЕ === | |
| Тип бизнеса: {business_type} | |
| Описание: {business_description or "Не указано"} | |
| Стиль продаж: {selling_style} | |
| === ТОВАРЫ/УСЛУГИ === | |
| {products_summary} | |
| === БАЗА ЗНАНИЙ (выдержки) === | |
| {kb_summary} | |
| === ТЕКУЩИЕ ПОЛЯ ДЛЯ СБОРА === | |
| {', '.join(custom_fields) if custom_fields else 'Не указаны'} | |
| === ЗАДАЧА === | |
| 1. Создай воронку продаж из 3-5 этапов, оптимизированную под этот бизнес. | |
| 2. Предложи поля квалификации — какую информацию AI должен собирать у каждого клиента. | |
| Для каждого ЭТАПА укажи: | |
| - name — название этапа (короткое, 1-2 слова) | |
| - description — описание перехода клиента на этот этап | |
| - ai_goal — подробная инструкция для AI: что узнавать, как вести диалог, какие техники использовать | |
| - exit_criteria — список полей которые нужно собрать чтобы перейти на следующий этап | |
| Для ПОЛЕЙ КВАЛИФИКАЦИИ (qualification_fields): | |
| МИНИМАЛЬНЫЙ набор полей для CRM. | |
| Обязательно: "Имя", "Контакт" (телефон или email). | |
| Сгенерируй РОВНО 4-6 полей, не больше. Только самые важные для продаж. | |
| ВАЖНО: | |
| - ai_goal должен быть очень подробным (минимум 2-3 предложения) | |
| - Включи конкретные техники продаж в ai_goal | |
| - exit_criteria — 1-2 критерия на этап (не больше!) | |
| - qualification_fields — РОВНО 4-6 полей, все с галочками | |
| Верни JSON объект в формате: | |
| {{ | |
| "stages": [ | |
| {{"name": "...", "description": "...", "ai_goal": "...", "exit_criteria": ["поле1", "поле2"]}}, | |
| ... | |
| ], | |
| "qualification_fields": ["Имя", "Контакт", "Бюджет", ...] | |
| }} | |
| Верни ТОЛЬКО JSON, без markdown и пояснений.""" | |
| # Call LLM via existing client with higher token limit | |
| try: | |
| import re | |
| import asyncio | |
| from google import genai | |
| from google.genai import types | |
| from app.core.config import settings | |
| # Use direct API call with higher token limit for long response | |
| client = genai.Client(api_key=settings.GEMINI_API_KEY) | |
| config = types.GenerateContentConfig( | |
| temperature=0.7, | |
| max_output_tokens=4000, # Higher limit for JSON array | |
| ) | |
| loop = asyncio.get_event_loop() | |
| response = await loop.run_in_executor( | |
| None, | |
| lambda: client.models.generate_content( | |
| model="gemini-2.0-flash", | |
| contents=prompt, | |
| config=config | |
| ) | |
| ) | |
| raw_text = response.text.strip() | |
| # Clean up JSON if wrapped in markdown | |
| if raw_text.startswith("```"): | |
| parts = raw_text.split("```") | |
| if len(parts) >= 2: | |
| raw_text = parts[1] | |
| if raw_text.startswith("json"): | |
| raw_text = raw_text[4:] | |
| raw_text = raw_text.strip() | |
| # Try to extract JSON object with regex as fallback | |
| if not raw_text.startswith("{"): | |
| match = re.search(r'\{[\s\S]*\}', raw_text) | |
| if match: | |
| raw_text = match.group(0) | |
| # Parse generated response | |
| ai_result = json.loads(raw_text) | |
| # Handle both old format (array) and new format (object with stages/qualification_fields) | |
| if isinstance(ai_result, list): | |
| # Old format - just stages array | |
| generated_stages = ai_result | |
| generated_qualification_fields = None | |
| else: | |
| # New format - object with stages and qualification_fields | |
| generated_stages = ai_result.get("stages", []) | |
| generated_qualification_fields = ai_result.get("qualification_fields", None) | |
| except json.JSONDecodeError as e: | |
| raise HTTPException( | |
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | |
| detail=f"Failed to parse AI response: {str(e)}" | |
| ) | |
| except Exception as e: | |
| raise HTTPException( | |
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | |
| detail=f"AI generation error: {str(e)}" | |
| ) | |
| # Save generated qualification_fields to tenant.ai_settings | |
| # MERGE with existing fields instead of replacing | |
| saved_qual_fields = False | |
| if generated_qualification_fields: | |
| existing_fields = set(ai_settings.get("qualification_fields", [])) | |
| # Merge: keep existing + add new unique ones | |
| merged_fields = list(existing_fields | set(generated_qualification_fields)) | |
| ai_settings["qualification_fields"] = merged_fields | |
| ai_settings["custom_fields"] = merged_fields | |
| tenant.ai_settings = ai_settings | |
| session.add(tenant) | |
| saved_qual_fields = True | |
| generated_qualification_fields = merged_fields # Update for count | |
| # Soft delete existing stages | |
| existing_result = await session.execute( | |
| select(SalesStage) | |
| .where(SalesStage.tenant_id == current_user.tenant_id) | |
| ) | |
| existing_stages = existing_result.scalars().all() | |
| for stage in existing_stages: | |
| stage.is_active = False | |
| session.add(stage) | |
| # Create new stages from AI response | |
| created_stages = [] | |
| for order_index, stage_data in enumerate(generated_stages, start=1): | |
| new_stage = SalesStage( | |
| tenant_id=current_user.tenant_id, | |
| name=stage_data.get("name", f"Этап {order_index}"), | |
| description=stage_data.get("description"), | |
| ai_goal=stage_data.get("ai_goal", "Продвигать клиента по воронке"), | |
| exit_criteria=stage_data.get("exit_criteria", []), | |
| order_index=order_index, | |
| is_active=True | |
| ) | |
| session.add(new_stage) | |
| created_stages.append(new_stage) | |
| await session.commit() | |
| # Refresh to get IDs | |
| for stage in created_stages: | |
| await session.refresh(stage) | |
| # Sync all exit criteria to tenant qualification fields | |
| await sync_tenant_qualification_fields(session, current_user.tenant_id) | |
| # Count actual qualification fields saved | |
| qual_fields_count = len(generated_qualification_fields) if generated_qualification_fields else 0 | |
| return GenerateFunnelResponse( | |
| success=True, | |
| message=f"Сгенерировано {len(created_stages)} этапов воронки" + (f" и {qual_fields_count} полей квалификации" if qual_fields_count > 0 else ""), | |
| stages=[ | |
| SalesStageResponse( | |
| id=stage.id, | |
| tenant_id=stage.tenant_id, | |
| name=stage.name, | |
| description=stage.description, | |
| order_index=stage.order_index, | |
| ai_goal=stage.ai_goal, | |
| exit_criteria=stage.exit_criteria or [], | |
| is_active=stage.is_active, | |
| created_at=stage.created_at, | |
| updated_at=stage.updated_at | |
| ) | |
| for stage in created_stages | |
| ] | |
| ) | |