Spaces:
Sleeping
Sleeping
Download backend/app/services/auto_sync_service.py from axeronis/microfunnel-api: direct link, hf CLI and curl.
- Browser
- Download file 9.26 kB
-
https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/services/auto_sync_service.py
- Command line
-
hf download hf://spaces/axeronis/microfunnel-api/backend/app/services/auto_sync_service.py
-
curl -L -o auto_sync_service.py https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/services/auto_sync_service.py
9.26 kB
| """ | |
| Auto CRM Sync Service | |
| Automatically syncs qualified leads to CRM systems: | |
| - Checks if lead meets CRM sync criteria | |
| - Retrieves active CRM integrations | |
| - Triggers sync for each integration | |
| - Updates lead sync status | |
| """ | |
| from typing import Dict, Any, Optional, List | |
| from datetime import datetime, timedelta | |
| from uuid import UUID | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlmodel import select | |
| from app.models.lead import Lead, LeadHeat | |
| from app.core.logging import get_logger | |
| logger = get_logger(__name__) | |
| # Try to import CRM integration models (may not exist) | |
| try: | |
| from app.models.crm_integration import CRMIntegration, SyncStatus | |
| from app.services.crm_sync import get_crm_sync_service | |
| CRM_AVAILABLE = True | |
| except ImportError: | |
| CRM_AVAILABLE = False | |
| CRMIntegration = None | |
| SyncStatus = None | |
| logger.warning("CRM integration module not available - auto sync disabled") | |
| class AutoSyncService: | |
| """Service for automatically syncing qualified leads to CRM.""" | |
| def __init__(self): | |
| self.crm_sync_service = get_crm_sync_service() if CRM_AVAILABLE else None | |
| self.min_sync_interval_minutes = 5 # Don't sync same lead more than once per 5 min | |
| async def check_and_sync_lead( | |
| self, | |
| session: AsyncSession, | |
| lead: Lead, | |
| qualification_data: Optional[Dict[str, Any]] = None | |
| ) -> Dict[str, Any]: | |
| """ | |
| Check if lead should be synced and perform sync. | |
| Args: | |
| session: Database session | |
| lead: Lead to potentially sync | |
| qualification_data: Optional qualification analysis results | |
| Returns: | |
| Sync result summary | |
| """ | |
| # Check basic sync criteria | |
| if not self._should_attempt_sync(lead): | |
| return { | |
| "synced": False, | |
| "reason": "Lead doesn't meet sync criteria", | |
| "criteria_check": { | |
| "heat_score": lead.heat_score, | |
| "has_email": bool(lead.email), | |
| "has_phone": bool(lead.phone) | |
| } | |
| } | |
| # Check cooldown period | |
| if lead.last_crm_sync_attempt: | |
| time_since_last = datetime.utcnow() - lead.last_crm_sync_attempt | |
| if time_since_last < timedelta(minutes=self.min_sync_interval_minutes): | |
| return { | |
| "synced": False, | |
| "reason": "Sync cooldown period active", | |
| "retry_after": self.min_sync_interval_minutes - int(time_since_last.total_seconds() / 60) | |
| } | |
| # Get active CRM integrations for tenant | |
| integrations = await self._get_active_integrations(session, lead.tenant_id) | |
| if not integrations: | |
| logger.info(f"No active CRM integrations for tenant {lead.tenant_id}") | |
| return { | |
| "synced": False, | |
| "reason": "No active CRM integrations configured" | |
| } | |
| # Update sync attempt timestamp | |
| lead.last_crm_sync_attempt = datetime.utcnow() | |
| lead.crm_sync_status = "syncing" | |
| session.add(lead) | |
| await session.commit() | |
| # Sync to each integration | |
| results = {} | |
| any_success = False | |
| for integration in integrations: | |
| try: | |
| result = await self.crm_sync_service.sync_lead_to_crm( | |
| session=session, | |
| lead=lead, | |
| integration=integration, | |
| force=False # Don't force if unchanged | |
| ) | |
| results[integration.integration_name] = result | |
| if result.get("success"): | |
| any_success = True | |
| logger.info( | |
| f"โ Synced lead {lead.id} to {integration.crm_type} " | |
| f"(integration: {integration.integration_name})" | |
| ) | |
| else: | |
| logger.warning( | |
| f"โ ๏ธ Failed to sync lead {lead.id} to {integration.crm_type}: " | |
| f"{result.get('error')}" | |
| ) | |
| except Exception as e: | |
| logger.error(f"โ Error syncing to {integration.integration_name}: {e}", exc_info=True) | |
| results[integration.integration_name] = { | |
| "success": False, | |
| "error": str(e) | |
| } | |
| # Update final sync status | |
| if any_success: | |
| lead.crm_sync_status = "synced" | |
| lead.last_crm_synced_at = datetime.utcnow() | |
| else: | |
| lead.crm_sync_status = "failed" | |
| session.add(lead) | |
| await session.commit() | |
| return { | |
| "synced": any_success, | |
| "total_integrations": len(integrations), | |
| "successful_syncs": sum(1 for r in results.values() if r.get("success")), | |
| "results": results | |
| } | |
| def _should_attempt_sync(self, lead: Lead) -> bool: | |
| """ | |
| Threshold Crossing Logic - prevents CRM spam. | |
| Syncs only when: 1) First time qualified, 2) New peak score | |
| """ | |
| # Must have contact | |
| if not lead.email and not lead.phone: | |
| return False | |
| if lead.heat_level == LeadHeat.JUNK: | |
| return False | |
| current = lead.heat_score | |
| # First time HOT | |
| if current >= 70 and not lead.ever_qualified: | |
| lead.ever_qualified = True | |
| lead.qualified_at = datetime.utcnow() | |
| lead.peak_heat_score = current | |
| logger.info(f"๐ฅ Lead {lead.id}: First HOT ({current})") | |
| return True | |
| # New peak | |
| if lead.ever_qualified and current > lead.peak_heat_score: | |
| lead.peak_heat_score = current | |
| logger.info(f"๐ Lead {lead.id}: New peak {current}") | |
| return True | |
| return False | |
| async def _get_active_integrations( | |
| self, | |
| session: AsyncSession, | |
| tenant_id: UUID | |
| ) -> List[CRMIntegration]: | |
| """Get all active CRM integrations for tenant.""" | |
| stmt = select(CRMIntegration).where( | |
| CRMIntegration.tenant_id == tenant_id, | |
| CRMIntegration.is_active == True, | |
| CRMIntegration.status == SyncStatus.ACTIVE, | |
| CRMIntegration.auto_sync == True # Must have auto-sync enabled | |
| ) | |
| result = await session.execute(stmt) | |
| integrations = list(result.scalars().all()) | |
| # Filter for integrations that sync to CRM (not from CRM) | |
| return [ | |
| i for i in integrations | |
| if i.sync_direction in ["to_crm", "bidirectional"] | |
| ] | |
| async def sync_all_qualified_leads( | |
| self, | |
| session: AsyncSession, | |
| tenant_id: UUID, | |
| limit: int = 50 | |
| ) -> Dict[str, Any]: | |
| """ | |
| Batch sync all qualified leads that haven't been synced recently. | |
| Useful for manual triggers or cron jobs. | |
| Args: | |
| session: Database session | |
| tenant_id: Tenant to sync leads for | |
| limit: Maximum number of leads to process | |
| Returns: | |
| Batch sync statistics | |
| """ | |
| # Get qualified leads that need syncing | |
| cutoff_time = datetime.utcnow() - timedelta(minutes=self.min_sync_interval_minutes) | |
| stmt = select(Lead).where( | |
| Lead.tenant_id == tenant_id, | |
| Lead.heat_score >= 70, | |
| Lead.crm_sync_status.in_(["pending", "failed", None]) | |
| ).where( | |
| (Lead.last_crm_sync_attempt == None) | | |
| (Lead.last_crm_sync_attempt < cutoff_time) | |
| ).limit(limit) | |
| result = await session.execute(stmt) | |
| leads = list(result.scalars().all()) | |
| stats = { | |
| "total_processed": len(leads), | |
| "successful": 0, | |
| "failed": 0, | |
| "skipped": 0, | |
| "errors": [] | |
| } | |
| for lead in leads: | |
| try: | |
| result = await self.check_and_sync_lead(session, lead) | |
| if result.get("synced"): | |
| stats["successful"] += 1 | |
| elif result.get("reason"): | |
| stats["skipped"] += 1 | |
| else: | |
| stats["failed"] += 1 | |
| except Exception as e: | |
| stats["failed"] += 1 | |
| stats["errors"].append({ | |
| "lead_id": str(lead.id), | |
| "error": str(e) | |
| }) | |
| logger.error(f"Error in batch sync for lead {lead.id}: {e}", exc_info=True) | |
| return stats | |
| # Singleton instance | |
| _auto_sync_service: Optional[AutoSyncService] = None | |
| def get_auto_sync_service() -> AutoSyncService: | |
| """Get auto sync service singleton.""" | |
| global _auto_sync_service | |
| if _auto_sync_service is None: | |
| _auto_sync_service = AutoSyncService() | |
| return _auto_sync_service | |