Build a sales intelligence ingestion: data contracts, dedup, mapping to CRM, and…
- User
Build a sales intelligence ingestion: data contracts, dedup, mapping to CRM, and enrichment QA.
Assistant
Build a sales intelligence ingestion: data contracts, dedup, mapping to CRM, and enrichment QA.
The user wants to build a "sales intelligence ingestion" system. The prompt is quite concise and covers four specific key areas:
Goal: Provide a comprehensive architectural guide and code snippets (Python/pseudo-code) to implement this system.
Target Audience: Data Engineers, Backend Engineers, or Architects looking for a structured approach.
Key Components to Address:
Drafting the Content - Section by Section:
LeadInputSchema.dedupe library or simple pandas logic + Redis set.Refining the Code Examples:
Self-Correction/Review during drafting:
Structure of the final response:
Let's write the response following this structure. I will focus on a modular design where each stage is decoupled, ideally via a queue or step functions.
Key detail on Enrichment QA: This is often overlooked. Just because Clearbit returns data doesn't mean it's right for this specific lead. I need to include a confidence score check.
Key detail on Dedup: Normalization (lowercase, strip whitespace, fix typos in common domains like gmal.com) is crucial before deduping.
Key detail on CRM: Rate limiting and batching are vital for Salesforce/HubSpot APIs.
Let's generate the solution. Building a Sales Intelligence ingestion engine requires a modular architecture that prioritizes data quality over raw speed. In sales ops, one bad phone number costs more than 100 dropped records.
Here is a comprehensive architectural guide and implementation strategy for a Sales Intelligence Ingestion system.
We will use a "Validation Diamond" approach: Accept broad inputs, validate strictly against contracts, enrich/merge, and output a narrow, high-quality stream to the CRM.
[ External Sources ] (CSV, APIs, Webhooks)
|
v
[ 1. Ingestion & Normalization ]
|
v
[ 2. Data Contracts ] (Schema Validation)
|
v
[ 3. Smart Deduplication ] (Blocking + Fuzzy Matching)
|
v
[ 4. Enrichment QA ] (Confidence Scoring)
|
v
[ 5. CRM Mapper ] (ETL to Salesforce/HubSpot)
|
v
[ Target CRM ]
Before touching your database, you need a contract. This ensures that "Email" is always a string and "Revenue" is always an integer. We use Pydantic in Python for this.
Goal: Reject malformed data before it enters your logic loops.
from pydantic import BaseModel, EmailStr, HttpUrl, Field, validator
from typing import Optional, List
from datetime import datetime
class CompanySchema(BaseModel):
name: str = Field(..., min_length=2)
domain: Optional[HttpUrl]
crm_id: Optional[str] # Foreign key to CRM Account
size: Optional[str]
industry: Optional[str]
class ContactSchema(BaseModel):
first_name: str
last_name: str
email: EmailStr # Pydantic validates email format automatically
company: Optional[CompanySchema]
title: Optional[str]
linkedin_url: Optional[HttpUrl]
@validator('title')
def normalize_title(cls, v):
# Normalize common variations (e.g., SWE -> Software Engineer)
mapping = {"SWE": "Software Engineer", "VP": "Vice President"}
return mapping.get(v, v)
# Example Usage
try:
raw_data = {"first_name": "Alice", "email": "alice@example.com", "title": "SWE"}
valid_contact = ContactSchema(**raw_data)
print(valid_contact.json())
except Exception as e:
print(f"Contract Violation: {e}")
Deduplication is the hardest part. You cannot rely on exact string matches (e.g., "Google Inc." vs "Google").
The Strategy:
from fuzzywuzzy import fuzz
import hashlib
def generate_entity_signature(email: str, domain: str) -> str:
"""Creates a unique hash for exact matching."""
return hashlib.md5(f"{email}|{domain}".encode()).hexdigest()
def check_fuzzy_match(input_name: str, existing_names: list, threshold=85):
"""
Checks if the input name is similar to any existing names.
Returns the match if found.
"""
for existing in existing_names:
score = fuzz.token_set_ratio(input_name, existing)
if score >= threshold:
return existing
return None
# Logic Flow
def process_ingestion(new_record, db_records):
# 1. Exact Match Check (Cheap)
new_sig = generate_entity_signature(new_record.email, new_record.company.domain)
if new_sig in db_records:
return "UPDATE_EXISTING"
# 2. Fuzzy Match Check (Expensive - only run if no exact match)
# Assume we fetched potential matches by company domain first
company_match = check_fuzzy_match(new_record.company.name, [c.name for c in db_records])
if company_match:
return "MERGE_CANDIDATE"
return "CREATE_NEW"
You likely enrich data using tools like Clearbit, Apollo, or PeopleDataLabs. However, you must QA this enriched data to ensure the AI/Enrichment tool didn't hallucinate.
QA Logic:
class EnrichmentQA:
def verify_email(self, email):
# Mock function for SMTP verification logic
# In prod use libraries like 'verify-email' or APIs like ZeroBounce
return "valid"
def calculate_confidence(self, record: ContactSchema, enrichment_data: dict) -> float:
score = 0.0
# Heuristic 1: Do we have a name?
if record.first_name and record.last_name: score += 0.2
# Heuristic 2: Is the email deliverable?
if self.verify_email(record.email): score += 0.4
# Heuristic 3: Does the enrichment company domain match the email domain?
# (Prevents associating a gmail user with a corporate account incorrectly)
email_domain = record.email.split("@")[1]
enrich_domain = enrichment_data.get("company_domain")
if email_domain == enrich_domain: score += 0.4
return score
# Usage
qa = EnrichmentQA()
confidence = qa.calculate_confidence(contact, enrichment_data)
if confidence > 0.8:
push_to_crm_queue(contact)
else:
send_to_slack_review_channel(contact)
CRMs (Salesforce/HubSpot) are notoriously strict. This layer converts your clean Data Contract objects into CRM-specific payloads.
Best Practice: Use an Upsert strategy (Update if exists, Insert if new) based on a unique key (Email or CRM ID) to prevent creating duplicates in the CRM itself.
# Mapper for Salesforce
def map_to_salesforce(contact: ContactSchema) -> dict:
return {
"FirstName": contact.first_name,
"LastName": contact.last_name,
"Email": contact.email,
"Title": contact.title,
# Salesforce requires specific IDs for picklists (like Industry)
"Industry": map_industry_to_sf_picklist(contact.company.industry),
# Logical external ID for upserting
"External_Id__c": contact.email
}
def sync_to_crm(payload):
# Pseudo-code for SF API
# sf.Contact.upsert(data=payload, external_id_field='External_Id__c')
pass
To support this logic, you need a specific infrastructure stack.
pg_trgm)Do not use simple SQL for sales data. You need trigram matching for fuzzy search.
CREATE EXTENSION pg_trgm;CREATE INDEX idx_company_name_trgm ON companies USING gin (name gin_trgm_ops);SELECT * FROM companies
WHERE name % 'Googel' -- Returns 'Google' with similarity logic
Ingestion should be asynchronous.
Build a dashboard for: