ifixkart-backend/app/services/CrmService.py

370 lines
14 KiB
Python

from sqlalchemy.orm import Session
from sqlalchemy import select, func
from typing import List, Optional, Dict, Any
import ulid
from app.models.CrmModel import CrmCustomer, CrmContact, CrmLead, CrmDeal
from app.models.OrderModel import Order
from app.models.ServiceModel import ServiceJob
from app.schemas.Crm import CrmCustomerCreate, CrmCustomerUpdate, CrmLeadCreate, CrmLeadUpdate, CrmLeadConvert, CrmDealCreate, CrmDealUpdate, CrmContactCreate
from app.core.events.event_publisher import publish_business_event
class CrmService:
def __init__(self, db: Session, tenant_id: str = "tenant_default"):
self.db = db
self.tenant_id = tenant_id
# --- CUSTOMER MANAGEMENT ---
def create_customer(self, data: CrmCustomerCreate) -> CrmCustomer:
customer = CrmCustomer(
customer_id=str(ulid.ULID()),
tenant_id=self.tenant_id,
name=data.name,
email=data.email,
phone=data.phone,
sales_tier=data.sales_tier or "BRONZE",
service_tier=data.service_tier or "STANDARD",
notes=data.notes
)
self.db.add(customer)
self.db.commit()
self.db.refresh(customer)
publish_business_event(
event_type="CRM_CUSTOMER_CREATED",
payload={"customer_id": customer.customer_id, "name": customer.name, "phone": customer.phone},
tenant_id=self.tenant_id,
aggregate_id=customer.customer_id
)
return customer
def get_customer(self, customer_id: str) -> Optional[CrmCustomer]:
stmt = select(CrmCustomer).where(
CrmCustomer.customer_id == customer_id,
CrmCustomer.tenant_id == self.tenant_id,
CrmCustomer.deleted_at.is_(None)
)
return self.db.execute(stmt).scalar_one_or_none()
def list_customers(self, skip: int = 0, limit: int = 50, search: Optional[str] = None) -> List[CrmCustomer]:
stmt = select(CrmCustomer).where(
CrmCustomer.tenant_id == self.tenant_id,
CrmCustomer.deleted_at.is_(None)
)
if search:
stmt = stmt.where(
(CrmCustomer.name.ilike(f"%{search}%")) |
(CrmCustomer.phone.ilike(f"%{search}%")) |
(CrmCustomer.email.ilike(f"%{search}%"))
)
stmt = stmt.offset(skip).limit(limit).order_by(CrmCustomer.created_at.desc())
return list(self.db.execute(stmt).scalars().all())
def update_customer(self, customer_id: str, data: CrmCustomerUpdate) -> Optional[CrmCustomer]:
customer = self.get_customer(customer_id)
if not customer:
return None
update_dict = data.model_dump(exclude_unset=True)
for key, val in update_dict.items():
setattr(customer, key, val)
self.recompute_customer_tiers(customer)
self.db.commit()
self.db.refresh(customer)
return customer
def recompute_customer_tiers(self, customer: CrmCustomer) -> None:
"""Dynamically computes sales_tier, service_tier, and is_dual_customer status."""
is_dual = customer.total_orders_count > 0 and customer.total_repairs_count > 0
customer.is_dual_customer = is_dual
ltv = customer.total_lifetime_value_inr
if ltv >= 100000:
customer.sales_tier = "PLATINUM"
elif ltv >= 50000:
customer.sales_tier = "GOLD"
elif ltv >= 10000:
customer.sales_tier = "SILVER"
else:
customer.sales_tier = "BRONZE"
if is_dual or customer.total_repairs_count >= 5:
customer.service_tier = "VIP"
elif customer.total_repairs_count >= 2:
customer.service_tier = "PRIORITY"
else:
customer.service_tier = "STANDARD"
# --- CUSTOMER 360 AGGREGATOR ---
def get_customer_360(self, customer_id: str) -> Optional[Dict[str, Any]]:
customer = self.get_customer(customer_id)
if not customer:
return None
stmt_contacts = select(CrmContact).where(CrmContact.customer_id == customer_id, CrmContact.tenant_id == self.tenant_id)
contacts = list(self.db.execute(stmt_contacts).scalars().all())
stmt_leads = select(CrmLead).where(CrmLead.customer_id == customer_id, CrmLead.tenant_id == self.tenant_id)
leads = list(self.db.execute(stmt_leads).scalars().all())
stmt_deals = select(CrmDeal).where(CrmDeal.customer_id == customer_id, CrmDeal.tenant_id == self.tenant_id)
deals = list(self.db.execute(stmt_deals).scalars().all())
return {
"customer": customer,
"contacts": contacts,
"leads": leads,
"deals": deals,
"orders_summary": {
"total_orders": customer.total_orders_count,
"total_spent_inr": customer.total_lifetime_value_inr
},
"repairs_summary": {
"total_repairs": customer.total_repairs_count,
"service_tier": customer.service_tier,
"is_vip": customer.service_tier == "VIP"
}
}
# --- LEADS ENGINE ---
def create_lead(self, data: CrmLeadCreate) -> CrmLead:
lead = CrmLead(
lead_id=str(ulid.ULID()),
tenant_id=self.tenant_id,
customer_id=data.customer_id,
title=data.title,
phone=data.phone,
email=data.email,
first_name=data.first_name,
last_name=data.last_name,
source=data.source or "STOREFRONT",
status=data.status or "NEW",
score=data.score or 10,
assigned_user_id=data.assigned_user_id,
notes=data.notes
)
self.db.add(lead)
# Auto-sync deal for Kanban Pipeline parity
stage_map = {
"NEW": "NEW",
"CONTACTED": "CONTACTED",
"QUALIFIED": "PROPOSAL_SENT",
"QUOTE_DRAFT": "PROPOSAL_SENT",
"QUOTE_SENT": "PROPOSAL_SENT",
"CONVERTED": "CLOSED_WON",
"LOST": "CLOSED_LOST"
}
deal_stage = stage_map.get(lead.status, "NEW")
deal = CrmDeal(
deal_id=str(ulid.ULID()),
tenant_id=self.tenant_id,
lead_id=lead.lead_id,
customer_id=lead.customer_id,
title=lead.title,
stage=deal_stage,
estimated_value=float(lead.quote_amount or 5000.0),
probability_percent=50,
notes=lead.notes
)
self.db.add(deal)
self.db.commit()
self.db.refresh(lead)
publish_business_event(
event_type="CRM_LEAD_CREATED",
payload={"lead_id": lead.lead_id, "title": lead.title, "source": lead.source},
tenant_id=self.tenant_id,
aggregate_id=lead.lead_id
)
return lead
def list_leads(self, skip: int = 0, limit: int = 50, status: Optional[str] = None) -> List[CrmLead]:
stmt = select(CrmLead).where(CrmLead.tenant_id == self.tenant_id, CrmLead.deleted_at.is_(None))
if status:
stmt = stmt.where(CrmLead.status == status)
stmt = stmt.offset(skip).limit(limit).order_by(CrmLead.created_at.desc())
return list(self.db.execute(stmt).scalars().all())
def get_lead(self, lead_id: str) -> Optional[CrmLead]:
stmt = select(CrmLead).where(
CrmLead.lead_id == lead_id,
CrmLead.tenant_id == self.tenant_id,
CrmLead.deleted_at.is_(None)
)
return self.db.execute(stmt).scalar_one_or_none()
def update_lead(self, lead_id: str, data: CrmLeadUpdate) -> Optional[CrmLead]:
lead = self.get_lead(lead_id)
if not lead:
return None
update_dict = data.model_dump(exclude_unset=True)
for key, val in update_dict.items():
setattr(lead, key, val)
if data.quote_amount is not None or data.quote_title is not None:
if not lead.quote_sent_at:
from datetime import datetime, timezone
lead.quote_sent_at = datetime.now(timezone.utc).replace(tzinfo=None)
# Sync linked deal stage
if data.status or data.quote_amount is not None:
stage_map = {
"NEW": "NEW",
"CONTACTED": "CONTACTED",
"QUALIFIED": "PROPOSAL_SENT",
"QUOTE_DRAFT": "PROPOSAL_SENT",
"QUOTE_SENT": "PROPOSAL_SENT",
"CONVERTED": "CLOSED_WON",
"LOST": "CLOSED_LOST"
}
target_stage = stage_map.get(lead.status, lead.status)
stmt_deal = select(CrmDeal).where(CrmDeal.lead_id == lead.lead_id, CrmDeal.tenant_id == self.tenant_id)
existing_deal = self.db.execute(stmt_deal).scalar_one_or_none()
if existing_deal:
if data.status:
existing_deal.stage = target_stage
if data.quote_amount is not None:
existing_deal.estimated_value = float(data.quote_amount)
else:
# Create missing deal if not exists
new_deal = CrmDeal(
deal_id=str(ulid.ULID()),
tenant_id=self.tenant_id,
lead_id=lead.lead_id,
customer_id=lead.customer_id,
title=lead.title,
stage=target_stage,
estimated_value=float(lead.quote_amount or 5000.0),
probability_percent=50,
notes=lead.notes
)
self.db.add(new_deal)
self.db.commit()
self.db.refresh(lead)
publish_business_event(
event_type="CRM_LEAD_UPDATED",
payload={"lead_id": lead.lead_id, "status": lead.status},
tenant_id=self.tenant_id,
aggregate_id=lead.lead_id
)
return lead
def convert_lead(self, lead_id: str, data: CrmLeadConvert) -> Dict[str, Any]:
lead = self.get_lead(lead_id)
if not lead:
raise ValueError("Lead not found")
customer = None
if lead.customer_id:
customer = self.get_customer(lead.customer_id)
if not customer and data.customer_phone:
stmt = select(CrmCustomer).where(
CrmCustomer.phone == data.customer_phone,
CrmCustomer.tenant_id == self.tenant_id
)
customer = self.db.execute(stmt).scalar_one_or_none()
if not customer:
cust_name = data.customer_name or lead.title or "New Lead Customer"
cust_phone = data.customer_phone or "0000000000"
customer = CrmCustomer(
customer_id=str(ulid.ULID()),
tenant_id=self.tenant_id,
name=cust_name,
email=data.customer_email,
phone=cust_phone,
sales_tier="BRONZE",
service_tier="STANDARD"
)
self.db.add(customer)
self.db.flush()
lead.customer_id = customer.customer_id
lead.status = "CONVERTED"
category = (data.category or "ECOMMERCE").upper()
if category == "ECOMMERCE":
customer.total_orders_count += 1
elif category == "SERVICE":
customer.total_repairs_count += 1
elif category == "BOTH":
customer.total_orders_count += 1
customer.total_repairs_count += 1
self.recompute_customer_tiers(customer)
deal_title = data.deal_title or f"Converted Deal - {lead.title}"
deal = CrmDeal(
deal_id=str(ulid.ULID()),
tenant_id=self.tenant_id,
lead_id=lead.lead_id,
customer_id=customer.customer_id,
title=deal_title,
stage="REQUIREMENT_AUDIT",
estimated_value=data.estimated_value or 0.0,
probability_percent=75,
notes=data.notes or lead.notes
)
self.db.add(deal)
self.db.commit()
self.db.refresh(customer)
self.db.refresh(deal)
self.db.refresh(lead)
publish_business_event(
event_type="CRM_LEAD_CONVERTED",
payload={
"lead_id": lead.lead_id,
"customer_id": customer.customer_id,
"deal_id": deal.deal_id,
"is_dual_customer": customer.is_dual_customer
},
tenant_id=self.tenant_id,
aggregate_id=lead.lead_id
)
return {
"lead": lead,
"customer": customer,
"deal": deal,
"is_dual_customer": customer.is_dual_customer
}
# --- DEALS KANBAN ENGINE ---
def create_deal(self, data: CrmDealCreate) -> CrmDeal:
val = data.estimated_value if data.estimated_value is not None else (data.value or 0.0)
deal = CrmDeal(
deal_id=str(ulid.ULID()),
tenant_id=self.tenant_id,
lead_id=data.lead_id,
customer_id=data.customer_id,
title=data.title,
stage=data.stage or "NEW",
estimated_value=val,
probability_percent=data.probability_percent or 50,
assigned_user_id=data.assigned_user_id,
notes=data.notes
)
self.db.add(deal)
self.db.commit()
self.db.refresh(deal)
publish_business_event(
event_type="CRM_DEAL_CREATED",
payload={"deal_id": deal.deal_id, "title": deal.title, "value": deal.estimated_value},
tenant_id=self.tenant_id,
aggregate_id=deal.deal_id
)
return deal
def list_deals(self, skip: int = 0, limit: int = 50, stage: Optional[str] = None) -> List[CrmDeal]:
stmt = select(CrmDeal).where(CrmDeal.tenant_id == self.tenant_id, CrmDeal.deleted_at.is_(None))
if stage:
stmt = stmt.where(CrmDeal.stage == stage)
stmt = stmt.offset(skip).limit(limit).order_by(CrmDeal.created_at.desc())
return list(self.db.execute(stmt).scalars().all())