Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(billing): reject harmonic sub-entities and fill account fields (#114580)

Abhischek73fa244a18e0
diff --git a/ee/billing/salesforce_enrichment/account_fields.py b/ee/billing/salesforce_enrichment/account_fields.py
new file mode 100644
index 000000000000..d27bdf8657ee
--- /dev/null
+++ b/ee/billing/salesforce_enrichment/account_fields.py
@@ -0,0 +1,237 @@
+from typing import Any
+
+from .harmonic_company import describes_company, dict_field, harmonic_headcount, traction_latest, website_domain
+
+# Account.Industry picklist values, read from the Salesforce org on 2026-10-09. The picklist is not restricted, so
+# Salesforce accepts any string. Writes are held to these values to keep stray spellings out of the field.
+INDUSTRY_PICKLIST = frozenset(
+ {
+ "Aerospace & Defense",
+ "Agriculture",
+ "Air Freight & Logistics",
+ "Apparel",
+ "Automotive",
+ "Banking",
+ "Beverages",
+ "Biotechnology",
+ "Capital Markets",
+ "Chemicals",
+ "Commercial Services & Supplies",
+ "Communications",
+ "Construction",
+ "Construction & Engineering",
+ "Consulting",
+ "Consumer Services",
+ "Distributors",
+ "Diversified Consumer Services",
+ "Diversified Financial Services",
+ "Diversified Telecommunication Services",
+ "Education",
+ "Education Services",
+ "Electrical Equipment",
+ "Electronics",
+ "Energy",
+ "Engineering",
+ "Entertainment",
+ "Environmental",
+ "Family Services",
+ "Finance",
+ "Food & Beverage",
+ "Food & Staples Retailing",
+ "Food Products",
+ "Government",
+ "Health Care Equipment & Supplies",
+ "Health Care Providers & Services",
+ "Hospitality",
+ "Hotels, Restaurants & Leisure",
+ "IT Services",
+ "Industrial Conglomerates",
+ "Industrials",
+ "Insurance",
+ "Internet Software & Services",
+ "Leisure Products",
+ "Life Sciences Tools & Services",
+ "Machinery",
+ "Manufacturing",
+ "Media",
+ "Not For Profit",
+ "Other",
+ "Paper & Forest Products",
+ "Personal Products",
+ "Pharmaceuticals",
+ "Professional Services",
+ "Real Estate",
+ "Recreation",
+ "Retail",
+ "Retailing",
+ "Road & Rail",
+ "Semiconductors & Semiconductor Equipment",
+ "Shipping",
+ "Software",
+ "Specialized Consumer Services",
+ "Specialty Retail",
+ "Technology",
+ "Telecommunications",
+ "Textiles, Apparel & Luxury Goods",
+ "Transportation",
+ "Utilities",
+ "Wireless Telecommunication Services",
+ }
+)
+
+# Harmonic tag spellings, lowercased, and the picklist value each one maps to.
+INDUSTRY_ALIASES: dict[str, str] = {
+ "artificial intelligence": "Software",
+ "ai / ml": "Software",
+ "ai/ml": "Software",
+ "developer tools": "Software",
+ "developer operations & ai building tools": "Software",
+ "business software services": "Software",
+ "enterprise productivity & automation": "Software",
+ "saas": "Software",
+ "software development": "Software",
+ "fintech": "Finance",
+ "financial services": "Finance",
+ "healthtech": "Health Care Providers & Services",
+ "healthcare": "Health Care Providers & Services",
+ "e-commerce": "Retailing",
+ "ecommerce": "Retailing",
+ "edtech": "Education Services",
+ "cybersecurity": "Software",
+ "information technology": "IT Services",
+ "internet": "Internet Software & Services",
+ "web services": "Internet Software & Services",
+ "biotech": "Biotechnology",
+ "crypto": "Capital Markets",
+ "blockchain": "Capital Markets",
+ "gaming": "Entertainment",
+ "gaming & interactive entertainment": "Entertainment",
+ "logistics": "Air Freight & Logistics",
+ "real estate": "Real Estate",
+ "consumer": "Diversified Consumer Services",
+ "hardware": "Electronics",
+ "robotics": "Machinery",
+ "semiconductors": "Semiconductors & Semiconductor Equipment",
+ "telecommunications": "Telecommunications",
+ "media": "Media",
+ "digital media & content platforms": "Media",
+ "insurance": "Insurance",
+ "legaltech": "Professional Services",
+ "hrtech": "Professional Services",
+ "marketplace": "Internet Software & Services",
+}
+
+# Industries that describe whom a company sells to as readily as what it does. A company that builds software for
+# banks carries a finance tag, so a tag that maps to one of these names the industry only when no other tag maps.
+SECTOR_INDUSTRIES = frozenset({"Finance", "Banking", "Insurance", "Capital Markets", "Diversified Financial Services"})
+
+# Account.Company_LinkedIn__c is a URL(255) field. Salesforce rejects the whole record for a longer value.
+LINKEDIN_URL_MAX_LENGTH = 255
+
+LINKEDIN_COUNT_FIELDS = ("LinkedIn_Engineer_Count__c", "LinkedIn_Rolecount__c")
+
+
+def _map_industry(tag: str) -> str | None:
+ if tag in INDUSTRY_PICKLIST:
+ return tag
+ return INDUSTRY_ALIASES.get(tag.lower())
+
+
+def _tags(company: dict[str, Any], key: str) -> list[dict[str, Any]]:
+ tags = company.get(key)
+ if not isinstance(tags, list):
+ return []
+ return [tag for tag in tags if isinstance(tag, dict)]
+
+
+def _tag_values(company: dict[str, Any]) -> list[str]:
+ legacy = sorted(_tags(company, "tags"), key=lambda tag: not tag.get("isPrimaryTag"))
+ newer = _tags(company, "tagsV2")
+ return [tag["displayValue"] for tag in legacy + newer if isinstance(tag.get("displayValue"), str)]
+
+
+def account_industry(company: dict[str, Any]) -> str | None:
+ """The Account.Industry picklist value for a company, or None when no tag maps to one.
+
+ Harmonic has no industry field, so its tags stand in. The legacy tags name the product more often than the
+ newer sector-led ones, so they come first, led by the tag Harmonic marks as primary.
+ """
+ mapped = [industry for tag in _tag_values(company) if (industry := _map_industry(tag)) is not None]
+ for industry in mapped:
+ if industry not in SECTOR_INDUSTRIES:
+ return industry
+ return mapped[0] if mapped else None
+
+
+def _total_funding(company: dict[str, Any]) -> Any:
+ total = dict_field(company, "funding").get("fundingTotal")
+ if total == 0 and not describes_company(company):
+ return None
+ return total
+
+
+def _founded_year(company: dict[str, Any]) -> int | None:
+ date = dict_field(company, "foundingDate").get("date")
+ if not isinstance(date, str) or "-" not in date:
+ return None
+ try:
+ return int(date.split("-")[0])
+ except ValueError:
+ return None
+
+
+def _linkedin_url(company: dict[str, Any], queried_domain: str) -> str | None:
+ # Harmonic can return a record whose facts fit the queried company while its web identity belongs to another
+ # company. The LinkedIn page is written only when the website Harmonic reports is on the queried domain.
+ if website_domain(company) != queried_domain:
+ return None
+ url = dict_field(dict_field(company, "socials"), "linkedin").get("url")
+ return url if isinstance(url, str) and 0 < len(url) <= LINKEDIN_URL_MAX_LENGTH else None
+
+
+def _linkedin_headcounts(company: dict[str, Any]) -> dict[str, int | float]:
+ # The pct_engineers__c formula divides the engineer count by the role count, so the two are written only as a
+ # pair. One fresh count beside a stale one produces a ratio that neither source reported, and a role count of
+ # zero makes the formula divide by zero.
+ engineering = traction_latest(company, "headcountEngineering")
+ total = traction_latest(company, "headcount")
+ if engineering is None or total is None or total <= 0:
+ return {}
+ return {"LinkedIn_Engineer_Count__c": engineering, "LinkedIn_Rolecount__c": total}
+
+
+def overwritten_account_fields(company: dict[str, Any]) -> dict[str, Any]:
+ """The canonical Account fields that always take Harmonic's value."""
+ fields = {
+ "Total_Funding__c": _total_funding(company),
+ "Last_Funding_Date__c": dict_field(company, "funding").get("lastFundingAt"),
+ "Founded_year__c": _founded_year(company),
+ }
+ return {field: value for field, value in fields.items() if value is not None}
+
+
+def fill_only_account_fields(company: dict[str, Any], *, queried_domain: str) -> dict[str, Any]:
+ """The canonical Account fields that take Harmonic's value only while the Account holds none.
+
+ Other writers also set these fields, and a different value from Harmonic is not evidence that theirs is wrong.
+ Pass the result through unoccupied_fields() with the Account's current values before it is written.
+ """
+ fields = {
+ "NumberOfEmployees": harmonic_headcount(company),
+ "Industry": account_industry(company),
+ "Company_LinkedIn__c": _linkedin_url(company, queried_domain),
+ **_linkedin_headcounts(company),
+ }
+ return {field: value for field, value in fields.items() if value is not None}
+
+
+def unoccupied_fields(fill_fields: dict[str, Any], account: dict[str, Any]) -> dict[str, Any]:
+ """The fill-only fields that the Account's current values leave room for.
+
+ A field that the Account read did not return is unknown, not empty, and is not written.
+ """
+ fields = {field: value for field, value in fill_fields.items() if field in account and account[field] in (None, "")}
+ if not all(field in fields for field in LINKEDIN_COUNT_FIELDS):
+ for field in LINKEDIN_COUNT_FIELDS:
+ fields.pop(field, None)
+ return fields
diff --git a/ee/billing/salesforce_enrichment/constants.py b/ee/billing/salesforce_enrichment/constants.py
index 5b613d282414..2c1928781353 100644
--- a/ee/billing/salesforce_enrichment/constants.py
+++ b/ee/billing/salesforce_enrichment/constants.py
@@ -12,7 +12,7 @@ SALESFORCE_UPDATE_BATCH_SIZE: int = 200 # Max records per sObject Collections A
DEFAULT_CHUNK_SIZE: int = 5000
# Harmonic GraphQL query for company enrichment
-HARMONIC_COMPANY_ENRICHMENT_QUERY = """
+_HARMONIC_ENRICHMENT_QUERY_HEAD = """
mutation($identifiers: CompanyEnrichmentIdentifiersInput!) {
enrichCompanyByIdentifiers(identifiers: $identifiers) {
companyFound
@@ -110,10 +110,35 @@ mutation($identifiers: CompanyEnrichmentIdentifiersInput!) {
displayValue
dateAdded
}
- }
+"""
+_HARMONIC_ENRICHMENT_QUERY_TAIL = """ }
}
}
"""
+HARMONIC_COMPANY_ENRICHMENT_QUERY = _HARMONIC_ENRICHMENT_QUERY_HEAD + _HARMONIC_ENRICHMENT_QUERY_TAIL
+
+# The Salesforce Account job also writes the company's LinkedIn page. It has its own query so that the payload the
+# other callers of the client fetch, and archive, does not include it.
+HARMONIC_ACCOUNT_ENRICHMENT_QUERY = (
+ _HARMONIC_ENRICHMENT_QUERY_HEAD
+ + """ socials {
+ linkedin {
+ url
+ }
+ }
+"""
+ + _HARMONIC_ENRICHMENT_QUERY_TAIL
+)
+
+# Canonical Account fields that the Harmonic enrichment writes only when they hold no value. The job reads their
+# current values immediately before it writes.
+ACCOUNT_FILL_FIELDS: tuple[str, ...] = (
+ "Industry",
+ "NumberOfEmployees",
+ "Company_LinkedIn__c",
+ "LinkedIn_Engineer_Count__c",
+ "LinkedIn_Rolecount__c",
+)
# Salesforce query for accounts with websites
SALESFORCE_ACCOUNTS_QUERY = """
diff --git a/ee/billing/salesforce_enrichment/enrichment.py b/ee/billing/salesforce_enrichment/enrichment.py
index 646e65ecf2f9..63f256255888 100644
--- a/ee/billing/salesforce_enrichment/enrichment.py
+++ b/ee/billing/salesforce_enrichment/enrichment.py
@@ -1,6 +1,7 @@
import time
+import asyncio
from datetime import UTC, datetime
-from typing import Any
+from typing import TYPE_CHECKING, Any
from urllib.parse import urlparse
from django.utils import timezone
@@ -14,8 +15,11 @@ from posthog.egress.limiter.policies import Priority
from posthog.exceptions_capture import capture_exception
from posthog.temporal.common.logger import get_logger
+from .account_fields import fill_only_account_fields, overwritten_account_fields, unoccupied_fields
from .constants import (
+ ACCOUNT_FILL_FIELDS,
DEFAULT_CHUNK_SIZE,
+ HARMONIC_ACCOUNT_ENRICHMENT_QUERY,
HARMONIC_BATCH_SIZE,
METRIC_PERIODS,
PERSONAL_EMAIL_DOMAINS,
@@ -23,9 +27,13 @@ from .constants import (
YC_INVESTOR_NAME,
)
from .harmonic_client import AsyncHarmonicClient
+from .harmonic_company import is_sub_entity
from .redis_cache import get_accounts_from_redis
from .salesforce_client import get_salesforce_client
+if TYPE_CHECKING:
+ from simple_salesforce import Salesforce
+
LOGGER = get_logger(__name__)
@@ -242,19 +250,8 @@ def _extract_primary_tag(tags: list, tags_v2: list) -> str | None:
return None
-def prepare_salesforce_update_data(account_id: str, harmonic_data: dict[str, Any]) -> dict[str, Any] | None:
- """Convert enriched data to Salesforce field mappings for bulk update.
-
- Args:
- account_id: Salesforce Account.Id
- harmonic_data: Output from transform_harmonic_data()
-
- Returns:
- Dict ready for Salesforce sObject Collections API
- """
- if not harmonic_data:
- return None
-
+def _harmonic_mirror_fields(harmonic_data: dict[str, Any]) -> dict[str, Any]:
+ """Every Account field that only this job writes, with None where Harmonic has no value."""
funding = harmonic_data.get("funding", {})
company_info = harmonic_data.get("company_info", {})
metrics = harmonic_data.get("metrics", {})
@@ -263,21 +260,14 @@ def prepare_salesforce_update_data(account_id: str, harmonic_data: dict[str, Any
current_metrics = {metric_name: metric_data.get("current_value") for metric_name, metric_data in metrics.items()}
- founding_date = company_info.get("founding_date", "")
- founded_year = int(founding_date.split("-")[0]) if founding_date and "-" in founding_date else None
-
- update_data = {
- "Id": account_id,
+ return {
# Company Info
"harmonic_company_name__c": company_info.get("name"),
"harmonic_company_type__c": company_info.get("type"),
"harmonic_industry__c": _extract_primary_tag(tags, tags_v2),
"harmonic_last_update__c": timezone.now().strftime("%Y-%m-%d"),
- "Founded_year__c": founded_year,
# Funding Info
"harmonic_last_funding__c": funding.get("lastFundingTotal"),
- "Last_Funding_Date__c": funding.get("lastFundingAt"),
- "Total_Funding__c": funding.get("fundingTotal"),
"harmonic_funding_stage__c": funding.get("fundingStage"),
# YC Flag
"harmonic_is_yc_company__c": harmonic_data.get("is_yc_company"),
@@ -303,10 +293,108 @@ def prepare_salesforce_update_data(account_id: str, harmonic_data: dict[str, Any
"harmonic_web_traffic_180d__c": _get_historical_metric_value(metrics, "webTraffic", "180d"),
}
- # Remove None values to avoid Salesforce errors
- filtered_update_data = {k: v for k, v in update_data.items() if v is not None}
- return filtered_update_data
+def prepare_salesforce_update_data(account_id: str, harmonic_data: dict[str, Any]) -> dict[str, Any] | None:
+ """Convert enriched data to Salesforce field mappings for bulk update.
+
+ Args:
+ account_id: Salesforce Account.Id
+ harmonic_data: Output from transform_harmonic_data()
+
+ Returns:
+ Dict ready for Salesforce sObject Collections API
+ """
+ if not harmonic_data:
+ return None
+
+ # A None value is left out, so that a field Harmonic stops reporting keeps the value from an earlier run.
+ mirror_fields = {k: v for k, v in _harmonic_mirror_fields(harmonic_data).items() if v is not None}
+
+ return {"Id": account_id, **mirror_fields}
+
+
+def prepare_mirror_clearing_data(account_id: str) -> dict[str, Any]:
+ """Build the update that removes what earlier runs stamped on an Account from a Harmonic sub-entity.
+
+ The canonical fields are left alone. Other writers also set them, and the record does not say which value
+ came from the sub-entity.
+ """
+ # The field names come from the mapping that stamps them, so that a field added there is also cleared here.
+ cleared: dict[str, Any] = dict.fromkeys(_harmonic_mirror_fields({}))
+ # A Salesforce checkbox cannot hold null.
+ cleared["harmonic_is_yc_company__c"] = False
+
+ return {"Id": account_id, **cleared}
+
+
+def prepare_account_update(account_id: str, company: dict[str, Any]) -> dict[str, Any] | None:
+ """Build the update for one Account from Harmonic's answer for its domain.
+
+ The fill-only fields are not included. They depend on the Account's current values, and
+ add_unoccupied_fill_fields() adds them immediately before the write.
+
+ Args:
+ account_id: Salesforce Account.Id
+ company: Raw company from the Harmonic API
+
+ Returns:
+ Dict ready for Salesforce sObject Collections API, or None if the company cannot be transformed
+ """
+ if is_sub_entity(company):
+ return prepare_mirror_clearing_data(account_id)
+
+ harmonic_data = transform_harmonic_data(company)
+ update_data = prepare_salesforce_update_data(account_id, harmonic_data) if harmonic_data else None
+ if update_data is None:
+ return None
+
+ return {**update_data, **overwritten_account_fields(company)}
+
+
+def _read_fill_field_values(sf: "Salesforce", account_ids: list[str]) -> dict[str, dict[str, Any]]:
+ """Read the current values of ACCOUNT_FILL_FIELDS from Salesforce, keyed by Account Id.
+
+ An Account whose read fails is left out of the result.
+ """
+ logger = LOGGER.bind(function="_read_fill_field_values")
+ current_values: dict[str, dict[str, Any]] = {}
+
+ for start in range(0, len(account_ids), SALESFORCE_UPDATE_BATCH_SIZE):
+ query = format_soql(
+ f"SELECT Id, {', '.join(ACCOUNT_FILL_FIELDS)} FROM Account WHERE Id IN {{}}",
+ account_ids[start : start + SALESFORCE_UPDATE_BATCH_SIZE],
+ )
+ try:
+ current_values.update((record["Id"], record) for record in sf.query_all(query)["records"])
+ except Exception as e:
+ logger.exception("Failed to read current Account values", error=str(e))
+ capture_exception(e)
+
+ return current_values
+
+
+def add_unoccupied_fill_fields(
+ sf: "Salesforce", update_records: list[dict[str, Any]], fill_fields_by_account: dict[str, dict[str, Any]]
+) -> None:
+ """Add each Account's fill-only fields to its update record, for the fields that hold no value in Salesforce.
+
+ The current values are read here, immediately before the write. The cached Account records can be hours old,
+ and a value that another writer set in that time must not be replaced. Salesforce has no conditional update,
+ so a value set between this read and the write can still be replaced.
+
+ Args:
+ sf: simple_salesforce.Salesforce client
+ update_records: List of dicts with Id + field updates, changed in place
+ fill_fields_by_account: Output from fill_only_account_fields(), keyed by Account Id
+ """
+ current_values = _read_fill_field_values(
+ sf, [account_id for account_id, fill_fields in fill_fields_by_account.items() if fill_fields]
+ )
+
+ for record in update_records:
+ fill_fields = fill_fields_by_account.get(record["Id"])
+ if fill_fields:
+ record.update(unoccupied_fields(fill_fields, current_values.get(record["Id"], {})))
@frozen
@@ -507,6 +595,7 @@ def _build_result(
records_processed: int = 0,
records_enriched: int = 0,
records_updated: int = 0,
+ records_rejected_sub_entity: int = 0,
total_accounts_in_chunk: int = 0,
errors: list[str] | None = None,
error: str | None = None,
@@ -521,6 +610,7 @@ def _build_result(
"records_processed": records_processed,
"records_enriched": records_enriched,
"records_updated": records_updated,
+ "records_rejected_sub_entity": records_rejected_sub_entity,
"success_rate": success_rate,
"total_time": round(time.time() - start_time, 2),
"total_accounts_in_chunk": total_accounts_in_chunk,
@@ -746,15 +836,18 @@ async def _enrich_specific_domain_debug(
if not accounts:
return _build_debug_error_result(chunk_number, start_time, domain, "No Salesforce accounts found")
- async with AsyncHarmonicClient(priority=Priority.BATCH, source="salesforce_enrichment_debug") as harmonic_client:
+ async with AsyncHarmonicClient(
+ priority=Priority.BATCH, source="salesforce_enrichment_debug", query=HARMONIC_ACCOUNT_ENRICHMENT_QUERY
+ ) as harmonic_client:
harmonic_results = await harmonic_client.enrich_companies_batch([domain])
harmonic_result = harmonic_results[0] if harmonic_results else None
- if not harmonic_result:
+ if not harmonic_result or not isinstance(harmonic_result, dict):
return _build_debug_error_result(chunk_number, start_time, domain, "No Harmonic data found", accounts)
- harmonic_data = transform_harmonic_data(harmonic_result)
- if not harmonic_data:
+ rejected_sub_entity = is_sub_entity(harmonic_result)
+ harmonic_data = None if rejected_sub_entity else transform_harmonic_data(harmonic_result)
+ if not rejected_sub_entity and not harmonic_data:
return _build_debug_error_result(
chunk_number, start_time, domain, "Failed to transform Harmonic data", accounts
)
@@ -762,7 +855,7 @@ async def _enrich_specific_domain_debug(
update_records = [
update_data
for account in accounts
- if (update_data := prepare_salesforce_update_data(account["Id"], harmonic_data))
+ if (update_data := prepare_account_update(account["Id"], harmonic_result))
]
salesforce_updated = False
@@ -774,6 +867,10 @@ async def _enrich_specific_domain_debug(
try:
if update_records:
sf = get_salesforce_client()
+ if not rejected_sub_entity:
+ fill_fields = fill_only_account_fields(harmonic_result, queried_domain=domain)
+ fill_fields_by_account = {record["Id"]: fill_fields for record in update_records}
+ await asyncio.to_thread(add_unoccupied_fill_fields, sf, update_records, fill_fields_by_account)
bulk_update_salesforce_accounts(sf, update_records)
salesforce_updated = True
records_updated = len(update_records)
@@ -795,6 +892,7 @@ async def _enrich_specific_domain_debug(
"salesforce_accounts": [f"{acc['Name']} ({acc['Id']})" for acc in accounts],
"accounts_updated": records_updated,
"domain": domain,
+ "rejected_sub_entity": rejected_sub_entity,
"all_fields_match": field_comparison["all_fields_match"] if field_comparison else None,
}
if update_error:
@@ -805,8 +903,9 @@ async def _enrich_specific_domain_debug(
chunk_number,
start_time,
records_processed=len(accounts),
- records_enriched=1,
+ records_enriched=0 if rejected_sub_entity else 1,
records_updated=records_updated,
+ records_rejected_sub_entity=len(accounts) if rejected_sub_entity else 0,
),
"summary": summary,
"enriched_data": harmonic_data,
@@ -881,9 +980,13 @@ async def enrich_accounts_chunked_async(
total_enriched = 0
total_failed = 0
+ total_rejected = 0
update_records = []
+ fill_fields_by_account: dict[str, dict[str, Any]] = {}
- async with AsyncHarmonicClient(priority=Priority.BATCH, source="salesforce_enrichment_bulk") as harmonic_client:
+ async with AsyncHarmonicClient(
+ priority=Priority.BATCH, source="salesforce_enrichment_bulk", query=HARMONIC_ACCOUNT_ENRICHMENT_QUERY
+ ) as harmonic_client:
for batch_start in range(0, len(account_data), HARMONIC_BATCH_SIZE):
batch_end = min(batch_start + HARMONIC_BATCH_SIZE, len(account_data))
batch = account_data[batch_start:batch_end]
@@ -897,23 +1000,35 @@ async def enrich_accounts_chunked_async(
for account_info, harmonic_result in zip(batch, harmonic_results):
account_id = account_info["account_id"]
- if harmonic_result:
- harmonic_data = transform_harmonic_data(harmonic_result)
+ # A response that is not a company record counts as a failed lookup and must not stop the chunk.
+ if not isinstance(harmonic_result, dict):
+ total_failed += 1
+ continue
- if harmonic_data:
- total_enriched += 1
- update_data = prepare_salesforce_update_data(account_id, harmonic_data)
- if update_data:
- update_records.append(update_data)
- else:
- total_failed += 1
- else:
- total_failed += 1
- else:
+ update_data = prepare_account_update(account_id, harmonic_result)
+ if update_data is None:
total_failed += 1
+ continue
+
+ update_records.append(update_data)
+ if is_sub_entity(harmonic_result):
+ total_rejected += 1
+ logger.info(
+ "Rejected Harmonic sub-entity",
+ account_id=account_id,
+ harmonic_name=harmonic_result.get("name"),
+ harmonic_website=_safe_dict(harmonic_result.get("website")).get("url"),
+ )
+ else:
+ total_enriched += 1
+ fill_fields_by_account[account_id] = fill_only_account_fields(
+ harmonic_result, queried_domain=account_info["domain"]
+ )
# Update Salesforce accounts
if update_records:
+ # The read runs in a thread, so that it does not hold the event loop in addition to the write below.
+ await asyncio.to_thread(add_unoccupied_fill_fields, sf, update_records, fill_fields_by_account)
bulk_update_salesforce_accounts(sf, update_records)
result = _build_result(
@@ -922,6 +1037,7 @@ async def enrich_accounts_chunked_async(
records_processed=len(account_data),
records_enriched=total_enriched,
records_updated=len(update_records),
+ records_rejected_sub_entity=total_rejected,
total_accounts_in_chunk=len(accounts),
)
diff --git a/ee/billing/salesforce_enrichment/harmonic_client.py b/ee/billing/salesforce_enrichment/harmonic_client.py
index aa78b6bb561d..f442f13c1302 100644
--- a/ee/billing/salesforce_enrichment/harmonic_client.py
+++ b/ee/billing/salesforce_enrichment/harmonic_client.py
@@ -57,12 +57,21 @@ class AsyncHarmonicClient:
starved or shed. The weekly bulk job passes ``Priority.BATCH`` explicitly so it yields to
that traffic instead.
+ ``query`` is the GraphQL document for the company lookups. A caller that needs more company fields than
+ the default passes its own document, so that the payload of the other callers does not grow.
+
Usage:
async with AsyncHarmonicClient(priority=Priority.BATCH, source="my_job") as client:
data = await client.enrich_company_by_domain("posthog.com")
"""
- def __init__(self, *, priority: Priority = Priority.CRITICAL, source: str = "harmonic_client") -> None:
+ def __init__(
+ self,
+ *,
+ priority: Priority = Priority.CRITICAL,
+ source: str = "harmonic_client",
+ query: str = HARMONIC_COMPANY_ENRICHMENT_QUERY,
+ ) -> None:
self.api_key = settings.HARMONIC_API_KEY
if not self.api_key:
raise ValueError("Missing Harmonic API key: HARMONIC_API_KEY")
@@ -71,6 +80,7 @@ class AsyncHarmonicClient:
self._session_cm: Any = None
self.priority = priority
self.source = source
+ self.query = query
async def __aenter__(self):
"""Async context manager entry - create session."""
@@ -123,7 +133,7 @@ class AsyncHarmonicClient:
# Key in a header, not a query param: aiohttp errors carry request_info.real_url,
# so a URL-borne key would leak into exception telemetry when a lookup raises.
headers={"apikey": self.api_key},
- json={"query": HARMONIC_COMPANY_ENRICHMENT_QUERY, "variables": variables},
+ json={"query": self.query, "variables": variables},
)
response.raise_for_status()
data = await response.json()
@@ -194,7 +204,7 @@ class AsyncHarmonicClient:
# Key in a header, not a query param: aiohttp errors carry request_info.real_url,
# so a URL-borne key would leak into exception telemetry when a lookup raises.
headers={"apikey": self.api_key},
- json={"query": HARMONIC_COMPANY_ENRICHMENT_QUERY, "variables": variables},
+ json={"query": self.query, "variables": variables},
)
response.raise_for_status()
data = await response.json()
diff --git a/ee/billing/salesforce_enrichment/harmonic_company.py b/ee/billing/salesforce_enrichment/harmonic_company.py
new file mode 100644
index 000000000000..61b3654279fc
--- /dev/null
+++ b/ee/billing/salesforce_enrichment/harmonic_company.py
@@ -0,0 +1,108 @@
+import re
+from typing import Any
+from urllib.parse import urlparse
+
+# ISO 639-1 language codes.
+_LANGUAGE_CODES = frozenset(
+ (
+ "aa ab ae af ak am an ar as av ay az ba be bg bi bm bn bo br bs ca ce ch co cr cs cu cv cy da de dv dz ee el "
+ "en eo es et eu fa ff fi fj fo fr fy ga gd gl gn gu gv ha he hi ho hr ht hu hy hz ia id ie ig ii ik io is it "
+ "iu ja jv ka kg ki kj kk kl km kn ko kr ks ku kv kw ky la lb lg li ln lo lt lu lv mg mh mi mk ml mn mr ms mt "
+ "my na nb nd ne ng nl nn no nr nv ny oc oj om or os pa pi pl ps pt qu rm rn ro ru rw sa sc sd se sg sh si sk "
+ "sl sm sn so sq sr ss st su sv sw ta te tg th ti tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa wo xh yi "
+ "yo za zh zu"
+ ).split()
+)
+
+# ISO 3166-1 alpha-2 country codes. A site can put the landing page for one country under its code, as in "/us".
+_COUNTRY_CODES = frozenset(
+ (
+ "ad ae af ag ai al am ao aq ar as at au aw ax az ba bb bd be bf bg bh bi bj bl bm bn bo bq br bs bt bv bw by "
+ "bz ca cc cd cf cg ch ci ck cl cm cn co cr cu cv cw cx cy cz de dj dk dm do dz ec ee eg eh er es et fi fj fk "
+ "fm fo fr ga gb gd ge gf gg gh gi gl gm gn gp gq gr gs gt gu gw gy hk hm hn hr ht hu id ie il im in io iq ir "
+ "is it je jm jo jp ke kg kh ki km kn kp kr kw ky kz la lb lc li lk lr ls lt lu lv ly ma mc md me mf mg mh mk "
+ "ml mm mn mo mp mq mr ms mt mu mv mw mx my mz na nc ne nf ng ni nl no np nr nu nz om pa pe pf pg ph pk pl pm "
+ "pn pr ps pt pw py qa re ro rs ru rw sa sb sc sd se sg sh si sj sk sl sm sn so sr ss st sv sx sy sz tc td tf "
+ "tg th tj tk tl tm tn to tr tt tv tw tz ua ug um us uy uz va vc ve vg vi vn vu wf ws ye yt za zm zw"
+ ).split()
+)
+
+# A path segment whose first subtag is in neither set, such as a product page, is not a locale.
+_LOCALE_PREFIXES = _LANGUAGE_CODES | _COUNTRY_CODES
+
+# A language or country code, then an optional language, script or region, then an optional region: "en", "us",
+# "de-at", "us-en", "zh-Hant", "zh-Hant-TW", "es-419".
+_LOCALE_SEGMENT = re.compile(r"^([a-z]{2})(?:[-_][a-z]{2,4})?(?:[-_](?:[a-z]{2}|\d{3}))?$", re.IGNORECASE)
+_INDEX_FILE = re.compile(r"^(index|default|home)\.[a-z]+$", re.IGNORECASE)
+
+
+def _is_locale(segment: str) -> bool:
+ match = _LOCALE_SEGMENT.match(segment)
+ return match is not None and match.group(1).lower() in _LOCALE_PREFIXES
+
+
+def website_path_is_root(url: str) -> bool:
+ """Whether a website URL points at the root of its site.
+
+ A lone language or country segment, or an index file, is still the root, because a localized landing page
+ belongs to the company itself. A URL that cannot be parsed counts as the root, so that a record is never rejected
+ on a guess.
+ """
+ try:
+ path = urlparse(url if "://" in url else f"https://{url}").path
+ except ValueError:
+ return True
+ segments = [segment for segment in path.split("/") if segment]
+ if segments and _INDEX_FILE.match(segments[-1]):
+ segments.pop()
+ return not segments or (len(segments) == 1 and _is_locale(segments[0]))
+
+
+def dict_field(record: dict[str, Any], key: str) -> dict[str, Any]:
+ value = record.get(key)
+ return value if isinstance(value, dict) else {}
+
+
+def is_sub_entity(company: dict[str, Any]) -> bool:
+ """Whether Harmonic answered a domain lookup with a different entity that lives under that domain.
+
+ Harmonic keys an entity on its website. A ventures arm, a school within a university, or one product of a
+ platform has a page under the parent's domain as its website, and a lookup of the parent's domain can return
+ it. Its name, headcount and funding do not describe the parent.
+ """
+ url = dict_field(company, "website").get("url")
+ return isinstance(url, str) and bool(url) and not website_path_is_root(url)
+
+
+def traction_latest(company: dict[str, Any], metric: str) -> int | float | None:
+ latest = dict_field(dict_field(company, "tractionMetrics"), metric).get("latestMetricValue")
+ return latest if isinstance(latest, int | float) else None
+
+
+def harmonic_headcount(company: dict[str, Any]) -> int | None:
+ """The company's current headcount, from the company record or else the latest traction reading.
+
+ Harmonic can report zero where it has no reading, so only a positive count is a headcount.
+ """
+ for count in (company.get("headcount"), traction_latest(company, "headcount")):
+ if isinstance(count, int | float) and count > 0:
+ return int(count)
+ return None
+
+
+def describes_company(company: dict[str, Any]) -> bool:
+ """Whether the record names and sizes a company.
+
+ Harmonic can report a company as found and return a record with almost no facts. Zero funding on such a record
+ means that Harmonic has no data, not that the company raised nothing.
+ """
+ name = company.get("name")
+ return isinstance(name, str) and bool(name) and harmonic_headcount(company) is not None
+
+
+def website_domain(company: dict[str, Any]) -> str | None:
+ """The domain Harmonic reports for the company's website, lowercased and without a www prefix."""
+ domain = dict_field(company, "website").get("domain")
+ if not isinstance(domain, str):
+ return None
+ return domain.lower().strip().removeprefix("www.") or None
diff --git a/ee/billing/test/test_account_fields.py b/ee/billing/test/test_account_fields.py
new file mode 100644
index 000000000000..dfdc4f63c6a6
--- /dev/null
+++ b/ee/billing/test/test_account_fields.py
@@ -0,0 +1,218 @@
+from typing import Any
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from ee.billing.salesforce_enrichment.account_fields import (
+ account_industry,
+ fill_only_account_fields,
+ overwritten_account_fields,
+ unoccupied_fields,
+)
+from ee.billing.salesforce_enrichment.constants import ACCOUNT_FILL_FIELDS
+
+DOMAIN = "example.com"
+
+
+def _tag(value: str, primary: bool = False) -> dict[str, Any]:
+ return {"displayValue": value, "isPrimaryTag": primary}
+
+
+def _company(**overrides: Any) -> dict[str, Any]:
+ company: dict[str, Any] = {
+ "name": "Example Corp",
+ "headcount": 120,
+ "website": {"url": "https://example.com", "domain": "example.com"},
+ "socials": {"linkedin": {"url": "https://www.linkedin.example/company/example-corp"}},
+ "tractionMetrics": {
+ "headcount": {"latestMetricValue": 118},
+ "headcountEngineering": {"latestMetricValue": 40},
+ },
+ "tags": [_tag("Software", primary=True)],
+ "funding": {"fundingTotal": 5000000, "lastFundingAt": "2025-02-25T00:00:00Z"},
+ "foundingDate": {"date": "2015-03-01T00:00:00Z"},
+ }
+ company.update(overrides)
+ return company
+
+
+def _fields(company: dict[str, Any], account: dict[str, Any] | None = None) -> dict[str, Any]:
+ fill_fields = fill_only_account_fields(company, queried_domain=DOMAIN)
+ return {**overwritten_account_fields(company), **unoccupied_fields(fill_fields, {"Id": "001X", **(account or {})})}
+
+
+class TestAccountIndustry(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "primary_legacy_tag_leads",
+ {"tags": [_tag("Retail"), _tag("Software", primary=True)]},
+ "Software",
+ ),
+ (
+ "legacy_tags_before_tags_v2",
+ {"tags": [_tag("Retail")], "tagsV2": [_tag("Software")]},
+ "Retail",
+ ),
+ (
+ "sector_industry_loses_to_another_mapped_tag",
+ {"tags": [_tag("Financial Services", primary=True)], "tagsV2": [_tag("AI / ML")]},
+ "Software",
+ ),
+ (
+ "sector_industry_wins_when_alone",
+ {"tags": [_tag("Insurance", primary=True), _tag("Unmapped Thing")]},
+ "Insurance",
+ ),
+ ("no_tag_maps", {"tags": [_tag("Unmapped Thing")], "tagsV2": [_tag("Other Unmapped")]}, None),
+ ("alias_is_case_insensitive", {"tags": [_tag("AI / Ml")]}, "Software"),
+ ("tag_that_is_not_a_record_is_skipped", {"tags": [None, _tag("SaaS")]}, "Software"),
+ ]
+ )
+ def test_account_industry(self, _name: str, company: dict[str, Any], expected: str | None) -> None:
+ assert account_industry(company) == expected
+
+
+class TestCanonicalAccountFields(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("employees_none", "NumberOfEmployees", None, True, 120),
+ ("employees_empty_string", "NumberOfEmployees", "", True, 120),
+ ("employees_occupied", "NumberOfEmployees", 7, False, None),
+ (
+ "linkedin_url_none",
+ "Company_LinkedIn__c",
+ None,
+ True,
+ "https://www.linkedin.example/company/example-corp",
+ ),
+ ("linkedin_url_occupied", "Company_LinkedIn__c", "https://other.example/page", False, None),
+ ("industry_empty", "Industry", None, True, "Software"),
+ ("industry_outside_picklist", "Industry", "Software Development", False, None),
+ ("industry_in_picklist", "Industry", "Retail", False, None),
+ ]
+ )
+ def test_fill_rule_follows_the_current_value(
+ self, _name: str, field: str, current: str | int | None, written: bool, expected: str | int | None
+ ) -> None:
+ fields = _fields(_company(), {field: current})
+ if written:
+ assert fields[field] == expected
+ else:
+ assert field not in fields
+
+ @parameterized.expand([("NumberOfEmployees",), ("Company_LinkedIn__c",), ("Industry",)])
+ def test_field_not_read_is_unknown_not_empty(self, field: str) -> None:
+ assert field not in _fields(_company(), {})
+
+ @parameterized.expand(
+ [
+ ("both_empty", {"LinkedIn_Engineer_Count__c": None, "LinkedIn_Rolecount__c": ""}, True),
+ ("engineer_count_occupied", {"LinkedIn_Engineer_Count__c": 5, "LinkedIn_Rolecount__c": None}, False),
+ ("role_count_occupied", {"LinkedIn_Engineer_Count__c": None, "LinkedIn_Rolecount__c": 50}, False),
+ ("one_side_not_read", {"LinkedIn_Engineer_Count__c": None}, False),
+ ]
+ )
+ def test_linkedin_counts_are_written_only_as_an_empty_pair(
+ self, _name: str, account: dict[str, Any], written: bool
+ ) -> None:
+ fields = _fields(_company(), account)
+ if written:
+ assert fields["LinkedIn_Engineer_Count__c"] == 40
+ assert fields["LinkedIn_Rolecount__c"] == 118
+ else:
+ assert "LinkedIn_Engineer_Count__c" not in fields
+ assert "LinkedIn_Rolecount__c" not in fields
+
+ @parameterized.expand(
+ [
+ ("missing_engineering", {"headcount": {"latestMetricValue": 118}}),
+ ("missing_total", {"headcountEngineering": {"latestMetricValue": 40}}),
+ ("zero_total", {"headcount": {"latestMetricValue": 0}, "headcountEngineering": {"latestMetricValue": 0}}),
+ ]
+ )
+ def test_linkedin_counts_need_both_traction_metrics(self, _name: str, traction: dict[str, Any]) -> None:
+ fields = _fields(
+ _company(tractionMetrics=traction),
+ {"LinkedIn_Engineer_Count__c": None, "LinkedIn_Rolecount__c": None},
+ )
+ assert "LinkedIn_Engineer_Count__c" not in fields
+ assert "LinkedIn_Rolecount__c" not in fields
+
+ @parameterized.expand(
+ [
+ ("zero_without_name", {"name": None}, 0, False),
+ ("zero_without_headcount", {"headcount": None, "tractionMetrics": {}}, 0, False),
+ ("zero_with_zero_headcount", {"headcount": 0, "tractionMetrics": {}}, 0, False),
+ ("zero_with_name_and_headcount", {}, 0, True),
+ ("positive_without_name", {"name": None}, 250000, True),
+ ("positive_without_headcount", {"headcount": None, "tractionMetrics": {}}, 250000, True),
+ ]
+ )
+ def test_total_funding_zero_is_written_only_for_a_described_company(
+ self, _name: str, overrides: dict[str, Any], total: int, written: bool
+ ) -> None:
+ company = _company(funding={"fundingTotal": total}, **overrides)
+ fields = _fields(company)
+ if written:
+ assert fields["Total_Funding__c"] == total
+ else:
+ assert "Total_Funding__c" not in fields
+
+ @parameterized.expand(
+ [
+ ("company_headcount", {"headcount": 120}, 120),
+ (
+ "traction_fallback",
+ {"headcount": None, "tractionMetrics": {"headcount": {"latestMetricValue": 118}}},
+ 118,
+ ),
+ (
+ "traction_fallback_for_a_zero_headcount",
+ {"headcount": 0, "tractionMetrics": {"headcount": {"latestMetricValue": 118}}},
+ 118,
+ ),
+ ]
+ )
+ def test_number_of_employees_source(self, _name: str, overrides: dict[str, Any], expected: int) -> None:
+ assert _fields(_company(**overrides), {"NumberOfEmployees": None})["NumberOfEmployees"] == expected
+
+ def test_every_fill_only_field_is_read_before_the_write(self) -> None:
+ assert set(fill_only_account_fields(_company(), queried_domain=DOMAIN)) == set(ACCOUNT_FILL_FIELDS)
+
+ def test_zero_headcount_is_not_written(self) -> None:
+ company = _company(headcount=0, tractionMetrics={"headcount": {"latestMetricValue": 0}})
+ assert "NumberOfEmployees" not in _fields(company, {"NumberOfEmployees": None})
+
+ @parameterized.expand(
+ [
+ ("same_domain", {"domain": "example.com"}, True),
+ ("www_and_case_ignored", {"domain": "WWW.Example.com"}, True),
+ ("other_domain", {"domain": "example.org"}, False),
+ ("no_domain", {}, False),
+ ]
+ )
+ def test_linkedin_url_needs_the_queried_domain(self, _name: str, website: dict[str, Any], written: bool) -> None:
+ fields = _fields(_company(website=website), {"Company_LinkedIn__c": None})
+ assert ("Company_LinkedIn__c" in fields) is written
+
+ @parameterized.expand([("at_limit", 255, True), ("over_limit", 256, False)])
+ def test_linkedin_url_length_limit(self, _name: str, length: int, written: bool) -> None:
+ url = "https://www.linkedin.example/" + "a" * (length - len("https://www.linkedin.example/"))
+ company = _company(socials={"linkedin": {"url": url}})
+ assert ("Company_LinkedIn__c" in _fields(company, {"Company_LinkedIn__c": None})) is written
+
+ @parameterized.expand(
+ [
+ ("year_precision_date", {"date": "1983-01-01T00:00:00Z"}, 1983),
+ ("malformed_date", {"date": "not-a-date"}, None),
+ ("missing_date", {}, None),
+ ]
+ )
+ def test_founded_year(self, _name: str, founding_date: dict[str, Any], expected: int | None) -> None:
+ fields = _fields(_company(foundingDate=founding_date))
+ if expected is None:
+ assert "Founded_year__c" not in fields
+ else:
+ assert fields["Founded_year__c"] == expected
diff --git a/ee/billing/test/test_harmonic_client.py b/ee/billing/test/test_harmonic_client.py
index 27bb9e806fae..803b75f8b864 100644
--- a/ee/billing/test/test_harmonic_client.py
+++ b/ee/billing/test/test_harmonic_client.py
@@ -5,6 +5,8 @@ from typing import Any
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
+from django.test import override_settings
+
import aiohttp
from parameterized import parameterized
from prometheus_client import REGISTRY
@@ -13,6 +15,10 @@ from posthog.egress.harmonic.limiter import HARMONIC_WINDOW_SECONDS
from posthog.egress.harmonic.transport import HarmonicEgressBudgetExhausted
from posthog.egress.limiter.policies import Priority
+from ee.billing.salesforce_enrichment.constants import (
+ HARMONIC_ACCOUNT_ENRICHMENT_QUERY,
+ HARMONIC_COMPANY_ENRICHMENT_QUERY,
+)
from ee.billing.salesforce_enrichment.harmonic_client import (
_ENRICH_MAX_ATTEMPTS,
_ENRICH_MAX_CONCURRENT_LOOKUPS,
@@ -49,6 +55,7 @@ def _client(*, priority=Priority.NORMAL):
client.api_key = "test-key"
client.priority = priority
client.source = "test"
+ client.query = HARMONIC_COMPANY_ENRICHMENT_QUERY
client.session = MagicMock()
return client
@@ -205,6 +212,28 @@ async def test_strict_sends_api_key_as_header_not_in_url_or_params_and_uses_clie
assert call.kwargs["source"] == "billing_bulk"
+ [
+ ("default_query", {}, HARMONIC_COMPANY_ENRICHMENT_QUERY, False),
+ ("query_argument", {"query": HARMONIC_ACCOUNT_ENRICHMENT_QUERY}, HARMONIC_ACCOUNT_ENRICHMENT_QUERY, True),
+ ]
+)
+async def test_strict_sends_the_query_the_client_was_built_with(
+ _name: str, kwargs: dict[str, Any], expected_query: str, fetches_socials: bool
+) -> None:
+ with override_settings(HARMONIC_API_KEY="test-key"):
+ client = AsyncHarmonicClient(**kwargs)
+ client.session = MagicMock()
+ mock_request = AsyncMock(side_effect=[_found({"name": "Example Corp"})])
+ with patch(HARMONIC_REQUEST, new=mock_request):
+ await client.enrich_company_by_domain_strict("example.com")
+
+ sent_query = mock_request.call_args.kwargs["json"]["query"]
+ assert sent_query == expected_query
+ assert ("socials" in sent_query) is fetches_socials
+
+
@pytest.mark.asyncio
async def test_non_strict_sends_api_key_as_header_not_in_url_or_params():
mock_request = AsyncMock(side_effect=[_found({"name": "PostHog"})])
diff --git a/ee/billing/test/test_harmonic_company.py b/ee/billing/test/test_harmonic_company.py
new file mode 100644
index 000000000000..df59937c0f55
--- /dev/null
+++ b/ee/billing/test/test_harmonic_company.py
@@ -0,0 +1,55 @@
+from typing import Any
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from ee.billing.salesforce_enrichment.harmonic_company import is_sub_entity, website_path_is_root
+
+
+class TestWebsitePathIsRoot(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("bare_root", "https://example.com", True),
+ ("trailing_slash", "https://example.com/", True),
+ ("index_html", "https://example.com/index.html", True),
+ ("default_aspx", "https://example.com/default.aspx", True),
+ ("home_html", "https://example.com/home.html", True),
+ ("language_segment", "https://example.com/en", True),
+ ("language_segment_trailing_slash", "https://example.com/en/", True),
+ ("language_with_region", "https://example.com/de-at", True),
+ ("language_with_script", "https://example.com/zh-Hant", True),
+ ("language_with_script_and_region", "https://example.com/zh-Hant-TW", True),
+ ("language_with_numeric_region", "https://example.com/es-419", True),
+ ("country_segment", "https://example.com/us", True),
+ ("country_then_language", "https://example.com/us-en", True),
+ ("rare_language", "https://example.com/cy", True),
+ ("schemeless_domain", "example.com", True),
+ ("schemeless_www_with_slash", "www.example.com/", True),
+ ("hash_route_on_the_root", "https://example.com/#/overview", True),
+ ("unparseable_url", "https://[broken", True),
+ ("two_letters_that_are_not_a_language_or_country", "https://example.com/ds", False),
+ ("nested_path", "https://example.com/ventures/fund", False),
+ ("country_then_language_file", "https://example.com/us/en.html", False),
+ ("product_path", "https://example.com/products/widgets", False),
+ ("hash_route_under_a_path", "https://example.com/portal/#/overview", False),
+ ("login_page", "https://example.com/login", False),
+ ]
+ )
+ def test_website_path_is_root(self, _name: str, url: str, expected: bool) -> None:
+ assert website_path_is_root(url) is expected
+
+
+class TestIsSubEntity(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("no_website_key", {"name": "Example Corp"}, False),
+ ("website_not_a_dict", {"website": "https://example.com/ventures"}, False),
+ ("null_url", {"website": {"url": None}}, False),
+ ("empty_url", {"website": {"url": ""}}, False),
+ ("root_url", {"website": {"url": "https://example.com/"}}, False),
+ ("path_url", {"website": {"url": "https://example.com/ventures"}}, True),
+ ]
+ )
+ def test_is_sub_entity(self, _name: str, company: dict[str, Any], expected: bool) -> None:
+ assert is_sub_entity(company) is expected
diff --git a/ee/billing/test/test_salesforce_enrichment.py b/ee/billing/test/test_salesforce_enrichment.py
index 5b8eb3dfa860..78cd151b641a 100644
--- a/ee/billing/test/test_salesforce_enrichment.py
+++ b/ee/billing/test/test_salesforce_enrichment.py
@@ -2,23 +2,32 @@ import copy
import json
from contextlib import contextmanager
from pathlib import Path
+from typing import Any
import pytest
import time_machine
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
from django.test import SimpleTestCase
from parameterized import parameterized
+from ee.billing.salesforce_enrichment.constants import (
+ ACCOUNT_FILL_FIELDS,
+ HARMONIC_ACCOUNT_ENRICHMENT_QUERY,
+ SALESFORCE_UPDATE_BATCH_SIZE,
+)
from ee.billing.salesforce_enrichment.enrichment import (
_extract_domain,
_is_yc_funded,
_normalize_datetime_string,
_values_match,
+ add_unoccupied_fill_fields,
enrich_accounts_async,
get_salesforce_accounts_by_domain,
is_excluded_domain,
+ prepare_account_update,
+ prepare_mirror_clearing_data,
prepare_salesforce_update_data,
transform_harmonic_data,
)
@@ -32,6 +41,7 @@ def mock_harmonic_client():
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
mock_client.__aexit__ = AsyncMock(return_value=None)
mock_class.return_value = mock_client
+ mock_client.client_class = mock_class
yield mock_client
@@ -230,13 +240,18 @@ class TestHarmonicDataTransformation(SimpleTestCase):
assert salesforce_data["harmonic_company_type__c"] == "STARTUP"
assert salesforce_data["harmonic_industry__c"] == "Enterprise Software"
assert "harmonic_last_update__c" in salesforce_data
- assert salesforce_data["Founded_year__c"] == 1983
# Funding fields
- assert salesforce_data["Total_Funding__c"] == 900000000
assert salesforce_data["harmonic_funding_stage__c"] == "EXITED"
assert salesforce_data["harmonic_last_funding__c"] == 500000000
- assert salesforce_data["Last_Funding_Date__c"] == "2025-02-25T00:00:00Z"
+
+ for canonical in ("Founded_year__c", "Total_Funding__c", "Last_Funding_Date__c"):
+ assert canonical not in salesforce_data
+ account_update = prepare_account_update(account_id, harmonic_response)
+ assert account_update is not None
+ assert account_update["Founded_year__c"] == 1983
+ assert account_update["Total_Funding__c"] == 900000000
+ assert account_update["Last_Funding_Date__c"] == "2025-02-25T00:00:00Z"
# Current metrics
assert salesforce_data["harmonic_headcount__c"] == 5015
@@ -265,6 +280,32 @@ class TestHarmonicDataTransformation(SimpleTestCase):
for key, value in salesforce_data.items():
assert value is not None, f"Field {key} should not be None"
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
+ def test_mirror_clearing_data_covers_every_stamped_field_and_no_canonical_field(self) -> None:
+ transformed_data = transform_harmonic_data(load_harmonic_fixture())
+ assert transformed_data is not None
+ stamped = prepare_salesforce_update_data("001EXAMPLE123", transformed_data)
+ assert stamped is not None
+
+ cleared = prepare_mirror_clearing_data("001EXAMPLE123")
+
+ assert set(stamped) <= set(cleared)
+ assert {k: v for k, v in cleared.items() if v is not None} == {
+ "Id": "001EXAMPLE123",
+ "harmonic_is_yc_company__c": False,
+ }
+ for canonical in (
+ "Total_Funding__c",
+ "Last_Funding_Date__c",
+ "Founded_year__c",
+ "NumberOfEmployees",
+ "Industry",
+ "Company_LinkedIn__c",
+ "LinkedIn_Engineer_Count__c",
+ "LinkedIn_Rolecount__c",
+ ):
+ assert canonical not in cleared
+
@time_machine.travel("2025-07-29T12:00:00Z", tick=False)
def test_transform_harmonic_data_missing_funding(self):
"""Test transform_harmonic_data handles missing funding section."""
@@ -724,16 +765,25 @@ class TestSpecificDomainEnrichment(SimpleTestCase):
assert result["summary"]["salesforce_update_succeeded"] is False
assert "excluded" in result["error"]
+ @parameterized.expand(
+ [
+ ("not_found", None),
+ ("empty_record", {}),
+ ("not_a_record", ["not", "a", "company"]),
+ ]
+ )
@pytest.mark.asyncio
@time_machine.travel("2025-07-29T12:00:00Z", tick=False)
- async def test_specific_domain_enrichment_no_harmonic_data(self):
+ async def test_specific_domain_enrichment_no_harmonic_data(
+ self, _name: str, harmonic_result: dict[str, Any] | list[str] | None
+ ) -> None:
"""Test handling when Harmonic returns no data for domain."""
mock_accounts = [
{"Id": "001EXAMPLE1", "Name": "Test Company 1", "Domain__c": "unknown-domain.xyz"},
]
with mock_harmonic_client() as mock_client:
- mock_client.enrich_companies_batch = AsyncMock(return_value=[None])
+ mock_client.enrich_companies_batch = AsyncMock(return_value=[harmonic_result])
with patch(
"ee.billing.salesforce_enrichment.enrichment.get_salesforce_accounts_by_domain",
@@ -777,7 +827,10 @@ class TestSpecificDomainEnrichment(SimpleTestCase):
"ee.billing.salesforce_enrichment.enrichment.get_salesforce_accounts_by_domain",
return_value=mock_accounts,
) as mock_get_accounts:
- with patch("ee.billing.salesforce_enrichment.enrichment.get_salesforce_client"):
+ with patch("ee.billing.salesforce_enrichment.enrichment.get_salesforce_client") as mock_get_sf:
+ mock_get_sf.return_value.query_all.return_value = {
+ "records": [{"Id": "001EXAMPLE1", "NumberOfEmployees": None, "Industry": "Retail"}]
+ }
with patch(
"ee.billing.salesforce_enrichment.enrichment.bulk_update_salesforce_accounts"
) as mock_bulk_update:
@@ -788,6 +841,9 @@ class TestSpecificDomainEnrichment(SimpleTestCase):
# Verify Salesforce was updated
mock_bulk_update.assert_called_once()
+ (update_record,) = mock_bulk_update.call_args[0][1]
+ assert update_record["NumberOfEmployees"] == 5015
+ assert "Industry" not in update_record
# Verify result
assert result["summary"]["salesforce_update_succeeded"] is True
@@ -904,6 +960,150 @@ class TestSpecificDomainEnrichment(SimpleTestCase):
# Verify query_all was called to fetch the updated data
assert mock_sf.query_all.called
+ @pytest.mark.asyncio
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
+ async def test_specific_domain_sub_entity_sends_the_clearing_record(self) -> None:
+ sub_entity = {
+ **load_harmonic_fixture(),
+ "website": {"url": "https://example.com/ventures", "domain": "example.com"},
+ }
+ mock_accounts = [{"Id": "001EXAMPLE1", "Name": "Test Company", "Domain__c": "example.com"}]
+
+ with (
+ mock_harmonic_client() as mock_client,
+ patch(
+ "ee.billing.salesforce_enrichment.enrichment.get_salesforce_accounts_by_domain",
+ return_value=mock_accounts,
+ ),
+ patch("ee.billing.salesforce_enrichment.enrichment.get_salesforce_client") as mock_get_sf,
+ patch("ee.billing.salesforce_enrichment.enrichment.bulk_update_salesforce_accounts") as mock_bulk_update,
+ ):
+ mock_client.enrich_companies_batch = AsyncMock(return_value=[sub_entity])
+ mock_get_sf.return_value.query_all.return_value = {
+ "records": [{"Id": "001EXAMPLE1", **dict.fromkeys(ACCOUNT_FILL_FIELDS)}]
+ }
+
+ result = await enrich_accounts_async(specific_domain="example.com")
+
+ assert mock_client.client_class.call_args.kwargs["query"] == HARMONIC_ACCOUNT_ENRICHMENT_QUERY
+ assert mock_bulk_update.call_args[0][1] == [prepare_mirror_clearing_data("001EXAMPLE1")]
+ assert result["summary"]["rejected_sub_entity"] is True
+ assert result["records_rejected_sub_entity"] == 1
+ assert result["records_enriched"] == 0
+ assert result["enriched_data"] is None
+
+
+class TestChunkEnrichment(SimpleTestCase):
+ SUB_ENTITY = {
+ **load_harmonic_fixture(),
+ "website": {"url": "https://example.org/ventures", "domain": "example.org"},
+ }
+ NORMAL = {
+ **load_harmonic_fixture(),
+ "socials": {"linkedin": {"url": "https://www.linkedin.example/company/ex"}},
+ }
+ CACHED_ACCOUNTS = [
+ {"Id": "001SUB", "Name": "Synthetic Ventures", "Website": "https://example.org"},
+ {"Id": "001NORMAL", "Name": "Example Corp", "Website": "https://example.com"},
+ {"Id": "001MALFORMED", "Name": "Example Org", "Website": "https://example.net"},
+ ]
+
+ async def _run_chunk(self, query_all: MagicMock) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]:
+ with (
+ mock_harmonic_client() as mock_client,
+ patch("ee.billing.salesforce_enrichment.enrichment.get_salesforce_client") as mock_get_sf,
+ patch(
+ "ee.billing.salesforce_enrichment.enrichment.get_accounts_from_redis",
+ new=AsyncMock(return_value=self.CACHED_ACCOUNTS),
+ ),
+ patch("ee.billing.salesforce_enrichment.enrichment.posthoganalytics.capture"),
+ patch("ee.billing.salesforce_enrichment.enrichment.capture_exception"),
+ ):
+ mock_client.enrich_companies_batch = AsyncMock(
+ return_value=[self.SUB_ENTITY, self.NORMAL, ["not", "a", "company"]]
+ )
+ mock_sf = mock_get_sf.return_value
+ mock_sf.query_all = query_all
+ mock_sf.restful.return_value = [{"success": True}, {"success": True}]
+
+ result = await enrich_accounts_async(chunk_number=0, chunk_size=10)
+
+ assert mock_client.client_class.call_args.kwargs["query"] == HARMONIC_ACCOUNT_ENRICHMENT_QUERY
+ mock_sf.restful.assert_called_once()
+ assert mock_sf.restful.call_args.args == ("composite/sobjects",)
+ assert mock_sf.restful.call_args.kwargs["method"] == "PATCH"
+ records = {
+ record["Id"]: {field: value for field, value in record.items() if field != "attributes"}
+ for record in mock_sf.restful.call_args.kwargs["json"]["records"]
+ }
+ return result, records
+
+ @pytest.mark.asyncio
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
+ async def test_chunk_clears_sub_entity_accounts_and_fills_empty_fields_of_normal_ones(self) -> None:
+ empty = dict.fromkeys(ACCOUNT_FILL_FIELDS)
+ current_values = [{"Id": "001SUB", **empty}, {"Id": "001NORMAL", **empty, "NumberOfEmployees": 7}]
+
+ result, records = await self._run_chunk(MagicMock(return_value={"records": current_values}))
+
+ assert set(records) == {"001SUB", "001NORMAL"}
+
+ assert records["001SUB"] == prepare_mirror_clearing_data("001SUB")
+ assert records["001SUB"]["harmonic_company_name__c"] is None
+ assert records["001SUB"]["harmonic_is_yc_company__c"] is False
+
+ normal_record = records["001NORMAL"]
+ assert normal_record["harmonic_company_name__c"] == "Example Corp"
+ assert normal_record["Total_Funding__c"] == 900000000
+ assert normal_record["Company_LinkedIn__c"] == "https://www.linkedin.example/company/ex"
+ assert normal_record["Industry"] == "Software"
+ assert "NumberOfEmployees" not in normal_record
+
+ assert result["records_processed"] == 3
+ assert result["records_rejected_sub_entity"] == 1
+ assert result["records_enriched"] == 1
+
+ @pytest.mark.asyncio
+ @time_machine.travel("2025-07-29T12:00:00Z", tick=False)
+ async def test_chunk_fills_nothing_when_current_values_cannot_be_read(self) -> None:
+ _, records = await self._run_chunk(MagicMock(side_effect=Exception("query failed")))
+
+ normal_record = records["001NORMAL"]
+ assert normal_record["harmonic_company_name__c"] == "Example Corp"
+ assert normal_record["Total_Funding__c"] == 900000000
+ for fill_field in ACCOUNT_FILL_FIELDS:
+ assert fill_field not in normal_record
+
+
+class TestAddUnoccupiedFillFields(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("every_batch_is_read", False, SALESFORCE_UPDATE_BATCH_SIZE + 1),
+ ("a_failed_batch_does_not_stop_the_next", True, 1),
+ ]
+ )
+ def test_reads_accounts_in_batches(self, _name: str, first_batch_fails: bool, expected_filled: int) -> None:
+ account_ids = [f"001{index:015d}" for index in range(SALESFORCE_UPDATE_BATCH_SIZE + 1)]
+ update_records: list[dict[str, Any]] = [{"Id": account_id} for account_id in account_ids]
+
+ def query_all(query: str) -> dict[str, list[dict[str, Any]]]:
+ if first_batch_fails and account_ids[0] in query:
+ raise Exception("query failed")
+ return {
+ "records": [
+ {"Id": account_id, "NumberOfEmployees": None} for account_id in account_ids if account_id in query
+ ]
+ }
+
+ sf = MagicMock()
+ sf.query_all.side_effect = query_all
+
+ with patch("ee.billing.salesforce_enrichment.enrichment.capture_exception"):
+ add_unoccupied_fill_fields(sf, update_records, dict.fromkeys(account_ids, {"NumberOfEmployees": 120}))
+
+ assert sf.query_all.call_count == 2
+ assert sum(record.get("NumberOfEmployees") == 120 for record in update_records) == expected_filled
+
class TestValuesMatch(SimpleTestCase):
@parameterized.expand(