: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add freshsales selector lookup tables (#108299)
Tom Owers32b37be00348
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 928cfadbe0dc..05945cb6fa98 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -3376,14 +3376,14 @@ Note: Ticket conversations and canned responses are per-parent sub-resources, so## Freshsales — gaps-Today (9): `completed_tasks`, `contacts`, `deals`, `leads`, `open_tasks`, `past_appointments`, `sales_accounts`, `sales_activities`, `upcoming_appointments`+Today (13): `completed_tasks`, `contacts`, `deal_pipelines`, `deal_stages`, `deals`, `leads`, `lifecycle_stages`, `open_tasks`, `owners`, `past_appointments`, `sales_accounts`, `sales_activities`, `upcoming_appointments`Diffed against: <https://developers.freshworks.com/crm/api/>-- [ ] `/api/selector/owners` — user lookup - resolves owner_id on contacts, deals, accounts, tasks and activities; there is no users table today (high)-- [ ] `/api/selector/deal_stages` — lookup resolving deal_stage_id, required for any pipeline or conversion analysis (high)-- [ ] `/api/selector/deal_pipelines` — lookup resolving deal_pipeline_id on deals (high)-- [ ] `/api/selector/lifecycle_stages` — lookup resolving lifecycle_stage_id on contacts and accounts (high)+- [x] `/api/selector/owners` — user lookup - resolves owner_id on contacts, deals, accounts, tasks and activities; there is no users table today (high)+- [x] `/api/selector/deal_stages` — lookup resolving deal_stage_id, required for any pipeline or conversion analysis (high)+- [x] `/api/selector/deal_pipelines` — lookup resolving deal_pipeline_id on deals (high)+- [x] `/api/selector/lifecycle_stages` — lookup resolving lifecycle_stage_id on contacts and accounts (high)- [ ] `/api/selector/lead_sources` — lookup resolving lead_source_id - the core attribution dimension (high)- [ ] `/api/selector/sales_activity_types (+ /sales_activity_outcomes)` — lookups resolving type and outcome IDs on the sales_activities already synced (high)- [ ] `/api/selector/contact_statuses` — lookup resolving contact_status_id (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/canonical_descriptions.pyindex a4d395f9cce6..3dde29fbf124 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/canonical_descriptions.py@@ -150,4 +150,39 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"docs_url": "https://developers.freshworks.com/crm/api/#appointments","columns": _APPOINTMENT_COLUMNS,},+ "owners": {+ "description": "A user in the Freshsales portal. Resolves the owner_id carried on contacts, accounts, deals, tasks and sales activities.",+ "docs_url": "https://developers.freshworks.com/crm/api/#admin_configuration",+ "columns": {+ "id": "Unique identifier for the user.",+ "display_name": "Display name of the user.",+ "email": "Email address of the user.",+ },+ },+ "deal_stages": {+ "description": "A stage in a deal pipeline. Resolves the deal_stage_id carried on deals.",+ "docs_url": "https://developers.freshworks.com/crm/api/#admin_configuration",+ "columns": {+ "id": "Unique identifier for the deal stage.",+ "name": "Name of the deal stage.",+ "deal_pipeline_id": "ID of the pipeline the stage belongs to.",+ },+ },+ "deal_pipelines": {+ "description": "A deal pipeline configured in the portal. Resolves the deal_pipeline_id carried on deals.",+ "docs_url": "https://developers.freshworks.com/crm/api/#admin_configuration",+ "columns": {+ "id": "Unique identifier for the deal pipeline.",+ "name": "Name of the deal pipeline.",+ },+ },+ "lifecycle_stages": {+ "description": "A lifecycle stage configured in the portal. Resolves the lifecycle_stage_id carried on contacts and accounts.",+ "docs_url": "https://developers.freshworks.com/crm/api/#admin_configuration",+ "columns": {+ "id": "Unique identifier for the lifecycle stage.",+ "name": "Name of the lifecycle stage.",+ "contact_statuses": "Contact statuses that belong to the lifecycle stage.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/freshsales.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/freshsales.pyindex 14a3fdfc079d..e71aa8231a21 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/freshsales.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/freshsales.py@@ -82,6 +82,9 @@ def _build_page_url(else:path = f"{root}/{config.resource}"+ if config.is_selector:+ return f"{path}?{urlencode(config.params)}" if config.params else path+params: dict[str, Any] = {"page": page, "per_page": per_page, **config.params}if config.sort:params["sort"] = config.sort@@ -113,6 +116,37 @@ def _fetch_page(session: Any, url: str, logger: FilteringBoundLogger) -> dict:return response.json()+def _extract_items(data: dict, object_key: str, allow_fallback: bool = False) -> list[dict]:+ items = data.get(object_key)+ if isinstance(items, list):+ return items+ if allow_fallback:+ return next((v for v in data.values() if isinstance(v, list)), [])+ return []+++def _get_selector_fanout_rows(+ session: Any, root: str, config: FreshsalesEndpointConfig, logger: FilteringBoundLogger+) -> Iterator[list[dict]]:+ fanout = config.selector_fanout+ assert fanout is not None++ parents_response = _fetch_page(session, f"{root}/{fanout.parent_resource}", logger)+ parents = _extract_items(parents_response, fanout.parent_object_key, allow_fallback=True)+ if not parents:+ logger.warning(f"Freshsales: no parents found at '{fanout.parent_resource}' for '{config.name}'")+ return++ for parent in parents:+ parent_id = parent.get("id")+ if parent_id is None:+ continue+ data = _fetch_page(session, f"{root}/{fanout.child_path.format(parent_id=parent_id)}", logger)+ items = _extract_items(data, config.object_key, allow_fallback=True)+ if items:+ yield items++def _resolve_view_id(session: Any, root: str, resource: str, logger: FilteringBoundLogger) -> Optional[int]:"""View-based objects are listed through a saved "view". Discover its id via /<resource>/filters,preferring the account-wide "All ..." view."""@@ -165,18 +199,25 @@ def get_rows(returnraise ValueError(f"Freshsales: could not resolve a view for '{endpoint}'")+ if config.selector_fanout is not None:+ yield from _get_selector_fanout_rows(session, root, config, logger)+ return+page = resume.next_page if resume is not None else 1while page <= MAX_PAGES:url = _build_page_url(root, config, view_id, page)data = _fetch_page(session, url, logger)- items = data.get(config.object_key) or []+ items = _extract_items(data, config.object_key, allow_fallback=config.is_selector)if not items:breakyield items+ if config.is_selector:+ break+meta = data.get("meta") or {}total_pages = meta.get("total_pages")# `total_pages` is missing on some endpoints (e.g. appointments), so also stop on a short page.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/settings.pyindex 8bc4bd527693..09e3d695edb0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/settings.py@@ -4,7 +4,16 @@ from typing import Optionalfrom products.warehouse_sources.backend.types import IncrementalField-@dataclass+@dataclass(frozen=True)+class FreshsalesSelectorFanout:+ # Parent selector to enumerate, e.g. "selector/deal_pipelines".+ parent_resource: str+ parent_object_key: str+ # Child path per parent, formatted with the parent's id.+ child_path: str+++@dataclass(frozen=True)class FreshsalesEndpointConfig:name: str# API resource segment, e.g. "contacts" -> /crm/sales/api/contacts/...@@ -24,6 +33,14 @@ class FreshsalesEndpointConfig:sort: Optional[str] = None# Some objects (notably leads) don't exist on every Freshsales account; a 404 means "skip", not "fail".tolerate_missing: bool = False+ # Selector endpoints are portal-wide lookup collections returned whole in a single unpaginated+ # response: they ignore page/per_page, so asking for page 2 re-returns the same list. Freshsales+ # also doesn't publish their response bodies, so the envelope key falls back to whatever list the+ # response carries rather than silently syncing an empty table.+ is_selector: bool = False+ # Some selector endpoints only cover the default parent, so the whole collection needs a walk+ # over the parent selector instead of one request.+ selector_fanout: Optional[FreshsalesSelectorFanout] = None# Incremental sync is full-refresh only for now (see note below), so this stays empty for every# endpoint. Kept as the source of truth so enabling incremental later is a settings-only change.incremental_fields: list[IncrementalField] = field(default_factory=list)@@ -97,6 +114,37 @@ FRESHSALES_ENDPOINTS: dict[str, FreshsalesEndpointConfig] = {object_key="appointments",params={"filter": "upcoming"},),+ "owners": FreshsalesEndpointConfig(+ name="owners",+ resource="selector/owners",+ object_key="users",+ is_selector=True,+ ),+ "deal_stages": FreshsalesEndpointConfig(+ name="deal_stages",+ resource="selector/deal_stages",+ object_key="deal_stages",+ is_selector=True,+ # /selector/deal_stages returns the default pipeline's stages only, so an account with more+ # than one pipeline would be missing the stages its deals point at.+ selector_fanout=FreshsalesSelectorFanout(+ parent_resource="selector/deal_pipelines",+ parent_object_key="deal_pipelines",+ child_path="selector/deal_pipelines/{parent_id}/deal_stages",+ ),+ ),+ "deal_pipelines": FreshsalesEndpointConfig(+ name="deal_pipelines",+ resource="selector/deal_pipelines",+ object_key="deal_pipelines",+ is_selector=True,+ ),+ "lifecycle_stages": FreshsalesEndpointConfig(+ name="lifecycle_stages",+ resource="selector/lifecycle_stages",+ object_key="lifecycle_stages",+ is_selector=True,+ ),}ENDPOINTS = tuple(FRESHSALES_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/tests/test_freshsales.py b/products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/tests/test_freshsales.pyindex a1f61e6184d8..13aa0e50aee8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/tests/test_freshsales.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/freshsales/tests/test_freshsales.py@@ -108,6 +108,12 @@ class TestBuildPageUrl:assert "filter=open" in urlassert "sort=" not in url+ def test_selector_endpoint_omits_paging_params(self) -> None:+ url = _build_page_url(+ "https://acme.myfreshworks.com/crm/sales/api", FRESHSALES_ENDPOINTS["owners"], view_id=None, page=1+ )+ assert url == "https://acme.myfreshworks.com/crm/sales/api/selector/owners"+class TestResolveViewId:def test_prefers_all_view(self) -> None:@@ -194,6 +200,53 @@ class TestGetRows:assert "/contacts/filters" in session.get.call_args_list[0].args[0]assert "/contacts/view/3?" in session.get.call_args_list[1].args[0]+ def test_selector_endpoint_stops_after_one_request(self) -> None:+ # A full page must not trigger a second request: selectors ignore paging and would re-return+ # the same rows until the page cap.+ page = _resp(body={"users": [{"id": i} for i in range(100)]})+ manager = _FakeResumeManager()++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.freshsales.freshsales.make_tracked_session"+ ) as mocked:+ session = _session([page])+ mocked.return_value = session+ batches = list(get_rows("acme", "acme", "owners", MagicMock(), manager)) # type: ignore[arg-type]++ assert len(batches) == 1+ assert len(batches[0]) == 100+ assert session.get.call_count == 1+ assert manager.saved == []++ def test_selector_falls_back_to_the_only_list_in_the_envelope(self) -> None:+ # Freshsales doesn't publish selector response bodies; an unexpected envelope key must not+ # silently sync an empty table.+ manager = _FakeResumeManager()+ batches = self._run("owners", [_resp(body={"portal_users": [{"id": 1, "name": "Ann"}]})], manager)+ assert batches == [[{"id": 1, "name": "Ann"}]]++ def test_deal_stages_walks_every_pipeline(self) -> None:+ # /selector/deal_stages covers the default pipeline only, so a single request would miss the+ # stages that deals in every other pipeline point at.+ pipelines = _resp(body={"deal_pipelines": [{"id": 1, "name": "Sales"}, {"id": 2, "name": "Renewals"}]})+ stages_1 = _resp(body={"deal_stages": [{"id": 10, "name": "New", "deal_pipeline_id": 1}]})+ stages_2 = _resp(body={"deal_stages": [{"id": 20, "name": "Due", "deal_pipeline_id": 2}]})+ manager = _FakeResumeManager()++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.freshsales.freshsales.make_tracked_session"+ ) as mocked:+ session = _session([pipelines, stages_1, stages_2])+ mocked.return_value = session+ batches = list(get_rows("acme", "acme", "deal_stages", MagicMock(), manager)) # type: ignore[arg-type]++ assert [row["id"] for batch in batches for row in batch] == [10, 20]+ assert [call.args[0].rsplit("/api/", 1)[1] for call in session.get.call_args_list] == [+ "selector/deal_pipelines",+ "selector/deal_pipelines/1/deal_stages",+ "selector/deal_pipelines/2/deal_stages",+ ]+def test_tolerates_missing_object(self) -> None:# leads object absent -> /filters 404 -> stream yields nothing instead of failing.manager = _FakeResumeManager()