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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from typing import List, Dict, Any, Optional
|
| 6 |
+
from pydantic import BaseModel, Field, EmailStr, validator
|
| 7 |
+
from fastapi import FastAPI, HTTPException, Query, Depends, Request
|
| 8 |
+
from fastapi.responses import JSONResponse, Response
|
| 9 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
+
from fastapi.openapi.utils import get_openapi
|
| 11 |
+
import httpx
|
| 12 |
+
from dotenv import load_dotenv
|
| 13 |
+
|
| 14 |
+
# LangChain and OpenAI imports
|
| 15 |
+
try:
|
| 16 |
+
from langchain_openai import ChatOpenAI
|
| 17 |
+
from langchain.prompts import ChatPromptTemplate
|
| 18 |
+
LANGCHAIN_AVAILABLE = True
|
| 19 |
+
except ImportError:
|
| 20 |
+
LANGCHAIN_AVAILABLE = False
|
| 21 |
+
print("Warning: LangChain not available. Install with: pip install langchain langchain-openai")
|
| 22 |
+
|
| 23 |
+
load_dotenv()
|
| 24 |
+
|
| 25 |
+
# Configuration
|
| 26 |
+
SMARTLEAD_API_KEY = os.getenv("SMARTLEAD_API_KEY")
|
| 27 |
+
SMARTLEAD_BASE_URL = "https://server.smartlead.ai/api/v1"
|
| 28 |
+
|
| 29 |
+
# Initialize FastAPI app
|
| 30 |
+
app = FastAPI(
|
| 31 |
+
title="Smartlead API - Complete Integration",
|
| 32 |
+
version="2.0.0",
|
| 33 |
+
description="Comprehensive FastAPI wrapper for Smartlead email automation platform",
|
| 34 |
+
docs_url="/docs",
|
| 35 |
+
redoc_url="/redoc"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# Add CORS middleware
|
| 39 |
+
app.add_middleware(
|
| 40 |
+
CORSMiddleware,
|
| 41 |
+
allow_origins=["*"],
|
| 42 |
+
allow_credentials=True,
|
| 43 |
+
allow_methods=["*"],
|
| 44 |
+
allow_headers=["*"],
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
# ============================================================================
|
| 48 |
+
# DATA MODELS
|
| 49 |
+
# ============================================================================
|
| 50 |
+
|
| 51 |
+
class CreateCampaignRequest(BaseModel):
|
| 52 |
+
name: str = Field(..., description="Campaign name")
|
| 53 |
+
client_id: Optional[int] = Field(None, description="Client ID (leave null if no client)")
|
| 54 |
+
|
| 55 |
+
class CampaignScheduleRequest(BaseModel):
|
| 56 |
+
timezone: str = Field(..., description="Timezone for the campaign schedule (e.g., 'America/Los_Angeles')")
|
| 57 |
+
days_of_the_week: List[int] = Field(..., description="Days of the week for scheduling [0=Sunday, 1=Monday, 2=Tuesday, 3=Wednesday, 4=Thursday, 5=Friday, 6=Saturday]")
|
| 58 |
+
start_hour: str = Field(..., description="Start hour for sending emails in HH:MM format (e.g., '09:00')")
|
| 59 |
+
end_hour: str = Field(..., description="End hour for sending emails in HH:MM format (e.g., '18:00')")
|
| 60 |
+
min_time_btw_emails: int = Field(..., description="Minimum time in minutes between sending emails")
|
| 61 |
+
max_new_leads_per_day: int = Field(..., description="Maximum number of new leads to process per day")
|
| 62 |
+
schedule_start_time: str = Field(..., description="Schedule start time in ISO 8601 format (e.g., '2023-04-25T07:29:25.978Z')")
|
| 63 |
+
|
| 64 |
+
class CampaignSettingsRequest(BaseModel):
|
| 65 |
+
track_settings: List[str] = Field(..., description="Tracking settings array (allowed values: DONT_TRACK_EMAIL_OPEN, DONT_TRACK_LINK_CLICK, DONT_TRACK_REPLY_TO_AN_EMAIL)")
|
| 66 |
+
stop_lead_settings: str = Field(..., description="Settings for stopping leads (allowed values: CLICK_ON_A_LINK, OPEN_AN_EMAIL)")
|
| 67 |
+
unsubscribe_text: str = Field(..., description="Text for the unsubscribe link")
|
| 68 |
+
send_as_plain_text: bool = Field(..., description="Whether emails should be sent as plain text")
|
| 69 |
+
follow_up_percentage: int = Field(ge=0, le=100, description="Follow-up percentage (max 100, min 0)")
|
| 70 |
+
client_id: Optional[int] = Field(None, description="Client ID (leave as null if not needed)")
|
| 71 |
+
enable_ai_esp_matching: bool = Field(False, description="Enable AI ESP matching (by default is false)")
|
| 72 |
+
|
| 73 |
+
class LeadInput(BaseModel):
|
| 74 |
+
first_name: Optional[str] = Field(None, description="Lead's first name")
|
| 75 |
+
last_name: Optional[str] = Field(None, description="Lead's last name")
|
| 76 |
+
email: str = Field(..., description="Lead's email address")
|
| 77 |
+
phone_number: Optional[str] = Field(None, description="Lead's phone number")
|
| 78 |
+
company_name: Optional[str] = Field(None, description="Lead's company name")
|
| 79 |
+
website: Optional[str] = Field(None, description="Lead's website")
|
| 80 |
+
location: Optional[str] = Field(None, description="Lead's location")
|
| 81 |
+
custom_fields: Optional[Dict[str, str]] = Field(None, description="Custom fields as key-value pairs")
|
| 82 |
+
linkedin_profile: Optional[str] = Field(None, description="Lead's LinkedIn profile URL")
|
| 83 |
+
company_url: Optional[str] = Field(None, description="Company website URL")
|
| 84 |
+
|
| 85 |
+
class LeadSettings(BaseModel):
|
| 86 |
+
ignore_global_block_list: bool = Field(True, description="Ignore leads if they are in the global block list")
|
| 87 |
+
ignore_unsubscribe_list: bool = Field(True, description="Ignore leads if they are in the unsubscribe list")
|
| 88 |
+
ignore_duplicate_leads_in_other_campaign: bool = Field(False, description="Allow leads to be added even if they are duplicates in other campaigns")
|
| 89 |
+
|
| 90 |
+
class AddLeadsRequest(BaseModel):
|
| 91 |
+
lead_list: List[LeadInput] = Field(..., max_items=100, description="List of leads to add (maximum 100 leads)")
|
| 92 |
+
settings: Optional[LeadSettings] = Field(None, description="Settings for lead processing")
|
| 93 |
+
|
| 94 |
+
class AddLeadsResponse(BaseModel):
|
| 95 |
+
ok: bool = Field(..., description="Indicates if the operation was successful")
|
| 96 |
+
upload_count: int = Field(..., description="Number of leads successfully uploaded")
|
| 97 |
+
total_leads: int = Field(..., description="Total number of leads attempted to upload")
|
| 98 |
+
already_added_to_campaign: int = Field(..., description="Number of leads already present in the campaign")
|
| 99 |
+
duplicate_count: int = Field(..., description="Number of duplicate emails found")
|
| 100 |
+
invalid_email_count: int = Field(..., description="Number of leads with invalid email format")
|
| 101 |
+
unsubscribed_leads: Any = Field(..., description="Number of leads that had previously unsubscribed (can be int or empty list)")
|
| 102 |
+
|
| 103 |
+
class SeqDelayDetails(BaseModel):
|
| 104 |
+
delay_in_days: int = Field(..., description="Delay in days before sending this sequence")
|
| 105 |
+
|
| 106 |
+
class SeqVariant(BaseModel):
|
| 107 |
+
subject: str = Field(..., description="Email subject line")
|
| 108 |
+
email_body: str = Field(..., description="Email body content (HTML format)")
|
| 109 |
+
variant_label: str = Field(..., description="Variant label (A, B, C, etc.)")
|
| 110 |
+
id: Optional[int] = Field(None, description="Variant ID (only for updating, not for creating)")
|
| 111 |
+
|
| 112 |
+
class CampaignSequence(BaseModel):
|
| 113 |
+
id: Optional[int] = Field(None, description="Sequence ID (only for updating, not for creating)")
|
| 114 |
+
seq_number: int = Field(..., description="Sequence number (1, 2, 3, etc.)")
|
| 115 |
+
seq_delay_details: SeqDelayDetails = Field(..., description="Delay details for this sequence")
|
| 116 |
+
seq_variants: Optional[List[SeqVariant]] = Field(None, description="Email variants for A/B testing")
|
| 117 |
+
subject: Optional[str] = Field("", description="Subject line (blank for follow-up in same thread)")
|
| 118 |
+
email_body: Optional[str] = Field(None, description="Email body content (HTML format)")
|
| 119 |
+
|
| 120 |
+
class SaveSequencesRequest(BaseModel):
|
| 121 |
+
sequences: List[CampaignSequence] = Field(..., description="List of campaign sequences")
|
| 122 |
+
|
| 123 |
+
class GenerateSequencesRequest(BaseModel):
|
| 124 |
+
job_description: str = Field(..., description="Job description to generate sequences for")
|
| 125 |
+
|
| 126 |
+
class Campaign(BaseModel):
|
| 127 |
+
id: int = Field(..., description="The unique ID of the campaign")
|
| 128 |
+
user_id: int = Field(..., description="The ID of the user who owns the campaign")
|
| 129 |
+
created_at: datetime = Field(..., description="Timestamp of when the campaign was created")
|
| 130 |
+
updated_at: datetime = Field(..., description="Timestamp of the last update to the campaign")
|
| 131 |
+
status: str = Field(..., description="Current status of the campaign (DRAFTED, ACTIVE, COMPLETED, STOPPED, PAUSED)")
|
| 132 |
+
name: str = Field(..., description="The name of the campaign")
|
| 133 |
+
track_settings: str = Field(..., description="Tracking settings string (e.g., 'DONT_REPLY_TO_AN_EMAIL')")
|
| 134 |
+
scheduler_cron_value: Optional[str] = Field(None, description="Scheduling details as JSON string")
|
| 135 |
+
min_time_btwn_emails: int = Field(..., description="Minimum time between emails in minutes")
|
| 136 |
+
max_leads_per_day: int = Field(..., description="Maximum number of leads to process per day")
|
| 137 |
+
stop_lead_settings: str = Field(..., description="Settings for stopping leads (REPLY_TO_AN_EMAIL, CLICK_ON_ANY_LINK, etc.)")
|
| 138 |
+
enable_ai_esp_matching: bool = Field(..., description="Indicates if AI ESP matching is enabled")
|
| 139 |
+
send_as_plain_text: bool = Field(..., description="Indicates if emails for this campaign are sent as plain text")
|
| 140 |
+
follow_up_percentage: str = Field(..., description="The percentage of follow-up emails allocated (e.g., '40%')")
|
| 141 |
+
unsubscribe_text: Optional[str] = Field(None, description="The text used for the unsubscribe link")
|
| 142 |
+
parent_campaign_id: Optional[int] = Field(None, description="Parent campaign ID if this is a child campaign")
|
| 143 |
+
client_id: Optional[int] = Field(None, description="The ID of the client associated with the campaign (null if not attached to a client)")
|
| 144 |
+
|
| 145 |
+
@validator('scheduler_cron_value', pre=True)
|
| 146 |
+
def parse_scheduler_cron_value(cls, v):
|
| 147 |
+
"""Parse scheduler_cron_value from JSON string to dict if needed"""
|
| 148 |
+
if isinstance(v, str) and v:
|
| 149 |
+
try:
|
| 150 |
+
import json
|
| 151 |
+
return json.loads(v)
|
| 152 |
+
except json.JSONDecodeError:
|
| 153 |
+
return v
|
| 154 |
+
return v
|
| 155 |
+
|
| 156 |
+
@validator('follow_up_percentage', pre=True)
|
| 157 |
+
def parse_follow_up_percentage(cls, v):
|
| 158 |
+
"""Ensure follow_up_percentage is returned as string with % sign"""
|
| 159 |
+
if isinstance(v, int):
|
| 160 |
+
return f"{v}%"
|
| 161 |
+
return v
|
| 162 |
+
|
| 163 |
+
class Lead(BaseModel):
|
| 164 |
+
id: int
|
| 165 |
+
email: EmailStr
|
| 166 |
+
first_name: Optional[str]
|
| 167 |
+
last_name: Optional[str]
|
| 168 |
+
company: Optional[str]
|
| 169 |
+
position: Optional[str]
|
| 170 |
+
phone_number: Optional[str]
|
| 171 |
+
linkedin_url: Optional[str]
|
| 172 |
+
status: Optional[str]
|
| 173 |
+
|
| 174 |
+
# Additional models for new endpoints
|
| 175 |
+
class LeadCategoryUpdateRequest(BaseModel):
|
| 176 |
+
category_id: int = Field(..., description="Category ID to assign to the lead")
|
| 177 |
+
pause_lead: bool = Field(False, description="Whether to pause the lead after category update")
|
| 178 |
+
|
| 179 |
+
class CampaignStatusUpdateRequest(BaseModel):
|
| 180 |
+
status: str = Field(..., description="New campaign status (PAUSED, STOPPED, START)")
|
| 181 |
+
|
| 182 |
+
class ResumeLeadRequest(BaseModel):
|
| 183 |
+
resume_lead_with_delay_days: Optional[int] = Field(None, description="Delay in days before resuming (defaults to 0)")
|
| 184 |
+
|
| 185 |
+
class DomainBlockListRequest(BaseModel):
|
| 186 |
+
domain_block_list: List[str] = Field(..., description="List of domains/emails to block")
|
| 187 |
+
client_id: Optional[int] = Field(None, description="Client ID if blocking is client-specific")
|
| 188 |
+
|
| 189 |
+
class WebhookRequest(BaseModel):
|
| 190 |
+
id: Optional[int] = Field(None, description="Webhook ID (null for creating new)")
|
| 191 |
+
name: str = Field(..., description="Webhook name")
|
| 192 |
+
webhook_url: str = Field(..., description="Webhook URL")
|
| 193 |
+
event_types: List[str] = Field(..., description="List of event types to listen for")
|
| 194 |
+
categories: Optional[List[str]] = Field(None, description="List of categories to filter by")
|
| 195 |
+
|
| 196 |
+
class WebhookDeleteRequest(BaseModel):
|
| 197 |
+
id: int = Field(..., description="Webhook ID to delete")
|
| 198 |
+
|
| 199 |
+
class ClientRequest(BaseModel):
|
| 200 |
+
name: str = Field(..., description="Client name")
|
| 201 |
+
email: str = Field(..., description="Client email")
|
| 202 |
+
permission: List[str] = Field(..., description="List of permissions")
|
| 203 |
+
logo: Optional[str] = Field(None, description="Client logo text")
|
| 204 |
+
logo_url: Optional[str] = Field(None, description="Client logo URL")
|
| 205 |
+
password: str = Field(..., description="Client password")
|
| 206 |
+
|
| 207 |
+
class MessageHistoryRequest(BaseModel):
|
| 208 |
+
email_stats_id: str = Field(..., description="Email stats ID for the specific email")
|
| 209 |
+
email_body: str = Field(..., description="Reply message email body")
|
| 210 |
+
reply_message_id: str = Field(..., description="Message ID to reply to")
|
| 211 |
+
reply_email_time: str = Field(..., description="Time of the message being replied to")
|
| 212 |
+
reply_email_body: str = Field(..., description="Body of the message being replied to")
|
| 213 |
+
cc: Optional[str] = Field(None, description="CC recipients")
|
| 214 |
+
bcc: Optional[str] = Field(None, description="BCC recipients")
|
| 215 |
+
add_signature: bool = Field(True, description="Whether to add signature")
|
| 216 |
+
|
| 217 |
+
# ============================================================================
|
| 218 |
+
# HELPER FUNCTIONS
|
| 219 |
+
# ============================================================================
|
| 220 |
+
|
| 221 |
+
def _get_smartlead_url(endpoint: str) -> str:
|
| 222 |
+
return f"{SMARTLEAD_BASE_URL}/{endpoint.lstrip('/')}"
|
| 223 |
+
|
| 224 |
+
async def call_smartlead_api(method: str, endpoint: str, data: Any = None, params: Dict[str, Any] = None) -> Any:
|
| 225 |
+
if SMARTLEAD_API_KEY == "your-api-key-here":
|
| 226 |
+
raise HTTPException(status_code=400, detail="Smartlead API key not configured")
|
| 227 |
+
if params is None:
|
| 228 |
+
params = {}
|
| 229 |
+
params['api_key'] = SMARTLEAD_API_KEY
|
| 230 |
+
url = _get_smartlead_url(endpoint)
|
| 231 |
+
|
| 232 |
+
try:
|
| 233 |
+
async with httpx.AsyncClient(timeout=30.0) as client:
|
| 234 |
+
if method.upper() in ("GET", "DELETE"):
|
| 235 |
+
resp = await client.request(method, url, params=params)
|
| 236 |
+
else:
|
| 237 |
+
resp = await client.request(method, url, params=params, json=data)
|
| 238 |
+
|
| 239 |
+
if resp.status_code >= 400:
|
| 240 |
+
# Try to parse error response as JSON for better error handling
|
| 241 |
+
try:
|
| 242 |
+
error_data = resp.json()
|
| 243 |
+
error_message = error_data.get('message', error_data.get('error', 'Unknown error'))
|
| 244 |
+
error_detail = error_data.get('detail', error_data.get('description', ''))
|
| 245 |
+
|
| 246 |
+
raise HTTPException(
|
| 247 |
+
status_code=resp.status_code,
|
| 248 |
+
detail={
|
| 249 |
+
"error": True,
|
| 250 |
+
"message": error_message,
|
| 251 |
+
"detail": error_detail,
|
| 252 |
+
"endpoint": endpoint,
|
| 253 |
+
"method": method,
|
| 254 |
+
"status_code": resp.status_code
|
| 255 |
+
}
|
| 256 |
+
)
|
| 257 |
+
except (ValueError, KeyError):
|
| 258 |
+
# Fallback to raw text if JSON parsing fails
|
| 259 |
+
raise HTTPException(
|
| 260 |
+
status_code=resp.status_code,
|
| 261 |
+
detail={
|
| 262 |
+
"error": True,
|
| 263 |
+
"message": "API request failed",
|
| 264 |
+
"detail": resp.text,
|
| 265 |
+
"endpoint": endpoint,
|
| 266 |
+
"method": method,
|
| 267 |
+
"status_code": resp.status_code
|
| 268 |
+
}
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
return resp.json()
|
| 272 |
+
|
| 273 |
+
except httpx.TimeoutException:
|
| 274 |
+
raise HTTPException(
|
| 275 |
+
status_code=408,
|
| 276 |
+
detail={
|
| 277 |
+
"error": True,
|
| 278 |
+
"message": "Request timeout",
|
| 279 |
+
"detail": "The request to Smartlead API timed out",
|
| 280 |
+
"endpoint": endpoint,
|
| 281 |
+
"method": method
|
| 282 |
+
}
|
| 283 |
+
)
|
| 284 |
+
except httpx.RequestError as e:
|
| 285 |
+
raise HTTPException(
|
| 286 |
+
status_code=503,
|
| 287 |
+
detail={
|
| 288 |
+
"error": True,
|
| 289 |
+
"message": "Service unavailable",
|
| 290 |
+
"detail": f"Failed to connect to Smartlead API: {str(e)}",
|
| 291 |
+
"endpoint": endpoint,
|
| 292 |
+
"method": method
|
| 293 |
+
}
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
# ============================================================================
|
| 297 |
+
# CAMPAIGN ENDPOINTS
|
| 298 |
+
# ============================================================================
|
| 299 |
+
|
| 300 |
+
@app.post("/campaigns/create", response_model=Dict[str, Any], tags=["Campaigns"])
|
| 301 |
+
async def create_campaign(campaign: CreateCampaignRequest):
|
| 302 |
+
"""Create a new campaign in Smartlead"""
|
| 303 |
+
return await call_smartlead_api("POST", "campaigns/create", data=campaign.dict())
|
| 304 |
+
|
| 305 |
+
@app.get("/campaigns", response_model=Dict[str, Any], tags=["Campaigns"])
|
| 306 |
+
async def list_campaigns():
|
| 307 |
+
"""Fetch all campaigns from Smartlead API"""
|
| 308 |
+
campaigns = await call_smartlead_api("GET", "campaigns")
|
| 309 |
+
return {"campaigns": campaigns, "total": len(campaigns), "source": "smartlead"}
|
| 310 |
+
|
| 311 |
+
@app.get("/campaigns/{campaign_id}", response_model=Campaign, tags=["Campaigns"])
|
| 312 |
+
async def get_campaign(campaign_id: int):
|
| 313 |
+
"""Get Campaign By Id"""
|
| 314 |
+
return await call_smartlead_api("GET", f"campaigns/{campaign_id}")
|
| 315 |
+
|
| 316 |
+
@app.post("/campaigns/{campaign_id}/settings", response_model=Dict[str, Any], tags=["Campaigns"])
|
| 317 |
+
async def update_campaign_settings(campaign_id: int, settings: CampaignSettingsRequest):
|
| 318 |
+
"""Update Campaign General Settings"""
|
| 319 |
+
return await call_smartlead_api("POST", f"campaigns/{campaign_id}/settings", data=settings.dict())
|
| 320 |
+
|
| 321 |
+
@app.post("/campaigns/{campaign_id}/schedule", response_model=Dict[str, Any], tags=["Campaigns"])
|
| 322 |
+
async def schedule_campaign(campaign_id: int, schedule: CampaignScheduleRequest):
|
| 323 |
+
"""Update Campaign Schedule"""
|
| 324 |
+
return await call_smartlead_api("POST", f"campaigns/{campaign_id}/schedule", data=schedule.dict())
|
| 325 |
+
|
| 326 |
+
@app.delete("/campaigns/{campaign_id}", response_model=Dict[str, Any], tags=["Campaigns"])
|
| 327 |
+
async def delete_campaign(campaign_id: int):
|
| 328 |
+
"""Delete Campaign"""
|
| 329 |
+
return await call_smartlead_api("DELETE", f"campaigns/{campaign_id}")
|
| 330 |
+
|
| 331 |
+
@app.post("/campaigns/{campaign_id}/status", response_model=Dict[str, Any], tags=["Campaigns"])
|
| 332 |
+
async def patch_campaign_status(campaign_id: int, request: CampaignStatusUpdateRequest):
|
| 333 |
+
"""Patch campaign status"""
|
| 334 |
+
return await call_smartlead_api("POST", f"campaigns/{campaign_id}/status", data=request.dict())
|
| 335 |
+
|
| 336 |
+
@app.get("/campaigns/{campaign_id}/analytics", response_model=Any, tags=["Analytics"])
|
| 337 |
+
async def campaign_analytics(campaign_id: int):
|
| 338 |
+
"""Fetch analytics for a campaign"""
|
| 339 |
+
return await call_smartlead_api("GET", f"campaigns/{campaign_id}/analytics")
|
| 340 |
+
|
| 341 |
+
@app.get("/campaigns/{campaign_id}/statistics", response_model=Dict[str, Any], tags=["Analytics"])
|
| 342 |
+
async def fetch_campaign_statistics_by_campaign_id(
|
| 343 |
+
campaign_id: int,
|
| 344 |
+
offset: int = 0,
|
| 345 |
+
limit: int = 100,
|
| 346 |
+
email_sequence_number: Optional[int] = None,
|
| 347 |
+
email_status: Optional[str] = None
|
| 348 |
+
):
|
| 349 |
+
"""Fetch Campaign Statistics By Campaign Id"""
|
| 350 |
+
params = {"offset": offset, "limit": limit}
|
| 351 |
+
if email_sequence_number:
|
| 352 |
+
params["email_sequence_number"] = email_sequence_number
|
| 353 |
+
if email_status:
|
| 354 |
+
params["email_status"] = email_status
|
| 355 |
+
return await call_smartlead_api("GET", f"campaigns/{campaign_id}/statistics", params=params)
|
| 356 |
+
|
| 357 |
+
@app.get("/campaigns/{campaign_id}/analytics-by-date", response_model=Dict[str, Any], tags=["Analytics"])
|
| 358 |
+
async def fetch_campaign_statistics_by_date_range(
|
| 359 |
+
campaign_id: int,
|
| 360 |
+
start_date: str,
|
| 361 |
+
end_date: str
|
| 362 |
+
):
|
| 363 |
+
"""Fetch Campaign Statistics By Campaign Id And Date Range"""
|
| 364 |
+
params = {"start_date": start_date, "end_date": end_date}
|
| 365 |
+
return await call_smartlead_api("GET", f"campaigns/{campaign_id}/analytics-by-date", params=params)
|
| 366 |
+
|
| 367 |
+
# ============================================================================
|
| 368 |
+
# LEAD MANAGEMENT ENDPOINTS
|
| 369 |
+
# ============================================================================
|
| 370 |
+
|
| 371 |
+
@app.get("/campaigns/{campaign_id}/leads", response_model=Dict[str, Any], tags=["Leads"])
|
| 372 |
+
async def get_campaign_leads(campaign_id: int, offset: int = 0, limit: int = 100):
|
| 373 |
+
"""List all leads by campaign id"""
|
| 374 |
+
params = {"offset": offset, "limit": limit}
|
| 375 |
+
return await call_smartlead_api("GET", f"campaigns/{campaign_id}/leads", params=params)
|
| 376 |
+
|
| 377 |
+
@app.post("/campaigns/{campaign_id}/leads", response_model=Dict[str, Any], tags=["Leads"])
|
| 378 |
+
async def add_leads_to_campaign(campaign_id: int, request: AddLeadsRequest):
|
| 379 |
+
"""Add leads to a campaign by ID"""
|
| 380 |
+
request_data = request.dict()
|
| 381 |
+
|
| 382 |
+
# Clean up the data - remove None values and empty strings
|
| 383 |
+
for lead in request_data.get("lead_list", []):
|
| 384 |
+
lead_cleaned = {k: v for k, v in lead.items() if v is not None and v != ""}
|
| 385 |
+
|
| 386 |
+
if "custom_fields" in lead_cleaned:
|
| 387 |
+
custom_fields = lead_cleaned["custom_fields"]
|
| 388 |
+
if custom_fields:
|
| 389 |
+
custom_fields_cleaned = {k: v for k, v in custom_fields.items() if v is not None and v != ""}
|
| 390 |
+
if custom_fields_cleaned:
|
| 391 |
+
lead_cleaned["custom_fields"] = custom_fields_cleaned
|
| 392 |
+
else:
|
| 393 |
+
lead_cleaned.pop("custom_fields", None)
|
| 394 |
+
else:
|
| 395 |
+
lead_cleaned.pop("custom_fields", None)
|
| 396 |
+
|
| 397 |
+
lead.clear()
|
| 398 |
+
lead.update(lead_cleaned)
|
| 399 |
+
|
| 400 |
+
request_data["lead_list"] = [lead for lead in request_data["lead_list"] if lead]
|
| 401 |
+
|
| 402 |
+
if not request_data["lead_list"]:
|
| 403 |
+
raise HTTPException(status_code=400, detail="No valid leads to add. Please provide at least one lead with an email address.")
|
| 404 |
+
|
| 405 |
+
if "settings" not in request_data or request_data["settings"] is None:
|
| 406 |
+
request_data["settings"] = {
|
| 407 |
+
"ignore_global_block_list": True,
|
| 408 |
+
"ignore_unsubscribe_list": True,
|
| 409 |
+
"ignore_duplicate_leads_in_other_campaign": False
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
return await call_smartlead_api("POST", f"campaigns/{campaign_id}/leads", data=request_data)
|
| 413 |
+
|
| 414 |
+
@app.post("/campaigns/{campaign_id}/leads/bulk", response_model=Dict[str, Any], tags=["Leads"])
|
| 415 |
+
async def add_bulk_leads(campaign_id: int, leads: List[LeadInput]):
|
| 416 |
+
"""Add multiple leads to a Smartlead campaign (legacy endpoint)"""
|
| 417 |
+
request = AddLeadsRequest(lead_list=leads)
|
| 418 |
+
return await call_smartlead_api("POST", f"campaigns/{campaign_id}/leads", data=request.dict())
|
| 419 |
+
|
| 420 |
+
@app.post("/campaigns/{campaign_id}/leads/{lead_id}/resume", response_model=Dict[str, Any], tags=["Leads"])
|
| 421 |
+
async def resume_lead_by_campaign_id(campaign_id: int, lead_id: int, request: ResumeLeadRequest):
|
| 422 |
+
"""Resume Lead By Campaign ID"""
|
| 423 |
+
return await call_smartlead_api("POST", f"campaigns/{campaign_id}/leads/{lead_id}/resume", data=request.dict())
|
| 424 |
+
|
| 425 |
+
@app.post("/campaigns/{campaign_id}/leads/{lead_id}/pause", response_model=Dict[str, Any], tags=["Leads"])
|
| 426 |
+
async def pause_lead_by_campaign_id(campaign_id: int, lead_id: int):
|
| 427 |
+
"""Pause Lead By Campaign ID"""
|
| 428 |
+
return await call_smartlead_api("POST", f"campaigns/{campaign_id}/leads/{lead_id}/pause")
|
| 429 |
+
|
| 430 |
+
@app.delete("/campaigns/{campaign_id}/leads/{lead_id}", response_model=Dict[str, Any], tags=["Leads"])
|
| 431 |
+
async def delete_lead_by_campaign_id(campaign_id: int, lead_id: int):
|
| 432 |
+
"""Delete Lead By Campaign ID"""
|
| 433 |
+
return await call_smartlead_api("DELETE", f"campaigns/{campaign_id}/leads/{lead_id}")
|
| 434 |
+
|
| 435 |
+
@app.post("/campaigns/{campaign_id}/leads/{lead_id}/unsubscribe", response_model=Dict[str, Any], tags=["Leads"])
|
| 436 |
+
async def unsubscribe_lead_from_campaign(campaign_id: int, lead_id: int):
|
| 437 |
+
"""Unsubscribe/Pause Lead From Campaign"""
|
| 438 |
+
return await call_smartlead_api("POST", f"campaigns/{campaign_id}/leads/{lead_id}/unsubscribe")
|
| 439 |
+
|
| 440 |
+
@app.post("/leads/{lead_id}/unsubscribe", response_model=Dict[str, Any], tags=["Leads"])
|
| 441 |
+
async def unsubscribe_lead_from_all_campaigns(lead_id: int):
|
| 442 |
+
"""Unsubscribe Lead From All Campaigns"""
|
| 443 |
+
return await call_smartlead_api("POST", f"leads/{lead_id}/unsubscribe")
|
| 444 |
+
|
| 445 |
+
@app.post("/leads/{lead_id}", response_model=Dict[str, Any], tags=["Leads"])
|
| 446 |
+
async def update_lead(lead_id: int, lead_data: Dict[str, Any]):
|
| 447 |
+
"""Update lead using the Lead ID"""
|
| 448 |
+
return await call_smartlead_api("POST", f"leads/{lead_id}", data=lead_data)
|
| 449 |
+
|
| 450 |
+
@app.post("/campaigns/{campaign_id}/leads/{lead_id}/category", response_model=Dict[str, Any], tags=["Leads"])
|
| 451 |
+
async def update_lead_category_by_campaign(campaign_id: int, lead_id: int, request: LeadCategoryUpdateRequest):
|
| 452 |
+
"""Update a lead's category based on their campaign"""
|
| 453 |
+
return await call_smartlead_api("POST", f"campaigns/{campaign_id}/leads/{lead_id}/category", data=request.dict())
|
| 454 |
+
|
| 455 |
+
@app.post("/leads/add-domain-block-list", response_model=Dict[str, Any], tags=["Leads"])
|
| 456 |
+
async def add_domain_to_global_block_list(request: DomainBlockListRequest):
|
| 457 |
+
"""Add Lead/Domain to Global Block List"""
|
| 458 |
+
return await call_smartlead_api("POST", "leads/add-domain-block-list", data=request.dict())
|
| 459 |
+
|
| 460 |
+
@app.get("/leads/fetch-categories", response_model=List[Dict[str, Any]], tags=["Leads"])
|
| 461 |
+
async def fetch_lead_categories():
|
| 462 |
+
"""Fetch lead categories"""
|
| 463 |
+
return await call_smartlead_api("GET", "leads/fetch-categories")
|
| 464 |
+
|
| 465 |
+
@app.get("/leads", response_model=Dict[str, Any], tags=["Leads"])
|
| 466 |
+
async def fetch_lead_by_email_address(email: str):
|
| 467 |
+
"""Fetch lead by email address"""
|
| 468 |
+
return await call_smartlead_api("GET", "leads", params={"email": email})
|
| 469 |
+
|
| 470 |
+
@app.get("/leads/{lead_id}/campaigns", response_model=List[Dict[str, Any]], tags=["Leads"])
|
| 471 |
+
async def campaigns_for_lead(lead_id: int):
|
| 472 |
+
"""Fetch all campaigns that a lead belongs to"""
|
| 473 |
+
return await call_smartlead_api("GET", f"leads/{lead_id}/campaigns")
|
| 474 |
+
|
| 475 |
+
@app.get("/campaigns/{campaign_id}/leads/check", response_model=Dict[str, Any], tags=["Leads"])
|
| 476 |
+
async def check_lead_in_campaign(campaign_id: int, email: str):
|
| 477 |
+
"""Check if a lead exists in a campaign using efficient indexed lookups"""
|
| 478 |
+
try:
|
| 479 |
+
# Step 1: Get the global lead_id for the email address
|
| 480 |
+
lead_response = await call_smartlead_api("GET", "leads", params={"email": email})
|
| 481 |
+
|
| 482 |
+
if not lead_response or "id" not in lead_response:
|
| 483 |
+
return {
|
| 484 |
+
"exists": False,
|
| 485 |
+
"message": "Lead not found",
|
| 486 |
+
"email": email,
|
| 487 |
+
"campaign_id": campaign_id
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
lead_id = lead_response["id"]
|
| 491 |
+
|
| 492 |
+
# Step 2: Get all campaigns for this lead
|
| 493 |
+
campaigns_response = await call_smartlead_api("GET", f"leads/{lead_id}/campaigns")
|
| 494 |
+
|
| 495 |
+
if not campaigns_response:
|
| 496 |
+
return {
|
| 497 |
+
"exists": False,
|
| 498 |
+
"message": "No campaigns found for lead",
|
| 499 |
+
"email": email,
|
| 500 |
+
"campaign_id": campaign_id,
|
| 501 |
+
"lead_id": lead_id
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
# Step 3: Check if the target campaign_id exists in the lead's campaigns
|
| 505 |
+
campaign_exists = any(campaign.get("id") == campaign_id for campaign in campaigns_response)
|
| 506 |
+
|
| 507 |
+
return {
|
| 508 |
+
"exists": campaign_exists,
|
| 509 |
+
"message": "Lead found in campaign" if campaign_exists else "Lead not found in campaign",
|
| 510 |
+
"email": email,
|
| 511 |
+
"campaign_id": campaign_id,
|
| 512 |
+
"lead_id": lead_id,
|
| 513 |
+
"total_campaigns_for_lead": len(campaigns_response)
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
except HTTPException as e:
|
| 517 |
+
if e.status_code == 404:
|
| 518 |
+
return {
|
| 519 |
+
"exists": False,
|
| 520 |
+
"message": "Lead not found",
|
| 521 |
+
"email": email,
|
| 522 |
+
"campaign_id": campaign_id
|
| 523 |
+
}
|
| 524 |
+
raise e
|
| 525 |
+
except Exception as e:
|
| 526 |
+
raise HTTPException(status_code=500, detail=f"Error checking lead in campaign: {str(e)}")
|
| 527 |
+
|
| 528 |
+
@app.get("/campaigns/{campaign_id}/leads-export", tags=["Leads"])
|
| 529 |
+
async def export_data_from_campaign(campaign_id: int):
|
| 530 |
+
"""Export data from a campaign as CSV"""
|
| 531 |
+
if SMARTLEAD_API_KEY == "your-api-key-here":
|
| 532 |
+
raise HTTPException(status_code=400, detail="Smartlead API key not configured")
|
| 533 |
+
|
| 534 |
+
url = _get_smartlead_url(f"campaigns/{campaign_id}/leads-export")
|
| 535 |
+
params = {"api_key": SMARTLEAD_API_KEY}
|
| 536 |
+
|
| 537 |
+
try:
|
| 538 |
+
async with httpx.AsyncClient(timeout=30.0) as client:
|
| 539 |
+
resp = await client.get(url, params=params)
|
| 540 |
+
|
| 541 |
+
if resp.status_code >= 400:
|
| 542 |
+
# Try to parse error response as JSON for better error handling
|
| 543 |
+
try:
|
| 544 |
+
error_data = resp.json()
|
| 545 |
+
error_message = error_data.get('message', error_data.get('error', 'Unknown error'))
|
| 546 |
+
error_detail = error_data.get('detail', error_data.get('description', ''))
|
| 547 |
+
|
| 548 |
+
raise HTTPException(
|
| 549 |
+
status_code=resp.status_code,
|
| 550 |
+
detail={
|
| 551 |
+
"error": True,
|
| 552 |
+
"message": error_message,
|
| 553 |
+
"detail": error_detail,
|
| 554 |
+
"endpoint": f"campaigns/{campaign_id}/leads-export",
|
| 555 |
+
"method": "GET",
|
| 556 |
+
"status_code": resp.status_code
|
| 557 |
+
}
|
| 558 |
+
)
|
| 559 |
+
except (ValueError, KeyError):
|
| 560 |
+
# Fallback to raw text if JSON parsing fails
|
| 561 |
+
raise HTTPException(
|
| 562 |
+
status_code=resp.status_code,
|
| 563 |
+
detail={
|
| 564 |
+
"error": True,
|
| 565 |
+
"message": "API request failed",
|
| 566 |
+
"detail": resp.text,
|
| 567 |
+
"endpoint": f"campaigns/{campaign_id}/leads-export",
|
| 568 |
+
"method": "GET",
|
| 569 |
+
"status_code": resp.status_code
|
| 570 |
+
}
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
# Return CSV data with proper headers
|
| 574 |
+
return Response(
|
| 575 |
+
content=resp.text,
|
| 576 |
+
media_type="text/csv",
|
| 577 |
+
headers={
|
| 578 |
+
"Content-Disposition": f"attachment; filename=campaign_{campaign_id}_leads.csv"
|
| 579 |
+
}
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
except httpx.TimeoutException:
|
| 583 |
+
raise HTTPException(
|
| 584 |
+
status_code=408,
|
| 585 |
+
detail={
|
| 586 |
+
"error": True,
|
| 587 |
+
"message": "Request timeout",
|
| 588 |
+
"detail": "The request to Smartlead API timed out",
|
| 589 |
+
"endpoint": f"campaigns/{campaign_id}/leads-export",
|
| 590 |
+
"method": "GET"
|
| 591 |
+
}
|
| 592 |
+
)
|
| 593 |
+
except httpx.RequestError as e:
|
| 594 |
+
raise HTTPException(
|
| 595 |
+
status_code=503,
|
| 596 |
+
detail={
|
| 597 |
+
"error": True,
|
| 598 |
+
"message": "Service unavailable",
|
| 599 |
+
"detail": f"Failed to connect to Smartlead API: {str(e)}",
|
| 600 |
+
"endpoint": f"campaigns/{campaign_id}/leads-export",
|
| 601 |
+
"method": "GET"
|
| 602 |
+
}
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
# ============================================================================
|
| 606 |
+
# SEQUENCE ENDPOINTS
|
| 607 |
+
# ============================================================================
|
| 608 |
+
|
| 609 |
+
@app.get("/campaigns/{campaign_id}/sequences", response_model=Any, tags=["Sequences"])
|
| 610 |
+
async def get_campaign_sequences(campaign_id: int):
|
| 611 |
+
"""Fetch email sequences for a campaign"""
|
| 612 |
+
return await call_smartlead_api("GET", f"campaigns/{campaign_id}/sequences")
|
| 613 |
+
|
| 614 |
+
@app.post("/campaigns/{campaign_id}/sequences", response_model=Dict[str, Any], tags=["Sequences"])
|
| 615 |
+
async def save_campaign_sequences(campaign_id: int, request: SaveSequencesRequest):
|
| 616 |
+
"""Save Campaign Sequence"""
|
| 617 |
+
return await call_smartlead_api("POST", f"campaigns/{campaign_id}/sequences", data=request.dict())
|
| 618 |
+
|
| 619 |
+
@app.post("/campaigns/{campaign_id}/sequences/generate", response_model=Dict[str, Any], tags=["Sequences"])
|
| 620 |
+
async def generate_campaign_sequences(campaign_id: int, request: GenerateSequencesRequest):
|
| 621 |
+
"""Generate Campaign Sequences using LLM"""
|
| 622 |
+
job_description = request.job_description
|
| 623 |
+
generated_sequences = await generate_sequences_with_llm(job_description)
|
| 624 |
+
save_request = SaveSequencesRequest(sequences=generated_sequences)
|
| 625 |
+
result = await call_smartlead_api("POST", f"campaigns/{campaign_id}/sequences", data=save_request.dict())
|
| 626 |
+
|
| 627 |
+
return {
|
| 628 |
+
"ok": True,
|
| 629 |
+
"message": "Sequences generated and saved successfully",
|
| 630 |
+
"generated_sequences": [seq.dict() for seq in generated_sequences],
|
| 631 |
+
"save_result": result
|
| 632 |
+
}
|
| 633 |
+
|
| 634 |
+
# ============================================================================
|
| 635 |
+
# WEBHOOK ENDPOINTS
|
| 636 |
+
# ============================================================================
|
| 637 |
+
|
| 638 |
+
@app.get("/campaigns/{campaign_id}/webhooks", response_model=List[Dict[str, Any]], tags=["Webhooks"])
|
| 639 |
+
async def fetch_webhooks_by_campaign_id(campaign_id: int):
|
| 640 |
+
"""Fetch Webhooks By Campaign ID"""
|
| 641 |
+
return await call_smartlead_api("GET", f"campaigns/{campaign_id}/webhooks")
|
| 642 |
+
|
| 643 |
+
@app.post("/campaigns/{campaign_id}/webhooks", response_model=Dict[str, Any], tags=["Webhooks"])
|
| 644 |
+
async def add_update_campaign_webhook(campaign_id: int, request: WebhookRequest):
|
| 645 |
+
"""Add / Update Campaign Webhook"""
|
| 646 |
+
return await call_smartlead_api("POST", f"campaigns/{campaign_id}/webhooks", data=request.dict())
|
| 647 |
+
|
| 648 |
+
@app.delete("/campaigns/{campaign_id}/webhooks", response_model=Dict[str, Any], tags=["Webhooks"])
|
| 649 |
+
async def delete_campaign_webhook(campaign_id: int, request: WebhookDeleteRequest):
|
| 650 |
+
"""Delete Campaign Webhook"""
|
| 651 |
+
return await call_smartlead_api("DELETE", f"campaigns/{campaign_id}/webhooks", data=request.dict())
|
| 652 |
+
|
| 653 |
+
# ============================================================================
|
| 654 |
+
# CLIENT MANAGEMENT ENDPOINTS
|
| 655 |
+
# ============================================================================
|
| 656 |
+
|
| 657 |
+
@app.post("/client/save", response_model=Dict[str, Any], tags=["Clients"])
|
| 658 |
+
async def add_client_to_system(request: ClientRequest):
|
| 659 |
+
"""Add Client To System (Whitelabel or not)"""
|
| 660 |
+
return await call_smartlead_api("POST", "client/save", data=request.dict())
|
| 661 |
+
|
| 662 |
+
@app.get("/client", response_model=List[Dict[str, Any]], tags=["Clients"])
|
| 663 |
+
async def fetch_all_clients():
|
| 664 |
+
"""Fetch all clients"""
|
| 665 |
+
return await call_smartlead_api("GET", "client")
|
| 666 |
+
|
| 667 |
+
# ============================================================================
|
| 668 |
+
# MESSAGE HISTORY AND REPLY ENDPOINTS
|
| 669 |
+
# ============================================================================
|
| 670 |
+
|
| 671 |
+
@app.get("/campaigns/{campaign_id}/leads/{lead_id}/message-history", response_model=Dict[str, Any], tags=["Messages"])
|
| 672 |
+
async def fetch_lead_message_history_based_on_campaign(campaign_id: int, lead_id: int):
|
| 673 |
+
"""Fetch Lead Message History Based On Campaign"""
|
| 674 |
+
return await call_smartlead_api("GET", f"campaigns/{campaign_id}/leads/{lead_id}/message-history")
|
| 675 |
+
|
| 676 |
+
@app.post("/campaigns/{campaign_id}/reply-email-thread", response_model=Dict[str, Any], tags=["Messages"])
|
| 677 |
+
async def reply_to_lead_from_master_inbox(campaign_id: int, request: MessageHistoryRequest):
|
| 678 |
+
"""Reply To Lead From Master Inbox via API"""
|
| 679 |
+
return await call_smartlead_api("POST", f"campaigns/{campaign_id}/reply-email-thread", data=request.dict())
|
| 680 |
+
|
| 681 |
+
# ============================================================================
|
| 682 |
+
# EMAIL ACCOUNT ENDPOINTS
|
| 683 |
+
# ============================================================================
|
| 684 |
+
|
| 685 |
+
@app.get("/email-accounts", response_model=Dict[str, Any], tags=["Email Accounts"])
|
| 686 |
+
async def list_email_accounts(offset: int = 0, limit: int = 100):
|
| 687 |
+
"""List all email accounts with optional pagination"""
|
| 688 |
+
params = {"offset": offset, "limit": limit}
|
| 689 |
+
return await call_smartlead_api("GET", "email-accounts", params=params)
|
| 690 |
+
|
| 691 |
+
@app.post("/email-accounts/save", response_model=Any, tags=["Email Accounts"])
|
| 692 |
+
async def save_email_account(account: Dict[str, Any]):
|
| 693 |
+
"""Create an Email Account"""
|
| 694 |
+
return await call_smartlead_api("POST", "email-accounts/save", data=account)
|
| 695 |
+
|
| 696 |
+
@app.get("/email-accounts/{account_id}", response_model=Any, tags=["Email Accounts"])
|
| 697 |
+
async def get_email_account(account_id: int):
|
| 698 |
+
"""Fetch Email Account By ID"""
|
| 699 |
+
return await call_smartlead_api("GET", f"email-accounts/{account_id}")
|
| 700 |
+
|
| 701 |
+
@app.post("/email-accounts/{account_id}", response_model=Any, tags=["Email Accounts"])
|
| 702 |
+
async def update_email_account(account_id: int, payload: Dict[str, Any]):
|
| 703 |
+
"""Update Email Account"""
|
| 704 |
+
return await call_smartlead_api("POST", f"email-accounts/{account_id}", data=payload)
|
| 705 |
+
|
| 706 |
+
@app.post("/email-accounts/{account_id}/warmup", response_model=Any, tags=["Email Accounts"])
|
| 707 |
+
async def set_warmup(account_id: int, payload: Dict[str, Any]):
|
| 708 |
+
"""Add/Update Warmup To Email Account"""
|
| 709 |
+
return await call_smartlead_api("POST", f"email-accounts/{account_id}/warmup", data=payload)
|
| 710 |
+
|
| 711 |
+
@app.get("/email-accounts/{account_id}/warmup-stats", response_model=Any, tags=["Email Accounts"])
|
| 712 |
+
async def get_warmup_stats(account_id: int):
|
| 713 |
+
"""Fetch Warmup Stats By Email Account ID"""
|
| 714 |
+
return await call_smartlead_api("GET", f"email-accounts/{account_id}/warmup-stats")
|
| 715 |
+
|
| 716 |
+
@app.get("/campaigns/{campaign_id}/email-accounts", response_model=Any, tags=["Email Accounts"])
|
| 717 |
+
async def list_campaign_email_accounts(campaign_id: int):
|
| 718 |
+
"""List all email accounts per campaign"""
|
| 719 |
+
return await call_smartlead_api("GET", f"campaigns/{campaign_id}/email-accounts")
|
| 720 |
+
|
| 721 |
+
@app.post("/campaigns/{campaign_id}/email-accounts", response_model=Any, tags=["Email Accounts"])
|
| 722 |
+
async def add_campaign_email_accounts(campaign_id: int, payload: Dict[str, Any]):
|
| 723 |
+
"""Add Email Account To A Campaign"""
|
| 724 |
+
return await call_smartlead_api("POST", f"campaigns/{campaign_id}/email-accounts", data=payload)
|
| 725 |
+
|
| 726 |
+
@app.delete("/campaigns/{campaign_id}/email-accounts", response_model=Any, tags=["Email Accounts"])
|
| 727 |
+
async def remove_campaign_email_accounts(campaign_id: int, payload: Dict[str, Any]):
|
| 728 |
+
"""Remove Email Account From A Campaign"""
|
| 729 |
+
return await call_smartlead_api("DELETE", f"campaigns/{campaign_id}/email-accounts", data=payload)
|
| 730 |
+
|
| 731 |
+
@app.post("/email-accounts/reconnect-failed-email-accounts", response_model=Dict[str, Any], tags=["Email Accounts"])
|
| 732 |
+
async def reconnect_failed_email_accounts():
|
| 733 |
+
"""Reconnect failed email accounts"""
|
| 734 |
+
return await call_smartlead_api("POST", "email-accounts/reconnect-failed-email-accounts")
|
| 735 |
+
|
| 736 |
+
# ============================================================================
|
| 737 |
+
# UTILITY ENDPOINTS
|
| 738 |
+
# ============================================================================
|
| 739 |
+
|
| 740 |
+
@app.get("/health", response_model=Dict[str, Any], tags=["Utilities"])
|
| 741 |
+
async def health_check():
|
| 742 |
+
"""Health check endpoint to verify API connectivity"""
|
| 743 |
+
try:
|
| 744 |
+
campaigns = await call_smartlead_api("GET", "campaigns")
|
| 745 |
+
return {
|
| 746 |
+
"status": "healthy",
|
| 747 |
+
"message": "Smartlead API is accessible",
|
| 748 |
+
"campaigns_count": len(campaigns) if isinstance(campaigns, list) else 0,
|
| 749 |
+
"timestamp": datetime.now().isoformat()
|
| 750 |
+
}
|
| 751 |
+
except Exception as e:
|
| 752 |
+
return {
|
| 753 |
+
"status": "unhealthy",
|
| 754 |
+
"message": f"Smartlead API connection failed: {str(e)}",
|
| 755 |
+
"timestamp": datetime.now().isoformat()
|
| 756 |
+
}
|
| 757 |
+
|
| 758 |
+
@app.get("/api-info", response_model=Dict[str, Any], tags=["Utilities"])
|
| 759 |
+
async def api_info():
|
| 760 |
+
"""Get information about the API and available endpoints"""
|
| 761 |
+
return {
|
| 762 |
+
"name": "Smartlead API - Complete Integration",
|
| 763 |
+
"version": "2.0.0",
|
| 764 |
+
"description": "Comprehensive FastAPI wrapper for Smartlead email automation platform",
|
| 765 |
+
"base_url": SMARTLEAD_BASE_URL,
|
| 766 |
+
"available_endpoints": [
|
| 767 |
+
"Campaign Management",
|
| 768 |
+
"Lead Management",
|
| 769 |
+
"Sequence Management",
|
| 770 |
+
"Webhook Management",
|
| 771 |
+
"Client Management",
|
| 772 |
+
"Message History & Reply",
|
| 773 |
+
"Analytics",
|
| 774 |
+
"Email Account Management"
|
| 775 |
+
],
|
| 776 |
+
"documentation": "Based on Smartlead API documentation",
|
| 777 |
+
"timestamp": datetime.now().isoformat()
|
| 778 |
+
}
|
| 779 |
+
|
| 780 |
+
# ============================================================================
|
| 781 |
+
# AI SEQUENCE GENERATION FUNCTIONS
|
| 782 |
+
# ============================================================================
|
| 783 |
+
|
| 784 |
+
async def generate_sequences_with_llm(job_description: str) -> List[CampaignSequence]:
|
| 785 |
+
"""Generate email sequences using LangChain and OpenAI based on job description"""
|
| 786 |
+
|
| 787 |
+
if not LANGCHAIN_AVAILABLE:
|
| 788 |
+
return await generate_template_sequences(job_description)
|
| 789 |
+
|
| 790 |
+
try:
|
| 791 |
+
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 792 |
+
if not openai_api_key:
|
| 793 |
+
print("Warning: OPENAI_API_KEY not set. Using template sequences.")
|
| 794 |
+
return await generate_template_sequences(job_description)
|
| 795 |
+
|
| 796 |
+
llm = ChatOpenAI(
|
| 797 |
+
model="gpt-4",
|
| 798 |
+
temperature=0.7,
|
| 799 |
+
openai_api_key=openai_api_key
|
| 800 |
+
)
|
| 801 |
+
|
| 802 |
+
system_prompt = """You are an expert email sequence generator for recruitment campaigns.
|
| 803 |
+
|
| 804 |
+
Generate ONLY the subject lines and email body content for 3 professional email sequences.
|
| 805 |
+
|
| 806 |
+
Email Sequence Structure:
|
| 807 |
+
1. INTRODUCTION (Day 1): Ask for consent and interest in the role
|
| 808 |
+
2. OUTREACH (Day 3): Provide detailed job information
|
| 809 |
+
3. FOLLOW-UP (Day 5): Follow up on updates and next steps
|
| 810 |
+
|
| 811 |
+
Requirements:
|
| 812 |
+
- First sequence needs 2 A/B testing variants (A and B)
|
| 813 |
+
- Second and third sequences are follow-ups (no subject line needed)
|
| 814 |
+
- All emails should be HTML formatted with proper <br> tags
|
| 815 |
+
- Professional but friendly tone
|
| 816 |
+
- Include clear call-to-actions
|
| 817 |
+
- Focus on building consent and trust
|
| 818 |
+
|
| 819 |
+
Respond with ONLY a JSON object containing the email content:
|
| 820 |
+
{
|
| 821 |
+
"sequence1_variant_a": {
|
| 822 |
+
"subject": "Subject line for variant A",
|
| 823 |
+
"body": "HTML formatted email body for variant A"
|
| 824 |
+
},
|
| 825 |
+
"sequence1_variant_b": {
|
| 826 |
+
"subject": "Subject line for variant B",
|
| 827 |
+
"body": "HTML formatted email body for variant B"
|
| 828 |
+
},
|
| 829 |
+
"sequence2": {
|
| 830 |
+
"body": "HTML formatted email body for outreach"
|
| 831 |
+
},
|
| 832 |
+
"sequence3": {
|
| 833 |
+
"body": "HTML formatted email body for follow-up"
|
| 834 |
+
}
|
| 835 |
+
}
|
| 836 |
+
|
| 837 |
+
IMPORTANT: Respond with ONLY valid JSON. No additional text."""
|
| 838 |
+
|
| 839 |
+
prompt_template = ChatPromptTemplate.from_messages([
|
| 840 |
+
("system", system_prompt),
|
| 841 |
+
("human", "Generate email content for this job description: {job_description}")
|
| 842 |
+
])
|
| 843 |
+
|
| 844 |
+
messages = prompt_template.format_messages(job_description=job_description)
|
| 845 |
+
response = await llm.ainvoke(messages)
|
| 846 |
+
|
| 847 |
+
try:
|
| 848 |
+
content = response.content.strip()
|
| 849 |
+
|
| 850 |
+
if content.startswith("```json"):
|
| 851 |
+
content = content[7:]
|
| 852 |
+
if content.endswith("```"):
|
| 853 |
+
content = content[:-3]
|
| 854 |
+
|
| 855 |
+
content = content.strip()
|
| 856 |
+
parsed_data = json.loads(content)
|
| 857 |
+
sequences = create_sequences_from_content(parsed_data, job_description)
|
| 858 |
+
return sequences
|
| 859 |
+
|
| 860 |
+
except Exception as parse_error:
|
| 861 |
+
print(f"JSON parsing failed: {parse_error}")
|
| 862 |
+
return await generate_template_sequences(job_description)
|
| 863 |
+
|
| 864 |
+
except Exception as e:
|
| 865 |
+
print(f"Error generating sequences with LLM: {str(e)}")
|
| 866 |
+
return await generate_template_sequences(job_description)
|
| 867 |
+
|
| 868 |
+
def create_sequences_from_content(content: dict, job_description: str) -> List[CampaignSequence]:
|
| 869 |
+
"""Create CampaignSequence objects from parsed LLM content"""
|
| 870 |
+
|
| 871 |
+
sequences = []
|
| 872 |
+
|
| 873 |
+
# Sequence 1: Introduction with A/B variants
|
| 874 |
+
if "sequence1_variant_a" in content and "sequence1_variant_b" in content:
|
| 875 |
+
variants = []
|
| 876 |
+
|
| 877 |
+
if "sequence1_variant_a" in content:
|
| 878 |
+
var_a = content["sequence1_variant_a"]
|
| 879 |
+
variants.append(SeqVariant(
|
| 880 |
+
subject=var_a.get("subject", f"Quick question about {job_description}"),
|
| 881 |
+
email_body=var_a.get("body", ""),
|
| 882 |
+
variant_label="A"
|
| 883 |
+
))
|
| 884 |
+
|
| 885 |
+
if "sequence1_variant_b" in content:
|
| 886 |
+
var_b = content["sequence1_variant_b"]
|
| 887 |
+
variants.append(SeqVariant(
|
| 888 |
+
subject=var_b.get("subject", f"Interested in {job_description} opportunities?"),
|
| 889 |
+
email_body=var_b.get("body", ""),
|
| 890 |
+
variant_label="B"
|
| 891 |
+
))
|
| 892 |
+
|
| 893 |
+
sequences.append(CampaignSequence(
|
| 894 |
+
seq_number=1,
|
| 895 |
+
seq_delay_details=SeqDelayDetails(delay_in_days=1),
|
| 896 |
+
seq_variants=variants
|
| 897 |
+
))
|
| 898 |
+
|
| 899 |
+
# Sequence 2: Outreach
|
| 900 |
+
if "sequence2" in content:
|
| 901 |
+
seq2_body = content["sequence2"].get("body", "")
|
| 902 |
+
sequences.append(CampaignSequence(
|
| 903 |
+
seq_number=2,
|
| 904 |
+
seq_delay_details=SeqDelayDetails(delay_in_days=3),
|
| 905 |
+
subject="",
|
| 906 |
+
email_body=seq2_body
|
| 907 |
+
))
|
| 908 |
+
|
| 909 |
+
# Sequence 3: Follow-up
|
| 910 |
+
if "sequence3" in content:
|
| 911 |
+
seq3_body = content["sequence3"].get("body", "")
|
| 912 |
+
sequences.append(CampaignSequence(
|
| 913 |
+
seq_number=3,
|
| 914 |
+
seq_delay_details=SeqDelayDetails(delay_in_days=5),
|
| 915 |
+
subject="",
|
| 916 |
+
email_body=seq3_body
|
| 917 |
+
))
|
| 918 |
+
|
| 919 |
+
# Fill with templates if needed
|
| 920 |
+
while len(sequences) < 3:
|
| 921 |
+
if len(sequences) == 0:
|
| 922 |
+
sequences.append(CampaignSequence(
|
| 923 |
+
seq_number=1,
|
| 924 |
+
seq_delay_details=SeqDelayDetails(delay_in_days=1),
|
| 925 |
+
seq_variants=[
|
| 926 |
+
SeqVariant(
|
| 927 |
+
subject=f"Quick question about {job_description}",
|
| 928 |
+
email_body=f"""<p>Hi there,<br><br>
|
| 929 |
+
I came across your profile and noticed your experience in {job_description}.
|
| 930 |
+
I'm reaching out because we have some exciting opportunities that might be a great fit for your background.<br><br>
|
| 931 |
+
Before I share more details, I wanted to ask: Are you currently open to exploring new opportunities in this space?<br><br>
|
| 932 |
+
Would you be interested in hearing more about the roles we have available?<br><br>
|
| 933 |
+
Best regards,<br>
|
| 934 |
+
[Your Name]</p>""",
|
| 935 |
+
variant_label="A"
|
| 936 |
+
),
|
| 937 |
+
SeqVariant(
|
| 938 |
+
subject=f"Interested in {job_description} opportunities?",
|
| 939 |
+
email_body=f"""<p>Hello,<br><br>
|
| 940 |
+
I hope this message finds you well. I'm a recruiter specializing in {job_description} positions.<br><br>
|
| 941 |
+
I'd love to connect and share some opportunities that align with your expertise.
|
| 942 |
+
Are you currently open to exploring new roles in this space?<br><br>
|
| 943 |
+
If so, I can send you specific details about the positions we have available.<br><br>
|
| 944 |
+
Thanks,<br>
|
| 945 |
+
[Your Name]</p>""",
|
| 946 |
+
variant_label="B"
|
| 947 |
+
)
|
| 948 |
+
]
|
| 949 |
+
))
|
| 950 |
+
elif len(sequences) == 1:
|
| 951 |
+
sequences.append(CampaignSequence(
|
| 952 |
+
seq_number=2,
|
| 953 |
+
seq_delay_details=SeqDelayDetails(delay_in_days=3),
|
| 954 |
+
subject="",
|
| 955 |
+
email_body=f"""<p>Hi,<br><br>
|
| 956 |
+
Thanks for your interest! Here are more details about the {job_description} opportunities:<br><br>
|
| 957 |
+
<strong>Role Details:</strong><br>
|
| 958 |
+
• [Specific responsibilities]<br>
|
| 959 |
+
• [Required skills and experience]<br>
|
| 960 |
+
• [Team and company information]<br><br>
|
| 961 |
+
<strong>Benefits:</strong><br>
|
| 962 |
+
• [Compensation and benefits]<br>
|
| 963 |
+
• [Growth opportunities]<br>
|
| 964 |
+
• [Work environment]<br><br>
|
| 965 |
+
Would you be interested in a quick call to discuss this role in more detail?<br><br>
|
| 966 |
+
Best regards,<br>
|
| 967 |
+
[Your Name]</p>"""
|
| 968 |
+
))
|
| 969 |
+
elif len(sequences) == 2:
|
| 970 |
+
sequences.append(CampaignSequence(
|
| 971 |
+
seq_number=3,
|
| 972 |
+
seq_delay_details=SeqDelayDetails(delay_in_days=5),
|
| 973 |
+
subject="",
|
| 974 |
+
email_body=f"""<p>Hi,<br><br>
|
| 975 |
+
Just wanted to follow up on the {job_description} opportunity I shared.<br><br>
|
| 976 |
+
Have you had a chance to review the information? I'd love to hear your thoughts and answer any questions.<br><br>
|
| 977 |
+
If you're interested, I can help schedule next steps. If not, no worries at all!<br><br>
|
| 978 |
+
Thanks for your time!<br>
|
| 979 |
+
[Your Name]</p>"""
|
| 980 |
+
))
|
| 981 |
+
|
| 982 |
+
return sequences
|
| 983 |
+
|
| 984 |
+
async def generate_template_sequences(job_description: str) -> List[CampaignSequence]:
|
| 985 |
+
"""Generate template-based sequences as fallback"""
|
| 986 |
+
|
| 987 |
+
sequences = [
|
| 988 |
+
CampaignSequence(
|
| 989 |
+
seq_number=1,
|
| 990 |
+
seq_delay_details=SeqDelayDetails(delay_in_days=1),
|
| 991 |
+
seq_variants=[
|
| 992 |
+
SeqVariant(
|
| 993 |
+
subject=f"Quick question about {job_description}",
|
| 994 |
+
email_body=f"""<p>Hi there,<br><br>
|
| 995 |
+
I came across your profile and noticed your experience in {job_description}.
|
| 996 |
+
I'm reaching out because we have some exciting opportunities that might be a great fit for your background.<br><br>
|
| 997 |
+
Before I share more details, I wanted to ask: Are you currently open to exploring new opportunities in this space?<br><br>
|
| 998 |
+
Would you be interested in hearing more about the roles we have available?<br><br>
|
| 999 |
+
Best regards,<br>
|
| 1000 |
+
[Your Name]</p>""",
|
| 1001 |
+
variant_label="A"
|
| 1002 |
+
),
|
| 1003 |
+
SeqVariant(
|
| 1004 |
+
subject=f"Interested in {job_description} opportunities?",
|
| 1005 |
+
email_body=f"""<p>Hello,<br><br>
|
| 1006 |
+
I hope this message finds you well. I'm a recruiter specializing in {job_description} positions.<br><br>
|
| 1007 |
+
I'd love to connect and share some opportunities that align with your expertise.
|
| 1008 |
+
Are you currently open to exploring new roles in this space?<br><br>
|
| 1009 |
+
If so, I can send you specific details about the positions we have available.<br><br>
|
| 1010 |
+
Thanks,<br>
|
| 1011 |
+
[Your Name]</p>""",
|
| 1012 |
+
variant_label="B"
|
| 1013 |
+
)
|
| 1014 |
+
]
|
| 1015 |
+
),
|
| 1016 |
+
CampaignSequence(
|
| 1017 |
+
seq_number=2,
|
| 1018 |
+
seq_delay_details=SeqDelayDetails(delay_in_days=3),
|
| 1019 |
+
subject="",
|
| 1020 |
+
email_body=f"""<p>Hi,<br><br>
|
| 1021 |
+
Thanks for your interest! Here are more details about the {job_description} opportunities:<br><br>
|
| 1022 |
+
<strong>Role Details:</strong><br>
|
| 1023 |
+
• [Specific responsibilities]<br>
|
| 1024 |
+
• [Required skills and experience]<br>
|
| 1025 |
+
• [Team and company information]<br><br>
|
| 1026 |
+
<strong>Benefits:</strong><br>
|
| 1027 |
+
• [Compensation and benefits]<br>
|
| 1028 |
+
• [Growth opportunities]<br>
|
| 1029 |
+
• [Work environment]<br><br>
|
| 1030 |
+
Would you be interested in a quick call to discuss this role in more detail?<br><br>
|
| 1031 |
+
Best regards,<br>
|
| 1032 |
+
[Your Name]</p>"""
|
| 1033 |
+
),
|
| 1034 |
+
CampaignSequence(
|
| 1035 |
+
seq_number=3,
|
| 1036 |
+
seq_delay_details=SeqDelayDetails(delay_in_days=5),
|
| 1037 |
+
subject="",
|
| 1038 |
+
email_body=f"""<p>Hi,<br><br>
|
| 1039 |
+
Just wanted to follow up on the {job_description} opportunity I shared.<br><br>
|
| 1040 |
+
Have you had a chance to review the information? I'd love to hear your thoughts and answer any questions.<br><br>
|
| 1041 |
+
If you're interested, I can help schedule next steps. If not, no worries at all!<br><br>
|
| 1042 |
+
Thanks for your time!<br>
|
| 1043 |
+
[Your Name]</p>"""
|
| 1044 |
+
)
|
| 1045 |
+
]
|
| 1046 |
+
|
| 1047 |
+
return sequences
|
| 1048 |
+
|
| 1049 |
+
# ============================================================================
|
| 1050 |
+
# RATE LIMITING MIDDLEWARE
|
| 1051 |
+
# ============================================================================
|
| 1052 |
+
|
| 1053 |
+
class RateLimiter:
|
| 1054 |
+
def __init__(self, max_requests: int = 10, window_seconds: int = 2):
|
| 1055 |
+
self.max_requests = max_requests
|
| 1056 |
+
self.window_seconds = window_seconds
|
| 1057 |
+
self.requests = []
|
| 1058 |
+
|
| 1059 |
+
def is_allowed(self) -> bool:
|
| 1060 |
+
now = time.time()
|
| 1061 |
+
# Remove old requests outside the window
|
| 1062 |
+
self.requests = [req_time for req_time in self.requests if now - req_time < self.window_seconds]
|
| 1063 |
+
|
| 1064 |
+
if len(self.requests) >= self.max_requests:
|
| 1065 |
+
return False
|
| 1066 |
+
|
| 1067 |
+
self.requests.append(now)
|
| 1068 |
+
return True
|
| 1069 |
+
|
| 1070 |
+
# Global rate limiter instance
|
| 1071 |
+
rate_limiter = RateLimiter(max_requests=10, window_seconds=2)
|
| 1072 |
+
|
| 1073 |
+
@app.middleware("http")
|
| 1074 |
+
async def rate_limit_middleware(request: Request, call_next):
|
| 1075 |
+
"""Rate limiting middleware to respect Smartlead's API limits"""
|
| 1076 |
+
if not rate_limiter.is_allowed():
|
| 1077 |
+
return JSONResponse(
|
| 1078 |
+
status_code=429,
|
| 1079 |
+
content={
|
| 1080 |
+
"error": "Rate limit exceeded",
|
| 1081 |
+
"message": "Too many requests. Please wait before making another request.",
|
| 1082 |
+
"retry_after": 2
|
| 1083 |
+
}
|
| 1084 |
+
)
|
| 1085 |
+
|
| 1086 |
+
response = await call_next(request)
|
| 1087 |
+
return response
|
| 1088 |
+
|
| 1089 |
+
# ============================================================================
|
| 1090 |
+
# ERROR HANDLING
|
| 1091 |
+
# ============================================================================
|
| 1092 |
+
|
| 1093 |
+
@app.exception_handler(HTTPException)
|
| 1094 |
+
async def http_exception_handler(request: Request, exc: HTTPException):
|
| 1095 |
+
"""Custom HTTP exception handler"""
|
| 1096 |
+
return JSONResponse(
|
| 1097 |
+
status_code=exc.status_code,
|
| 1098 |
+
content={
|
| 1099 |
+
"error": True,
|
| 1100 |
+
"message": exc.detail,
|
| 1101 |
+
"status_code": exc.status_code,
|
| 1102 |
+
"timestamp": datetime.now().isoformat()
|
| 1103 |
+
}
|
| 1104 |
+
)
|
| 1105 |
+
|
| 1106 |
+
@app.exception_handler(Exception)
|
| 1107 |
+
async def general_exception_handler(request: Request, exc: Exception):
|
| 1108 |
+
"""General exception handler"""
|
| 1109 |
+
return JSONResponse(
|
| 1110 |
+
status_code=500,
|
| 1111 |
+
content={
|
| 1112 |
+
"error": True,
|
| 1113 |
+
"message": "Internal server error",
|
| 1114 |
+
"detail": str(exc) if os.getenv("DEBUG", "false").lower() == "true" else "An unexpected error occurred",
|
| 1115 |
+
"timestamp": datetime.now().isoformat()
|
| 1116 |
+
}
|
| 1117 |
+
)
|
| 1118 |
+
|
| 1119 |
+
# ============================================================================
|
| 1120 |
+
# CUSTOM OPENAPI SCHEMA
|
| 1121 |
+
# ============================================================================
|
| 1122 |
+
|
| 1123 |
+
def custom_openapi():
|
| 1124 |
+
if app.openapi_schema:
|
| 1125 |
+
return app.openapi_schema
|
| 1126 |
+
|
| 1127 |
+
openapi_schema = get_openapi(
|
| 1128 |
+
title="Smartlead API - Complete Integration",
|
| 1129 |
+
version="2.0.0",
|
| 1130 |
+
description="""
|
| 1131 |
+
# Smartlead API - Complete Integration
|
| 1132 |
+
|
| 1133 |
+
A comprehensive FastAPI wrapper for the Smartlead email automation platform.
|
| 1134 |
+
|
| 1135 |
+
## Features
|
| 1136 |
+
- **Campaign Management**: Create, update, and manage email campaigns
|
| 1137 |
+
- **Lead Management**: Add, update, and manage leads across campaigns
|
| 1138 |
+
- **Sequence Management**: Create and manage email sequences with AI generation
|
| 1139 |
+
- **Webhook Management**: Set up webhooks for real-time notifications
|
| 1140 |
+
- **Analytics**: Get detailed campaign analytics and statistics
|
| 1141 |
+
- **Email Account Management**: Manage email accounts and warmup
|
| 1142 |
+
- **Client Management**: Handle client accounts and permissions
|
| 1143 |
+
|
| 1144 |
+
## Authentication
|
| 1145 |
+
All requests require a Smartlead API key passed as a query parameter: `?api_key=YOUR_API_KEY`
|
| 1146 |
+
|
| 1147 |
+
## Rate Limits
|
| 1148 |
+
- 10 requests per 2 seconds (enforced automatically)
|
| 1149 |
+
|
| 1150 |
+
## Base URL
|
| 1151 |
+
- Smartlead API: `https://server.smartlead.ai/api/v1`
|
| 1152 |
+
""",
|
| 1153 |
+
routes=app.routes,
|
| 1154 |
+
)
|
| 1155 |
+
|
| 1156 |
+
# Add custom tags
|
| 1157 |
+
openapi_schema["tags"] = [
|
| 1158 |
+
{"name": "Campaigns", "description": "Campaign management operations"},
|
| 1159 |
+
{"name": "Leads", "description": "Lead management operations"},
|
| 1160 |
+
{"name": "Sequences", "description": "Email sequence management"},
|
| 1161 |
+
{"name": "Webhooks", "description": "Webhook management"},
|
| 1162 |
+
{"name": "Clients", "description": "Client account management"},
|
| 1163 |
+
{"name": "Messages", "description": "Message history and reply operations"},
|
| 1164 |
+
{"name": "Analytics", "description": "Campaign analytics and statistics"},
|
| 1165 |
+
{"name": "Email Accounts", "description": "Email account management"},
|
| 1166 |
+
{"name": "Utilities", "description": "Utility endpoints"}
|
| 1167 |
+
]
|
| 1168 |
+
|
| 1169 |
+
app.openapi_schema = openapi_schema
|
| 1170 |
+
return app.openapi_schema
|
| 1171 |
+
|
| 1172 |
+
app.openapi = custom_openapi
|
| 1173 |
+
|
| 1174 |
+
# ============================================================================
|
| 1175 |
+
# MAIN APPLICATION ENTRY POINT
|
| 1176 |
+
# ============================================================================
|
| 1177 |
+
|
| 1178 |
+
if __name__ == "__main__":
|
| 1179 |
+
import uvicorn
|
| 1180 |
+
|
| 1181 |
+
print("�� Starting Smartlead API - Complete Integration")
|
| 1182 |
+
print(f"�� API Documentation: http://localhost:8000/docs")
|
| 1183 |
+
print(f"📖 ReDoc Documentation: http://localhost:8000/redoc")
|
| 1184 |
+
print(f"�� Smartlead Base URL: {SMARTLEAD_BASE_URL}")
|
| 1185 |
+
print(f"⚡ Rate Limit: 10 requests per 2 seconds")
|
| 1186 |
+
|
| 1187 |
+
uvicorn.run(
|
| 1188 |
+
"final:app",
|
| 1189 |
+
host="0.0.0.0",
|
| 1190 |
+
port=8000,
|
| 1191 |
+
reload=True,
|
| 1192 |
+
log_level="info"
|
| 1193 |
+
)
|