from fastapi import APIRouter, Depends, HTTPException, status from sqlmodel import select, SQLModel from datetime import datetime from sqlmodel.ext.asyncio.session import AsyncSession from sqlalchemy.orm.attributes import flag_modified from typing import Optional, Dict, Any, List from uuid import UUID from pydantic import BaseModel from app.models.tenant import Tenant from app.models.tenant import SubscriptionPlan from app.models.partner import Partner from app.models import User, UserRole from app.api.deps import get_current_user from app.core.database import get_session, get_async_session # Added get_session from app.services.ai_memory_manager import get_memory_manager # Added from app.services.subscription_manager import SubscriptionManager from app.services.subscription_manager import SubscriptionManager from app.core.logging import get_logger from app.models.notification import NotificationSettings # Added router = APIRouter() # ============================================================================ # Schemas # ============================================================================ class TenantResponse(BaseModel): id: UUID name: str business_name: Optional[str] business_type: str ai_settings: Optional[Dict[str, Any]] ai_identity: Optional[Dict[str, Any]] = None # Added virtual field return tone_of_voice: Optional[str] sales_methodology: Optional[str] custom_instructions: Optional[str] banned_words: Optional[list] booking_settings: Optional[Dict[str, Any]] notification_settings: Optional[Dict[str, Any]] = None # Added for notifications manager_monthly_salary: int = 1000 tokens_balance: int is_active: bool referred_by: Optional[Dict[str, str]] = None ai_enabled: bool = True # Master AI toggle company_name: Optional[str] = None # Alias for business_name for frontend telegram_welcome_message: Optional[str] = None # Telegram /start instant message # Voice Settings voice_id: Optional[str] = "professional_male" voice_enabled: Optional[bool] = True voice_reference_url: Optional[str] = None class UpdateTenantRequest(BaseModel): ai_settings: Optional[Dict[str, Any]] = None ai_identity: Optional[Dict[str, Any]] = None # Added virtual field business_name: Optional[str] = None business_type: Optional[str] = None tone_of_voice: Optional[str] = None sales_methodology: Optional[str] = None custom_instructions: Optional[str] = None banned_words: Optional[list] = None booking_settings: Optional[Dict[str, Any]] = None manager_monthly_salary: Optional[int] = None company_name: Optional[str] = None notification_settings: Optional[Dict[str, Any]] = None # Telegram Welcome Message (instant /start response) telegram_welcome_message: Optional[str] = None # Voice Settings voice_id: Optional[str] = None voice_enabled: Optional[bool] = None voice_reference_url: Optional[str] = None ai_enabled: Optional[bool] = None # Master AI toggle # Timezone & Region timezone: Optional[str] = None # IANA timezone ID (e.g. 'Asia/Bishkek') region: Optional[str] = None # ISO country code (e.g. 'kg', 'ru') class BillingStats(SQLModel): plan: str conversations_used: int conversations_limit: Optional[int] usage_percentage: int is_over_limit: bool days_left: int subscription_end: Optional[datetime] is_expired: bool plan_name: str plan_price: int class ChangeSubscriptionRequest(SQLModel): plan: SubscriptionPlan # ============================================================================ # Endpoints # ============================================================================ @router.get("/me", response_model=TenantResponse) async def get_my_tenant( session: AsyncSession = Depends(get_async_session), current_user: User = Depends(get_current_user) ): """ Get current user's tenant information including referral info. Shortcut for GET /tenants/{tenant_id} using current user. """ # 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" ) # Get referring partner info (if exists) referred_by = None if tenant.partner_ref_id: result = await session.execute( select(Partner).where(Partner.id == tenant.partner_ref_id) ) referring_partner = result.scalar_one_or_none() if referring_partner: referred_by = { "partner_id": str(referring_partner.id), "company_name": referring_partner.company_name, "referral_code": referring_partner.referral_code } # print(f"ℹ️ Tenant {tenant.name} was referred by: {referring_partner.company_name}") # Prepare ai_identity ai_identity = (tenant.ai_settings or {}).get("ai_identity", {}) return TenantResponse( id=tenant.id, name=tenant.name, business_name=tenant.business_name, business_type=getattr(tenant, "business_type", "hybrid"), ai_settings=tenant.ai_settings, ai_identity=ai_identity, tone_of_voice=getattr(tenant, 'tone_of_voice', 'Professional'), sales_methodology=getattr(tenant, 'sales_methodology', 'Consultative'), custom_instructions=getattr(tenant, 'custom_instructions', ''), banned_words=getattr(tenant, 'banned_words', []), booking_settings=tenant.booking_settings, notification_settings=tenant.notification_settings, tokens_balance=tenant.tokens_balance, is_active=tenant.is_active, manager_monthly_salary=tenant.manager_monthly_salary, referred_by=referred_by, # Voice Settings voice_id=getattr(tenant, 'voice_id', 'professional_male'), voice_enabled=getattr(tenant, 'voice_enabled', True), voice_reference_url=getattr(tenant, 'voice_reference_url', None), ai_enabled=getattr(tenant, 'ai_enabled', True), company_name=tenant.business_name, # company_name alias telegram_welcome_message=getattr(tenant, 'telegram_welcome_message', None) ) @router.patch("/me", response_model=TenantResponse) async def update_my_tenant( request: UpdateTenantRequest, session: AsyncSession = Depends(get_async_session), current_user: User = Depends(get_current_user) ): """ Update current user's tenant settings. Shortcut for PATCH /tenants/{tenant_id} using current user. """ # PERMISSION CHECK: Only OWNER or SUPERUSER can update settings if current_user.role != UserRole.OWNER and not current_user.is_superuser: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Only OWNER can update settings. Managers have read-only access." ) tenant_id = current_user.tenant_id # Get tenant result = await session.execute( select(Tenant).where(Tenant.id == tenant_id) ) tenant = result.scalar_one_or_none() if not tenant: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Tenant not found" ) # Update fields if request.ai_settings is not None: current_settings = tenant.ai_settings or {} # SYNC: Ensure qualification_fields and custom_fields are identical new_fields = None if "qualification_fields" in request.ai_settings: new_fields = request.ai_settings["qualification_fields"] elif "custom_fields" in request.ai_settings: new_fields = request.ai_settings["custom_fields"] if new_fields is not None: request.ai_settings["qualification_fields"] = new_fields request.ai_settings["custom_fields"] = new_fields current_settings.update(request.ai_settings) tenant.ai_settings = current_settings if request.ai_identity is not None: current_settings = tenant.ai_settings or {} current_settings["ai_identity"] = request.ai_identity tenant.ai_settings = current_settings if request.business_name is not None: tenant.business_name = request.business_name if request.company_name is not None: tenant.business_name = request.company_name # company_name maps to business_name in model tenant.name = request.company_name # Also update display name if request.business_type is not None: tenant.business_type = request.business_type # FIXED: Save persona fields to DIRECT tenant fields (not ai_settings JSON) # This syncs behavior with PATCH /{tenant_id} endpoint and demo-chat if request.tone_of_voice is not None: tenant.tone_of_voice = request.tone_of_voice if request.sales_methodology is not None: tenant.sales_methodology = request.sales_methodology if request.custom_instructions is not None: tenant.custom_instructions = request.custom_instructions if request.banned_words is not None: tenant.banned_words = request.banned_words if request.booking_settings is not None: old_settings = tenant.booking_settings or {} new_settings = request.booking_settings tenant.booking_settings = new_settings # SYNC RESOURCE HOURS: Clamp resource hours to company hours if they go beyond new_working_hours = new_settings.get('working_hours', {}) new_working_days = new_settings.get('working_days', ['mon', 'tue', 'wed', 'thu', 'fri']) company_start = new_working_hours.get('start', '09:00') company_end = new_working_hours.get('end', '18:00') # Map day code to key (mon->0, tue->1, etc.) day_code_to_key = {'mon': '0', 'tue': '1', 'wed': '2', 'thu': '3', 'fri': '4', 'sat': '5', 'sun': '6'} allowed_keys = [day_code_to_key[d] for d in new_working_days if d in day_code_to_key] # Update all resources of this tenant from app.models.booking import Resource resources_result = await session.execute( select(Resource).where(Resource.tenant_id == tenant_id) ) resources = resources_result.scalars().all() for resource in resources: if not resource.working_hours: continue updated_hours = {} for day_key, hours in resource.working_hours.items(): # Skip days that are now non-working if day_key not in allowed_keys: continue res_start = hours.get('start', '09:00') res_end = hours.get('end', '18:00') # Clamp: if resource starts earlier than company, use company start if res_start < company_start: res_start = company_start # Clamp: if resource ends later than company, use company end if res_end > company_end: res_end = company_end # Only keep valid hours (start < end after clamping) if res_start < res_end: updated_hours[day_key] = {'start': res_start, 'end': res_end} if updated_hours != resource.working_hours: resource.working_hours = updated_hours if updated_hours else None flag_modified(resource, "working_hours") session.add(resource) if request.manager_monthly_salary is not None: tenant.manager_monthly_salary = request.manager_monthly_salary if request.notification_settings is not None: tenant.notification_settings = request.notification_settings # [NEW] Sync with NotificationSettings table try: stmt = select(NotificationSettings).where(NotificationSettings.tenant_id == tenant_id) res = await session.execute(stmt) ns = res.scalar_one_or_none() if not ns: ns = NotificationSettings(tenant_id=tenant_id) session.add(ns) # Update fields settings_dict = request.notification_settings # IDs if "telegram_chat_id" in settings_dict: ns.telegram_chat_id = settings_dict.get("telegram_chat_id") if "telegram_channel_id" in settings_dict: ns.telegram_channel_id = settings_dict.get("telegram_channel_id") # Toggles if "notify_on_lead_heat" in settings_dict: ns.notify_hot_leads = settings_dict.get("notify_on_lead_heat") if "notify_on_booking" in settings_dict: ns.notify_bookings = settings_dict.get("notify_on_booking") if "notify_on_order" in settings_dict: ns.notify_orders = settings_dict.get("notify_on_order") if "notify_qualification_complete" in settings_dict: ns.notify_qualification_complete = settings_dict.get("notify_qualification_complete") # Granular Escalations if "notify_escalations" in settings_dict: ns.notify_escalations = settings_dict.get("notify_escalations") if "notify_escalation_high" in settings_dict: ns.notify_escalation_high = settings_dict.get("notify_escalation_high") if "notify_escalation_medium" in settings_dict: ns.notify_escalation_medium = settings_dict.get("notify_escalation_medium") if "notify_escalation_low" in settings_dict: ns.notify_escalation_low = settings_dict.get("notify_escalation_low") session.add(ns) except Exception as e: # Don't fail the whole request # logger.error(f"Failed to sync notification settings table: {e}") pass # Telegram Welcome Message for /start command if request.telegram_welcome_message is not None: tenant.telegram_welcome_message = request.telegram_welcome_message # Voice Settings if request.voice_id is not None: tenant.voice_id = request.voice_id if request.voice_enabled is not None: tenant.voice_enabled = request.voice_enabled if request.voice_reference_url is not None: tenant.voice_reference_url = request.voice_reference_url # AI Master Toggle if request.ai_enabled is not None: tenant.ai_enabled = request.ai_enabled # Timezone & Region if request.timezone is not None: tenant.timezone = request.timezone if request.region is not None: tenant.region = request.region # Mark JSON fields as modified so SQLAlchemy tracks changes flag_modified(tenant, "ai_settings") flag_modified(tenant, "notification_settings") session.add(tenant) await session.commit() await session.refresh(tenant) # IMPORTANT: Invalidate AI Memory so new settings take effect immediately await get_memory_manager().invalidate_memory(session, tenant) return TenantResponse( id=tenant.id, name=tenant.name, business_name=tenant.business_name, business_type=tenant.business_type, ai_settings=tenant.ai_settings, ai_identity=(tenant.ai_settings or {}).get("ai_identity"), # FIXED: Read from tenant fields (source of truth), not ai_settings JSON tone_of_voice=tenant.tone_of_voice, sales_methodology=tenant.sales_methodology, custom_instructions=tenant.custom_instructions, banned_words=tenant.banned_words, booking_settings=tenant.booking_settings, notification_settings=tenant.notification_settings, tokens_balance=tenant.tokens_balance, is_active=tenant.is_active, manager_monthly_salary=tenant.manager_monthly_salary, referred_by=None, # Voice Settings voice_id=getattr(tenant, 'voice_id', 'professional_male'), voice_enabled=getattr(tenant, 'voice_enabled', True), voice_reference_url=getattr(tenant, 'voice_reference_url', None), ai_enabled=getattr(tenant, 'ai_enabled', True), company_name=tenant.business_name, telegram_welcome_message=getattr(tenant, 'telegram_welcome_message', None) ) @router.get("/me/usage") async def get_my_usage_stats( session: AsyncSession = Depends(get_async_session), current_user: User = Depends(get_current_user) ): """ Получить статистику использования текущего tenant. Возвращает: - Информация о плане - Использовано диалогов - Лимит диалогов - Процент использования - Дней до окончания подписки """ # 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" ) usage_stats = await SubscriptionManager.get_usage_stats(tenant) plan_info = SubscriptionManager.get_plan_info(tenant.subscription_plan) return { "plan": plan_info, "usage": usage_stats, "subscription_status": tenant.subscription_status } @router.get("/{tenant_id}", response_model=TenantResponse) async def get_tenant( tenant_id: UUID, session: AsyncSession = Depends(get_async_session), current_user: User = Depends(get_current_user) ): """ Get tenant details including AI settings. """ # Verify user belongs to this tenant if current_user.tenant_id != tenant_id: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Access denied to this tenant" ) # Get tenant result = await session.execute( select(Tenant).where(Tenant.id == tenant_id) ) tenant = result.scalar_one_or_none() if not tenant: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Tenant not found" ) # Get referring partner info (if exists) referred_by = None if tenant.partner_ref_id: result = await session.execute( select(Partner).where(Partner.id == tenant.partner_ref_id) ) referring_partner = result.scalar_one_or_none() if referring_partner: referred_by = { "partner_id": str(referring_partner.id), "company_name": referring_partner.company_name, "referral_code": referring_partner.referral_code } return TenantResponse( id=tenant.id, name=tenant.name, business_name=tenant.business_name, ai_settings=tenant.ai_settings, tone_of_voice=getattr(tenant, 'tone_of_voice', 'Professional'), sales_methodology=getattr(tenant, 'sales_methodology', 'Consultative'), custom_instructions=getattr(tenant, 'custom_instructions', ''), banned_words=getattr(tenant, 'banned_words', []), booking_settings=tenant.booking_settings, notification_settings=tenant.notification_settings, tokens_balance=tenant.tokens_balance, is_active=tenant.is_active, referred_by=referred_by ) @router.patch("/{tenant_id}", response_model=TenantResponse) async def update_tenant( tenant_id: UUID, request: UpdateTenantRequest, session: AsyncSession = Depends(get_async_session), current_user: User = Depends(get_current_user) ): """ Update tenant settings (AI configuration, business name, etc.). OWNER ONLY - Managers cannot edit settings. """ # 1. PERMISSION CHECK: Only OWNER or SUPERUSER can update settings if current_user.role != UserRole.OWNER and not current_user.is_superuser: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Only OWNER can update settings. Managers have read-only access." ) # 2. Verify user belongs to this tenant if current_user.tenant_id != tenant_id: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Access denied to this tenant" ) # 3. Get tenant result = await session.execute( select(Tenant).where(Tenant.id == tenant_id) ) tenant = result.scalar_one_or_none() if not tenant: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Tenant not found" ) # 4. Update fields with proper JSONB merge for ai_settings if request.ai_settings is not None: # Merge new settings provided current_settings = tenant.ai_settings or {} # SYNC: Ensure qualification_fields and custom_fields are identical new_fields = None if "qualification_fields" in request.ai_settings: new_fields = request.ai_settings["qualification_fields"] elif "custom_fields" in request.ai_settings: new_fields = request.ai_settings["custom_fields"] if new_fields is not None: request.ai_settings["qualification_fields"] = new_fields request.ai_settings["custom_fields"] = new_fields current_settings.update(request.ai_settings) tenant.ai_settings = current_settings if request.ai_identity is not None: # Save ai_identity INSIDE ai_settings current_settings = tenant.ai_settings or {} current_settings["ai_identity"] = request.ai_identity tenant.ai_settings = current_settings if request.business_name is not None: tenant.business_name = request.business_name if request.business_type is not None: tenant.business_type = request.business_type if request.tone_of_voice is not None: tenant.tone_of_voice = request.tone_of_voice if request.sales_methodology is not None: tenant.sales_methodology = request.sales_methodology if request.custom_instructions is not None: tenant.custom_instructions = request.custom_instructions if request.banned_words is not None: tenant.banned_words = request.banned_words if request.manager_monthly_salary is not None: tenant.manager_monthly_salary = request.manager_monthly_salary if request.booking_settings is not None: tenant.booking_settings = request.booking_settings # AI Master Toggle if request.ai_enabled is not None: tenant.ai_enabled = request.ai_enabled # Telegram Welcome Message if request.telegram_welcome_message is not None: tenant.telegram_welcome_message = request.telegram_welcome_message # 5. CRITICAL: Mark ai_settings as modified for SQLAlchemy JSON tracking flag_modified(tenant, "ai_settings") session.add(tenant) await session.commit() await session.refresh(tenant) # SIGNAL: Invalidate AI Memory await get_memory_manager().invalidate_memory(session, tenant) # Prepare response (extract ai_identity from ai_settings) ai_identity = (tenant.ai_settings or {}).get("ai_identity", {}) return TenantResponse( id=tenant.id, name=tenant.name, business_name=tenant.business_name, business_type=getattr(tenant, "business_type", "hybrid"), ai_settings=tenant.ai_settings, ai_identity=ai_identity, tone_of_voice=getattr(tenant, 'tone_of_voice', 'Professional'), sales_methodology=getattr(tenant, 'sales_methodology', 'Consultative'), custom_instructions=getattr(tenant, 'custom_instructions', ''), banned_words=getattr(tenant, 'banned_words', []), booking_settings=tenant.booking_settings, tokens_balance=tenant.tokens_balance, is_active=tenant.is_active, manager_monthly_salary=tenant.manager_monthly_salary, referred_by=None, # Not needed in update response # Voice Settings voice_id=getattr(tenant, 'voice_id', 'professional_male'), voice_enabled=getattr(tenant, 'voice_enabled', True), voice_reference_url=getattr(tenant, 'voice_reference_url', None), ai_enabled=getattr(tenant, 'ai_enabled', True), company_name=tenant.business_name, telegram_welcome_message=getattr(tenant, 'telegram_welcome_message', None) )