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(data-warehouse): add freshsales lookup and marketing list tables (#109104)

Tom Owersd0603ee17698
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.md
index 802ec897d286..dea295346240 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,7 +3376,7 @@ Note: Ticket conversations and canned responses are per-parent sub-resources, so
## Freshsales — gaps
-Today (13): `completed_tasks`, `contacts`, `deal_pipelines`, `deal_stages`, `deals`, `leads`, `lifecycle_stages`, `open_tasks`, `owners`, `past_appointments`, `sales_accounts`, `sales_activities`, `upcoming_appointments`
+Today (18): `completed_tasks`, `contacts`, `deal_pipelines`, `deal_stages`, `deals`, `lead_sources`, `leads`, `lifecycle_stages`, `list_contacts`, `lists`, `open_tasks`, `owners`, `past_appointments`, `sales_accounts`, `sales_activities`, `sales_activity_outcomes`, `sales_activity_types`, `upcoming_appointments`
Diffed against: <https://developers.freshworks.com/crm/api/>
@@ -3384,12 +3384,12 @@ Diffed against: <https://developers.freshworks.com/crm/api/>
- [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)
+- [x] `/api/selector/lead_sources` — lookup resolving lead_source_id - the core attribution dimension (high). Added as `lead_sources`.
+- [x] `/api/selector/sales_activity_types (+ /sales_activity_outcomes)` — lookups resolving type and outcome IDs on the sales_activities already synced (high). Added as `sales_activity_types` and `sales_activity_outcomes`.
- [ ] `/api/selector/contact_statuses` — lookup resolving contact_status_id (medium)
- [ ] `/api/selector/territories` — lookup resolving territory_id for regional breakdowns (medium)
-- [ ] `/api/lists (+ /lists/{id} contacts)` — marketing lists and their contact membership (medium)
-- [ ] `/api/cpq/products` — product catalog referenced by deals and quotes (medium)
+- [x] `/api/lists (+ /lists/{id} contacts)` — marketing lists and their contact membership (medium). Added as `lists` and `list_contacts` (fan-out over `lists` to `/api/contacts/lists/{id}`).
+- ~~`/api/cpq/products`~~ — not listable: the API reference documents create, view by id, update, delete and bulk actions on `/api/cpq/products`, but no endpoint that lists the catalog (medium)
- [ ] `/api/cpq/cpq_documents (+ /{id}/related_products)` — quotes/documents with their product line items - quoted vs won revenue (medium)
- [ ] `/api/contacts/{id}/activities.json` — per-contact activity timeline (notes, calls, emails) not reachable from any synced table (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.py
index 3dde29fbf124..9c259d499ad8 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
@@ -185,4 +185,48 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"contact_statuses": "Contact statuses that belong to the lifecycle stage.",
},
},
+ "lead_sources": {
+ "description": "A lead source configured in the portal. Resolves the lead_source_id carried on contacts and deals.",
+ "docs_url": "https://developers.freshworks.com/crm/api/#admin_configuration",
+ "columns": {
+ "id": "Unique identifier for the lead source.",
+ "name": "Name of the lead source.",
+ },
+ },
+ "sales_activity_types": {
+ "description": "A sales activity type configured in the portal. Resolves the sales_activity_type_id carried on sales activities.",
+ "docs_url": "https://developers.freshworks.com/crm/api/#admin_configuration",
+ "columns": {
+ "id": "Unique identifier for the sales activity type.",
+ "name": "Name of the sales activity type.",
+ },
+ },
+ "sales_activity_outcomes": {
+ "description": "An outcome that can be recorded on a sales activity. Resolves the sales_activity_outcome_id carried on sales activities.",
+ "docs_url": "https://developers.freshworks.com/crm/api/#admin_configuration",
+ "columns": {
+ "id": "Unique identifier for the sales activity outcome.",
+ "name": "Name of the sales activity outcome.",
+ },
+ },
+ "lists": {
+ "description": "A marketing list of contacts.",
+ "docs_url": "https://developers.freshworks.com/crm/api/#marketing_lists",
+ "columns": {
+ "id": "Unique identifier for the marketing list.",
+ "name": "Name of the marketing list.",
+ },
+ },
+ "list_contacts": {
+ "description": "Membership of contacts in marketing lists. One row per contact per list, with the contact's details.",
+ "docs_url": "https://developers.freshworks.com/crm/api/#marketing_lists",
+ "columns": _columns(
+ id="Unique identifier for the contact.",
+ list_id="ID of the marketing list the contact belongs to.",
+ first_name="The contact's first name.",
+ last_name="The contact's last name.",
+ display_name="The contact's display name.",
+ email="The contact's primary email address.",
+ ),
+ },
}
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.py
index e71aa8231a21..5cb9e431e704 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
@@ -13,6 +13,8 @@ from requests.exceptions import (
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -40,10 +42,19 @@ class FreshsalesRetryableError(Exception):
pass
[email protected](frozen=True)
class FreshsalesResumeConfig:
next_page: int
view_id: Optional[int] = None
+ # Parent being paged when the stream is a paginated fan-out (e.g. the list for list_contacts).
+ parent_id: Optional[int] = None
+
+
+@frozen
+class FreshsalesPage:
+ number: int
+ items: list[dict]
+ has_more: bool
def _normalize_alias(domain: str) -> str:
@@ -125,6 +136,63 @@ def _extract_items(data: dict, object_key: str, allow_fallback: bool = False) ->
return []
+def _iter_pages(
+ session: Any, path: str, object_key: str, logger: FilteringBoundLogger, start_page: int = 1
+) -> Iterator[FreshsalesPage]:
+ page = start_page
+ while page <= MAX_PAGES:
+ data = _fetch_page(session, f"{path}?{urlencode({'page': page, 'per_page': DEFAULT_PAGE_SIZE})}", logger)
+ items = _extract_items(data, object_key)
+ if not items:
+ return
+
+ total_pages = (data.get("meta") or {}).get("total_pages")
+ has_more = not ((total_pages is not None and page >= total_pages) or len(items) < DEFAULT_PAGE_SIZE)
+ yield FreshsalesPage(number=page, items=items, has_more=has_more)
+ if not has_more:
+ return
+ page += 1
+
+ logger.warning(f"Freshsales: reached max page cap ({MAX_PAGES}) for '{path}'; results may be truncated")
+
+
+def _get_paginated_fanout_rows(
+ session: Any,
+ root: str,
+ config: FreshsalesEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FreshsalesResumeConfig],
+ resume: Optional[FreshsalesResumeConfig],
+) -> Iterator[list[dict]]:
+ fanout = config.selector_fanout
+ assert fanout is not None
+
+ parent_ids = [
+ parent["id"]
+ for page in _iter_pages(session, f"{root}/{fanout.parent_resource}", fanout.parent_object_key, logger)
+ for parent in page.items
+ if parent.get("id") is not None
+ ]
+
+ start_index, start_page = 0, 1
+ # A parent deleted since the saved run restarts the walk; merge dedupes the re-read rows.
+ if resume is not None and resume.parent_id in parent_ids:
+ start_index, start_page = parent_ids.index(resume.parent_id), resume.next_page
+
+ for parent_id in parent_ids[start_index:]:
+ child_url = f"{root}/{fanout.child_path.format(parent_id=parent_id)}"
+ for page in _iter_pages(session, child_url, config.object_key, logger, start_page):
+ items = page.items
+ if fanout.parent_id_column:
+ items = [{**item, fanout.parent_id_column: parent_id} for item in items]
+ yield items
+ if page.has_more:
+ resumable_source_manager.save_state(
+ FreshsalesResumeConfig(next_page=page.number + 1, parent_id=parent_id)
+ )
+ start_page = 1
+
+
def _get_selector_fanout_rows(
session: Any, root: str, config: FreshsalesEndpointConfig, logger: FilteringBoundLogger
) -> Iterator[list[dict]]:
@@ -200,7 +268,10 @@ def get_rows(
raise 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)
+ if config.selector_fanout.paginated:
+ yield from _get_paginated_fanout_rows(session, root, config, logger, resumable_source_manager, resume)
+ else:
+ yield from _get_selector_fanout_rows(session, root, config, logger)
return
page = resume.next_page if resume is not None else 1
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.py
index 09e3d695edb0..b831f2999817 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
@@ -11,6 +11,11 @@ class FreshsalesSelectorFanout:
parent_object_key: str
# Child path per parent, formatted with the parent's id.
child_path: str
+ # Page through the parent and each child. Selectors return everything in one response; listing
+ # APIs such as /lists don't.
+ paginated: bool = False
+ # Column that carries the parent id on each child row, for children whose rows don't include it.
+ parent_id_column: Optional[str] = None
@dataclass(frozen=True)
@@ -145,6 +150,45 @@ FRESHSALES_ENDPOINTS: dict[str, FreshsalesEndpointConfig] = {
object_key="lifecycle_stages",
is_selector=True,
),
+ "lead_sources": FreshsalesEndpointConfig(
+ name="lead_sources",
+ resource="selector/lead_sources",
+ object_key="lead_sources",
+ is_selector=True,
+ ),
+ "sales_activity_types": FreshsalesEndpointConfig(
+ name="sales_activity_types",
+ resource="selector/sales_activity_types",
+ object_key="sales_activity_types",
+ is_selector=True,
+ ),
+ "sales_activity_outcomes": FreshsalesEndpointConfig(
+ name="sales_activity_outcomes",
+ resource="selector/sales_activity_outcomes",
+ object_key="sales_activity_outcomes",
+ is_selector=True,
+ ),
+ "lists": FreshsalesEndpointConfig(
+ name="lists",
+ resource="lists",
+ object_key="lists",
+ ),
+ "list_contacts": FreshsalesEndpointConfig(
+ name="list_contacts",
+ # Probed by check_credentials; rows come from the fan-out below.
+ resource="lists",
+ object_key="contacts",
+ # A contact can belong to several lists.
+ primary_key=["list_id", "id"],
+ partition_key="created_at",
+ selector_fanout=FreshsalesSelectorFanout(
+ parent_resource="lists",
+ parent_object_key="lists",
+ child_path="contacts/lists/{parent_id}",
+ paginated=True,
+ parent_id_column="list_id",
+ ),
+ ),
}
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.py
index 13aa0e50aee8..d2b716c153ce 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
@@ -247,6 +247,60 @@ class TestGetRows:
"selector/deal_pipelines/2/deal_stages",
]
+ def test_list_contacts_pages_every_list_and_tags_rows_with_list_id(self) -> None:
+ # /lists and /contacts/lists/{id} are paginated, unlike selectors, and the contact rows don't
+ # say which list they came from.
+ lists_page = _resp(body={"lists": [{"id": 1}, {"id": 2}], "meta": {"total_pages": 1}})
+ list_1_page_1 = _resp(body={"contacts": [{"id": i} for i in range(100)], "meta": {"total_pages": 2}})
+ list_1_page_2 = _resp(body={"contacts": [{"id": 100}], "meta": {"total_pages": 2}})
+ list_2_page_1 = _resp(body={"contacts": [{"id": 0}], "meta": {"total_pages": 1}})
+ manager = _FakeResumeManager()
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.freshsales.freshsales.make_tracked_session"
+ ) as mocked:
+ session = _session([lists_page, list_1_page_1, list_1_page_2, list_2_page_1])
+ mocked.return_value = session
+ batches = list(get_rows("acme", "acme", "list_contacts", MagicMock(), manager)) # type: ignore[arg-type]
+
+ rows = [row for batch in batches for row in batch]
+ assert len(rows) == 102
+ assert rows[100] == {"id": 100, "list_id": 1}
+ assert rows[101] == {"id": 0, "list_id": 2}
+ assert [call.args[0].rsplit("/api/", 1)[1] for call in session.get.call_args_list] == [
+ "lists?page=1&per_page=100",
+ "contacts/lists/1?page=1&per_page=100",
+ "contacts/lists/1?page=2&per_page=100",
+ "contacts/lists/2?page=1&per_page=100",
+ ]
+ assert manager.saved == [FreshsalesResumeConfig(next_page=2, parent_id=1)]
+
+ @parameterized.expand(
+ [
+ ("saved_list_still_exists", 2, ["contacts/lists/2?page=3&per_page=100"]),
+ (
+ "saved_list_deleted",
+ 9,
+ ["contacts/lists/1?page=1&per_page=100", "contacts/lists/2?page=1&per_page=100"],
+ ),
+ ]
+ )
+ def test_list_contacts_resumes_at_saved_list_and_page(
+ self, _name: str, saved_list_id: int, expected_child_calls: list[str]
+ ) -> None:
+ lists_page = _resp(body={"lists": [{"id": 1}, {"id": 2}], "meta": {"total_pages": 1}})
+ child_pages = [_resp(body={"contacts": [{"id": 5}]}) for _ in expected_child_calls]
+ manager = _FakeResumeManager(FreshsalesResumeConfig(next_page=3, parent_id=saved_list_id))
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.freshsales.freshsales.make_tracked_session"
+ ) as mocked:
+ session = _session([lists_page, *child_pages])
+ mocked.return_value = session
+ list(get_rows("acme", "acme", "list_contacts", MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert [call.args[0].rsplit("/api/", 1)[1] for call in session.get.call_args_list[1:]] == expected_child_calls
+
def test_tolerates_missing_object(self) -> None:
# leads object absent -> /filters 404 -> stream yields nothing instead of failing.
manager = _FakeResumeManager()
@@ -311,6 +365,7 @@ class TestFreshsalesSource:
("deals", ["id"], "created_at"),
("sales_activities", ["id"], None),
("open_tasks", ["id"], None),
+ ("list_contacts", ["list_id", "id"], "created_at"),
]
)
def test_source_response_shape(self, endpoint: str, primary_keys: list[str], partition_key: Optional[str]) -> None: