Spaces:
Running

File size: 7,252 Bytes
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20ee727
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
560824b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd34c6f
 
 
 
 
 
 
560824b
 
 
 
 
 
cd34c6f
 
560824b
 
 
 
cd34c6f
560824b
b9f9102
560824b
cd34c6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
560824b
cd34c6f
560824b
cd34c6f
560824b
 
 
 
 
 
 
 
cd34c6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
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)