from sqlmodel import SQLModel, Field, Relationship, Column, JSON from sqlalchemy import TEXT from typing import Optional, List, Dict, Any from datetime import datetime from uuid import UUID, uuid4 try: from pgvector.sqlalchemy import Vector PGVECTOR_AVAILABLE = True except ImportError: PGVECTOR_AVAILABLE = False Vector = None class KnowledgeBase(SQLModel, table=True): """RAG knowledge base for each tenant.""" __tablename__ = "knowledge_base" id: UUID = Field(default_factory=uuid4, primary_key=True) # CRITICAL: Multitenancy tenant_id: UUID = Field(foreign_key="tenants.id", index=True) # Content content_chunk: str = Field(sa_column=Column(TEXT)) # Vector embedding - store as TEXT but treat as vector in queries # pgvector operators will work when we cast in SQL embedding: Optional[str] = Field( default=None, sa_column=Column(TEXT) if not PGVECTOR_AVAILABLE else Column(Vector(1536)) ) # Metadata source_type: str = "manual" # "manual", "pdf", "website", "api" source_file: Optional[str] = None source_url: Optional[str] = None # Categorization category: Optional[str] = None # "product_info", "pricing", "faq", "objection_handling" tags: Optional[str] = None # Comma-separated tags # Status is_active: bool = Field(default=True) # Timestamps created_at: datetime = Field(default_factory=datetime.utcnow) updated_at: datetime = Field(default_factory=datetime.utcnow) # Relationships tenant: Optional["Tenant"] = Relationship(back_populates="knowledge_base") class SalesScript(SQLModel, table=True): """Predefined scripts for handling objections and scenarios.""" __tablename__ = "sales_scripts" id: UUID = Field(default_factory=uuid4, primary_key=True) # CRITICAL: Multitenancy tenant_id: UUID = Field(foreign_key="tenants.id", index=True) # Script metadata name: str trigger_intent: str # "objection_price", "objection_timing", "qualification_budget" # Script content instruction_text: str = Field(sa_column=Column(TEXT)) example_response: Optional[str] = Field(default=None, sa_column=Column(TEXT)) # Conditions psychotype_target: Optional[str] = None # Apply only to specific psychotype heat_level_min: Optional[int] = None # Apply only if heat_score >= this # Performance tracking usage_count: int = Field(default=0) success_count: int = Field(default=0) # Status is_active: bool = Field(default=True) # Timestamps created_at: datetime = Field(default_factory=datetime.utcnow) updated_at: datetime = Field(default_factory=datetime.utcnow) # Relationships tenant: Optional["Tenant"] = Relationship(back_populates="sales_scripts") class PaymentMethod(SQLModel, table=True): """Payment methods and requisites for the tenant.""" __tablename__ = "payment_methods" id: UUID = Field(default_factory=uuid4, primary_key=True) tenant_id: UUID = Field(foreign_key="tenants.id", index=True) # Payment Details name: str # "Банковская карта", "Kaspi QR", "Реквизиты компании" payment_type: str = "requisites" # "requisites", "link", "qr_code", "image" # Content (depends on type) requisites_text: Optional[str] = Field(default=None, sa_column=Column(TEXT)) # Bank details text payment_link: Optional[str] = None # Payment URL image_url: Optional[str] = None # QR code or card image # AI Instructions send_condition: str = "on_request" # "on_request", "after_agreement", "always" ai_instruction: Optional[str] = Field(default=None, sa_column=Column(TEXT)) # When/how to send # Status is_active: bool = Field(default=True) sort_order: int = Field(default=0) created_at: datetime = Field(default_factory=datetime.utcnow) updated_at: datetime = Field(default_factory=datetime.utcnow) class KnowledgeFile(SQLModel, table=True): """Informational files for coaches, courses, etc. Universal content delivery system: - Coaches: materials by day - B2B: materials by funnel stage - AI-driven: smart contextual sending """ __tablename__ = "knowledge_files" id: UUID = Field(default_factory=uuid4, primary_key=True) tenant_id: UUID = Field(foreign_key="tenants.id", index=True) # File Info name: str # "Урок 1", "Инструкция по курсу" file_type: str = "document" # "document", "image", "video", "link", "qr", "audio" # Content (depends on type) file_url: Optional[str] = None # S3/CDN URL for uploaded files external_link: Optional[str] = None # YouTube, Google Drive, etc. thumbnail_url: Optional[str] = None # Preview image description: Optional[str] = Field(default=None, sa_column=Column(TEXT)) text_content: Optional[str] = Field(default=None, sa_column=Column(TEXT)) # Direct text paste # ===== FLEXIBLE SEND CONDITIONS ===== # on_request: when client asks # by_day: on specific day of course # by_stage: when lead reaches funnel stage # by_event: on specific event (purchase, signup) # ai_decides: AI determines based on instruction # manual: operator only send_condition: str = "on_request" # For "by_day" condition trigger_day: Optional[int] = None # Day 1, 2, 3... (None if not by_day) # For "by_stage" condition trigger_stage_id: Optional[UUID] = Field( default=None, foreign_key="sales_stages.id" ) # For "by_event" condition trigger_event: Optional[str] = None # "purchase", "booking", "signup", custom # Legacy fields (for backwards compatibility) trigger_keywords: Optional[str] = None # Comma-separated keywords trigger_stage: Optional[str] = None # Funnel stage name (legacy) # AI Instructions - what AI should know about when/how to send ai_instruction: Optional[str] = Field(default=None, sa_column=Column(TEXT)) # Status is_active: bool = Field(default=True) sort_order: int = Field(default=0) created_at: datetime = Field(default_factory=datetime.utcnow) updated_at: datetime = Field(default_factory=datetime.utcnow) class LeadContentProgress(SQLModel, table=True): """Tracks which content has been sent to each lead. Used for: - Preventing duplicate sends - Day-based course progress - Analytics """ __tablename__ = "lead_content_progress" id: UUID = Field(default_factory=uuid4, primary_key=True) lead_id: UUID = Field(foreign_key="leads.id", index=True) knowledge_file_id: UUID = Field(foreign_key="knowledge_files.id", index=True) # When was content sent sent_at: Optional[datetime] = None # Tracking (optional) viewed_at: Optional[datetime] = None # If we track opens # Course-specific: when did this lead "start" the course # Used to calculate which day they're on course_start_date: Optional[datetime] = None created_at: datetime = Field(default_factory=datetime.utcnow)