Spaces:
Running

axeronis commited on
Commit
e734753
·
1 Parent(s): cb7ca84

Subscription fixes: admin bypass, reactivation block, realtime push

Browse files
backend/app/services/reactivation_service.py CHANGED
@@ -42,6 +42,21 @@ class ReactivationService:
42
 
43
  for lead in candidates:
44
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  # 2. Evaluate with AI
46
  logger.info(f"🤔 Evaluating lead {lead.id} ({lead.name})...")
47
 
@@ -196,6 +211,21 @@ class ReactivationService:
196
 
197
  for lead in candidates:
198
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  history = await self._get_lead_history(session, lead)
200
  evaluation = await self.ai_core.evaluate_reactivation(session, lead, history)
201
 
@@ -412,9 +442,48 @@ class ReactivationService:
412
 
413
  session.add(db_message)
414
  await session.commit()
 
415
 
416
  logger.info(f"💾 Saved reactivation message to conversation {conversation.id}")
417
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
  except Exception as e:
419
  logger.error(f"Failed to save reactivation message: {e}")
420
 
 
42
 
43
  for lead in candidates:
44
  try:
45
+ # CHECK SUBSCRIPTION - skip if tenant subscription expired
46
+ tenant = await session.get(Tenant, lead.tenant_id)
47
+ if not tenant:
48
+ logger.warning(f"⏭️ Skipping {lead.name} - tenant not found")
49
+ results["skipped_ai"] += 1
50
+ continue
51
+ if tenant.subscription_status in ["expired", "cancelled", "suspended"]:
52
+ logger.info(f"⏭️ Skipping {lead.name} - tenant subscription {tenant.subscription_status}")
53
+ results["skipped_ai"] += 1
54
+ continue
55
+ if tenant.subscription_end and datetime.utcnow() > tenant.subscription_end:
56
+ logger.info(f"⏭️ Skipping {lead.name} - subscription ended {tenant.subscription_end}")
57
+ results["skipped_ai"] += 1
58
+ continue
59
+
60
  # 2. Evaluate with AI
61
  logger.info(f"🤔 Evaluating lead {lead.id} ({lead.name})...")
62
 
 
211
 
212
  for lead in candidates:
213
  try:
214
+ # CHECK SUBSCRIPTION - skip if tenant subscription expired
215
+ tenant = await session.get(Tenant, lead.tenant_id)
216
+ if not tenant:
217
+ logger.warning(f"⏭️ Skipping hot lead {lead.name} - tenant not found")
218
+ results["skipped"] += 1
219
+ continue
220
+ if tenant.subscription_status in ["expired", "cancelled", "suspended"]:
221
+ logger.info(f"⏭️ Skipping hot lead {lead.name} - subscription {tenant.subscription_status}")
222
+ results["skipped"] += 1
223
+ continue
224
+ if tenant.subscription_end and datetime.utcnow() > tenant.subscription_end:
225
+ logger.info(f"⏭️ Skipping hot lead {lead.name} - subscription ended")
226
+ results["skipped"] += 1
227
+ continue
228
+
229
  history = await self._get_lead_history(session, lead)
230
  evaluation = await self.ai_core.evaluate_reactivation(session, lead, history)
231
 
 
442
 
443
  session.add(db_message)
444
  await session.commit()
445
+ await session.refresh(db_message) # Get the generated ID
446
 
447
  logger.info(f"💾 Saved reactivation message to conversation {conversation.id}")
448
 
449
+ # PUSH TO REALTIME - so frontend shows the message immediately
450
+ try:
451
+ from app.core.config import settings
452
+ import httpx
453
+
454
+ # Push to Supabase Realtime via REST (same as webhook does)
455
+ supabase_url = settings.SUPABASE_URL
456
+ supabase_key = settings.SUPABASE_SERVICE_KEY
457
+
458
+ if supabase_url and supabase_key:
459
+ # Broadcast to the conversation channel
460
+ channel_name = f"messages:{conversation.id}"
461
+ broadcast_url = f"{supabase_url}/realtime/v1/api/broadcast"
462
+
463
+ async with httpx.AsyncClient() as client:
464
+ await client.post(
465
+ broadcast_url,
466
+ headers={
467
+ "Authorization": f"Bearer {supabase_key}",
468
+ "Content-Type": "application/json"
469
+ },
470
+ json={
471
+ "event": "new_message",
472
+ "channel": channel_name,
473
+ "payload": {
474
+ "id": str(db_message.id),
475
+ "conversation_id": str(conversation.id),
476
+ "sender_type": "ai",
477
+ "content": display_content,
478
+ "created_at": db_message.created_at.isoformat()
479
+ }
480
+ },
481
+ timeout=5.0
482
+ )
483
+ logger.info(f"📡 Pushed reactivation message to realtime channel {channel_name}")
484
+ except Exception as rt_err:
485
+ logger.warning(f"Failed to push to realtime (non-critical): {rt_err}")
486
+
487
  except Exception as e:
488
  logger.error(f"Failed to save reactivation message: {e}")
489
 
backend/app/services/subscription_manager.py CHANGED
@@ -47,7 +47,8 @@ class SubscriptionManager:
47
  cls,
48
  tenant: Tenant,
49
  session: AsyncSession,
50
- user_email: Optional[str] = None
 
51
  ) -> Tuple[bool, Optional[str]]:
52
  """
53
  Проверить может ли tenant создать новый диалог.
@@ -56,7 +57,11 @@ class SubscriptionManager:
56
  (can_create: bool, reason: Optional[str])
57
  """
58
 
59
- # ADMIN BYPASS - admin gets unlimited access
 
 
 
 
60
  if user_email and user_email.lower() == cls.ADMIN_EMAIL.lower():
61
  return True, None
62
 
 
47
  cls,
48
  tenant: Tenant,
49
  session: AsyncSession,
50
+ user_email: Optional[str] = None,
51
+ is_superuser: bool = False
52
  ) -> Tuple[bool, Optional[str]]:
53
  """
54
  Проверить может ли tenant создать новый диалог.
 
57
  (can_create: bool, reason: Optional[str])
58
  """
59
 
60
+ # ADMIN BYPASS - superuser gets unlimited access (role check)
61
+ if is_superuser:
62
+ return True, None
63
+
64
+ # ADMIN BYPASS - admin email gets unlimited access (legacy)
65
  if user_email and user_email.lower() == cls.ADMIN_EMAIL.lower():
66
  return True, None
67