File size: 13,223 Bytes
a758b0c 90f252d a758b0c 90f252d b7a94e7 c544d0e b7a94e7 c544d0e b7a94e7 c544d0e b7a94e7 483b968 b7a94e7 c544d0e b7a94e7 c544d0e b7a94e7 c544d0e b7a94e7 c544d0e b7a94e7 829620f 483b968 829620f 483b968 829620f 483b968 829620f c544d0e 6beacc7 53c8a1f 6beacc7 646ae8e 53c8a1f 62054ce 53c8a1f 6beacc7 53c8a1f 6beacc7 2169ed9 42bd84b ab1535a 729c393 ab1535a 22f2680 ab1535a 22f2680 ab1535a 729c393 ab1535a 729c393 ab1535a 729c393 ab1535a 729c393 ab1535a 762b66d 54f9ee3 762b66d 729c393 ab1535a f7aa5b7 ab1535a 22f2680 ab1535a 22f2680 ab1535a | 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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | from datetime import datetime, timedelta
from config import supabase
async def get_or_create_user(wa_id: str, name: str = None) -> dict:
"""Get existing user or create new one"""
if not supabase:
return {"wa_id": wa_id, "name": name or "Unknown"}
try:
# Try to get existing user
response = supabase.table("users").select("*").eq("wa_id", wa_id).execute()
if response.data:
# User exists, update if name provided
user = response.data[0]
if name and name != user.get("name"):
supabase.table("users").update({"name": name, "updated_at": datetime.utcnow().isoformat()}).eq("wa_id", wa_id).execute()
user["name"] = name
return user
else:
# Create new user
new_user = {
"wa_id": wa_id,
"name": name or "Unknown",
"created_at": datetime.utcnow().isoformat(),
"updated_at": datetime.utcnow().isoformat()
}
response = supabase.table("users").insert(new_user).execute()
return response.data[0] if response.data else new_user
except Exception as e:
print(f"Error in get_or_create_user: {e}")
return {"wa_id": wa_id, "name": name or "Unknown"}
async def update_user_activity(wa_id: str):
"""Update user's last activity timestamp"""
if not supabase:
return
try:
supabase.table("users").update({"updated_at": datetime.utcnow().isoformat()}).eq("wa_id", wa_id).execute()
except Exception as e:
print(f"Error updating user activity: {e}")
# --- Session Management ---
async def get_active_session(wa_id: str) -> dict:
"""Get the active session for a user (not ended and within 3 hours)"""
if not supabase:
return None
try:
# Calculate 3 hours ago
three_hours_ago = datetime.utcnow() - timedelta(hours=3)
response = supabase.table("chat_sessions").select("*").eq("wa_id", wa_id).eq("ended", False).gte("last_activity", three_hours_ago.isoformat()).order("last_activity", desc=True).limit(1).execute()
return response.data[0] if response.data else None
except Exception as e:
print(f"Error getting active session: {e}")
return None
async def create_new_session(wa_id: str) -> dict:
"""Create a new chat session for a user"""
if not supabase:
return {"id": "local_session", "wa_id": wa_id, "started_at": datetime.utcnow().isoformat(), "last_activity": datetime.utcnow().isoformat(), "ended": False}
try:
new_session = {
"wa_id": wa_id,
"started_at": datetime.utcnow().isoformat(),
"last_activity": datetime.utcnow().isoformat(),
"ended": False
}
response = supabase.table("chat_sessions").insert(new_session).execute()
return response.data[0] if response.data else new_session
except Exception as e:
print(f"Error creating new session: {e}")
return {"id": "local_session", "wa_id": wa_id, "started_at": datetime.utcnow().isoformat(), "last_activity": datetime.utcnow().isoformat(), "ended": False}
async def update_session_activity(session_id: str):
"""Update session's last activity timestamp"""
if not supabase or session_id == "local_session":
return
try:
supabase.table("chat_sessions").update({"last_activity": datetime.utcnow().isoformat()}).eq("id", session_id).execute()
except Exception as e:
print(f"Error updating session activity: {e}")
async def end_session(session_id: str):
"""Mark a session as ended"""
if not supabase or session_id == "local_session":
return
try:
supabase.table("chat_sessions").update({"ended": True}).eq("id", session_id).execute()
except Exception as e:
print(f"Error ending session: {e}")
# --- Message Management ---
async def save_message(session_id: str, wa_id: str, wamid: str, role: str, content: str):
"""Save a message to the database"""
if not supabase or session_id == "local_session":
return
try:
message = {
"session_id": session_id,
"wa_id": wa_id,
"wamid": wamid,
"role": role,
"content": content,
"created_at": datetime.utcnow().isoformat()
}
supabase.table("messages").insert(message).execute()
except Exception as e:
print(f"Error saving message: {e}")
async def get_session_messages(session_id: str, limit: int = 10) -> list:
"""Get recent messages for a session (for memory context)"""
if not supabase or session_id == "local_session":
return []
try:
response = supabase.table("messages").select("*").eq("session_id", session_id).order("created_at", desc=True).limit(limit).execute()
# Reverse to get chronological order
messages = response.data[::-1] if response.data else []
return messages
except Exception as e:
print(f"Error getting session messages: {e}")
return []
# --- Session Management Helper ---
async def get_or_create_active_session(wa_id: str) -> dict:
"""Get active session or create new one if needed"""
active_session = await get_active_session(wa_id)
if active_session:
# Update activity
await update_session_activity(active_session["id"])
return active_session
else:
# Create new session
return await create_new_session(wa_id)
async def get_user(wa_id: str):
"""Get user by WhatsApp ID"""
if not supabase:
return None
try:
response = supabase.table("users").select("*").eq("wa_id", wa_id).execute()
return response.data[0] if response.data else None
except Exception as e:
print(f"Error getting user: {e}")
return None
async def list_users(limit: int = 50, offset: int = 0):
"""List all users with pagination"""
if not supabase:
return {"users": [], "count": 0}
try:
response = supabase.table("users").select("*").range(offset, offset + limit - 1).order("created_at", desc=True).execute()
return {"users": response.data, "count": len(response.data)}
except Exception as e:
print(f"Error listing users: {e}")
return {"users": [], "count": 0}
async def update_user_name(wa_id: str, name: str):
"""Update user name"""
if not supabase:
return None
try:
response = supabase.table("users").update({
"name": name,
"updated_at": datetime.utcnow().isoformat()
}).eq("wa_id", wa_id).execute()
return response.data[0] if response.data else None
except Exception as e:
print(f"Error updating user: {e}")
return None
# --- Persona Management ---
async def get_user_persona(wa_id: str) -> dict:
"""
Fetch the persona row for this user.
Returns an empty dict if no data exists.
"""
if not supabase:
return {}
try:
resp = supabase\
.table("user_personas")\
.select("*")\
.eq("wa_id", wa_id)\
.single()\
.execute()
return resp.data or {}
except Exception as e:
print(f"Error getting user persona: {e}")
return {}
async def update_user_persona(wa_id: str, updates: dict):
"""
Apply partial updates to the persona row.
Automatically sets `updated_at` to now().
"""
if not supabase:
return
try:
updates_with_ts = {**updates, "updated_at": datetime.utcnow().isoformat()}
# First try to get existing persona
existing = supabase.table("user_personas").select("*").eq("wa_id", wa_id).execute()
if existing.data:
# Update existing record
supabase\
.table("user_personas")\
.update(updates_with_ts)\
.eq("wa_id", wa_id)\
.execute()
else:
# Create new record
new_persona = {
"wa_id": wa_id,
"created_at": datetime.utcnow().isoformat(),
**updates_with_ts
}
supabase.table("user_personas").insert(new_persona).execute()
except Exception as e:
print(f"Error updating user persona: {e}")
# --- Intent Management ---
async def get_or_create_user_intent(session_id: str, wa_id: str) -> dict:
"""
Fetch or create the intent record for this session.
"""
try:
resp = supabase \
.table("user_intents") \
.select("*") \
.eq("session_id", session_id) \
.single() \
.execute()
if resp.data:
return resp.data
except Exception as e:
# No record exists, create one
pass
new_intent = {
"session_id": session_id,
"wa_id": wa_id,
"location_preference": None,
"budget": None,
"size_preference_sqm": None,
"must_have": None,
"transaction_type": None,
"created_at": datetime.utcnow().isoformat(),
"updated_at": datetime.utcnow().isoformat()
}
insert = supabase.table("user_intents").insert(new_intent).execute()
return insert.data[0] if insert.data else new_intent
async def update_user_intent(session_id: str, updates: dict):
"""
Patch the intent record with any changed fields.
"""
if not supabase or session_id == "local_session":
return
try:
updates_with_ts = { **updates, "updated_at": datetime.utcnow().isoformat() }
supabase \
.table("user_intents") \
.update(updates_with_ts) \
.eq("session_id", session_id) \
.execute()
except Exception as e:
pass
# --- Property Search ---
async def search_properties(filters: dict) -> list:
"""
Returns up to 5 active properties matching the user's filters with flexible ranges.
"""
if not supabase:
return []
try:
# Start with base query
query = supabase.table("properties").select("*").eq("is_active", True)
# a. Location: try city first, then location field
loc = filters.get("location_preference")
if loc:
# Try city match first
city_query = query.ilike("city", f"%{loc}%")
city_resp = city_query.execute()
if city_resp.data:
query = city_query
else:
# Fallback to location field
query = supabase.table("properties").select("*").eq("is_active", True).ilike("location", f"%{loc}%")
# b. Budget range (target ± 50% tolerance)
budget = filters.get("budget")
if budget is not None:
# Allow properties within 50% of the target budget
min_budget = int(budget * 0.5) # 50% below target
max_budget = int(budget * 1.5) # 50% above target
query = query.gte("price", min_budget).lte("price", max_budget)
# c. Size range (target ± 50% tolerance)
size = filters.get("size_preference_sqm")
if size is not None:
# Allow properties within 50% of the target size
min_size = int(size * 0.5) # 50% below target
max_size = int(size * 1.5) # 50% above target
query = query.gte("size_sqm", min_size).lte("size_sqm", max_size)
# d. Transaction type (rent vs buy)
transaction_type = filters.get("transaction_type")
if transaction_type:
print(f"DEBUG - Filtering by transaction_type: {transaction_type}")
if transaction_type == "lease":
# For rent: filter by lease price type
query = query.eq("price_type", "lease")
print(f"DEBUG - Filtering for rental properties (lease)")
elif transaction_type == "sale":
# For buy: filter by sale price type
query = query.eq("price_type", "sale")
print(f"DEBUG - Filtering for sale properties (sale)")
else:
print(f"DEBUG - No transaction_type filter applied")
# Note: Must-have features are removed from database search
# They will be handled by the LLM in the chat response
# e. Order & limit
query = query.order("is_featured", desc=True).order("price").limit(5)
# f. Execute and return
resp = query.execute()
print(f"DEBUG - search_properties filters: {filters}")
print(f"DEBUG - properties returned: {len(resp.data) if resp.data else 0}")
if resp.data:
print(f"DEBUG - first property: {resp.data[0].get('title')} in {resp.data[0].get('city')}")
return resp.data or []
except Exception as e:
print(f"DEBUG - search_properties error: {e}")
return [] |