""" Demo Chat API - Test AI responses without saving to database """ from fastapi import APIRouter, Depends, HTTPException from pydantic import BaseModel from typing import List, Optional import logging from app.api.deps import get_current_user from app.core.database import get_async_session from app.models.user import User from app.models.tenant import Tenant from app.models.product import Product from app.models.booking import Service from app.services.ai_memory_manager import memory_manager from app.core.config import settings from sqlmodel import select logger = logging.getLogger(__name__) router = APIRouter(prefix="/demo", tags=["Demo"]) class DemoChatMessage(BaseModel): role: str # 'user' or 'ai' content: str class DemoChatRequest(BaseModel): message: str history: List[DemoChatMessage] = [] corrections: List[str] = [] # Legacy, kept for backwards compatibility mode: str = "normal" # "normal" = test like client, "correction" = owner mode with settings proposals class DemoChatResponse(BaseModel): response: str pending_action: Optional[dict] = None # Action waiting for user confirmation proposed_changes: List[dict] = [] # Changes proposed by AI in correction mode @router.post("/chat", response_model=DemoChatResponse) async def demo_chat( request: DemoChatRequest, current_user: User = Depends(get_current_user), session = Depends(get_async_session) ): """ Generate AI response for demo/testing purposes. NOW uses FULL AICore with all features: voice, products, booking, etc. Does NOT save to database - purely for testing AI behavior. """ try: from app.services.ai_core.settings_assistant import parse_ai_action, execute_setting_change, remove_action_from_response, get_setting_display_name from google import genai import re # Get tenant tenant = await session.get(Tenant, current_user.tenant_id) if not tenant: raise HTTPException(status_code=404, detail="Tenant not found") # DEBUG: Log current settings # FIXED: ai_identity is stored in ai_settings by settings/brain page ai_identity = (tenant.ai_settings or {}).get("ai_identity", {}) logger.info(f"🔍 Demo chat - bot_name from DB: {ai_identity.get('bot_name', 'NOT SET')}") # Build FULL context using memory manager (includes KB, products, settings) tenant_context = await memory_manager.build_tenant_context(session, tenant) # Add corrections to context if any (legacy support) corrections_prompt = "" if request.corrections: corrections_prompt = "\n\n[ВАЖНЫЕ ПРАВКИ ОТ ВЛАДЕЛЬЦА - СТРОГО СЛЕДУЙ]:\n" for i, correction in enumerate(request.corrections, 1): corrections_prompt += f"{i}. {correction}\n" # Build conversation history history_text = "" for msg in request.history[-10:]: role = "Клиент" if msg.role == "user" else "Ты" history_text += f"{role}: {msg.content}\n" # MODE SWITCH: Normal (client simulation) vs Correction (owner mode) if request.mode == "correction": # CORRECTION MODE: AI talks to business owner full_prompt = f"""Ты AI-консультант MicroFunnel. Ты общаешься с ВЛАДЕЛЬЦЕМ бизнеса, а НЕ с клиентом. === ТЕКУЩИЕ НАСТРОЙКИ БОТА === Имя бота: {ai_identity.get('bot_name', 'не задано')} Роль: {ai_identity.get('bot_role', 'не задана')} Пол: {ai_identity.get('bot_gender', 'не задан')} Тон общения: {tenant.tone_of_voice or 'не задан'} Методология: {tenant.sales_methodology or 'не задана'} Инструкции: {(tenant.custom_instructions or 'нет')[:200]} === ИСТОРИЯ ОБСУЖДЕНИЯ С ВЛАДЕЛЬЦЕМ === {history_text} Владелец: {request.message} === ТВОЯ ЗАДАЧА === 1. Помоги владельцу настроить AI-ассистента 2. Если он просит изменить настройки — ОБСУДИ сначала, потом предложи конкретные изменения 3. Отвечай дружелюбно и экспертно 4. Если владелец говорит что-то вроде "ты теперь X" или "называй себя Y" — уточни: "Хотите изменить имя бота на X?" 5. НЕ применяй изменения сам — только ОБСУЖДАЙ и ПРЕДЛАГАЙ Ответь как AI-консультант MicroFunnel:""" else: # NORMAL MODE: AI simulates client conversation full_prompt = f"""{tenant_context} {corrections_prompt} === ИСТОРИЯ ДИАЛОГА === {history_text} Клиент: {request.message} === ТВОЙ ОТВЕТ === Ответь как ассистент, следуя всем правилам выше. """ # Generate response using Gemini client = genai.Client(api_key=settings.GEMINI_API_KEY) response = client.models.generate_content( model=settings.GEMINI_MODEL, contents=full_prompt ) ai_response = response.text if response.text else "Не удалось сгенерировать ответ" ai_response = ai_response.strip() # ======================================================================== # SMART SETTINGS ASSISTANT: Parse __AI_ACTION__ but DON'T execute yet # Return as pending_action for frontend confirmation # ======================================================================== pending_action = None if "__AI_ACTION__" in ai_response: action = parse_ai_action(ai_response) if action: logger.info(f"🔧 Demo chat detected AI action (pending confirmation): {action}") # DON'T execute - return for user confirmation pending_action = { "type": action.get("type"), "path": action.get("path"), "value": action.get("value"), "display_path": get_setting_display_name(action.get("path", "")) } # Remove the action block from visible response ai_response = remove_action_from_response(ai_response) # Don't remove [SEND_VOICE] - let frontend handle it for demo # Just log what features were triggered has_voice = "[SEND_VOICE]" in ai_response has_media_match = re.search(r'\[SEND_MEDIA:([^\]]+)\]', ai_response) has_booking = "[BOOK_CONFIRMED:" in ai_response if has_voice: logger.info("🎤 Demo: Voice response requested") if has_media_match: logger.info(f"📎 Demo: Media requested: {has_media_match.group(1)}") if has_booking: logger.info("📅 Demo: Booking confirmed") # ======================================================================== # ENRICHMENT: Add Product Cards and File Info for Frontend # ======================================================================== from app.models.product import Product from app.models.knowledge import KnowledgeBase from sqlalchemy import select # 1. Detect Products mentioned in text (like webhook does) # Fetch all active products products_stmt = select(Product).where(Product.tenant_id == tenant.id, Product.is_active == True) products_result = await session.execute(products_stmt) products = products_result.scalars().all() ai_response_lower = ai_response.lower() shown_products = set() for product in products: if product.name.lower() in ai_response_lower: # Add SHOW_PRODUCT tag img_url = product.image_url or "" price = f"{product.price} {product.currency}" # Format: [SHOW_PRODUCT:ID|Name|Price|ImageURL] tag = f"\n[SHOW_PRODUCT:{product.id}|{product.name}|{price}|{img_url}]" ai_response += tag shown_products.add(product.id) logger.info(f"🛍️ Demo: Product detected: {product.name}") # 2. Enrich Media Tags [SEND_MEDIA:ID] -> [SHOW_FILE:ID|Name|Type] media_matches = re.finditer(r'\[SEND_MEDIA:([^\]]+)\]', ai_response) for match in media_matches: media_id_prefix = match.group(1) # Find file in KB # Since ID is shortened in tag, we search by prefix (or simulated lookup) # Actually AICore puts simplified ID. We need to find the real file. # Assuming id_prefix is enough to find via like or python filter stmt_kb = select(KnowledgeBase).where( KnowledgeBase.tenant_id == tenant.id, KnowledgeBase.id.cast(str).like(f"{media_id_prefix}%") ) kb_res = await session.execute(stmt_kb) kb_file = kb_res.scalars().first() if kb_file: # Replace with rich tag: [SHOW_FILE:ID|Name|Type] rich_tag = f"[SHOW_FILE:{kb_file.id}|{kb_file.name}|{kb_file.file_type}]" ai_response = ai_response.replace(match.group(0), rich_tag) logger.info(f"📎 Demo: Enriched file tag: {kb_file.name}") logger.info(f"🎮 Demo chat FULL response generated for tenant {tenant.id}") return DemoChatResponse(response=ai_response.strip(), pending_action=pending_action) except Exception as e: logger.error(f"❌ Demo chat error: {e}") raise HTTPException(status_code=500, detail=str(e)) # ============================================================================ # CONFIRM ACTION ENDPOINT - Execute pending settings change # ============================================================================ class ConfirmActionRequest(BaseModel): action: dict # The pending_action from chat response class ConfirmActionResponse(BaseModel): success: bool message: str changed_path: Optional[str] = None old_value: Optional[str] = None new_value: Optional[str] = None @router.post("/confirm-action", response_model=ConfirmActionResponse) async def confirm_action( request: ConfirmActionRequest, current_user: User = Depends(get_current_user), session = Depends(get_async_session) ): """ Execute a pending settings change after user confirmation. Called when user clicks "Apply" button in the confirmation UI. """ try: from app.services.ai_core.settings_assistant import execute_setting_change tenant = await session.get(Tenant, current_user.tenant_id) if not tenant: raise HTTPException(status_code=404, detail="Tenant not found") result = await execute_setting_change(session, tenant, request.action) if result.get("success"): logger.info(f"✅ Action confirmed and executed: {request.action.get('path')} = {request.action.get('value')}") return ConfirmActionResponse( success=True, message="Настройка успешно изменена", changed_path=result.get("changed_path"), old_value=str(result.get("old_value", "")), new_value=str(result.get("new_value", "")) ) else: return ConfirmActionResponse( success=False, message=result.get("message", "Ошибка при изменении настройки") ) except Exception as e: logger.error(f"❌ Confirm action error: {e}") raise HTTPException(status_code=500, detail=str(e)) # ============================================================================ # CONFIRM SMART CORRECTION - Apply pending smart correction changes # ============================================================================ class ConfirmSmartCorrectionRequest(BaseModel): pending_changes: List[dict] @router.post("/confirm-smart-correction", response_model=ConfirmActionResponse) async def confirm_smart_correction( request: ConfirmSmartCorrectionRequest, current_user: User = Depends(get_current_user), session = Depends(get_async_session) ): """ Apply pending smart correction changes after user confirmation. """ try: tenant = await session.get(Tenant, current_user.tenant_id) if not tenant: raise HTTPException(status_code=404, detail="Tenant not found") # CRITICAL: Use deepcopy so SQLAlchemy detects changes to JSONB fields import copy # FIXED: ai_identity is stored INSIDE ai_settings by settings/brain page ai_settings = copy.deepcopy(tenant.ai_settings or {}) ai_identity = ai_settings.get("ai_identity", {}) applied_count = 0 for change in request.pending_changes: field = change.get("field", "") new_value = change.get("new", "") # Map field names to settings paths # Bot identity goes to ai_settings.ai_identity if "Имя бота" in field: ai_identity["bot_name"] = new_value applied_count += 1 elif "Роль бота" in field: ai_identity["bot_role"] = new_value applied_count += 1 elif "Пол бота" in field: ai_identity["bot_gender"] = "female" if "Женский" in new_value else "male" applied_count += 1 # These go to direct tenant fields elif "Тон общения" in field: tenant.tone_of_voice = new_value applied_count += 1 elif "Методология продаж" in field: tenant.sales_methodology = new_value applied_count += 1 elif "Запрещённые" in field: if new_value.startswith("+"): banned = list(tenant.banned_words or []) banned.append(new_value[1:]) tenant.banned_words = banned applied_count += 1 elif "Инструкции" in field or "инструкц" in field.lower(): if "..." in new_value: full_value = change.get("full_value", new_value.replace("...", "")) else: full_value = new_value current = tenant.custom_instructions or "" # Smart instruction handling: detect and replace contradictions # Common contradicting patterns contradictions = [ (["на вы", "на «вы»", "обращайся на вы"], ["на ты", "на «ты»", "обращайся на ты"]), (["мужского рода", "мужской род"], ["женского рода", "женский род"]), (["формальн", "официальн"], ["неформальн", "разговорн"]), ] # Check if new instruction contradicts any existing ones lines = current.split("\n") if current else [] new_lower = full_value.lower() # Find which pattern group the new instruction belongs to for group_a, group_b in contradictions: in_a = any(p in new_lower for p in group_a) in_b = any(p in new_lower for p in group_b) if in_a or in_b: # Remove any existing contradicting instructions opposite = group_b if in_a else group_a lines = [line for line in lines if not any(p in line.lower() for p in opposite + (group_a if in_a else group_b))] # Add new instruction (avoiding duplicates) if full_value.strip() not in "\n".join(lines): lines.append(full_value.strip()) # Limit total instructions to prevent bloat (max 10 lines) if len(lines) > 10: lines = lines[-10:] tenant.custom_instructions = "\n".join(filter(None, lines)) applied_count += 1 elif "Идеальный клиент" in field or "клиент" in field.lower(): full_value = change.get("full_value", new_value.replace("...", "")) ai_settings["ideal_customer_profile"] = full_value applied_count += 1 elif "Описание бизнеса" in field or "бизнес" in field.lower(): full_value = change.get("full_value", new_value.replace("...", "")) ai_settings["business_description"] = full_value applied_count += 1 # PRODUCT ACTIONS action = change.get("action", "") if action == "update_product": product_id = change.get("product_id") product_field = change.get("product_field") product_value = change.get("product_value") if product_id and product_field and product_value is not None: from uuid import UUID product = await session.get(Product, UUID(product_id)) if product: if product_field == "price": product.price = float(product_value) elif product_field == "name": product.name = str(product_value) elif product_field == "description": product.description = str(product_value) session.add(product) applied_count += 1 elif action == "add_product": product_name = change.get("product_name") product_price = change.get("product_price", 0) product_description = change.get("product_description", "") if product_name: new_product = Product( tenant_id=tenant.id, name=product_name, price=float(product_price), description=product_description, currency="RUB" ) session.add(new_product) applied_count += 1 elif action == "delete_product": product_id = change.get("product_id") if product_id: from uuid import UUID product = await session.get(Product, UUID(product_id)) if product: product.is_active = False session.add(product) applied_count += 1 # SERVICE ACTIONS elif action == "update_service": service_id = change.get("service_id") service_field = change.get("service_field") service_value = change.get("service_value") if service_id and service_field and service_value is not None: from uuid import UUID service = await session.get(Service, UUID(service_id)) if service: if service_field == "price": service.price = float(service_value) elif service_field == "name": service.name = str(service_value) elif service_field == "duration_minutes": service.duration_minutes = int(service_value) session.add(service) applied_count += 1 elif action == "add_service": service_name = change.get("service_name") service_price = change.get("service_price", 0) service_duration = change.get("service_duration", 30) if service_name: new_service = Service( tenant_id=tenant.id, name=service_name, price=float(service_price), duration_minutes=int(service_duration), currency="RUB" ) session.add(new_service) applied_count += 1 if applied_count > 0: # DEBUG: Log what we're saving logger.info(f"🔧 Saving ai_identity to ai_settings: {ai_identity}") # FIXED: Save ai_identity INSIDE ai_settings where settings/brain reads from ai_settings["ai_identity"] = ai_identity tenant.ai_settings = ai_settings # CRITICAL: Mark JSONB field as modified so SQLAlchemy commits changes from sqlalchemy.orm.attributes import flag_modified flag_modified(tenant, "ai_settings") session.add(tenant) await session.commit() # Invalidate AI cache await memory_manager.invalidate_memory(session, tenant) logger.info(f"✅ Smart correction APPLIED for tenant {tenant.id}: {applied_count} changes") return ConfirmActionResponse( success=True, message=f"Применено {applied_count} изменений" ) else: return ConfirmActionResponse( success=False, message="Нет изменений для применения" ) except Exception as e: logger.error(f"❌ Confirm smart correction error: {e}") raise HTTPException(status_code=500, detail=str(e)) class SmartCorrectionRequest(BaseModel): correction: str last_ai_response: Optional[str] = None # What AI said that was wrong class SmartCorrectionResponse(BaseModel): success: bool changes: List[dict] # Applied changes (empty now - for backwards compat) pending_changes: List[dict] = [] # Changes waiting for confirmation message: str analysis: Optional[str] = None # Why AI was wrong @router.post("/smart-correct", response_model=SmartCorrectionResponse) async def smart_correct( request: SmartCorrectionRequest, current_user: User = Depends(get_current_user), session = Depends(get_async_session) ): """ AI-powered correction that analyzes WHY the bot responded incorrectly and modifies the appropriate tenant settings to fix it. """ try: from google import genai import json import re tenant = await session.get(Tenant, current_user.tenant_id) if not tenant: raise HTTPException(status_code=404, detail="Tenant not found") # Get FULL settings context - READ FROM CORRECT FIELDS ai_settings = tenant.ai_settings or {} # FIXED: ai_identity is stored INSIDE ai_settings by settings/brain page ai_identity = ai_settings.get("ai_identity", {}) playbook = ai_settings.get("playbook", {}) # Fetch Products (catalog) products_result = await session.execute( select(Product).where(Product.tenant_id == tenant.id, Product.is_active == True).limit(20) ) products = products_result.scalars().all() # Fetch Services (booking) services_result = await session.execute( select(Service).where(Service.tenant_id == tenant.id, Service.is_active == True).limit(20) ) services = services_result.scalars().all() # Build products list products_text = "" for p in products: products_text += f" - ID:{p.id} | {p.name} | {p.price} {p.currency}" if p.description: products_text += f" | {p.description[:50]}" products_text += "\n" if not products_text: products_text = " (нет товаров)" # Build services list services_text = "" for s in services: services_text += f" - ID:{s.id} | {s.name} | {s.price} {s.currency} | {s.duration_minutes} мин\n" if not services_text: services_text = " (нет услуг)" # Build comprehensive context - USE CORRECT TENANT FIELDS current_config = f""" === ТЕКУЩИЕ НАСТРОЙКИ AI (tenant: {tenant.id}) === [ЛИЧНОСТЬ БОТА] - Имя бота: {ai_identity.get('bot_name', 'AI Assistant')} - Роль: {ai_identity.get('bot_role', 'Менеджер по продажам')} - Пол: {ai_identity.get('bot_gender', 'female')} [ТОН И СТИЛЬ] - Тон общения: {tenant.tone_of_voice or 'Professional'} - Методология продаж: {tenant.sales_methodology or 'Consultative'} [КАТАЛОГ ТОВАРОВ] {products_text} [УСЛУГИ И ЗАПИСИ] {services_text} [ЗАПРЕТЫ] - Запрещённые слова: {tenant.banned_words or []} [ИНСТРУКЦИИ] {(tenant.custom_instructions or '(пусто)')[:500]} [PLAYBOOK - ЭТАПЫ ВОРОНКИ] {json.dumps(playbook.get('stages', []), ensure_ascii=False, indent=2)[:500] if playbook.get('stages') else '(нет этапов)'} [ДРУГОЕ] - Идеальный клиент: {ai_settings.get('ideal_customer_profile', '(не задано)')[:200]} - Описание бизнеса: {ai_settings.get('business_description', '(не задано)')[:200]} """ # Build the analysis prompt parse_prompt = f"""Ты эксперт по настройке AI-ассистентов. Пользователь указал проблему с ответом бота. {current_config} === ПРОБЛЕМА ПОЛЬЗОВАТЕЛЯ === "{request.correction}" {f'Ответ бота который не понравился: "{request.last_ai_response}"' if request.last_ai_response else ''} === КРИТИЧЕСКИ ВАЖНЫЕ ПРАВИЛА ИНТЕРПРЕТАЦИИ === 1. ИМЕНА И ЛИЧНОСТЬ: - "ты джарвис" / "тебя зовут X" / "твоё имя X" → action: "set_bot_name", value: "X" - "ты девушка" / "женский пол" → action: "set_bot_gender", value: "female" - "ты мужик" / "мужской пол" → action: "set_bot_gender", value: "male" - НЕ добавляй инструкции про имя — меняй само имя бота! 2. ТОН И СТИЛЬ: - "будь дружелюбнее" / "на ты" → action: "set_tone", value: "Friendly" - "формально" / "на вы" → action: "set_tone", value: "Professional" - "смело" / "агрессивно продавай" → action: "set_tone", value: "Bold" 3. ПОВЕДЕНИЕ: - "не говори X" / "не упоминай X" → action: "add_banned_word", value: "X" - "всегда делай X" / "обязательно Y" → action: "add_instruction", value: текст ПРИМЕРЫ: - Ввод: "ты джарвис" → {{"action": "set_bot_name", "value": "Джарвис", "reason": "Пользователь хочет имя бота Джарвис"}} - Ввод: "называй себя Анна" → {{"action": "set_bot_name", "value": "Анна", "reason": "Смена имени бота"}} - Ввод: "ты женщина" → {{"action": "set_bot_gender", "value": "female", "reason": "Смена пола бота"}} - Ввод: "общайся на ты" → {{"action": "set_tone", "value": "Friendly", "reason": "Дружелюбный тон = на ты"}} - Ввод: "не говори про скидки" → {{"action": "add_banned_word", "value": "скидки", "reason": "Запрет слова"}} === ДОСТУПНЫЕ ДЕЙСТВИЯ === НАСТРОЙКИ БОТА: - "set_bot_name": изменить имя бота (value: новое имя) - "set_bot_role": изменить роль (value: новая роль) - "set_bot_gender": изменить пол (value: "male" или "female") - "set_tone": изменить тон (value: Professional/Friendly/Empathetic/Bold) - "add_banned_word": добавить запрет (value: слово) - "remove_banned_word": убрать запрет (value: слово) - "add_instruction": добавить инструкцию (value: текст) — ТОЛЬКО для сложных правил поведения - "update_ideal_customer": обновить профиль клиента (value: описание) - "update_business_description": обновить описание бизнеса (value: описание) КАТАЛОГ (товары): - "update_product": изменить товар (id: UUID товара, field: "name"/"price"/"description", value: новое значение) - "add_product": добавить товар (name: название, price: цена, description: описание) - "delete_product": удалить товар (id: UUID товара) УСЛУГИ (записи): - "update_service": изменить услугу (id: UUID услуги, field: "name"/"price"/"duration_minutes", value: новое значение) - "add_service": добавить услугу (name: название, price: цена, duration_minutes: длительность) === ФОРМАТ ОТВЕТА === Верни JSON объект: {{ "analysis": "Краткое объяснение почему бот отвечал неправильно", "changes": [ {{"action": "действие", "value": "значение", "reason": "почему это исправит проблему"}} ] }} ВАЖНО: Верни ТОЛЬКО валидный JSON, без ```json и без пояснений снаружи JSON. """ client = genai.Client(api_key=settings.GEMINI_API_KEY) response = client.models.generate_content( model=settings.GEMINI_MODEL, contents=parse_prompt ) ai_response = response.text.strip() if response.text else "{}" # Clean markdown ai_response = re.sub(r'```json\s*', '', ai_response) ai_response = re.sub(r'```\s*', '', ai_response) # Parse JSON try: result = json.loads(ai_response) except json.JSONDecodeError: match = re.search(r'\{.*\}', ai_response, re.DOTALL) if match: result = json.loads(match.group()) else: result = {"analysis": "", "changes": []} analysis = result.get("analysis", "") changes = result.get("changes", []) if not changes: return SmartCorrectionResponse( success=False, changes=[], message="Не удалось определить какие настройки изменить", analysis=analysis ) # Apply changes applied_changes = [] for change in changes: action = change.get("action", "") value = change.get("value", "") reason = change.get("reason", "") # Bot identity - now correctly read from ai_settings.ai_identity if action == "set_bot_name" and value: old_value = ai_identity.get('bot_name', 'AI Assistant') applied_changes.append({ "field": "Имя бота", "section": "AI Мозг → Личность", "old": old_value, "new": value, "reason": reason }) elif action == "set_bot_role" and value: old_value = ai_identity.get('bot_role', 'Менеджер') applied_changes.append({ "field": "Роль бота", "section": "AI Мозг → Личность", "old": old_value, "new": value, "reason": reason }) elif action == "set_bot_gender" and value in ["male", "female"]: old_value = ai_identity.get('bot_gender', 'female') applied_changes.append({ "field": "Пол бота", "section": "AI Мозг → Личность", "old": "Женский" if old_value == "female" else "Мужской", "new": "Женский" if value == "female" else "Мужской", "reason": reason }) # Banned words - read from tenant.banned_words (correct field) elif action == "add_banned_word" and value: banned = list(tenant.banned_words or []) if value.lower() not in [w.lower() for w in banned]: applied_changes.append({ "field": "Запрещённые слова", "section": "AI Мозг → Фильтры", "old": "(не было)", "new": f"+{value}", "reason": reason }) elif action == "remove_banned_word" and value: banned = list(tenant.banned_words or []) if value.lower() in [w.lower() for w in banned]: applied_changes.append({ "field": "Запрещённые слова", "section": "AI Мозг → Фильтры", "old": value, "new": "(удалено)", "reason": reason }) # Custom instructions - read from tenant.custom_instructions (correct field) elif action == "add_instruction" and value: current = tenant.custom_instructions or "" if value not in current: applied_changes.append({ "field": "Инструкции", "section": "AI Мозг → Глобальный промпт", "old": "(добавлено новое)", "new": value[:100] + ("..." if len(value) > 100 else ""), "full_value": value, "reason": reason }) # Tone - read from tenant.tone_of_voice (correct field) elif action == "set_tone" and value: valid_tones = ["Professional", "Friendly", "Empathetic", "Bold"] tone_map = { "профессиональный": "Professional", "дружелюбный": "Friendly", "эмпатичный": "Empathetic", "уверенный": "Bold" } mapped = tone_map.get(value.lower(), value) if mapped in valid_tones: old_value = tenant.tone_of_voice or "Professional" applied_changes.append({ "field": "Тон общения", "section": "AI Мозг → Стиль", "old": old_value, "new": mapped, "reason": reason }) elif action == "update_ideal_customer" and value: old_value = ai_settings.get("ideal_customer_profile", "") ai_settings["ideal_customer_profile"] = value applied_changes.append({ "field": "Идеальный клиент", "section": "AI Мозг → Таргетинг", "old": old_value[:50] + "..." if old_value else "(пусто)", "new": value[:50] + "...", "full_value": value, "reason": reason }) elif action == "update_business_description" and value: old_value = ai_settings.get("business_description", "") ai_settings["business_description"] = value applied_changes.append({ "field": "Описание бизнеса", "section": "AI Мозг → О компании", "old": old_value[:50] + "..." if old_value else "(пусто)", "new": value[:50] + "...", "full_value": value, "reason": reason }) # PRODUCT ACTIONS elif action == "update_product": product_id = change.get("id") field = change.get("field") if product_id and field and value: # Find product by ID or name product = None for p in products: if str(p.id) == str(product_id) or p.name.lower() == str(product_id).lower(): product = p break if product: old_value = getattr(product, field, None) applied_changes.append({ "action": "update_product", "field": f"Товар: {product.name}", "section": "Каталог", "old": f"{field}: {old_value}", "new": f"{field}: {value}", "product_id": str(product.id), "product_field": field, "product_value": value, "reason": reason }) elif action == "add_product": name = change.get("name") price = change.get("price", 0) description = change.get("description", "") if name: applied_changes.append({ "action": "add_product", "field": f"Новый товар", "section": "Каталог", "old": "(нет)", "new": f"{name} — {price}₽", "product_name": name, "product_price": float(price) if price else 0, "product_description": description, "reason": reason }) elif action == "delete_product": product_id = change.get("id") if product_id: product = None for p in products: if str(p.id) == str(product_id) or p.name.lower() == str(product_id).lower(): product = p break if product: applied_changes.append({ "action": "delete_product", "field": f"Удаление товара", "section": "Каталог", "old": product.name, "new": "(удалён)", "product_id": str(product.id), "reason": reason }) # SERVICE ACTIONS elif action == "update_service": service_id = change.get("id") field = change.get("field") if service_id and field and value: service = None for s in services: if str(s.id) == str(service_id) or s.name.lower() == str(service_id).lower(): service = s break if service: old_value = getattr(service, field, None) applied_changes.append({ "action": "update_service", "field": f"Услуга: {service.name}", "section": "Записи", "old": f"{field}: {old_value}", "new": f"{field}: {value}", "service_id": str(service.id), "service_field": field, "service_value": value, "reason": reason }) elif action == "add_service": name = change.get("name") price = change.get("price", 0) duration = change.get("duration_minutes", 30) if name: applied_changes.append({ "action": "add_service", "field": f"Новая услуга", "section": "Записи", "old": "(нет)", "new": f"{name} — {price}₽, {duration} мин", "service_name": name, "service_price": float(price) if price else 0, "service_duration": int(duration) if duration else 30, "reason": reason }) if applied_changes: # DON'T save to database - return as pending for confirmation # Frontend will call /confirm-smart-correction to apply # Build detailed message for confirmation UI changes_lines = [] for c in applied_changes: changes_lines.append(f"• {c['field']} ({c['section']}): {c['old']} → {c['new']}") message = f"Подтвердите изменения:\n" + "\n".join(changes_lines) logger.info(f"🔧 Smart correction PENDING for tenant {tenant.id}: {len(applied_changes)} changes") return SmartCorrectionResponse( success=True, changes=[], # Empty - not applied yet pending_changes=applied_changes, # Waiting for confirmation message=message, analysis=analysis ) else: return SmartCorrectionResponse( success=False, changes=[], pending_changes=[], message="Изменения не найдены", analysis=analysis ) except Exception as e: logger.error(f"❌ Smart correction error: {e}") raise HTTPException(status_code=500, detail=str(e))