Spaces:
Running
Running
axeronis commited on
Commit Β·
887a0cb
1
Parent(s): 8721f8a
feat: hourly follow-up for hot leads (1 hour threshold)
Browse files
backend/app/main.py
CHANGED
|
@@ -223,7 +223,7 @@ async def on_startup():
|
|
| 223 |
|
| 224 |
# Start Background Tasks
|
| 225 |
asyncio.create_task(reactivation_scheduler_loop())
|
| 226 |
-
|
| 227 |
|
| 228 |
|
| 229 |
@app.on_event("shutdown")
|
|
@@ -237,6 +237,37 @@ async def on_shutdown():
|
|
| 237 |
logger.error("Error during shutdown", exc_info=True, err=str(e))
|
| 238 |
|
| 239 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
async def reactivation_scheduler_loop():
|
| 241 |
"""
|
| 242 |
Background loop to run Reactivation Service daily.
|
|
|
|
| 223 |
|
| 224 |
# Start Background Tasks
|
| 225 |
asyncio.create_task(reactivation_scheduler_loop())
|
| 226 |
+
asyncio.create_task(hot_leads_scheduler_loop()) # NEW: Hourly for hot leads
|
| 227 |
|
| 228 |
|
| 229 |
@app.on_event("shutdown")
|
|
|
|
| 237 |
logger.error("Error during shutdown", exc_info=True, err=str(e))
|
| 238 |
|
| 239 |
|
| 240 |
+
async def hot_leads_scheduler_loop():
|
| 241 |
+
"""
|
| 242 |
+
Background loop to run Hot Leads follow-up every hour.
|
| 243 |
+
Fast follow-up for HOT/WARM leads who went silent.
|
| 244 |
+
"""
|
| 245 |
+
from app.services.reactivation_service import get_reactivation_service
|
| 246 |
+
from app.core.database import async_session_factory
|
| 247 |
+
|
| 248 |
+
logger.info("π₯ Hot Leads Scheduler initialized (runs every hour)")
|
| 249 |
+
|
| 250 |
+
# Wait 5 minutes after startup before first run
|
| 251 |
+
await asyncio.sleep(5 * 60)
|
| 252 |
+
|
| 253 |
+
while True:
|
| 254 |
+
try:
|
| 255 |
+
logger.info("π₯ Running hourly hot leads follow-up...")
|
| 256 |
+
async with async_session_factory() as session:
|
| 257 |
+
service = get_reactivation_service()
|
| 258 |
+
await service.run_hot_leads_batch(session)
|
| 259 |
+
|
| 260 |
+
# Sleep 1 hour
|
| 261 |
+
await asyncio.sleep(60 * 60)
|
| 262 |
+
|
| 263 |
+
except asyncio.CancelledError:
|
| 264 |
+
logger.info("Hot leads scheduler cancelled")
|
| 265 |
+
break
|
| 266 |
+
except Exception as e:
|
| 267 |
+
logger.error(f"Hot leads scheduler error: {e}")
|
| 268 |
+
await asyncio.sleep(15 * 60) # Retry in 15 minutes
|
| 269 |
+
|
| 270 |
+
|
| 271 |
async def reactivation_scheduler_loop():
|
| 272 |
"""
|
| 273 |
Background loop to run Reactivation Service daily.
|
backend/app/services/reactivation_service.py
CHANGED
|
@@ -82,6 +82,77 @@ class ReactivationService:
|
|
| 82 |
logger.info(f"π Reactivation Batch Complete. Stats: {results}")
|
| 83 |
return results
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
async def find_stale_leads(self, session: AsyncSession, days_threshold: int = 2) -> List[Lead]:
|
| 86 |
"""
|
| 87 |
Find leads who:
|
|
|
|
| 82 |
logger.info(f"π Reactivation Batch Complete. Stats: {results}")
|
| 83 |
return results
|
| 84 |
|
| 85 |
+
async def find_hot_stale_leads(self, session: AsyncSession, hours_threshold: int = 1) -> List[Lead]:
|
| 86 |
+
"""
|
| 87 |
+
Find HOT leads who haven't responded within X hours.
|
| 88 |
+
Hot leads need faster follow-up (1 hour default).
|
| 89 |
+
"""
|
| 90 |
+
cutoff = datetime.utcnow() - timedelta(hours=hours_threshold)
|
| 91 |
+
|
| 92 |
+
# Only HOT leads
|
| 93 |
+
hot_heat_levels = [LeadHeat.HOT, LeadHeat.WARM]
|
| 94 |
+
|
| 95 |
+
# Exclude terminal statuses
|
| 96 |
+
excluded_statuses = [
|
| 97 |
+
LeadStatus.LOST,
|
| 98 |
+
LeadStatus.JUNK,
|
| 99 |
+
LeadStatus.DEAL_WON,
|
| 100 |
+
LeadStatus.ARCHIVED
|
| 101 |
+
]
|
| 102 |
+
|
| 103 |
+
stmt = select(Lead).where(
|
| 104 |
+
and_(
|
| 105 |
+
Lead.last_message_at < cutoff,
|
| 106 |
+
Lead.last_message_at > datetime.utcnow() - timedelta(days=7), # Not too old
|
| 107 |
+
col(Lead.heat_level).in_(hot_heat_levels),
|
| 108 |
+
col(Lead.status).notin_(excluded_statuses),
|
| 109 |
+
Lead.is_blocked == False
|
| 110 |
+
)
|
| 111 |
+
).limit(20) # Smaller batch for hot leads
|
| 112 |
+
|
| 113 |
+
result = await session.execute(stmt)
|
| 114 |
+
return result.scalars().all()
|
| 115 |
+
|
| 116 |
+
async def run_hot_leads_batch(self, session: AsyncSession):
|
| 117 |
+
"""
|
| 118 |
+
Fast follow-up for HOT leads only. Should run every hour.
|
| 119 |
+
"""
|
| 120 |
+
logger.info("π₯ Starting Hot Leads Fast Follow-Up...")
|
| 121 |
+
|
| 122 |
+
candidates = await self.find_hot_stale_leads(session, hours_threshold=1)
|
| 123 |
+
logger.info(f"π₯ Found {len(candidates)} hot leads needing follow-up")
|
| 124 |
+
|
| 125 |
+
results = {"processed": 0, "reactivated": 0, "skipped": 0, "errors": 0}
|
| 126 |
+
|
| 127 |
+
for lead in candidates:
|
| 128 |
+
try:
|
| 129 |
+
history = await self._get_lead_history(session, lead)
|
| 130 |
+
evaluation = await self.ai_core.evaluate_reactivation(session, lead, history)
|
| 131 |
+
|
| 132 |
+
if evaluation.get("decision"):
|
| 133 |
+
message = evaluation.get("draft_message")
|
| 134 |
+
if message:
|
| 135 |
+
logger.info(f"π₯ Hot follow-up for {lead.name}: {message[:50]}...")
|
| 136 |
+
success = await self.execute_reactivation(session, lead, message)
|
| 137 |
+
if success:
|
| 138 |
+
lead.last_message_at = datetime.utcnow()
|
| 139 |
+
session.add(lead)
|
| 140 |
+
await session.commit()
|
| 141 |
+
results["reactivated"] += 1
|
| 142 |
+
else:
|
| 143 |
+
results["errors"] += 1
|
| 144 |
+
else:
|
| 145 |
+
results["skipped"] += 1
|
| 146 |
+
|
| 147 |
+
results["processed"] += 1
|
| 148 |
+
|
| 149 |
+
except Exception as e:
|
| 150 |
+
logger.error(f"β Hot follow-up error for {lead.id}: {e}")
|
| 151 |
+
results["errors"] += 1
|
| 152 |
+
|
| 153 |
+
logger.info(f"π₯ Hot Leads Batch Complete. Stats: {results}")
|
| 154 |
+
return results
|
| 155 |
+
|
| 156 |
async def find_stale_leads(self, session: AsyncSession, days_threshold: int = 2) -> List[Lead]:
|
| 157 |
"""
|
| 158 |
Find leads who:
|