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 square import source (#61164)

Tom Owers648e8a8da029
diff --git a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr
index 4d81dc6a2021..800a3fff4b5e 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr
+++ b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr
@@ -1122,7 +1122,7 @@
WHERE and(equals(s.team_id, 99999), greaterOrEquals(s.min_first_timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')), globalIn(s.session_id,
(SELECT nullIf(nullIf(events.`$session_id`, ''), 'null') AS session_id
FROM events
- WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), equals(events.mat_pp_email, 'bla'), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))
+ WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'email'), ''), 'null'), '^"|"$', ''), 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))
GROUP BY nullIf(nullIf(events.`$session_id`, ''), 'null')
HAVING 1
ORDER BY min(toTimeZone(events.timestamp, 'UTC')) DESC
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 7eb5d1b6e80c..bb9239e62071 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -97,6 +97,7 @@ the row lists both.
| slack | HTTP | requests + `rest_source.RESTClient` | ✅ |
| snapchat_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
| snowflake | DB protocol | snowflake-connector-python | ➖ |
+| square | HTTP | requests | ✅ |
| stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| supabase | DB protocol | psycopg (delegates to PostgresSource) | ➖ |
| surveymonkey | HTTP | requests | ✅ |
@@ -210,7 +211,7 @@ doesn't conflict with concurrent PRs.
- sftp
- sharepoint
- smartsheet
-- square
+- surveymonkey
- trello
- twilio
- twitter_ads
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index f1a49d8b3d2c..aa226d7ddbb5 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -800,7 +800,8 @@ class SnowflakeSourceConfig(config.Config):
@config.config
class SquareSourceConfig(config.Config):
- pass
+ access_token: str
+ environment: Literal["production", "sandbox"] = config.value(default="production")
@config.config
diff --git a/posthog/temporal/data_imports/sources/square/settings.py b/posthog/temporal/data_imports/sources/square/settings.py
new file mode 100644
index 000000000000..de14735296f5
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/square/settings.py
@@ -0,0 +1,107 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class SquareEndpointConfig:
+ name: str
+ path: str
+ # Top-level key in the JSON response that holds the list of rows
+ # (e.g. `{"payments": [...]}` -> `"payments"`). Catalog uses `"objects"`.
+ data_key: str
+ primary_keys: list[str]
+ incremental_fields: list[IncrementalField]
+ # Stable datetime field used for partitioning. Must never change for a row
+ # (so `created_at`, never `updated_at`). `None` disables partitioning.
+ partition_key: Optional[str] = None
+ # Name of the server-side timestamp filter query param (e.g. `begin_time`).
+ # Only set when the API genuinely filters on it — this is what enables
+ # incremental sync. `None` => full refresh only.
+ time_filter_param: Optional[str] = None
+ # Whether the endpoint uses cursor pagination. `/v2/locations` returns every
+ # row in a single response with no cursor.
+ paginated: bool = True
+ # Static query params applied to every request (sort order, catalog types, ...).
+ extra_params: dict[str, str] = field(default_factory=dict)
+
+
+def _created_at_incremental_field() -> list[IncrementalField]:
+ return [
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
+
+
+# Endpoints are deliberately limited to the GET, cursor-paginated resources that
+# work with a single Personal Access Token and no per-location fan-out. Orders,
+# Invoices, Inventory and Team members all require POST `/search` calls scoped to
+# `location_ids`, so they're intentionally left out of this alpha implementation.
+SQUARE_ENDPOINTS: dict[str, SquareEndpointConfig] = {
+ # Payments and Refunds expose `begin_time`, a server-side filter on `created_at`,
+ # so they support incremental sync. Square sorts these DESC by default; we force
+ # ASC so the pipeline's cursor watermark advances correctly.
+ "payments": SquareEndpointConfig(
+ name="payments",
+ path="/v2/payments",
+ data_key="payments",
+ primary_keys=["id"],
+ partition_key="created_at",
+ time_filter_param="begin_time",
+ incremental_fields=_created_at_incremental_field(),
+ extra_params={"sort_order": "ASC"},
+ ),
+ "refunds": SquareEndpointConfig(
+ name="refunds",
+ path="/v2/refunds",
+ data_key="refunds",
+ primary_keys=["id"],
+ partition_key="created_at",
+ time_filter_param="begin_time",
+ incremental_fields=_created_at_incremental_field(),
+ extra_params={"sort_order": "ASC"},
+ ),
+ # `GET /v2/customers` has no server-side `created_at`/`updated_at` filter (only
+ # the POST `/v2/customers/search` endpoint does), so this is full refresh. We
+ # still sort by CREATED_AT ASC for stable pagination.
+ "customers": SquareEndpointConfig(
+ name="customers",
+ path="/v2/customers",
+ data_key="customers",
+ primary_keys=["id"],
+ partition_key="created_at",
+ incremental_fields=[],
+ extra_params={"sort_field": "CREATED_AT", "sort_order": "ASC"},
+ ),
+ # Locations returns every location in one response — no cursor, no time filter.
+ "locations": SquareEndpointConfig(
+ name="locations",
+ path="/v2/locations",
+ data_key="locations",
+ primary_keys=["id"],
+ partition_key="created_at",
+ incremental_fields=[],
+ paginated=False,
+ ),
+ # Catalog objects (items, categories, taxes, ...) only carry `updated_at`, not
+ # `created_at`, so there's no stable partition key — partitioning is disabled.
+ # `GET /v2/catalog/list` has no time filter, so it's full refresh.
+ "catalog": SquareEndpointConfig(
+ name="catalog",
+ path="/v2/catalog/list",
+ data_key="objects",
+ primary_keys=["id"],
+ incremental_fields=[],
+ ),
+}
+
+ENDPOINTS = tuple(SQUARE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in SQUARE_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/square/source.py b/posthog/temporal/data_imports/sources/square/source.py
index 1cebba76dd3c..e04f617b9e07 100644
--- a/posthog/temporal/data_imports/sources/square/source.py
+++ b/posthog/temporal/data_imports/sources/square/source.py
@@ -1,19 +1,33 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-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.generated_configs import SquareSourceConfig
+from posthog.temporal.data_imports.sources.square.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.square.square import (
+ SquareResumeConfig,
+ square_source,
+ validate_credentials as validate_square_credentials,
+)
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SquareSource(SimpleSource[SquareSourceConfig]):
+class SquareSource(ResumableSource[SquareSourceConfig, SquareResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SQUARE
@@ -23,7 +37,120 @@ class SquareSource(SimpleSource[SquareSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.SQUARE,
label="Square",
+ caption="""Enter a Square access token to pull your Square data into the PostHog Data warehouse.
+
+Create a **Personal Access Token** (or a production access token for your app) in the [Square Developer Dashboard](https://developer.squareup.com/apps).
+
+Grant these read permissions to the token for the data you want to sync:
+- `PAYMENTS_READ` (payments, refunds)
+- `CUSTOMERS_READ` (customers)
+- `MERCHANT_PROFILE_READ` (locations)
+- `ITEMS_READ` (catalog)
+""",
iconPath="/static/services/square.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/square",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_token",
+ label="Access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="EAAA...",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="environment",
+ label="Environment",
+ required=True,
+ defaultValue="production",
+ options=[
+ SourceFieldSelectConfigOption(
+ label="Production (connect.squareup.com)", value="production"
+ ),
+ SourceFieldSelectConfigOption(
+ label="Sandbox (connect.squareupsandbox.com)", value="sandbox"
+ ),
+ ],
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized": (
+ "Square rejected the access token. Generate a new token in the Square Developer "
+ "Dashboard and reconnect."
+ ),
+ "403 Client Error: Forbidden": (
+ "The Square access token is missing a required permission for this data. Grant the "
+ "relevant read scope (e.g. PAYMENTS_READ, CUSTOMERS_READ) and reconnect."
+ ),
+ }
+
+ def get_schemas(
+ self,
+ config: SquareSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,
+ supports_append=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in 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: SquareSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ is_valid, is_forbidden = validate_square_credentials(config.access_token, config.environment, schema_name)
+ if is_valid:
+ return True, None
+
+ # A 403 means the token is genuine but lacks the scope for this endpoint.
+ # Accept that at source-create (schema_name=None) — users may only grant
+ # scopes for the endpoints they intend to sync — and reject only when
+ # validating a specific schema.
+ if is_forbidden and schema_name is None:
+ return True, None
+
+ if is_forbidden:
+ return False, f"The Square access token is missing the permission required to sync '{schema_name}'"
+
+ return False, "Invalid Square access token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SquareResumeConfig]:
+ return ResumableSourceManager[SquareResumeConfig](inputs, SquareResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SquareSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SquareResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return square_source(
+ access_token=config.access_token,
+ environment=config.environment,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/posthog/temporal/data_imports/sources/square/square.py b/posthog/temporal/data_imports/sources/square/square.py
new file mode 100644
index 000000000000..afca56df66de
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/square/square.py
@@ -0,0 +1,200 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+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.square.settings import SQUARE_ENDPOINTS, SquareEndpointConfig
+
+# Square pins API behaviour to a dated version header. Bump deliberately after
+# re-reading the changelog — newer versions can reshape responses.
+SQUARE_API_VERSION = "2024-10-17"
+
+SQUARE_HOSTS = {
+ "production": "https://connect.squareup.com",
+ "sandbox": "https://connect.squareupsandbox.com",
+}
+
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class SquareRetryableError(Exception):
+ pass
+
+
+class SquareResumeConfig:
+ # The next-page pagination cursor returned by Square. Square cursors expire
+ # after ~5 minutes, so a resume that lands outside that window will re-fetch
+ # the stream from the start (merge dedupes on the primary key).
+ cursor: str
+
+
+def _base_url(environment: str) -> str:
+ return SQUARE_HOSTS.get(environment, SQUARE_HOSTS["production"])
+
+
+def _get_headers(access_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {access_token}",
+ "Square-Version": SQUARE_API_VERSION,
+ "Accept": "application/json",
+ }
+
+
+def _format_rfc3339(value: Any) -> str:
+ """Format an incremental value as the RFC 3339 timestamp Square expects."""
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%S.000Z")
+ return str(value)
+
+
+def _build_initial_params(
+ config: SquareEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, str]:
+ params: dict[str, str] = dict(config.extra_params)
+
+ if config.paginated:
+ params["limit"] = str(PAGE_SIZE)
+
+ if config.time_filter_param and should_use_incremental_field and db_incremental_field_last_value is not None:
+ params[config.time_filter_param] = _format_rfc3339(db_incremental_field_last_value)
+
+ return params
+
+
+def validate_credentials(access_token: str, environment: str, schema_name: Optional[str] = None) -> tuple[bool, bool]:
+ """Probe Square to confirm the token works.
+
+ Returns ``(is_valid, is_forbidden)``. ``is_forbidden`` distinguishes a 403
+ (valid token, missing scope) from a 401 (bad token) so the caller can accept
+ scope gaps at source-create time but reject them for a specific schema.
+ """
+ config = SQUARE_ENDPOINTS.get(schema_name) if schema_name else None
+ path = config.path if config else "/v2/locations"
+
+ # Keep the probe cheap on paginated endpoints, but never send `limit` to a
+ # non-paginated endpoint (e.g. /v2/locations) — Square may reject the unknown param.
+ params: dict[str, str] = {}
+ if config is not None and config.paginated:
+ params["limit"] = "1"
+
+ url = f"{_base_url(environment)}{path}"
+ if params:
+ url = f"{url}?{urlencode(params)}"
+
+ try:
+ response = make_tracked_session().get(url, headers=_get_headers(access_token), timeout=REQUEST_TIMEOUT_SECONDS)
+ except Exception:
+ return False, False
+
+ if response.status_code == 403:
+ return False, True
+
+ return response.status_code == 200, False
+
+
+def get_rows(
+ access_token: str,
+ environment: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SquareResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = SQUARE_ENDPOINTS[endpoint]
+ headers = _get_headers(access_token)
+ url = f"{_base_url(environment)}{config.path}"
+
+ initial_params = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor: Optional[str] = resume_config.cursor if resume_config else None
+ if cursor:
+ logger.debug(f"Square: resuming {endpoint} from saved cursor")
+
+ @retry(
+ retry=retry_if_exception_type((SquareRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch_page(params: dict[str, str]) -> dict[str, Any]:
+ response = make_tracked_session().get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise SquareRetryableError(f"Square API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Square API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ # Square encodes the original query in the cursor, so subsequent pages are
+ # requested with the cursor alone — re-sending filters/sort can error.
+ params = {"cursor": cursor} if cursor else initial_params
+ data = fetch_page(params)
+
+ items = data.get(config.data_key, [])
+ next_cursor = data.get("cursor")
+
+ if items:
+ yield items
+ # Save state only after yielding, so a crash re-yields the last batch
+ # rather than skipping it (merge dedupes on the primary key). No point
+ # persisting a cursor for non-paginated endpoints — there's nothing to
+ # resume into.
+ if config.paginated and next_cursor:
+ resumable_source_manager.save_state(SquareResumeConfig(cursor=next_cursor))
+
+ if not config.paginated or not next_cursor:
+ break
+
+ cursor = next_cursor
+
+
+def square_source(
+ access_token: str,
+ environment: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SquareResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = SQUARE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ access_token=access_token,
+ environment=environment,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ 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,
+ )
diff --git a/posthog/temporal/data_imports/sources/square/test_square.py b/posthog/temporal/data_imports/sources/square/test_square.py
new file mode 100644
index 000000000000..522a5438a955
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/square/test_square.py
@@ -0,0 +1,243 @@
+import json
+from datetime import UTC, date, datetime
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from requests import Response
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.square.settings import SQUARE_ENDPOINTS
+from posthog.temporal.data_imports.sources.square.square import (
+ SQUARE_HOSTS,
+ SquareResumeConfig,
+ _build_initial_params,
+ _format_rfc3339,
+ get_rows,
+ validate_credentials,
+)
+
+SQUARE_MODULE = "posthog.temporal.data_imports.sources.square.square"
+
+
+def _make_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 TestFormatRFC3339:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),
+ (
+ "microseconds_truncated",
+ datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC),
+ "2026-01-15T10:30:45.123Z",
+ ),
+ ("naive_assumed_utc", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),
+ ("string_passthrough", "2026-03-04T02:58:14.000Z", "2026-03-04T02:58:14.000Z"),
+ ]
+ )
+ def test_format_rfc3339(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_rfc3339(value) == expected
+
+ def test_no_plus_offset_in_output(self) -> None:
+ assert "+00:00" not in _format_rfc3339(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))
+
+
+class TestBuildInitialParams:
+ @parameterized.expand(
+ [
+ # incremental endpoint with a cursor value -> server-side begin_time filter
+ (
+ "incremental_endpoint_sets_begin_time",
+ "payments",
+ True,
+ datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ {"begin_time": "2026-03-04T02:58:14.000Z", "sort_order": "ASC", "limit": "100"},
+ [],
+ ),
+ # incremental endpoint, full refresh -> no begin_time
+ (
+ "incremental_endpoint_full_refresh_omits_begin_time",
+ "payments",
+ False,
+ None,
+ {"sort_order": "ASC"},
+ ["begin_time"],
+ ),
+ # customers has no server-side time filter, so even with an incremental
+ # value selected we must not invent a begin_time param.
+ (
+ "full_refresh_endpoint_never_sets_begin_time",
+ "customers",
+ True,
+ datetime(2026, 3, 4, tzinfo=UTC),
+ {"sort_field": "CREATED_AT"},
+ ["begin_time"],
+ ),
+ # non-paginated endpoint -> no limit param
+ (
+ "non_paginated_endpoint_omits_limit",
+ "locations",
+ False,
+ None,
+ {},
+ ["limit"],
+ ),
+ ]
+ )
+ def test_build_initial_params(
+ self,
+ _name: str,
+ endpoint: str,
+ should_use_incremental_field: bool,
+ last_value: Any,
+ expected_present: dict[str, str],
+ expected_absent: list[str],
+ ) -> None:
+ params = _build_initial_params(
+ SQUARE_ENDPOINTS[endpoint],
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ )
+ for key, value in expected_present.items():
+ assert params[key] == value
+ for key in expected_absent:
+ assert key not in params
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, (True, False)),
+ ("unauthorized", 401, (False, False)),
+ ("forbidden", 403, (False, True)),
+ ("server_error", 500, (False, False)),
+ ]
+ )
+ def test_status_code_mapping(self, _name: str, status_code: int, expected: tuple[bool, bool]) -> None:
+ with patch(f"{SQUARE_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _make_response({}, status_code=status_code)
+ assert validate_credentials("token", "production") == expected
+
+ def test_network_error_returns_invalid(self) -> None:
+ with patch(f"{SQUARE_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("token", "production") == (False, False)
+
+ def test_no_schema_probes_locations(self) -> None:
+ with patch(f"{SQUARE_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _make_response({}, status_code=200)
+ validate_credentials("token", "production")
+ url = mock_session.return_value.get.call_args.args[0]
+ assert url.startswith(f"{SQUARE_HOSTS['production']}/v2/locations")
+
+ def test_schema_probes_that_endpoint(self) -> None:
+ with patch(f"{SQUARE_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _make_response({}, status_code=200)
+ validate_credentials("token", "sandbox", schema_name="payments")
+ url = mock_session.return_value.get.call_args.args[0]
+ assert url.startswith(f"{SQUARE_HOSTS['sandbox']}/v2/payments")
+
+
+class TestGetRowsPagination:
+ def _drive(self, endpoint: str, manager: MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ """Drive get_rows with a mocked session, returning the params sent per page."""
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_get(_url: str, *, params: dict[str, Any], **_kwargs: Any) -> Response:
+ sent_params.append(dict(params or {}))
+ return next(response_iter)
+
+ with patch(f"{SQUARE_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = fake_get
+ list(
+ get_rows(
+ access_token="token",
+ environment="production",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ )
+ )
+ return sent_params
+
+ def test_fresh_run_saves_cursor_after_each_non_terminal_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_response({"payments": [{"id": "p1"}], "cursor": "cur-1"}),
+ _make_response({"payments": [{"id": "p2"}], "cursor": "cur-2"}),
+ _make_response({"payments": [{"id": "p3"}]}),
+ ]
+ sent_params = self._drive("payments", manager, responses)
+
+ # First request carries the query params; subsequent pages carry cursor only.
+ assert "cursor" not in sent_params[0]
+ assert sent_params[1] == {"cursor": "cur-1"}
+ assert sent_params[2] == {"cursor": "cur-2"}
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [SquareResumeConfig(cursor="cur-1"), SquareResumeConfig(cursor="cur-2")]
+
+ def test_resume_seeds_cursor_from_saved_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SquareResumeConfig(cursor="cur-resumed")
+
+ responses = [_make_response({"payments": [{"id": "p9"}]})]
+ sent_params = self._drive("payments", manager, responses)
+
+ assert sent_params == [{"cursor": "cur-resumed"}]
+ 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("payments", manager, [_make_response({"payments": [{"id": "only"}]})])
+ manager.save_state.assert_not_called()
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ self._drive("payments", manager, [_make_response({"payments": [{"id": "a"}]})])
+ manager.load_state.assert_not_called()
+
+ def test_non_paginated_endpoint_stops_after_one_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ # locations is non-paginated; even if Square returned a cursor we must not page.
+ sent_params = self._drive(
+ "locations", manager, [_make_response({"locations": [{"id": "L1"}], "cursor": "should-be-ignored"})]
+ )
+ assert len(sent_params) == 1
+ manager.save_state.assert_not_called()
+
+ def test_yields_rows_using_endpoint_data_key(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ response_iter = iter([_make_response({"objects": [{"id": "cat-1"}, {"id": "cat-2"}]})])
+
+ with patch(f"{SQUARE_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = lambda *a, **k: next(response_iter)
+ batches = list(
+ get_rows(
+ access_token="token",
+ environment="production",
+ endpoint="catalog",
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ )
+ )
+ assert batches == [[{"id": "cat-1"}, {"id": "cat-2"}]]
diff --git a/posthog/temporal/data_imports/sources/square/test_square_source.py b/posthog/temporal/data_imports/sources/square/test_square_source.py
new file mode 100644
index 000000000000..55954ebf4d9c
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/square/test_square_source.py
@@ -0,0 +1,143 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import SquareSourceConfig
+from posthog.temporal.data_imports.sources.square.settings import ENDPOINTS, SQUARE_ENDPOINTS
+from posthog.temporal.data_imports.sources.square.source import SquareSource
+from posthog.temporal.data_imports.sources.square.square import SquareResumeConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+INCREMENTAL_ENDPOINTS = {"payments", "refunds"}
+
+
+def _make_inputs(**overrides: Any) -> mock.MagicMock:
+ inputs = mock.MagicMock()
+ inputs.schema_name = overrides.get("schema_name", "payments")
+ inputs.should_use_incremental_field = overrides.get("should_use_incremental_field", False)
+ inputs.db_incremental_field_last_value = overrides.get("db_incremental_field_last_value", None)
+ return inputs
+
+
+class TestSquareSource:
+ def setup_method(self) -> None:
+ self.source = SquareSource()
+ self.team_id = 123
+ self.config = SquareSourceConfig(access_token="EAAA-test", environment="production")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.SQUARE
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Square"
+ assert config.label == "Square"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is not True
+ assert len(config.fields) == 2
+
+ access_token_field = config.fields[0]
+ assert isinstance(access_token_field, SourceFieldInputConfig)
+ assert access_token_field.name == "access_token"
+ assert access_token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert access_token_field.required is True
+
+ environment_field = config.fields[1]
+ assert isinstance(environment_field, SourceFieldSelectConfig)
+ assert environment_field.name == "environment"
+ assert environment_field.defaultValue == "production"
+ assert {o.value for o in environment_field.options} == {"production", "sandbox"}
+
+ def test_get_schemas_matches_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize("endpoint", sorted(SQUARE_ENDPOINTS))
+ def test_get_schemas_incremental_flags(self, endpoint: str) -> None:
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+ expected_incremental = endpoint in INCREMENTAL_ENDPOINTS
+ assert schema.supports_incremental is expected_incremental
+ assert schema.supports_append is expected_incremental
+ if expected_incremental:
+ assert [f["field"] for f in schema.incremental_fields] == ["created_at"]
+ else:
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["payments"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "payments"
+
+ def test_get_schemas_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "expected_key",
+ ["401 Client Error: Unauthorized", "403 Client Error: Forbidden"],
+ )
+ def test_non_retryable_errors(self, expected_key: str) -> None:
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ @pytest.mark.parametrize(
+ "mock_return, schema_name, expected_valid, expected_has_message",
+ [
+ ((True, False), None, True, False),
+ ((False, False), None, False, True), # 401 bad token
+ ((False, True), None, True, False), # 403 at source-create -> accepted
+ ((False, True), "payments", False, True), # 403 for a specific schema -> rejected
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.square.source.validate_square_credentials")
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ mock_return: tuple[bool, bool],
+ schema_name: str | None,
+ expected_valid: bool,
+ expected_has_message: bool,
+ ) -> None:
+ mock_validate.return_value = mock_return
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+ assert is_valid is expected_valid
+ assert (message is not None) is expected_has_message
+ mock_validate.assert_called_once_with(self.config.access_token, self.config.environment, schema_name)
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SquareResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.square.source.square_source")
+ def test_source_for_pipeline_passes_arguments(self, mock_square_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(
+ schema_name="refunds",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ )
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ _, kwargs = mock_square_source.call_args
+ assert kwargs["access_token"] == self.config.access_token
+ assert kwargs["environment"] == self.config.environment
+ assert kwargs["endpoint"] == "refunds"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+
+ @mock.patch("posthog.temporal.data_imports.sources.square.source.square_source")
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(
+ self, mock_square_source: mock.MagicMock
+ ) -> None:
+ inputs = _make_inputs(should_use_incremental_field=False, db_incremental_field_last_value="ignored")
+ self.source.source_for_pipeline(self.config, mock.MagicMock(spec=ResumableSourceManager), inputs)
+
+ _, kwargs = mock_square_source.call_args
+ assert kwargs["db_incremental_field_last_value"] is None