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 spotlercrm import source (#72616)

Tom Owers4574e6753375
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 6e1b0c83c555..678a92eb126d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -518,6 +518,7 @@ the row lists both.
| spacelift | HTTP (GraphQL) | requests | ✅ |
| sparkpost | HTTP | requests | ✅ |
| split_io | HTTP | requests | ✅ |
+| spotlercrm | HTTP | requests + `rest_source.RESTClient` | ✅ |
| squadcast | HTTP | requests | ✅ |
| square | HTTP | requests | ✅ |
| squarespace | HTTP | requests | ✅ |
@@ -951,7 +952,6 @@ doesn't conflict with concurrent PRs.
- sonatype_nexus
- spacelift
- spotify_ads
-- spotlercrm
- statsig
- strava
- streamelements
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/spotlercrm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/spotlercrm.py
index 87551bcc8f13..43ae8dbc1ace 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/spotlercrm.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/spotlercrm.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class SpotlerCRMSourceConfig(config.Config):
- pass
+ access_token: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/canonical_descriptions.py
new file mode 100644
index 000000000000..6250bfc9e210
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/canonical_descriptions.py
@@ -0,0 +1,136 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://support.reallysimplesystems.com/api-v4/"
+
+_COMMON_COLUMNS = {
+ "id": "Unique identifier for the record.",
+ "createddate": "When the record was created.",
+ "createdby": "ID of the user who created the record.",
+ "modifieddate": "When the record was last modified.",
+ "modifiedby": "ID of the user who last modified the record.",
+ "ownerid": "ID of the user who owns the record.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Accounts": {
+ "description": "Companies and organizations stored in the CRM.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "name": "Name of the account.",
+ "phone": "Main phone number for the account.",
+ "website": "Website URL for the account.",
+ "sector": "Industry sector of the account.",
+ "source": "How the account was acquired.",
+ "addressline": "Street address of the account.",
+ "addresscity": "City of the account's address.",
+ "addresscountry": "Country of the account's address.",
+ },
+ },
+ "Activities": {
+ "description": "Tasks, calls, meetings, and other activities logged against records.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "accountid": "ID of the account the activity relates to.",
+ "contactid": "ID of the contact the activity relates to.",
+ "caseid": "ID of the case the activity relates to.",
+ "type": "Type of activity (e.g. task, call, meeting).",
+ "date": "When the activity is scheduled or took place.",
+ "allday": "Whether the activity spans the whole day.",
+ "priority": "Priority of the activity.",
+ "status": "Current status of the activity.",
+ },
+ },
+ "Campaigns": {
+ "description": "Marketing campaigns. Requires the Spotler CRM Marketing tool add-on.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "name": "Name of the campaign.",
+ "type": "Type of the campaign.",
+ "status": "Current status of the campaign.",
+ "active": "Whether the campaign is active.",
+ "members": "Number of members in the campaign.",
+ "opportunities": "Number of opportunities generated by the campaign.",
+ "sales": "Sales value attributed to the campaign.",
+ },
+ },
+ "Cases": {
+ "description": "Customer service cases. Requires the Spotler CRM Service & Support tool add-on.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "accountid": "ID of the account the case belongs to.",
+ "subject": "Short summary of the case.",
+ "status": "Current status of the case.",
+ "opened": "When the case was opened.",
+ "caselevelid": "Severity or level of the case.",
+ },
+ },
+ "Contacts": {
+ "description": "People linked to accounts.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "accountid": "ID of the account the contact belongs to.",
+ "first": "First name of the contact.",
+ "last": "Last name of the contact.",
+ "salutation": "Salutation used for the contact.",
+ "email": "Email address of the contact.",
+ "phone": "Phone number of the contact.",
+ "jobtitle": "Job title of the contact.",
+ "decisionmaker": "Whether the contact is a decision maker.",
+ "leadscore": "Lead score of the contact.",
+ },
+ },
+ "Documents": {
+ "description": "Documents attached to CRM records.",
+ "docs_url": _DOCS_URL,
+ "columns": _COMMON_COLUMNS,
+ },
+ "Opportunities": {
+ "description": "Sales opportunities in the pipeline.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_COMMON_COLUMNS,
+ "accountid": "ID of the account the opportunity belongs to.",
+ "name": "Name of the opportunity.",
+ "status": "Current status of the opportunity.",
+ "probability": "Probability of winning the opportunity, as a percentage.",
+ "forecast": "Forecast value of the opportunity.",
+ "closedate": "Expected or actual close date of the opportunity.",
+ "nextstep": "Next step planned for the opportunity.",
+ "source": "How the opportunity was acquired.",
+ },
+ },
+ "OpportunityHistories": {
+ "description": "Historical stage and forecast changes for opportunities.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the history entry.",
+ "modifieddate": "When the change was made.",
+ "modifiedby": "ID of the user who made the change.",
+ "opportunitystatus": "Status of the opportunity at this point in its history.",
+ "probability": "Probability of winning at this point in the opportunity's history.",
+ "forecast": "Forecast value at this point in the opportunity's history.",
+ "closedate": "Expected close date at this point in the opportunity's history.",
+ "value": "Value of the opportunity at this point in its history.",
+ },
+ },
+ "OpportunityLines": {
+ "description": "Line items attached to opportunities.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the line item.",
+ "opportunityid": "ID of the opportunity the line item belongs to.",
+ "product": "Product the line item refers to.",
+ "quantity": "Quantity of the product.",
+ "unitprice": "Price per unit of the product.",
+ "createdby": "ID of the user who created the line item.",
+ "modifiedby": "ID of the user who last modified the line item.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/settings.py
new file mode 100644
index 000000000000..7af2199fe29a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/settings.py
@@ -0,0 +1,52 @@
+from dataclasses import dataclass
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+
+@dataclass(frozen=True)
+class SpotlerCRMEndpoint:
+ name: str
+ path: str
+ primary_key: str = "id"
+ # Stable datetime column used for partitioning. None where live samples don't
+ # confirm the column exists on every record.
+ partition_key: str | None = None
+
+
+SPOTLERCRM_ENDPOINTS: dict[str, SpotlerCRMEndpoint] = {
+ "Accounts": SpotlerCRMEndpoint(name="Accounts", path="/accounts", partition_key="createddate"),
+ "Activities": SpotlerCRMEndpoint(name="Activities", path="/activities", partition_key="createddate"),
+ "Campaigns": SpotlerCRMEndpoint(name="Campaigns", path="/campaigns"),
+ "Cases": SpotlerCRMEndpoint(name="Cases", path="/cases", partition_key="createddate"),
+ "Contacts": SpotlerCRMEndpoint(name="Contacts", path="/contacts", partition_key="createddate"),
+ "Documents": SpotlerCRMEndpoint(name="Documents", path="/documents"),
+ "Opportunities": SpotlerCRMEndpoint(name="Opportunities", path="/opportunities", partition_key="createddate"),
+ "OpportunityHistories": SpotlerCRMEndpoint(name="OpportunityHistories", path="/opportunityhistories"),
+ "OpportunityLines": SpotlerCRMEndpoint(name="OpportunityLines", path="/opportunity_lines"),
+}
+
+ENDPOINTS = tuple(SPOTLERCRM_ENDPOINTS.keys())
+
+# The v4 API has no documented server-side timestamp filter (records carry
+# `modifieddate`, but the `?q=` JSON filter isn't documented for incremental date
+# cutoffs), so every endpoint is full-refresh only.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in ENDPOINTS}
+
+ENDPOINT_DESCRIPTIONS: dict[str, str] = {
+ "Accounts": "Companies and organizations stored in the CRM.",
+ "Activities": "Tasks, calls, meetings, and other activities logged against records.",
+ "Campaigns": "Marketing campaigns. Requires the Spotler CRM Marketing tool add-on.",
+ "Cases": "Customer service cases. Requires the Spotler CRM Service & Support tool add-on.",
+ "Contacts": "People linked to accounts.",
+ "Documents": "Documents attached to CRM records.",
+ "Opportunities": "Sales opportunities in the pipeline.",
+ "OpportunityHistories": "Historical stage and forecast changes for opportunities.",
+ "OpportunityLines": "Line items attached to opportunities.",
+}
+
+# Endpoints gated behind paid add-ons start disabled so a default sync doesn't
+# permanently fail for accounts without the add-on.
+ENDPOINT_SHOULD_SYNC_DEFAULT: dict[str, bool] = {
+ "Campaigns": False,
+ "Cases": False,
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/source.py
index 90eb56ceca1d..c07dba048b55 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/source.py
@@ -1,32 +1,139 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.spotlercrm import (
SpotlerCRMSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.settings import (
+ ENDPOINT_DESCRIPTIONS,
+ ENDPOINT_SHOULD_SYNC_DEFAULT,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.spotlercrm import (
+ SpotlerCRMResumeConfig,
+ get_endpoint_permissions as get_spotlercrm_endpoint_permissions,
+ spotlercrm_source,
+ validate_credentials as validate_spotlercrm_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SpotlerCRMSource(SimpleSource[SpotlerCRMSourceConfig]):
+class SpotlerCRMSource(ResumableSource[SpotlerCRMSourceConfig, SpotlerCRMResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ supported_versions = ("v4",)
+ default_version = "v4"
+ api_docs_url = "https://support.reallysimplesystems.com/api-v4/"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SPOTLERCRM
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "403 Client Error": "Your Spotler CRM access token is invalid or expired, or your plan doesn't include this record type. Generate a new token under Settings / Integrations / API V4 and reconnect.",
+ "402 Client Error": "Your Spotler CRM access token was rejected. Generate a new token under Settings / Integrations / API V4 and reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: SpotlerCRMSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ descriptions=ENDPOINT_DESCRIPTIONS,
+ should_sync_default=ENDPOINT_SHOULD_SYNC_DEFAULT,
+ )
+
+ def validate_credentials(
+ self, config: SpotlerCRMSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_spotlercrm_credentials(config.access_token)
+
+ def get_endpoint_permissions(
+ self, config: SpotlerCRMSourceConfig, team_id: int, endpoints: list[str]
+ ) -> dict[str, str | None]:
+ return get_spotlercrm_endpoint_permissions(config.access_token, endpoints)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SpotlerCRMResumeConfig]:
+ return ResumableSourceManager[SpotlerCRMResumeConfig](inputs, SpotlerCRMResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SpotlerCRMSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SpotlerCRMResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return spotlercrm_source(
+ access_token=config.access_token,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.SPOTLER_CRM,
category=DataWarehouseSourceCategory.CRM,
- label="SpotlerCRM",
+ label="Spotler CRM",
+ caption="""Enter your Spotler CRM API access token to pull your CRM data into the PostHog Data warehouse.
+
+Generate a token in Spotler CRM under **Settings / Integrations / API V4** — it's shown only once, so copy it when you create it.
+
+Some record types need paid add-ons: Campaigns requires the Marketing tool, and Cases requires the Service & Support tool.""",
+ docsUrl="https://posthog.com/docs/cdp/sources/spotlercrm",
iconPath="/static/services/spotlercrm.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ keywords=["really simple systems", "spotler", "rss crm"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_token",
+ label="API access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="Enter your Spotler CRM access token",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/spotlercrm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/spotlercrm.py
new file mode 100644
index 000000000000..d7e7185e6912
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/spotlercrm.py
@@ -0,0 +1,223 @@
+import dataclasses
+from typing import Any, Optional
+
+from requests import Request, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.settings import SPOTLERCRM_ENDPOINTS
+
+BASE_URL = "https://apiv4.reallysimplesystems.com"
+PAGE_LIMIT = 100
+REQUEST_TIMEOUT_SECONDS = 30
+
+
+class SpotlerCRMResumeConfig:
+ next_page: int
+
+
+class SpotlerCRMPaginator(BasePaginator):
+ """Page-number paginator for Spotler CRM list endpoints.
+
+ Pages are 1-indexed (``?page=``); the response's top-level ``metadata.has_more``
+ signals whether another page exists. An empty ``list`` also terminates, since the
+ API returns no records (not an error) for a page past the end.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._page = 1
+
+ def init_request(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["page"] = self._page
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ if data is None or len(data) == 0:
+ self._has_next_page = False
+ return
+
+ self._page += 1
+
+ try:
+ has_more = response.json().get("metadata", {}).get("has_more")
+ except Exception:
+ has_more = None
+
+ # `has_more` is documented but not guaranteed on every deployment; when it's
+ # absent we keep paginating and rely on the empty-page stop above.
+ self._has_next_page = has_more is not False
+
+ def update_request(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["page"] = self._page
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ # self._page already points at the next page to fetch (update_state incremented it).
+ return {"page": self._page} if self._has_next_page else None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ page = state.get("page")
+ if page is not None:
+ self._page = int(page)
+ self._has_next_page = True
+
+
+def get_resource(name: str) -> EndpointResource:
+ endpoint = SPOTLERCRM_ENDPOINTS[name]
+ return {
+ "name": endpoint.name,
+ "table_name": endpoint.name.lower(),
+ # No server-side timestamp filter, so every sync is a full refresh.
+ "write_disposition": "replace",
+ "endpoint": {
+ "data_selector": "list[*].record",
+ "path": endpoint.path,
+ "params": {"limit": PAGE_LIMIT},
+ "paginator": SpotlerCRMPaginator(),
+ },
+ "table_format": "delta",
+ }
+
+
+def spotlercrm_source(
+ access_token: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[SpotlerCRMResumeConfig],
+) -> SourceResponse:
+ endpoint_config = SPOTLERCRM_ENDPOINTS[endpoint]
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": BASE_URL,
+ "auth": {
+ "type": "bearer",
+ "token": access_token,
+ },
+ "headers": {"Accept": "application/json"},
+ # `capture=False`: raw Accounts/Contacts/Activities/Documents rows carry arbitrary
+ # CRM custom fields and free-text content the name-based scrubbers can't recognise,
+ # so keep them out of the shared HTTP sample store (still metered and logged).
+ "session": make_tracked_session(
+ capture=False,
+ redact_values=(access_token,),
+ allow_redirects=False,
+ ),
+ },
+ "resource_defaults": {
+ "write_disposition": "replace",
+ },
+ "resources": [get_resource(endpoint)],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"page": resume_config.next_page}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist when there's a next page to resume to; the Redis TTL
+ # handles cleanup on completion.
+ if state and state.get("page"):
+ resumable_source_manager.save_state(SpotlerCRMResumeConfig(next_page=int(state["page"])))
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ partition_kwargs: dict[str, Any] = {}
+ if endpoint_config.partition_key is not None:
+ partition_kwargs = {
+ "partition_count": 1,
+ "partition_size": 1,
+ "partition_mode": "datetime",
+ "partition_format": "month",
+ "partition_keys": [endpoint_config.partition_key],
+ }
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=[endpoint_config.primary_key],
+ **partition_kwargs,
+ )
+
+
+def _probe_endpoint(access_token: str, path: str) -> Response:
+ # `capture=False`: probe responses return the same CRM record shapes as the sync, so
+ # exclude them from HTTP sample capture too.
+ return make_tracked_session(
+ redact_values=(access_token,),
+ capture=False,
+ allow_redirects=False,
+ ).get(
+ f"{BASE_URL}{path}",
+ params={"limit": 1},
+ headers={
+ "Authorization": f"Bearer {access_token}",
+ "Accept": "application/json",
+ },
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+
+def validate_credentials(access_token: str) -> tuple[bool, str | None]:
+ res = _probe_endpoint(access_token, "/accounts")
+ if res.status_code == 200:
+ return True, None
+
+ # The API answers 403 "Unauthenticated" for a bad token; the docs also list 402
+ # ("Forbidden, please check your access token").
+ if res.status_code in (402, 403):
+ return False, "Invalid Spotler CRM access token. Generate a new token under Settings / Integrations / API V4."
+
+ return False, f"Spotler CRM API returned an unexpected status: {res.status_code}"
+
+
+def get_endpoint_permissions(access_token: str, endpoints: list[str]) -> dict[str, str | None]:
+ """Per-table reachability for the schema picker.
+
+ Some record types are gated behind paid add-ons (Campaigns needs the Marketing
+ tool, Cases needs the Service & Support tool). Only a definite denial counts as
+ a missing permission; transient failures are treated as reachable.
+ """
+ permissions: dict[str, str | None] = {}
+ for name in endpoints:
+ endpoint = SPOTLERCRM_ENDPOINTS.get(name)
+ if endpoint is None:
+ permissions[name] = None
+ continue
+
+ try:
+ res = _probe_endpoint(access_token, endpoint.path)
+ except Exception:
+ permissions[name] = None
+ continue
+
+ if res.status_code in (402, 403, 404):
+ permissions[name] = (
+ f"Your Spotler CRM plan or access token can't read this record type (HTTP {res.status_code}). "
+ "It may require a paid add-on such as the Marketing or Service & Support tool."
+ )
+ else:
+ permissions[name] = None
+
+ return permissions
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/tests/test_spotlercrm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/tests/test_spotlercrm.py
new file mode 100644
index 000000000000..0c49606acbf3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/tests/test_spotlercrm.py
@@ -0,0 +1,285 @@
+import json
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Request, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.settings import SPOTLERCRM_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.spotlercrm import (
+ SpotlerCRMPaginator,
+ SpotlerCRMResumeConfig,
+ get_endpoint_permissions,
+ spotlercrm_source,
+ validate_credentials,
+)
+
+
+def _page_body(records: list[dict[str, Any]], has_more: bool | None = None) -> dict[str, Any]:
+ metadata: dict[str, Any] = {"url": "/accounts", "object_type": "list"}
+ if has_more is not None:
+ metadata["has_more"] = has_more
+ return {"metadata": metadata, "list": [{"metadata": {}, "record": record} for record in records]}
+
+
+def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+class TestSpotlerCRMPaginator:
+ def _json_response(self, body: dict[str, Any]) -> MagicMock:
+ response = MagicMock()
+ response.json.return_value = body
+ return response
+
+ def test_first_request_targets_page_one(self) -> None:
+ paginator = SpotlerCRMPaginator()
+ request = Request(method="GET", url="https://apiv4.reallysimplesystems.com/accounts")
+ paginator.init_request(request)
+
+ assert request.params["page"] == 1
+
+ @pytest.mark.parametrize(
+ ("body", "records", "expects_next"),
+ [
+ # has_more=True keeps paginating; the extracted rows are non-empty.
+ (_page_body([{"id": 1}], has_more=True), [{"id": 1}], True),
+ # has_more=False stops without paying an extra empty-page request.
+ (_page_body([{"id": 1}], has_more=False), [{"id": 1}], False),
+ # No has_more key: keep going while pages have records.
+ (_page_body([{"id": 1}]), [{"id": 1}], True),
+ # Empty page always terminates, even if has_more is missing.
+ (_page_body([]), [], False),
+ ],
+ )
+ def test_update_state_termination(self, body: dict[str, Any], records: list[Any], expects_next: bool) -> None:
+ paginator = SpotlerCRMPaginator()
+ paginator.update_state(self._json_response(body), records)
+
+ assert paginator.has_next_page is expects_next
+
+ def test_update_request_advances_to_next_page(self) -> None:
+ paginator = SpotlerCRMPaginator()
+ paginator.update_state(self._json_response(_page_body([{"id": 1}], has_more=True)), [{"id": 1}])
+
+ request = Request(method="GET", url="https://apiv4.reallysimplesystems.com/accounts")
+ paginator.update_request(request)
+
+ assert request.params["page"] == 2
+
+ def test_resume_state_round_trip(self) -> None:
+ paginator = SpotlerCRMPaginator()
+ paginator.update_state(self._json_response(_page_body([{"id": 1}], has_more=True)), [{"id": 1}])
+
+ assert paginator.get_resume_state() == {"page": 2}
+
+ resumed = SpotlerCRMPaginator()
+ resumed.set_resume_state({"page": 2})
+ request = Request(method="GET", url="https://apiv4.reallysimplesystems.com/accounts")
+ resumed.init_request(request)
+
+ assert request.params["page"] == 2
+ assert resumed.has_next_page is True
+
+ def test_no_resume_state_on_terminal_page(self) -> None:
+ paginator = SpotlerCRMPaginator()
+ paginator.update_state(self._json_response(_page_body([], has_more=False)), [])
+
+ assert paginator.get_resume_state() is None
+
+
+class TestSpotlerCRMSourceBehavior:
+ def _drive(
+ self, endpoint: str, manager: MagicMock, responses: list[Response]
+ ) -> tuple[list[dict[str, Any]], list[str], list[list[dict[str, Any]]]]:
+ """Drive ``spotlercrm_source`` with a mocked HTTP session.
+
+ Returns ``(sent_params, sent_urls, pages)`` where ``sent_params`` are shallow
+ copies of ``request.params`` captured at send-time (the Request object is
+ mutated in place between pages) and ``pages`` are the yielded row batches.
+ """
+ sent_params: list[dict[str, Any]] = []
+ sent_urls: list[str] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ sent_urls.append(request.url)
+ return next(response_iter)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.spotlercrm.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ source_response = spotlercrm_source(
+ access_token="test-token",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ )
+ pages = [list(page) for page in cast(Iterable[Any], source_response.items())]
+ return sent_params, sent_urls, pages
+
+ @pytest.mark.parametrize("endpoint", sorted(SPOTLERCRM_ENDPOINTS.keys()))
+ def test_requests_hit_the_configured_path_with_limit(self, endpoint: str) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ _, sent_urls, pages = self._drive(
+ endpoint, manager, [_make_http_response(_page_body([{"id": 1}], has_more=False))]
+ )
+
+ assert sent_urls == [f"https://apiv4.reallysimplesystems.com{SPOTLERCRM_ENDPOINTS[endpoint].path}"]
+ assert pages == [[{"id": 1}]]
+
+ def test_fresh_run_pages_forward_and_checkpoints_after_each_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response(_page_body([{"id": 1}], has_more=True)),
+ _make_http_response(_page_body([{"id": 2}], has_more=True)),
+ _make_http_response(_page_body([{"id": 3}], has_more=False)),
+ ]
+ sent_params, _, pages = self._drive("Accounts", manager, responses)
+
+ assert [p.get("page") for p in sent_params] == [1, 2, 3]
+ assert [p.get("limit") for p in sent_params] == [100, 100, 100]
+ assert pages == [[{"id": 1}], [{"id": 2}], [{"id": 3}]]
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [
+ SpotlerCRMResumeConfig(next_page=2),
+ SpotlerCRMResumeConfig(next_page=3),
+ ]
+
+ def test_resume_seeds_paginator_with_saved_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SpotlerCRMResumeConfig(next_page=5)
+
+ responses = [_make_http_response(_page_body([{"id": 42}], has_more=False))]
+ sent_params, _, _ = self._drive("Contacts", manager, responses)
+
+ assert [p.get("page") for p in sent_params] == [5]
+ manager.load_state.assert_called_once()
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ self._drive("Accounts", manager, [_make_http_response(_page_body([{"id": 1}], has_more=False))])
+
+ manager.save_state.assert_not_called()
+
+ def test_partitioning_only_on_endpoints_with_a_stable_created_column(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.spotlercrm.rest_api_resource"
+ ):
+ partitioned = spotlercrm_source("t", "Accounts", 1, "job", manager)
+ unpartitioned = spotlercrm_source("t", "OpportunityLines", 1, "job", manager)
+
+ assert partitioned.partition_keys == ["createddate"]
+ assert partitioned.partition_mode == "datetime"
+ assert unpartitioned.partition_keys is None
+ assert partitioned.primary_keys == ["id"]
+ assert unpartitioned.primary_keys == ["id"]
+
+
+class TestSpotlerCRMCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "expected_valid"),
+ [
+ (200, True),
+ (402, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ def test_validate_credentials_status_mapping(self, status_code: int, expected_valid: bool) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.spotlercrm.make_tracked_session"
+ ) as MockSession:
+ MockSession.return_value.get.return_value = _make_http_response({}, status_code=status_code)
+
+ valid, error = validate_credentials("test-token")
+
+ assert valid is expected_valid
+ assert (error is None) is expected_valid
+
+ @pytest.mark.parametrize(
+ ("status_code", "expects_reason"),
+ [
+ (200, False),
+ (402, True),
+ (403, True),
+ (404, True),
+ (500, False), # transient failures must not read as missing permissions
+ ],
+ )
+ def test_get_endpoint_permissions_status_mapping(self, status_code: int, expects_reason: bool) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.spotlercrm.make_tracked_session"
+ ) as MockSession:
+ MockSession.return_value.get.return_value = _make_http_response({}, status_code=status_code)
+
+ permissions = get_endpoint_permissions("test-token", ["Cases"])
+
+ assert (permissions["Cases"] is not None) is expects_reason
+
+ def test_get_endpoint_permissions_treats_network_errors_as_reachable(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.spotlercrm.make_tracked_session"
+ ) as MockSession:
+ MockSession.return_value.get.side_effect = ConnectionError("boom")
+
+ permissions = get_endpoint_permissions("test-token", ["Accounts"])
+
+ assert permissions["Accounts"] is None
+
+
+class TestSpotlerCRMHttpSampleCapture:
+ # CRM records carry arbitrary custom fields and free-text content the name-based
+ # scrubbers can't recognise, so both the sync and probe sessions must opt out of
+ # HTTP sample capture. Dropping `capture=False` would persist raw records to S3.
+ def test_sync_session_opts_out_of_capture(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.spotlercrm.make_tracked_session"
+ ) as MockSession,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.spotlercrm.rest_api_resource"
+ ),
+ ):
+ spotlercrm_source("test-token", "Accounts", 1, "job", manager)
+
+ MockSession.assert_called_once()
+ assert MockSession.call_args.kwargs["capture"] is False
+
+ def test_probe_session_opts_out_of_capture(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.spotlercrm.make_tracked_session"
+ ) as MockSession:
+ MockSession.return_value.get.return_value = _make_http_response({}, status_code=200)
+
+ validate_credentials("test-token")
+
+ assert MockSession.call_args.kwargs["capture"] is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/tests/test_spotlercrm_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/tests/test_spotlercrm_source.py
new file mode 100644
index 000000000000..4395c745ea87
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spotlercrm/tests/test_spotlercrm_source.py
@@ -0,0 +1,122 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.spotlercrm import (
+ SpotlerCRMSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.source import SpotlerCRMSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.spotlercrm import (
+ SpotlerCRMResumeConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestSpotlerCRMSource:
+ def setup_method(self) -> None:
+ self.source = SpotlerCRMSource()
+ self.config = SpotlerCRMSourceConfig(access_token="test-token")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.SPOTLERCRM
+
+ def test_source_is_released_with_alpha_status(self) -> None:
+ source_config = self.source.get_source_config
+
+ assert not source_config.unreleasedSource
+ assert source_config.releaseStatus == ReleaseStatus.ALPHA
+
+ def test_source_config_asks_for_a_secret_access_token(self) -> None:
+ fields = self.source.get_source_config.fields
+
+ assert len(fields) == 1
+ field = fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.name == "access_token"
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.required is True
+ assert field.secret is True
+
+ def test_get_schemas_lists_every_endpoint_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=1)
+
+ assert [s.name for s in schemas] == list(ENDPOINTS)
+ assert all(not s.supports_incremental for s in schemas)
+ assert all(not s.supports_append for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=1, names=["Accounts", "Contacts"])
+
+ assert {s.name for s in schemas} == {"Accounts", "Contacts"}
+
+ @pytest.mark.parametrize(
+ ("endpoint", "expected_default"),
+ [
+ ("Accounts", True),
+ ("Campaigns", False), # Marketing tool add-on
+ ("Cases", False), # Service & Support tool add-on
+ ],
+ )
+ def test_addon_gated_endpoints_start_disabled(self, endpoint: str, expected_default: bool) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, team_id=1)}
+
+ assert schemas[endpoint].should_sync_default is expected_default
+
+ def test_validate_credentials_uses_config_token(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.source.validate_spotlercrm_credentials"
+ ) as validate:
+ validate.return_value = (True, None)
+
+ assert self.source.validate_credentials(self.config, team_id=1) == (True, None)
+ validate.assert_called_once_with("test-token")
+
+ def test_source_for_pipeline_plumbs_schema_and_manager(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "Contacts"
+ inputs.team_id = 7
+ inputs.job_id = "job-1"
+ manager = MagicMock()
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.spotlercrm.source.spotlercrm_source"
+ ) as transport:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ transport.assert_called_once_with(
+ access_token="test-token",
+ endpoint="Contacts",
+ team_id=7,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ )
+
+ def test_resumable_source_manager_bound_to_resume_config(self) -> None:
+ inputs = MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert manager._data_class is SpotlerCRMResumeConfig
+
+ def test_auth_error_from_live_api_matches_non_retryable_pattern(self) -> None:
+ # The live API answers 403 for a bad token (verified with curl); make sure the
+ # HTTPError string requests raises for it maps to a non-retryable error.
+ response = requests.Response()
+ response.status_code = 403
+ response.url = "https://apiv4.reallysimplesystems.com/accounts"
+ response.reason = "Forbidden"
+
+ with pytest.raises(requests.HTTPError) as exc_info:
+ response.raise_for_status()
+
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(pattern in str(exc_info.value) for pattern in non_retryable)
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+
+ assert set(descriptions.keys()) == set(ENDPOINTS)