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): implement freshsales import source (#61593)

Tom Owers930092fa00a6
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 407fd319bc9c..ad1596586dbe 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -68,6 +68,7 @@ the row lists both.
| doit | HTTP | requests | ✅ |
| drip | HTTP | requests | ✅ |
| freshdesk | HTTP | requests | ✅ |
+| freshsales | HTTP | requests | ✅ |
| eventbrite | HTTP | requests | ✅ |
| github | HTTP | requests | ✅ |
| google_ads | gRPC | google-ads (googleads.client) | ✅ |
@@ -178,7 +179,6 @@ doesn't conflict with concurrent PRs.
- elasticsearch
- facebook_pages
- firebase
-- freshsales
- front
- fullstory
- gitlab
diff --git a/posthog/temporal/data_imports/sources/freshsales/freshsales.py b/posthog/temporal/data_imports/sources/freshsales/freshsales.py
new file mode 100644
index 000000000000..6301682d3fe3
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/freshsales/freshsales.py
@@ -0,0 +1,252 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+from requests.exceptions import (
+ ConnectionError as RequestsConnectionError,
+ HTTPError,
+ ReadTimeout,
+ RequestException,
+)
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.freshsales.settings import FRESHSALES_ENDPOINTS, FreshsalesEndpointConfig
+
+# Freshsales bundles live at https://<alias>.myfreshworks.com/crm/sales/api. We always template the
+# host from a validated alias, so the stored API key can only ever be sent to a *.myfreshworks.com
+# subdomain (defends against pointing the credential at an internal/attacker-controlled host).
+FRESHSALES_DOMAIN_SUFFIX = "myfreshworks.com"
+API_PATH = "/crm/sales/api"
+_ALIAS_RE = re.compile(r"[a-z0-9][a-z0-9-]*")
+
+DEFAULT_PAGE_SIZE = 100
+REQUEST_TIMEOUT = 60
+VALIDATE_TIMEOUT = 10
+# Safety net so a broken termination signal can't loop forever. At 100 rows/page this covers 500k
+# rows per endpoint; we log if it's ever hit so silent truncation is visible.
+MAX_PAGES = 5000
+
+
+class FreshsalesRetryableError(Exception):
+ pass
+
+
+class FreshsalesResumeConfig:
+ next_page: int
+ view_id: Optional[int] = None
+
+
+def _normalize_alias(domain: str) -> str:
+ value = (domain or "").strip().lower()
+ value = value.removeprefix("https://").removeprefix("http://")
+ # Tolerate a pasted full host/URL by keeping only the first subdomain label.
+ alias = value.split("/")[0].split(".")[0]
+ if not _ALIAS_RE.fullmatch(alias):
+ raise ValueError(
+ "Invalid Freshsales domain. Enter your bundle alias — the subdomain of your Freshsales URL "
+ "(e.g. 'yourcompany' for yourcompany.myfreshworks.com)."
+ )
+ return alias
+
+
+def _build_root(domain: str) -> str:
+ return f"https://{_normalize_alias(domain)}.{FRESHSALES_DOMAIN_SUFFIX}{API_PATH}"
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Token token={api_key}",
+ "Content-Type": "application/json",
+ }
+
+
+def _build_page_url(
+ root: str,
+ config: FreshsalesEndpointConfig,
+ view_id: Optional[int],
+ page: int,
+ per_page: int = DEFAULT_PAGE_SIZE,
+) -> str:
+ if config.requires_view:
+ path = f"{root}/{config.resource}/view/{view_id}"
+ else:
+ path = f"{root}/{config.resource}"
+
+ params: dict[str, Any] = {"page": page, "per_page": per_page, **config.params}
+ if config.sort:
+ params["sort"] = config.sort
+ params["sort_type"] = "asc"
+
+ return f"{path}?{urlencode(params)}"
+
+
+@retry(
+ # Only transport hiccups and explicit 429/5xx are retried — HTTPError (a RequestException
+ # subclass raised for 4xx by raise_for_status) must fail fast, not retry.
+ retry=retry_if_exception_type((FreshsalesRetryableError, RequestsConnectionError, ReadTimeout)),
+ stop=stop_after_attempt(5),
+ # No Retry-After header is documented, and the default ceiling is 1000 req/hour, so back off
+ # generously on 429/5xx.
+ wait=wait_exponential_jitter(initial=2, max=60),
+ reraise=True,
+)
+def _fetch_page(session: Any, url: str, logger: FilteringBoundLogger) -> dict:
+ response = session.get(url, timeout=REQUEST_TIMEOUT)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise FreshsalesRetryableError(f"Freshsales API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Freshsales API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+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."""
+ url = f"{root}/{resource}/filters"
+ try:
+ data = _fetch_page(session, url, logger)
+ except HTTPError as e:
+ if e.response is not None and e.response.status_code == 404:
+ return None
+ raise
+
+ views = data.get("filters")
+ if not isinstance(views, list) or not views:
+ # Fall back to any list-shaped value in the response.
+ views = next((v for v in data.values() if isinstance(v, list) and v), [])
+
+ if not views:
+ return None
+
+ for view in views:
+ name = str(view.get("name") or "").lower()
+ if name.startswith("all"):
+ return view.get("id")
+
+ return views[0].get("id")
+
+
+def get_rows(
+ api_key: str,
+ domain: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FreshsalesResumeConfig],
+) -> Iterator[list[dict]]:
+ config = FRESHSALES_ENDPOINTS[endpoint]
+ root = _build_root(domain)
+ session = make_tracked_session(headers=_get_headers(api_key), redact_values=(api_key,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ view_id: Optional[int] = None
+ if config.requires_view:
+ if resume is not None and resume.view_id is not None:
+ view_id = resume.view_id
+ else:
+ view_id = _resolve_view_id(session, root, config.resource, logger)
+ if view_id is None:
+ if config.tolerate_missing:
+ logger.info(f"Freshsales: no view found for '{endpoint}', skipping (object not enabled)")
+ return
+ raise ValueError(f"Freshsales: could not resolve a view for '{endpoint}'")
+
+ page = resume.next_page if resume is not None else 1
+
+ while 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 []
+ if not items:
+ break
+
+ yield items
+
+ 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.
+ on_last_page = (total_pages is not None and page >= total_pages) or len(items) < DEFAULT_PAGE_SIZE
+ if on_last_page:
+ break
+
+ page += 1
+ # Save AFTER yielding so a crash re-yields the last page (merge/replace dedupes) rather than skipping it.
+ resumable_source_manager.save_state(FreshsalesResumeConfig(next_page=page, view_id=view_id))
+ else:
+ logger.warning(f"Freshsales: reached max page cap ({MAX_PAGES}) for '{endpoint}'; results may be truncated")
+
+
+def freshsales_source(
+ api_key: str,
+ domain: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FreshsalesResumeConfig],
+) -> SourceResponse:
+ config = FRESHSALES_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(api_key, domain, endpoint, logger, resumable_source_manager),
+ primary_keys=config.primary_key,
+ partition_count=1 if config.partition_key else None,
+ partition_size=1 if config.partition_key else None,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode="asc",
+ )
+
+
+def check_credentials(
+ api_key: str, domain: str, schema_name: Optional[str] = None
+) -> tuple[bool, Optional[str], Optional[int]]:
+ """Probe Freshsales credentials. Returns ``(ok, error_message, status_code)``.
+
+ With ``schema_name=None`` (source create) it hits a cheap account-level endpoint. With a schema
+ name it probes that specific endpoint so per-endpoint scope can be confirmed.
+ """
+ try:
+ root = _build_root(domain)
+ except ValueError as e:
+ return False, str(e), None
+
+ session = make_tracked_session(headers=_get_headers(api_key), redact_values=(api_key,))
+
+ config = FRESHSALES_ENDPOINTS.get(schema_name) if schema_name else None
+ if config is not None:
+ if config.requires_view:
+ url = f"{root}/{config.resource}/filters"
+ else:
+ url = _build_page_url(root, config, None, page=1, per_page=1)
+ else:
+ url = f"{root}/selector/owners"
+
+ try:
+ response = session.get(url, timeout=VALIDATE_TIMEOUT)
+ except RequestException as e:
+ return False, str(e), None
+
+ if response.ok:
+ return True, None, response.status_code
+
+ if response.status_code == 401:
+ return False, "Invalid Freshsales API key", 401
+ if response.status_code == 403:
+ return False, "Your Freshsales API key does not have permission to access this resource", 403
+ if response.status_code == 404:
+ return False, "Freshsales account not found. Please check your domain (bundle alias).", 404
+
+ return False, f"Freshsales API returned status {response.status_code}", response.status_code
diff --git a/posthog/temporal/data_imports/sources/freshsales/settings.py b/posthog/temporal/data_imports/sources/freshsales/settings.py
new file mode 100644
index 000000000000..540fa72c42de
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/freshsales/settings.py
@@ -0,0 +1,106 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField
+
+
+@dataclass
+class FreshsalesEndpointConfig:
+ name: str
+ # API resource segment, e.g. "contacts" -> /crm/sales/api/contacts/...
+ resource: str
+ # Top-level array key in the JSON response envelope (Freshsales pluralizes the object name).
+ object_key: str
+ # View-based objects (contacts, deals, ...) must resolve a "view" id via /<resource>/filters
+ # before they can be listed. Direct-list objects (tasks, appointments, ...) are queried directly.
+ requires_view: bool = False
+ # Static query params sent on every request (e.g. {"filter": "open"} for tasks).
+ params: dict[str, str] = field(default_factory=dict)
+ primary_key: list[str] = field(default_factory=lambda: ["id"])
+ # Stable datetime field for datetime partitioning. Only set where the field is confirmed present
+ # and immutable (never updated_at).
+ partition_key: Optional[str] = None
+ # Sort field to request for stable pagination. Only set on endpoints that support `sort`.
+ 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
+ # 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)
+
+
+# Freshsales has no reliably paginated server-side timestamp filter: the only updated_at filter
+# (POST /filtered_search) silently drops custom fields and has undocumented pagination, so every
+# endpoint ships as full refresh (matching Airbyte's Freshsales connector). The view/scroll list
+# APIs return complete records but offer no server-side incremental cutoff.
+FRESHSALES_ENDPOINTS: dict[str, FreshsalesEndpointConfig] = {
+ "contacts": FreshsalesEndpointConfig(
+ name="contacts",
+ resource="contacts",
+ object_key="contacts",
+ requires_view=True,
+ partition_key="created_at",
+ sort="created_at",
+ ),
+ "sales_accounts": FreshsalesEndpointConfig(
+ name="sales_accounts",
+ resource="sales_accounts",
+ object_key="sales_accounts",
+ requires_view=True,
+ partition_key="created_at",
+ sort="created_at",
+ ),
+ "deals": FreshsalesEndpointConfig(
+ name="deals",
+ resource="deals",
+ object_key="deals",
+ requires_view=True,
+ partition_key="created_at",
+ sort="created_at",
+ ),
+ "leads": FreshsalesEndpointConfig(
+ name="leads",
+ resource="leads",
+ object_key="leads",
+ requires_view=True,
+ partition_key="created_at",
+ sort="created_at",
+ # Many newer "contacts-based" Freshsales accounts have no separate leads object.
+ tolerate_missing=True,
+ ),
+ "sales_activities": FreshsalesEndpointConfig(
+ name="sales_activities",
+ resource="sales_activities",
+ object_key="sales_activities",
+ ),
+ "open_tasks": FreshsalesEndpointConfig(
+ name="open_tasks",
+ resource="tasks",
+ object_key="tasks",
+ params={"filter": "open"},
+ ),
+ "completed_tasks": FreshsalesEndpointConfig(
+ name="completed_tasks",
+ resource="tasks",
+ object_key="tasks",
+ params={"filter": "completed"},
+ ),
+ "past_appointments": FreshsalesEndpointConfig(
+ name="past_appointments",
+ resource="appointments",
+ object_key="appointments",
+ params={"filter": "past"},
+ ),
+ "upcoming_appointments": FreshsalesEndpointConfig(
+ name="upcoming_appointments",
+ resource="appointments",
+ object_key="appointments",
+ params={"filter": "upcoming"},
+ ),
+}
+
+ENDPOINTS = tuple(FRESHSALES_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in FRESHSALES_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/freshsales/source.py b/posthog/temporal/data_imports/sources/freshsales/source.py
index 6c0e4e69137c..40c2bdd9d258 100644
--- a/posthog/temporal/data_imports/sources/freshsales/source.py
+++ b/posthog/temporal/data_imports/sources/freshsales/source.py
@@ -1,29 +1,133 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
+from posthog.temporal.data_imports.sources.freshsales.freshsales import (
+ FreshsalesResumeConfig,
+ check_credentials,
+ freshsales_source,
+)
+from posthog.temporal.data_imports.sources.freshsales.settings import ENDPOINTS, INCREMENTAL_FIELDS
from posthog.temporal.data_imports.sources.generated_configs import FreshsalesSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class FreshsalesSource(SimpleSource[FreshsalesSourceConfig]):
+class FreshsalesSource(ResumableSource[FreshsalesSourceConfig, FreshsalesResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.FRESHSALES
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The API key is sent to the host derived from `domain`; retargeting it must re-require the key.
+ return ["domain"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.FRESHSALES,
label="Freshsales",
+ caption="""Enter your Freshsales domain and API key to pull your Freshsales (Freshworks CRM) data into the PostHog Data warehouse.
+
+Both are available under **Profile settings → API settings** in Freshsales.
+
+- **Domain** is your bundle alias — the subdomain of your Freshsales URL (e.g. `yourcompany` for `yourcompany.myfreshworks.com`).
+- **API key** is sent as `Token token=<key>`. The key only exposes data the associated user can access, so make sure that user can read the objects you want to sync.
+""",
iconPath="/static/services/freshsales.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/freshsales",
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="domain",
+ label="Freshsales domain",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="yourcompany",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: FreshsalesSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in list(ENDPOINTS)
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: FreshsalesSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ ok, error, status = check_credentials(config.api_key, config.domain, schema_name)
+ if ok:
+ return True, None
+ # A 403 at source-create means a valid key without scope for the probed endpoint — accept it,
+ # since the user may only sync endpoints they can access. Sync-time 403s fail via get_non_retryable_errors.
+ if status == 403 and schema_name is None:
+ return True, None
+ return False, error
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your Freshsales API key is invalid or expired. Please generate a new key and reconnect.",
+ "403 Client Error": "Your Freshsales API key does not have permission to access this resource.",
+ "Invalid Freshsales API key": "Your Freshsales API key is invalid or expired. Please generate a new key and reconnect.",
+ }
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FreshsalesResumeConfig]:
+ return ResumableSourceManager[FreshsalesResumeConfig](inputs, FreshsalesResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: FreshsalesSourceConfig,
+ resumable_source_manager: ResumableSourceManager[FreshsalesResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return freshsales_source(
+ api_key=config.api_key,
+ domain=config.domain,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/posthog/temporal/data_imports/sources/freshsales/tests/test_freshsales.py b/posthog/temporal/data_imports/sources/freshsales/tests/test_freshsales.py
new file mode 100644
index 000000000000..07e11e745d76
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/freshsales/tests/test_freshsales.py
@@ -0,0 +1,270 @@
+import json
+from typing import Any, Optional
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from requests.exceptions import HTTPError
+
+from posthog.temporal.data_imports.sources.freshsales.freshsales import (
+ FreshsalesResumeConfig,
+ _build_page_url,
+ _build_root,
+ _normalize_alias,
+ _resolve_view_id,
+ check_credentials,
+ freshsales_source,
+ get_rows,
+)
+from posthog.temporal.data_imports.sources.freshsales.settings import FRESHSALES_ENDPOINTS
+
+
+def _resp(status: int = 200, body: Optional[dict] = None) -> MagicMock:
+ body = body or {}
+ response = MagicMock()
+ response.status_code = status
+ response.ok = 200 <= status < 300
+ response.json.return_value = body
+ response.text = json.dumps(body)
+ if response.ok:
+ response.raise_for_status.return_value = None
+ else:
+ response.raise_for_status.side_effect = HTTPError(response=response)
+ return response
+
+
+def _session(responses: list[MagicMock]) -> MagicMock:
+ session = MagicMock()
+ session.get.side_effect = responses
+ return session
+
+
+class _FakeResumeManager:
+ """In-memory stand-in for ResumableSourceManager."""
+
+ def __init__(self, state: Optional[FreshsalesResumeConfig] = None) -> None:
+ self.state = state
+ self.saved: list[FreshsalesResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self.state is not None
+
+ def load_state(self) -> Optional[FreshsalesResumeConfig]:
+ return self.state
+
+ def save_state(self, data: FreshsalesResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestNormalizeAlias:
+ @parameterized.expand(
+ [
+ ("plain_alias", "acme", "acme"),
+ ("uppercase", "ACME", "acme"),
+ ("full_host", "acme.myfreshworks.com", "acme"),
+ ("with_scheme", "https://acme.myfreshworks.com", "acme"),
+ ("with_path", "acme.myfreshworks.com/crm/sales", "acme"),
+ ("hyphenated", "personal-1234", "personal-1234"),
+ ("whitespace", " acme ", "acme"),
+ ]
+ )
+ def test_valid(self, _name: str, value: str, expected: str) -> None:
+ assert _normalize_alias(value) == expected
+
+ @parameterized.expand(
+ [
+ ("empty", ""),
+ ("underscore", "acme_corp"),
+ ("at_sign", "[email protected]"),
+ ("leading_hyphen", "-acme"),
+ ("space_inside", "acme corp"),
+ ]
+ )
+ def test_invalid(self, _name: str, value: str) -> None:
+ with pytest.raises(ValueError):
+ _normalize_alias(value)
+
+ def test_build_root_constrains_host(self) -> None:
+ assert _build_root("acme") == "https://acme.myfreshworks.com/crm/sales/api"
+
+
+class TestBuildPageUrl:
+ def test_view_endpoint_includes_view_and_sort(self) -> None:
+ url = _build_page_url(
+ "https://acme.myfreshworks.com/crm/sales/api", FRESHSALES_ENDPOINTS["contacts"], view_id=42, page=3
+ )
+ assert "/contacts/view/42?" in url
+ assert "page=3" in url
+ assert "per_page=100" in url
+ assert "sort=created_at" in url
+ assert "sort_type=asc" in url
+
+ def test_direct_endpoint_includes_static_params(self) -> None:
+ url = _build_page_url(
+ "https://acme.myfreshworks.com/crm/sales/api", FRESHSALES_ENDPOINTS["open_tasks"], view_id=None, page=1
+ )
+ assert "/tasks?" in url
+ assert "filter=open" in url
+ assert "sort=" not in url
+
+
+class TestResolveViewId:
+ def test_prefers_all_view(self) -> None:
+ session = _session(
+ [_resp(body={"filters": [{"id": 1, "name": "My contacts"}, {"id": 2, "name": "All Contacts"}]})]
+ )
+ assert _resolve_view_id(session, "https://acme.myfreshworks.com/crm/sales/api", "contacts", MagicMock()) == 2
+
+ def test_falls_back_to_first_view(self) -> None:
+ session = _session([_resp(body={"filters": [{"id": 7, "name": "Recently created"}]})])
+ assert _resolve_view_id(session, "https://acme.myfreshworks.com/crm/sales/api", "contacts", MagicMock()) == 7
+
+ def test_returns_none_on_404(self) -> None:
+ session = _session([_resp(status=404)])
+ assert _resolve_view_id(session, "https://acme.myfreshworks.com/crm/sales/api", "leads", MagicMock()) is None
+
+
+class TestGetRows:
+ def _run(self, endpoint: str, responses: list[MagicMock], manager: _FakeResumeManager) -> list[list[dict]]:
+ with patch(
+ "posthog.temporal.data_imports.sources.freshsales.freshsales.make_tracked_session",
+ return_value=_session(responses),
+ ):
+ return list(get_rows("acme", "acme", endpoint, MagicMock(), manager)) # type: ignore[arg-type]
+
+ def test_paginates_until_total_pages(self) -> None:
+ page1 = _resp(body={"sales_activities": [{"id": i} for i in range(100)], "meta": {"total_pages": 2}})
+ page2 = _resp(body={"sales_activities": [{"id": 100}], "meta": {"total_pages": 2}})
+ manager = _FakeResumeManager()
+
+ batches = self._run("sales_activities", [page1, page2], manager)
+
+ assert len(batches) == 2
+ assert batches[0][0] == {"id": 0}
+ assert batches[1] == [{"id": 100}]
+ # State saved after the first page only (pointing at the next page to fetch).
+ assert [s.next_page for s in manager.saved] == [2]
+
+ def test_stops_on_short_page_when_total_pages_missing(self) -> None:
+ # /appointments omits total_pages, so a page shorter than per_page ends pagination.
+ page1 = _resp(body={"appointments": [{"id": i} for i in range(10)]})
+ manager = _FakeResumeManager()
+
+ batches = self._run("upcoming_appointments", [page1], manager)
+
+ assert len(batches) == 1
+ assert manager.saved == []
+
+ def test_stops_on_empty_page(self) -> None:
+ manager = _FakeResumeManager()
+ batches = self._run("sales_activities", [_resp(body={"sales_activities": []})], manager)
+ assert batches == []
+
+ def test_resumes_from_saved_state(self) -> None:
+ # Resume at page 2 — the view id is already known so /filters is never fetched again.
+ page2 = _resp(body={"contacts": [{"id": 5}]})
+ manager = _FakeResumeManager(FreshsalesResumeConfig(next_page=2, view_id=99))
+
+ with patch("posthog.temporal.data_imports.sources.freshsales.freshsales.make_tracked_session") as mocked:
+ session = _session([page2])
+ mocked.return_value = session
+ batches = list(get_rows("acme", "acme", "contacts", MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert batches == [[{"id": 5}]]
+ called_url = session.get.call_args_list[0].args[0]
+ assert "/contacts/view/99?" in called_url
+ assert "page=2" in called_url
+
+ def test_view_endpoint_resolves_view_first(self) -> None:
+ filters = _resp(body={"filters": [{"id": 3, "name": "All Contacts"}]})
+ page1 = _resp(body={"contacts": [{"id": 1}]})
+ manager = _FakeResumeManager()
+
+ with patch("posthog.temporal.data_imports.sources.freshsales.freshsales.make_tracked_session") as mocked:
+ session = _session([filters, page1])
+ mocked.return_value = session
+ batches = list(get_rows("acme", "acme", "contacts", MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert batches == [[{"id": 1}]]
+ 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_tolerates_missing_object(self) -> None:
+ # leads object absent -> /filters 404 -> stream yields nothing instead of failing.
+ manager = _FakeResumeManager()
+ batches = self._run("leads", [_resp(status=404)], manager)
+ assert batches == []
+
+
+class TestCheckCredentials:
+ def _run(self, response: MagicMock, schema_name: Optional[str] = None, domain: str = "acme") -> Any:
+ with patch(
+ "posthog.temporal.data_imports.sources.freshsales.freshsales.make_tracked_session",
+ return_value=_session([response]),
+ ):
+ return check_credentials("key", domain, schema_name)
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, 200),
+ ("unauthorized", 401, False, 401),
+ ("forbidden", 403, False, 403),
+ ("not_found", 404, False, 404),
+ ("server_error", 500, False, 500),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status: int, expected_ok: bool, expected_status: Optional[int]) -> None:
+ ok, error, status_code = self._run(_resp(status=status))
+ assert ok is expected_ok
+ assert status_code == expected_status
+ if not expected_ok:
+ assert error
+
+ def test_invalid_domain_short_circuits(self) -> None:
+ ok, error, status_code = check_credentials("key", "bad domain", None)
+ assert ok is False
+ assert status_code is None
+ assert error is not None and "domain" in error.lower()
+
+ def test_source_create_probes_account_endpoint(self) -> None:
+ session = _session([_resp(status=200, body={})])
+ with patch(
+ "posthog.temporal.data_imports.sources.freshsales.freshsales.make_tracked_session",
+ return_value=session,
+ ):
+ check_credentials("key", "acme", None)
+ assert session.get.call_args.args[0].endswith("/selector/owners")
+
+ def test_schema_probe_targets_endpoint(self) -> None:
+ session = _session([_resp(status=200, body={})])
+ with patch(
+ "posthog.temporal.data_imports.sources.freshsales.freshsales.make_tracked_session",
+ return_value=session,
+ ):
+ check_credentials("key", "acme", "contacts")
+ # contacts requires a view, so it probes the filters endpoint.
+ assert "/contacts/filters" in session.get.call_args.args[0]
+
+
+class TestFreshsalesSource:
+ @parameterized.expand(
+ [
+ ("contacts", ["id"], "created_at"),
+ ("deals", ["id"], "created_at"),
+ ("sales_activities", ["id"], None),
+ ("open_tasks", ["id"], None),
+ ]
+ )
+ def test_source_response_shape(self, endpoint: str, primary_keys: list[str], partition_key: Optional[str]) -> None:
+ response = freshsales_source("key", "acme", endpoint, MagicMock(), MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ assert response.sort_mode == "asc"
+ if partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+ assert response.partition_format == "month"
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/posthog/temporal/data_imports/sources/freshsales/tests/test_freshsales_source.py b/posthog/temporal/data_imports/sources/freshsales/tests/test_freshsales_source.py
new file mode 100644
index 000000000000..44dd9128950b
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/freshsales/tests/test_freshsales_source.py
@@ -0,0 +1,124 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.freshsales.freshsales import FreshsalesResumeConfig
+from posthog.temporal.data_imports.sources.freshsales.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.freshsales.source import FreshsalesSource
+from posthog.temporal.data_imports.sources.generated_configs import FreshsalesSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+def _config(domain: str = "acme", api_key: str = "key") -> FreshsalesSourceConfig:
+ return FreshsalesSourceConfig.from_dict({"domain": domain, "api_key": api_key})
+
+
+def _inputs(schema_name: str = "contacts") -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-1",
+ source_id="source-1",
+ team_id=1,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="job-1",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+class TestFreshsalesSource:
+ def test_source_type(self) -> None:
+ assert FreshsalesSource().source_type == ExternalDataSourceType.FRESHSALES
+
+ def test_connection_host_fields(self) -> None:
+ # The API key is sent to a host derived from `domain`, so retargeting it must re-require the key.
+ assert FreshsalesSource().connection_host_fields == ["domain"]
+
+ def test_source_config_fields(self) -> None:
+ config = FreshsalesSource().get_source_config
+ assert config.label == "Freshsales"
+ assert config.unreleasedSource is True
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ fields = {f.name: f for f in config.fields}
+ assert set(fields) == {"domain", "api_key"}
+
+ domain_field = fields["domain"]
+ api_key_field = fields["api_key"]
+ assert isinstance(domain_field, SourceFieldInputConfig)
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert domain_field.type == SourceFieldInputConfigType.TEXT
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+
+ def test_get_schemas_full_refresh_only(self) -> None:
+ schemas = FreshsalesSource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # Freshsales has no verified server-side timestamp filter, so every endpoint is full refresh.
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filters_by_name(self) -> None:
+ schemas = FreshsalesSource().get_schemas(_config(), team_id=1, names=["contacts", "deals"])
+ assert {s.name for s in schemas} == {"contacts", "deals"}
+
+ @parameterized.expand(
+ [
+ ("valid", True, None, None, None, True),
+ ("invalid_key", False, "Invalid Freshsales API key", 401, None, False),
+ ("forbidden_at_create", False, "no scope", 403, None, True),
+ ("forbidden_for_schema", False, "no scope", 403, "contacts", False),
+ ("bad_domain", False, "Invalid Freshsales domain", None, None, False),
+ ]
+ )
+ def test_validate_credentials(
+ self,
+ _name: str,
+ check_ok: bool,
+ check_error: str | None,
+ check_status: int | None,
+ schema_name: str | None,
+ expected_ok: bool,
+ ) -> None:
+ with patch(
+ "posthog.temporal.data_imports.sources.freshsales.source.check_credentials",
+ return_value=(check_ok, check_error, check_status),
+ ):
+ ok, _error = FreshsalesSource().validate_credentials(_config(), team_id=1, schema_name=schema_name)
+ assert ok is expected_ok
+
+ def test_get_non_retryable_errors(self) -> None:
+ errors = FreshsalesSource().get_non_retryable_errors()
+ assert "401 Client Error" in errors
+ assert "403 Client Error" in errors
+
+ def test_get_resumable_source_manager_binds_data_class(self) -> None:
+ manager = FreshsalesSource().get_resumable_source_manager(_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is FreshsalesResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ sentinel = object()
+ manager = MagicMock()
+ with patch(
+ "posthog.temporal.data_imports.sources.freshsales.source.freshsales_source",
+ return_value=sentinel,
+ ) as mocked:
+ result = FreshsalesSource().source_for_pipeline(_config(), manager, _inputs("deals"))
+
+ assert result is sentinel
+ _args, kwargs = mocked.call_args
+ assert kwargs["api_key"] == "key"
+ assert kwargs["domain"] == "acme"
+ assert kwargs["endpoint"] == "deals"
+ assert kwargs["resumable_source_manager"] is manager
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index c6dde91d67f8..e78c32b980d8 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -361,7 +361,8 @@ class FreshdeskSourceConfig(config.Config):
@config.config
class FreshsalesSourceConfig(config.Config):
- pass
+ domain: str
+ api_key: str
@config.config