-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_client.py
More file actions
231 lines (182 loc) · 7.78 KB
/
api_client.py
File metadata and controls
231 lines (182 loc) · 7.78 KB
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
"""
API client for Lambda function to interact with the backend API.
"""
import os
import json
import aiohttp
import asyncio
from typing import Dict, List, Optional, Any, Union
from datetime import datetime
from dataclasses import dataclass
from database.models.user import User
@dataclass
class APIConfig:
"""API configuration."""
base_url: str
auth_token: str
timeout: int = 30
class APIClient:
"""Client for making API calls to the backend."""
def __init__(self, config: APIConfig):
self.config = config
self.session: Optional[aiohttp.ClientSession] = None
async def __aenter__(self):
"""Async context manager entry."""
self.session = aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=self.config.timeout),
headers={
"Authorization": f"ServiceAccount {self.config.auth_token}",
"Content-Type": "application/json",
},
)
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Async context manager exit."""
if self.session:
await self.session.close()
async def _make_request(
self,
method: str,
endpoint: str,
data: Optional[Dict] = None,
params: Optional[Dict] = None,
) -> Dict:
"""Make an HTTP request to the API."""
if not self.session:
raise RuntimeError("APIClient must be used as async context manager")
url = f"{self.config.base_url}{endpoint}"
try:
async with self.session.request(
method=method, url=url, json=data, params=params
) as response:
if response.status == 404:
return None
response.raise_for_status()
if response.content_type == "application/json":
return await response.json()
else:
return {"message": await response.text()}
except aiohttp.ClientError as e:
print(f"API request failed: {method} {url} - {e}")
raise
# Lead management endpoints
async def get_lead_by_thread_id(self, thread_id: str) -> Optional[Dict]:
"""Get lead by thread ID."""
return await self._make_request("GET", f"/leads/thread/{thread_id}")
async def create_lead(self, lead_data: Dict) -> Dict:
"""Create a new lead."""
return await self._make_request("POST", "/leads/", data=lead_data)
async def update_lead(self, lead_id: str, lead_data: Dict) -> Dict:
"""Update an existing lead."""
return await self._make_request("PUT", f"/leads/{lead_id}", data=lead_data)
async def mark_lead_qualified(self, thread_id: str) -> Optional[Dict]:
"""Mark a lead as qualified."""
return await self._make_request("PATCH", f"/leads/thread/{thread_id}/qualify")
# Deal management endpoints
async def create_deal(self, deal_data: Dict) -> Dict:
"""Create a new deal."""
return await self._make_request("POST", "/deals/", data=deal_data)
# Processed email endpoints
async def check_email_processed(self, message_id: str) -> bool:
"""Check if email was already processed."""
result = await self._make_request(
"GET", f"/leads/processed-emails/{message_id}"
)
return result is True if result is not None else False
async def mark_email_processed(self, message_id: str, thread_id: str) -> Dict:
"""Mark email as processed."""
return await self._make_request(
"POST",
"/leads/processed-emails/",
params={"message_id": message_id, "thread_id": thread_id},
)
# Blacklist endpoints
async def check_email_blacklisted(self, email: str) -> bool:
"""Check if email is blacklisted."""
result = await self._make_request("GET", f"/leads/blacklist/{email}")
return result is True if result is not None else False
# Simple message endpoints
async def create_simple_message(self, message_data: Dict) -> Dict:
"""Create a simple message."""
return await self._make_request("POST", "/simple-messages/", data=message_data)
async def get_conversation_history(
self, thread_id: str, limit: int = 50
) -> List[Dict]:
"""Get conversation history for a thread."""
result = await self._make_request(
"GET", f"/simple-messages/thread/{thread_id}", params={"limit": limit}
)
return result or []
# Conversation endpoints
async def get_conversation_by_thread_id(self, thread_id: str) -> Optional[Dict]:
"""Get conversation by thread ID."""
return await self._make_request("GET", f"/conversations/thread/{thread_id}")
async def create_conversation_for_deal(
self, deal_id: str, thread_id: Optional[str] = None
) -> Dict:
"""Create or get conversation for a deal with optional thread_id."""
return await self._make_request(
"POST",
"/conversations/for-deal",
params={"deal_id": deal_id, "thread_id": thread_id},
)
# Message endpoints
async def create_message_for_conversation(self, message_data: Dict) -> Dict:
"""Create a message in a conversation."""
return await self._make_request("POST", "/messages/", data=message_data)
# User endpoints
async def get_user_by_repflow_username(
self, repflow_username: str
) -> Optional[User]:
"""Get user by repflow username."""
result = await self._make_request(
"POST",
"/users/by-repflow-username",
data={"repflow_username": repflow_username},
)
return User.model_validate(result)
def create_api_client() -> APIClient:
"""Create API client with configuration from environment variables."""
base_url = os.environ.get("API_BASE_URL", "http://localhost:8000")
auth_token = os.environ.get("API_AUTH_TOKEN", "")
if not auth_token:
raise ValueError("API_AUTH_TOKEN environment variable is required")
config = APIConfig(base_url=base_url, auth_token=auth_token, timeout=30)
return APIClient(config)
# Helper functions for data conversion
def convert_datetime_for_api(dt: datetime) -> str:
"""Convert datetime to API-compatible string."""
if dt:
return dt.isoformat()
return None
def convert_lead_to_api_format(lead_data: Dict) -> Dict:
"""Convert lead data to API format."""
api_data = lead_data.copy()
# Convert datetime fields
if "created_at" in api_data:
api_data["created_at"] = convert_datetime_for_api(api_data["created_at"])
if "updated_at" in api_data:
api_data["updated_at"] = convert_datetime_for_api(api_data["updated_at"])
return api_data
def convert_message_to_api_format(message_data: Dict) -> Dict:
"""Convert message data to API format."""
api_data = message_data.copy()
# Convert datetime fields
if "timestamp" in api_data:
api_data["timestamp"] = convert_datetime_for_api(api_data["timestamp"])
if "created_at" in api_data:
api_data["created_at"] = convert_datetime_for_api(api_data["created_at"])
return api_data
def convert_deal_to_api_format(deal_data: Dict) -> Dict:
"""Convert deal data to API format."""
api_data = deal_data.copy()
# Convert datetime fields
if "dateReceived" in api_data:
api_data["dateReceived"] = convert_datetime_for_api(api_data["dateReceived"])
if "dueDate" in api_data:
api_data["dueDate"] = convert_datetime_for_api(api_data["dueDate"])
if "createdAt" in api_data:
api_data["createdAt"] = convert_datetime_for_api(api_data["createdAt"])
if "updatedAt" in api_data:
api_data["updatedAt"] = convert_datetime_for_api(api_data["updatedAt"])
return api_data