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): sync checkout.com report files as tables (#78672)

jake sciotto2e16b5a95dad
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/canonical_descriptions.py
index 4567a2f6eeb5..c844ec84ed23 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/canonical_descriptions.py
@@ -1,14 +1,28 @@
"""Canonical, documentation-sourced descriptions for Checkout.com endpoints and columns.
Sourced from the official Checkout.com API reference (https://api-reference.checkout.com/).
-Keyed by the endpoint names in `checkout_com.py` `ENDPOINTS`, which match the
-`ExternalDataSchema.name` of a synced Checkout.com table. Columns absent here fall back to LLM enrichment.
+Keyed by the schema names `get_schemas` returns: the endpoint names in `checkout_com.py`
+`ENDPOINTS`, plus the reports tables from `reports.py` (`reports` and the per-type
+`{type}_report` tables). Report file columns are account-configurable, so `{type}_report`
+entries only describe the injected metadata columns; the rest fall back to LLM enrichment.
"""
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
+# Every `{type}_report` table carries these columns, injected from the report listing
+# alongside the report file's own columns.
+_REPORT_ROWS_METADATA_COLUMNS: dict[str, str] = {
+ "report_id": "Identifier of the generated report this row was parsed from.",
+ "report_created_on": "Time at which the report was generated. Used as the incremental sync cursor.",
+ "report_from": "Start of the date range the report covers.",
+ "report_to": "End of the date range the report covers.",
+ "report_entity_id": "Identifier of the entity the report belongs to.",
+ "file_id": "Identifier of the report file this row was parsed from.",
+ "file_row_index": "Position of this row within the report file.",
+}
+
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"disputes": {
"description": "A dispute (chargeback) raised by a cardholder against a Checkout.com payment.",
@@ -30,4 +44,91 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"evidence_required_by": "Deadline by which evidence must be submitted.",
},
},
+ "reports": {
+ "description": "A report generated for your account via the Checkout.com Reports API, with the files it contains.",
+ "docs_url": "https://api-reference.checkout.com/#tag/Reports",
+ "columns": {
+ "id": "Unique identifier for the report.",
+ "created_on": "Time at which the report was generated.",
+ "last_modified_on": "Time at which the report was last modified.",
+ "type": "Type of the report (e.g. FinancialActions).",
+ "description": "Description of the report.",
+ "account": "Account the report belongs to (client and entity identifiers).",
+ "tags": "Tags associated with the report.",
+ "from": "Start of the date range the report covers.",
+ "to": "End of the date range the report covers.",
+ "files": "Files the report contains (identifier, filename, format).",
+ },
+ },
+ "financial_actions_report": {
+ "description": "Rows parsed from generated Financial Actions report files: one row per financial action (captures, refunds, chargebacks, fees) with processing and payout details.",
+ "docs_url": "https://www.checkout.com/docs/business-operations/retrieve-reports",
+ "columns": _REPORT_ROWS_METADATA_COLUMNS,
+ },
+ "payments": {
+ "description": "A payment request processed through Checkout.com, approved or declined.",
+ "docs_url": "https://api-reference.checkout.com/#tag/Payments",
+ "columns": {
+ "id": "Unique identifier for the payment.",
+ "requested_on": "Time at which the payment was requested. Used as the incremental sync cursor.",
+ "amount": "Payment amount, in the smallest currency unit.",
+ "currency": "Three-letter ISO currency code of the payment.",
+ "approved": "Whether the payment was approved.",
+ "status": "Current status of the payment (e.g. Authorized, Captured, Declined).",
+ "reference": "Your reference for the payment.",
+ "description": "Description of the payment.",
+ "payment_type": "Type of the payment (e.g. Regular, Recurring).",
+ "source": "Payment source details (instrument identifier, type, card metadata).",
+ "customer": "Customer associated with the payment (identifier, email, name).",
+ "processing": "Processing details such as acquirer identifiers.",
+ "metadata": "Custom key-value pairs attached to the payment.",
+ },
+ },
+ "payment_actions": {
+ "description": "An action taken on a payment: authorization, capture, refund, void or similar, with its outcome.",
+ "docs_url": "https://api-reference.checkout.com/#operation/getPaymentActions",
+ "columns": {
+ "id": "Unique identifier for the action.",
+ "type": "Type of the action (e.g. Authorization, Capture, Refund, Void).",
+ "processed_on": "Time at which the action was processed.",
+ "amount": "Action amount, in the smallest currency unit.",
+ "approved": "Whether the action was approved.",
+ "auth_code": "Authorization code returned by the issuer.",
+ "response_code": "Gateway response code for the action.",
+ "response_summary": "Human-readable summary of the gateway response.",
+ "reference": "Your reference for the action.",
+ "payment_id": "Identifier of the payment this action belongs to.",
+ "payment_requested_on": "Request time of the parent payment. Used as the incremental sync cursor.",
+ },
+ },
+ "customers": {
+ "description": "A customer record referenced by your payments.",
+ "docs_url": "https://api-reference.checkout.com/#tag/Customers",
+ "columns": {
+ "id": "Unique identifier for the customer.",
+ "email": "Email address of the customer.",
+ "name": "Name of the customer.",
+ "phone": "Phone number of the customer.",
+ "metadata": "Custom key-value pairs attached to the customer.",
+ "instruments": "Payment instruments stored for the customer.",
+ "payment_requested_on": "Request time of the payment that referenced this customer. Used as the incremental sync cursor.",
+ },
+ },
+ "instruments": {
+ "description": "A stored payment instrument (e.g. a saved card) referenced by your payments.",
+ "docs_url": "https://api-reference.checkout.com/#tag/Instruments",
+ "columns": {
+ "id": "Unique identifier for the instrument.",
+ "type": "Type of the instrument (e.g. card).",
+ "fingerprint": "Token that uniquely identifies the underlying card across instruments.",
+ "expiry_month": "Expiry month of the card.",
+ "expiry_year": "Expiry year of the card.",
+ "scheme": "Card scheme (e.g. Visa, Mastercard).",
+ "last4": "Last four digits of the card number.",
+ "bin": "Bank identification number of the card.",
+ "issuer": "Issuing bank of the card.",
+ "issuer_country": "Country of the issuing bank.",
+ "payment_requested_on": "Request time of the payment that referenced this instrument. Used as the incremental sync cursor.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/checkout_com.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/checkout_com.py
index 3709c43008ae..8612d7d61b80 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/checkout_com.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/checkout_com.py
@@ -25,16 +25,29 @@ CHECKOUT_HOSTS = {
# Disputes list pages cap at 250.
PAGE_SIZE = 250
-# Checkout.com has no list-all-payments endpoint — bulk payment data only
-# exists via report files. Disputes are the one honest list surface.
+# Checkout.com has no list-all-payments endpoint; disputes are the one API list
+# surface. Bulk payment data ships as generated report files, handled in reports.py.
ENDPOINTS = ("disputes",)
@dataclasses.dataclass
class CheckoutComResumeConfig:
+ """Checkpoint for whichever endpoint the running job syncs.
+
+ One dataclass covers disputes and the report tables because a job only ever
+ syncs one schema, so the unused fields simply stay at their defaults.
+ """
+
# Disputes paginate with limit/skip; static params are rebuilt from job
# inputs on resume.
- skip: int
+ skip: int = 0
+ # Report tables checkpoint the last fully-yielded report, so a resume
+ # fast-forwards the listing and skips what already synced.
+ report_created_on: str | None = None
+ report_id: str | None = None
+ # Payments-search tables checkpoint the end of the last fully-processed
+ # search window, which becomes the next attempt's range start.
+ search_window_to: str | None = None
def _hosts(environment: str) -> dict[str, str]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/payments.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/payments.py
new file mode 100644
index 000000000000..0a1f98401434
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/payments.py
@@ -0,0 +1,372 @@
+"""Checkout.com payments, payment actions, customers and instruments.
+
+Bulk payment objects come from ``POST /payments/search`` (the one server-side
+listing surface; ``GET /payments`` only looks up by reference). The search
+request supports ``query``, ``from``/``to`` and ``limit`` (max 1000) but no
+documented page cursor, so listing walks the time range and recursively splits
+any window that fills a whole page; a window returning fewer than ``limit``
+rows is provably complete.
+
+``payment_actions``, ``customers`` and ``instruments`` have no listing
+endpoints at all, so their syncs walk the same payment windows and fan out to
+``GET /payments/{id}/actions``, ``GET /customers/{id}`` and
+``GET /instruments/{id}`` for the ids those payments reference.
+"""
+
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.checkout_com import (
+ CheckoutComResumeConfig,
+ _format_timestamp,
+ _hosts,
+ _make_auth,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.reports import (
+ _make_api_session,
+ _strip_links,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import OAuth2Auth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+
+PAYMENTS_ENDPOINTS = ("payments", "payment_actions", "customers", "instruments")
+
+# The search endpoint caps `limit` at 1000.
+SEARCH_PAGE_LIMIT = 1000
+REQUEST_TIMEOUT_SECONDS = 120
+# How far back the first (non-incremental) sync reaches when no start date is configured.
+DEFAULT_BACKFILL_DAYS = 365
+# A window that still fills a whole page at this span can't be split further; anything
+# past it is yielded with an error log rather than silently truncated.
+MIN_WINDOW = timedelta(seconds=1)
+# Bound one sync's API usage: searches are one call per ~1000 payments, fan-out lookups
+# are one call per payment/customer/instrument. A capped run stops after the last fully
+# processed window, so the next run continues from its watermark.
+MAX_SEARCH_REQUESTS_PER_SYNC = 2_000
+MAX_FANOUT_LOOKUPS_PER_SYNC = 10_000
+FANOUT_CHUNK_SIZE = 500
+
+
+class _SyncBudget:
+ """Counts API calls for one sync and says when to stop cleanly."""
+
+ def __init__(self, searches: int, lookups: int) -> None:
+ self.searches_left = searches
+ self.lookups_left = lookups
+ self.exhausted = False
+
+
[email protected](frozen=True, kw_only=True)
+class _Window:
+ start: datetime
+ end: datetime
+
+
+def _to_datetime(value: Any) -> datetime | None:
+ """Coerce a stored watermark or configured start date (datetime, date or ISO string) into UTC."""
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ try:
+ parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)
+
+
+def _resolve_start(
+ start_date: Optional[str],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ resume_window_to: Optional[str],
+ now: datetime,
+) -> datetime:
+ # A resume checkpoint is always at or past the incremental watermark, so it wins.
+ resumed = _to_datetime(resume_window_to)
+ if resumed is not None:
+ return resumed
+ if should_use_incremental_field:
+ watermark = _to_datetime(db_incremental_field_last_value)
+ if watermark is not None:
+ return watermark
+ configured = _to_datetime(start_date) if start_date else None
+ if configured is not None:
+ return configured
+ return now - timedelta(days=DEFAULT_BACKFILL_DAYS)
+
+
+def _search_payments(
+ session: requests.Session,
+ auth: OAuth2Auth,
+ api_base: str,
+ window: _Window,
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ body = {
+ "from": _format_timestamp(window.start),
+ "to": _format_timestamp(window.end),
+ "limit": SEARCH_PAGE_LIMIT,
+ }
+ response = session.post(f"{api_base}/payments/search", json=body, auth=auth, timeout=REQUEST_TIMEOUT_SECONDS)
+ if not response.ok:
+ logger.error(f"Checkout.com API error: status={response.status_code}, url={api_base}/payments/search")
+ response.raise_for_status()
+ payload = response.json()
+ data = payload.get("data") if isinstance(payload, dict) else None
+ if not isinstance(data, list):
+ return []
+ return [payment for payment in data if isinstance(payment, dict)]
+
+
+def _iter_payment_windows(
+ session: requests.Session,
+ auth: OAuth2Auth,
+ api_base: str,
+ window: _Window,
+ logger: FilteringBoundLogger,
+ budget: _SyncBudget,
+) -> Iterator[tuple[_Window, list[dict[str, Any]]]]:
+ """Yield ascending, provably complete windows of payments.
+
+ A page holding exactly ``SEARCH_PAGE_LIMIT`` rows may have dropped results, so
+ that window is split in half and re-queried (left half first, preserving
+ ascending order) until it fits in one page or reaches ``MIN_WINDOW``.
+ """
+ if window.end <= window.start:
+ return
+ if budget.searches_left <= 0:
+ budget.exhausted = True
+ return
+ budget.searches_left -= 1
+
+ payments = _search_payments(session, auth, api_base, window, logger)
+ if len(payments) < SEARCH_PAGE_LIMIT or (window.end - window.start) <= MIN_WINDOW:
+ if len(payments) >= SEARCH_PAGE_LIMIT:
+ logger.error(
+ "Checkout.com payments window is full at the minimum span; some payments in it may be missing",
+ window_start=_format_timestamp(window.start),
+ window_end=_format_timestamp(window.end),
+ )
+ payments.sort(key=lambda payment: (str(payment.get("requested_on") or ""), str(payment.get("id") or "")))
+ yield window, payments
+ return
+
+ middle = window.start + (window.end - window.start) / 2
+ yield from _iter_payment_windows(session, auth, api_base, _Window(start=window.start, end=middle), logger, budget)
+ yield from _iter_payment_windows(session, auth, api_base, _Window(start=middle, end=window.end), logger, budget)
+
+
+def _fanout_get(
+ session: requests.Session,
+ auth: OAuth2Auth,
+ url: str,
+ logger: FilteringBoundLogger,
+) -> Optional[dict[str, Any] | list[Any]]:
+ """One fan-out GET; a 404 means the record no longer exists and is skipped."""
+ response = session.get(url, auth=auth, timeout=REQUEST_TIMEOUT_SECONDS)
+ if response.status_code == 404:
+ return None
+ if not response.ok:
+ logger.error(f"Checkout.com API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+ payload = response.json()
+ return payload if isinstance(payload, dict | list) else None
+
+
+def _extract_action_items(payload: dict[str, Any] | list[Any] | None) -> list[dict[str, Any]]:
+ # The SDKs model the actions response as an `items` wrapper; accept a bare array
+ # and a `data` wrapper too so a representation change doesn't zero the table.
+ if isinstance(payload, list):
+ items: Any = payload
+ elif isinstance(payload, dict):
+ items = payload.get("items") if isinstance(payload.get("items"), list) else payload.get("data")
+ else:
+ items = None
+ if not isinstance(items, list):
+ return []
+ return [item for item in items if isinstance(item, dict)]
+
+
+def _payment_actions_rows(
+ session: requests.Session,
+ auth: OAuth2Auth,
+ api_base: str,
+ payment: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ payment_id = str(payment.get("id") or "")
+ payload = _fanout_get(session, auth, f"{api_base}/payments/{payment_id}/actions", logger)
+ rows = []
+ for action in _extract_action_items(payload):
+ row = _strip_links(action)
+ # The parent payment's id and request time key the row to its payment and
+ # carry the incremental watermark; they always win over same-named fields.
+ row["payment_id"] = payment_id
+ row["payment_requested_on"] = payment.get("requested_on")
+ rows.append(row)
+ return rows
+
+
+def _referenced_id(payment: dict[str, Any], endpoint: str) -> Optional[str]:
+ if endpoint == "customers":
+ customer = payment.get("customer")
+ raw = customer.get("id") if isinstance(customer, dict) else None
+ prefix = "cus_"
+ else:
+ source = payment.get("source")
+ raw = source.get("id") if isinstance(source, dict) else None
+ prefix = "src_"
+ value = str(raw or "")
+ # Only vault-stored records are fetchable; other source ids (tokens, one-off
+ # payment methods) have no GET endpoint.
+ return value if value.startswith(prefix) else None
+
+
+def _referenced_record_row(
+ session: requests.Session,
+ auth: OAuth2Auth,
+ api_base: str,
+ endpoint: str,
+ record_id: str,
+ payment: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> Optional[dict[str, Any]]:
+ payload = _fanout_get(session, auth, f"{api_base}/{endpoint}/{record_id}", logger)
+ if not isinstance(payload, dict):
+ return None
+ row = _strip_links(payload)
+ row["payment_requested_on"] = payment.get("requested_on")
+ return row
+
+
+def _get_rows(
+ environment: str,
+ client_id: str,
+ client_secret: str,
+ schema_name: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CheckoutComResumeConfig],
+ start_date: Optional[str],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+) -> Iterator[list[dict[str, Any]]]:
+ hosts = _hosts(environment)
+ auth = _make_auth(environment, client_id, client_secret)
+ session = _make_api_session(client_secret)
+ budget = _SyncBudget(searches=MAX_SEARCH_REQUESTS_PER_SYNC, lookups=MAX_FANOUT_LOOKUPS_PER_SYNC)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ now = datetime.now(UTC)
+ start = _resolve_start(
+ start_date,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ resume.search_window_to if resume is not None else None,
+ now,
+ )
+
+ seen_ids: set[str] = set()
+ chunk: list[dict[str, Any]] = []
+ for window, payments in _iter_payment_windows(
+ session, auth, hosts["api"], _Window(start=start, end=now), logger, budget
+ ):
+ for payment in payments:
+ if schema_name == "payments":
+ chunk.append(_strip_links(payment))
+ elif schema_name == "payment_actions":
+ if not str(payment.get("id") or ""):
+ continue
+ if budget.lookups_left <= 0:
+ budget.exhausted = True
+ break
+ budget.lookups_left -= 1
+ chunk.extend(_payment_actions_rows(session, auth, hosts["api"], payment, logger))
+ else:
+ record_id = _referenced_id(payment, schema_name)
+ if record_id is None or record_id in seen_ids:
+ continue
+ seen_ids.add(record_id)
+ if budget.lookups_left <= 0:
+ budget.exhausted = True
+ break
+ budget.lookups_left -= 1
+ row = _referenced_record_row(session, auth, hosts["api"], schema_name, record_id, payment, logger)
+ if row is not None:
+ chunk.append(row)
+ if len(chunk) >= FANOUT_CHUNK_SIZE:
+ yield chunk
+ chunk = []
+ if budget.exhausted:
+ # The interrupted window is not checkpointed, so the next attempt or the
+ # next scheduled sync re-covers it (merge dedupes overlapping rows).
+ break
+ resumable_source_manager.save_state(CheckoutComResumeConfig(search_window_to=_format_timestamp(window.end)))
+ if budget.exhausted:
+ logger.warning(
+ "Checkout.com sync hit its per-run API budget; continuing from the last complete window next run",
+ schema=schema_name,
+ )
+ if chunk:
+ yield chunk
+
+
+def checkout_com_payments_source(
+ environment: str,
+ client_id: str,
+ client_secret: str,
+ schema_name: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CheckoutComResumeConfig],
+ start_date: Optional[str] = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ if schema_name not in PAYMENTS_ENDPOINTS:
+ raise ValueError(f"Unknown Checkout.com schema: {schema_name}")
+
+ if schema_name == "payments":
+ primary_keys = ["id"]
+ partition_keys: Optional[list[str]] = ["requested_on"]
+ elif schema_name == "payment_actions":
+ # Action ids look globally unique, but the API doesn't document that scope,
+ # so the parent payment id is part of the key.
+ primary_keys = ["payment_id", "id"]
+ partition_keys = ["payment_requested_on"]
+ else:
+ # Customers and instruments are point lookups keyed by their own id; they
+ # carry no stable creation timestamp to partition on.
+ primary_keys = ["id"]
+ partition_keys = None
+
+ return SourceResponse(
+ name=schema_name,
+ items=lambda: _get_rows(
+ environment=environment,
+ client_id=client_id,
+ client_secret=client_secret,
+ schema_name=schema_name,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ start_date=start_date,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=primary_keys,
+ partition_count=1 if partition_keys else None,
+ partition_size=1 if partition_keys else None,
+ partition_mode="datetime" if partition_keys else None,
+ partition_format="month" if partition_keys else None,
+ partition_keys=partition_keys,
+ # Windows walk oldest-first and each window is sorted before yielding, so the
+ # watermark only moves forward.
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/reports.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/reports.py
new file mode 100644
index 000000000000..0d550d6b9046
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/reports.py
@@ -0,0 +1,457 @@
+"""Checkout.com Reports API support.
+
+Checkout.com exposes no list-all endpoint for bulk payment data; it ships as
+generated report files (CSV) retrieved via the Reports API. Two kinds of table
+come from here:
+
+- ``reports``: one row per generated report (the ``GET /reports`` listing).
+- ``{type}_report`` (e.g. ``financial_actions_report``): the parsed CSV rows of
+ every report file of that type, discovered dynamically from the account's
+ reports. Column sets vary per account because report templates are
+ configurable, so rows keep the file's own (normalized) headers plus injected
+ ``report_*`` / ``file_*`` metadata columns.
+"""
+
+import re
+import csv
+import codecs
+import contextlib
+from collections.abc import Iterable, Iterator
+from typing import Any, Optional
+from urllib.parse import parse_qs, urlparse
+
+import requests
+import structlog
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.checkout_com import (
+ CheckoutComResumeConfig,
+ _format_timestamp,
+ _hosts,
+ _make_auth,
+)
+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.auth import OAuth2Auth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+
+# The reports listing defaults to (and caps at) 100 results per page.
+REPORTS_PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 120
+# Report files can be large for high-volume merchants; give downloads more room.
+REPORT_FILE_TIMEOUT_SECONDS = 600
+# Yield parsed CSV rows in chunks rather than one list per file.
+REPORT_CHUNK_SIZE = 5000
+# Guard against a pagination loop (a next link that never advances) and bound how much
+# a single listing walks. 1000 pages is ~100k reports, centuries of daily reports; a
+# sync that hits it fails loudly rather than syncing a partial listing (see
+# CheckoutComReportsListingError).
+MAX_LIST_PAGES = 1000
+# Schema discovery runs inline on API requests, so it reads fewer pages; report types
+# repeat constantly, so the most recent pages carry every active type.
+MAX_DISCOVERY_PAGES = 10
+
+REPORTS_METADATA_ENDPOINT = "reports"
+REPORT_TABLE_SUFFIX = "_report"
+
+logger: FilteringBoundLogger = structlog.get_logger(__name__)
+
+
+class CheckoutComReportsListingError(Exception):
+ """The reports listing could not be walked to completion.
+
+ Raised before any rows are yielded: yielding a partial listing would advance the
+ incremental watermark past the reports that were never listed, permanently
+ excluding them from later syncs.
+ """
+
+
+def report_type_table_name(report_type: str) -> Optional[str]:
+ """Stable table name for an API report type, e.g. ``FinancialActions`` -> ``financial_actions_report``.
+
+ Schema names are persisted, and sync-time routing matches a stored name against the
+ types the listing returns, so this mapping must stay deterministic. Returns ``None``
+ when the type carries no usable characters.
+ """
+ spaced = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", report_type or "")
+ cleaned = re.sub(r"[^0-9a-zA-Z]+", "_", spaced).strip("_").lower()
+ if not cleaned:
+ return None
+ return f"{cleaned}{REPORT_TABLE_SUFFIX}"
+
+
+def _normalize_header(header: str) -> str:
+ """``Response Code`` becomes the stable column ``response_code``."""
+ return re.sub(r"[^0-9a-zA-Z]+", "_", header).strip("_").lower()
+
+
+def _make_api_session(client_secret: str) -> requests.Session:
+ # allow_redirects=False so the bearer token never rides a redirect to another host;
+ # the file download endpoint redirects to signed storage URLs, which are fetched
+ # with a separate credential-free session (see _open_report_file). capture=False
+ # because report bodies carry transaction identifiers, amounts and card metadata
+ # the name-based scrubbers can't recognise.
+ return make_tracked_session(redact_values=(client_secret,), allow_redirects=False, capture=False)
+
+
+def _make_file_session(signed_url: str) -> requests.Session:
+ # The signed URL's query string carries replayable download credentials (e.g.
+ # X-Amz-Signature, X-Amz-Security-Token), and the shared URL scrubber doesn't know
+ # the storage provider's parameter names, so every raw query component is redacted
+ # by value. Raw (undecoded) segments are used so the literals match the logged URL.
+ raw_query = urlparse(signed_url).query
+ redact_values = tuple(
+ {raw_query, *(segment.partition("=")[2] for segment in raw_query.split("&") if "=" in segment)} - {""}
+ )
+ return make_tracked_session(allow_redirects=True, capture=False, redact_values=redact_values)
+
+
+def _next_pagination_token(payload: dict[str, Any]) -> Optional[str]:
+ """Pull ``pagination_token`` out of ``_links.next``.
+
+ Only the token is kept; the next page is rebuilt against our own host, so a
+ tampered response can't point the authenticated request at another server.
+ """
+ links = payload.get("_links")
+ if not isinstance(links, dict):
+ return None
+ next_link = links.get("next")
+ if not isinstance(next_link, dict):
+ return None
+ href = next_link.get("href")
+ if not isinstance(href, str) or not href:
+ return None
+ values = parse_qs(urlparse(href).query).get("pagination_token")
+ return values[0] if values else None
+
+
+def _list_reports(
+ session: requests.Session,
+ auth: OAuth2Auth,
+ api_base: str,
+ logger: FilteringBoundLogger,
+ created_after: Optional[str] = None,
+ max_pages: int = MAX_LIST_PAGES,
+ raise_when_capped: bool = False,
+) -> Iterator[dict[str, Any]]:
+ params: dict[str, Any] = {"limit": REPORTS_PAGE_SIZE}
+ if created_after is not None:
+ # `created_after` is inclusive ("created on or after"), so boundary reports can
+ # reappear; callers dedupe via primary keys or a completed-report checkpoint.
+ params["created_after"] = created_after
+
+ pagination_token: Optional[str] = None
+ for _ in range(max_pages):
+ page_params = dict(params)
+ if pagination_token:
+ page_params["pagination_token"] = pagination_token
+ response = session.get(f"{api_base}/reports", params=page_params, auth=auth, timeout=REQUEST_TIMEOUT_SECONDS)
+ if not response.ok:
+ logger.error(f"Checkout.com API error: status={response.status_code}, url={api_base}/reports")
+ response.raise_for_status()
+ payload = response.json()
+ data = payload.get("data") if isinstance(payload, dict) else None
+ if not isinstance(data, list) or not data:
+ return
+ for report in data:
+ if isinstance(report, dict):
+ yield report
+ next_token = _next_pagination_token(payload)
+ if not next_token or next_token == pagination_token:
+ return
+ pagination_token = next_token
+ if raise_when_capped:
+ # Continuing with a partial listing would advance the watermark past the
+ # unlisted reports and permanently skip them.
+ raise CheckoutComReportsListingError(
+ f"Checkout.com returned more than {max_pages} pages of reports; refusing to sync a partial listing"
+ )
+ logger.warning("Checkout.com reports listing hit the page cap; not all reports were listed", max_pages=max_pages)
+
+
+def _collect_reports_ascending(
+ session: requests.Session,
+ auth: OAuth2Auth,
+ api_base: str,
+ logger: FilteringBoundLogger,
+ created_after: Optional[str],
+) -> list[dict[str, Any]]:
+ """List reports and sort them oldest-first.
+
+ The listing's order is not documented, and `sort_mode="asc"` promises the pipeline
+ an ascending incremental watermark, so ordering is enforced here. Report objects are
+ small (the file contents are fetched separately), so buffering the listing is cheap.
+ """
+ reports = list(
+ _list_reports(
+ session,
+ auth,
+ api_base,
+ logger,
+ created_after=created_after,
+ max_pages=MAX_LIST_PAGES,
+ raise_when_capped=True,
+ )
+ )
+ reports.sort(key=lambda report: (str(report.get("created_on") or ""), str(report.get("id") or "")))
+ return reports
+
+
+def _strip_links(value: Any) -> Any:
+ if isinstance(value, dict):
+ return {key: _strip_links(item) for key, item in value.items() if key != "_links"}
+ if isinstance(value, list):
+ return [_strip_links(item) for item in value]
+ return value
+
+
+def _open_report_file(
+ api_session: requests.Session,
+ auth: OAuth2Auth,
+ api_base: str,
+ report_id: str,
+ file_id: str,
+) -> Iterator[requests.Response]:
+ """Open a streaming response for one report file.
+
+ ``GET /reports/{id}/files/{file_id}`` redirects to a signed storage URL. The
+ redirect is followed manually with a credential-free session so the bearer token
+ is only ever sent to the Checkout.com API host; the session is built per URL so
+ its redaction set covers that URL's signing parameters (see _make_file_session).
+ """
+ response = api_session.get(
+ f"{api_base}/reports/{report_id}/files/{file_id}",
+ auth=auth,
+ stream=True,
+ timeout=REPORT_FILE_TIMEOUT_SECONDS,
+ )
+ try:
+ if response.status_code in (301, 302, 303, 307, 308):
+ location = response.headers.get("Location")
+ if not location or not location.startswith("https://"):
+ raise ValueError(f"Checkout.com file download for {file_id} redirected without an https location")
+ download = _make_file_session(location).get(location, stream=True, timeout=REPORT_FILE_TIMEOUT_SECONDS)
+ else:
+ download = response
+ try:
+ if not download.ok:
+ download.raise_for_status()
+ yield download
+ finally:
+ if download is not response:
+ download.close()
+ finally:
+ response.close()
+
+
+def _parse_report_file_rows(
+ lines: Iterable[str],
+ metadata: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> Iterator[dict[str, Any]]:
+ # `lines` is any iterator of physical CSV lines (a live response stream or a
+ # StringIO), so a large report is parsed row-by-row without buffering the file.
+ reader = csv.reader(lines)
+ headers: Optional[list[str]] = None
+ row_index = 0
+ for row in reader:
+ if headers is None:
+ headers = [_normalize_header(header) for header in row]
+ continue
+ if not any(cell.strip() for cell in row):
+ continue
+ # zip would silently truncate a short row and misalign columns, corrupting the
+ # data; skip the malformed line instead so the failure is visible.
+ if len(row) != len(headers):
+ logger.warning(
+ "Checkout.com report row length mismatch; skipping row",
+ expected=len(headers),
+ got=len(row),
+ report_id=metadata.get("report_id"),
+ file_id=metadata.get("file_id"),
+ )
+ continue
+ parsed: dict[str, Any] = dict(zip(headers, row))
+ # The injected metadata columns carry the dedupe key and incremental watermark,
+ # so they always win over a same-named column in the CSV itself.
+ parsed.update(metadata)
+ parsed["file_row_index"] = row_index
+ row_index += 1
+ yield parsed
+
+
+def _report_metadata_rows(reports: list[dict[str, Any]]) -> Iterator[list[dict[str, Any]]]:
+ # `_links` hrefs carry pagination and signed-download URLs; they're transport
+ # details, not data, so keep them out of the warehouse.
+ rows = [_strip_links(report) for report in reports]
+ if rows:
+ yield rows
+
+
+def _report_file_rows(
+ reports: list[dict[str, Any]],
+ api_session: requests.Session,
+ auth: OAuth2Auth,
+ api_base: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CheckoutComResumeConfig],
+ completed_report_id: Optional[str],
+) -> Iterator[list[dict[str, Any]]]:
+ for report in reports:
+ report_id = str(report.get("id") or "")
+ if not report_id or report_id == completed_report_id:
+ continue
+ created_on = str(report.get("created_on") or "")
+ raw_account = report.get("account")
+ account: dict[str, Any] = raw_account if isinstance(raw_account, dict) else {}
+ chunk: list[dict[str, Any]] = []
+ for file in report.get("files") or []:
+ if not isinstance(file, dict):
+ continue
+ file_id = str(file.get("id") or "")
+ file_format = str(file.get("format") or "")
+ if not file_id:
+ continue
+ if file_format.upper() != "CSV":
+ logger.warning(
+ "Checkout.com report file is not CSV; skipping file",
+ report_id=report_id,
+ file_id=file_id,
+ format=file_format,
+ )
+ continue
+ metadata = {
+ "report_id": report_id,
+ "report_created_on": created_on,
+ "report_from": report.get("from"),
+ "report_to": report.get("to"),
+ "report_entity_id": account.get("entity_id"),
+ "file_id": file_id,
+ }
+ with _open_report_file(api_session, auth, api_base, report_id, file_id) as download:
+ # Decode compression on the fly and read physical lines off the socket so
+ # quoted multi-line CSV fields survive (unlike `iter_lines`, which strips
+ # the terminators csv needs).
+ download.raw.decode_content = True
+ lines = codecs.getreader("utf-8")(download.raw)
+ for parsed in _parse_report_file_rows(lines, metadata, logger):
+ chunk.append(parsed)
+ if len(chunk) >= REPORT_CHUNK_SIZE:
+ yield chunk
+ chunk = []
+ if chunk:
+ yield chunk
+ # Checkpoint after the report's files are fully yielded, so a crash re-yields the
+ # in-progress report (merge dedupes on file_id + file_row_index) rather than
+ # skipping it. `created_on` is stored verbatim because it goes straight back into
+ # the API's own `created_after` filter on resume.
+ resumable_source_manager.save_state(CheckoutComResumeConfig(report_created_on=created_on, report_id=report_id))
+
+
+def discover_report_types(environment: str, client_id: str, client_secret: str) -> dict[str, str]:
+ """Map table name -> report type for the report types visible to these credentials.
+
+ Used by ``get_schemas``, which runs inline on API requests, so the listing is
+ bounded to the most recent pages. Raises on any API failure; the caller degrades
+ to the static schema catalog.
+ """
+ hosts = _hosts(environment)
+ auth = _make_auth(environment, client_id, client_secret)
+ session = _make_api_session(client_secret)
+ discovered: dict[str, str] = {}
+ for report in _list_reports(session, auth, hosts["api"], logger, max_pages=MAX_DISCOVERY_PAGES):
+ report_type = str(report.get("type") or "")
+ table_name = report_type_table_name(report_type)
+ if table_name is not None and table_name != REPORTS_METADATA_ENDPOINT and table_name not in discovered:
+ discovered[table_name] = report_type
+ return discovered
+
+
+def _get_rows(
+ environment: str,
+ client_id: str,
+ client_secret: str,
+ schema_name: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CheckoutComResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+) -> Iterator[list[dict[str, Any]]]:
+ hosts = _hosts(environment)
+ auth = _make_auth(environment, client_id, client_secret)
+ api_session = _make_api_session(client_secret)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ created_after: Optional[str] = None
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ created_after = _format_timestamp(db_incremental_field_last_value)
+ completed_report_id: Optional[str] = None
+ if resume is not None and resume.report_created_on:
+ # The checkpoint is always at or past the incremental watermark, so it wins.
+ created_after = resume.report_created_on
+ completed_report_id = resume.report_id
+
+ reports = _collect_reports_ascending(api_session, auth, hosts["api"], logger, created_after)
+
+ if schema_name == REPORTS_METADATA_ENDPOINT:
+ yield from _report_metadata_rows(reports)
+ return
+
+ matching = [report for report in reports if report_type_table_name(str(report.get("type") or "")) == schema_name]
+ yield from _report_file_rows(
+ matching,
+ api_session,
+ auth,
+ hosts["api"],
+ logger,
+ resumable_source_manager,
+ completed_report_id,
+ )
+
+
+def checkout_com_reports_source(
+ environment: str,
+ client_id: str,
+ client_secret: str,
+ schema_name: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CheckoutComResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ if schema_name != REPORTS_METADATA_ENDPOINT and not schema_name.endswith(REPORT_TABLE_SUFFIX):
+ raise ValueError(f"Unknown Checkout.com schema: {schema_name}")
+
+ if schema_name == REPORTS_METADATA_ENDPOINT:
+ primary_keys = ["id"]
+ partition_keys = ["created_on"]
+ else:
+ # Report templates are account-configurable, so CSV columns carry no reliable
+ # natural key; a file's contents are immutable once generated, so the position
+ # within the file is a stable synthetic key.
+ primary_keys = ["file_id", "file_row_index"]
+ partition_keys = ["report_created_on"]
+
+ return SourceResponse(
+ name=schema_name,
+ items=lambda: _get_rows(
+ environment=environment,
+ client_id=client_id,
+ client_secret=client_secret,
+ schema_name=schema_name,
+ 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=primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=partition_keys,
+ # Reports are sorted oldest-first before yielding, so the watermark only moves forward.
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/source.py
index 5c7dfb41697b..637eb3d328b8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/source.py
@@ -1,5 +1,7 @@
from typing import Optional, cast
+import structlog
+
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
@@ -17,6 +19,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_c
checkout_com_source,
validate_credentials as validate_checkout_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.payments import (
+ PAYMENTS_ENDPOINTS,
+ checkout_com_payments_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.reports import (
+ REPORTS_METADATA_ENDPOINT,
+ checkout_com_reports_source,
+ discover_report_types,
+)
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,
@@ -29,6 +40,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
SourceSchema,
build_endpoint_schemas,
+ incremental_field,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.checkoutcom import (
@@ -36,6 +48,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
)
from products.warehouse_sources.backend.types import ExternalDataSourceType, IncrementalField, IncrementalFieldType
+logger = structlog.get_logger(__name__)
+
_DISPUTES_INCREMENTAL_FIELDS: list[IncrementalField] = [
{
"label": "last_update",
@@ -45,10 +59,33 @@ _DISPUTES_INCREMENTAL_FIELDS: list[IncrementalField] = [
},
]
+# The reports listing filters server-side on `created_after`.
+_REPORTS_INCREMENTAL_FIELDS: list[IncrementalField] = [incremental_field("created_on")]
+_REPORT_ROWS_INCREMENTAL_FIELDS: list[IncrementalField] = [incremental_field("report_created_on")]
+
+# Payments search filters server-side on `from`/`to` over the payment request time;
+# the fan-out tables inherit that cursor through the payment that references them.
+_PAYMENTS_INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "payments": [incremental_field("requested_on")],
+ "payment_actions": [incremental_field("payment_requested_on")],
+ "customers": [incremental_field("payment_requested_on")],
+ "instruments": [incremental_field("payment_requested_on")],
+}
+
+_PAYMENTS_ENDPOINT_DESCRIPTIONS: dict[str, str] = {
+ "payments": "Payment requests (approved and declined) from the payments search API.",
+ "payment_actions": "Authorization, capture, refund and void actions for each payment.",
+ "customers": "Customer records referenced by your payments.",
+ "instruments": "Stored payment instruments referenced by your payments.",
+}
+
@SourceRegistry.register
class CheckoutComSource(ResumableSource[CheckoutComSourceConfig, CheckoutComResumeConfig]):
- lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ # The catalog listed without credentials is the static part (disputes + reports);
+ # the per-report-type tables need credentials to discover, so `get_schemas` only
+ # reaches the API when the config carries real keys.
+ lists_tables_without_credentials = True
api_docs_url = "https://api-reference.checkout.com/"
@@ -57,13 +94,35 @@ class CheckoutComSource(ResumableSource[CheckoutComSourceConfig, CheckoutComResu
return ExternalDataSourceType.CHECKOUTCOM
def get_non_retryable_errors(self) -> dict[str, str | None]:
- return {
+ # The 403 matches are path-qualified so an expired signed storage URL (a different
+ # host) stays retryable, and so each endpoint gets the right scope hint. Action
+ # lookups match on `/payments/pay_` because `/payments` alone would also match
+ # the search path.
+ errors: dict[str, str | None] = {
# Permanent token-exchange failures (invalid_client, bad request, …) all carry
# the framework's stable marker; transient 429/5xx token errors don't.
OAUTH2_PERMANENT_ERROR_MARKER: "Checkout.com authentication failed. Please check your access key ID and secret (and that they match the selected environment).",
- "403 Client Error: Forbidden for url: https://api.checkout.com": "Checkout.com denied access. Please check that your access key has the disputes scope.",
- "403 Client Error: Forbidden for url: https://api.sandbox.checkout.com": "Checkout.com denied access. Please check that your access key has the disputes scope.",
}
+ for host in ("https://api.checkout.com", "https://api.sandbox.checkout.com"):
+ errors[f"403 Client Error: Forbidden for url: {host}/disputes"] = (
+ "Checkout.com denied access. Please check that your access key has the disputes scope."
+ )
+ errors[f"403 Client Error: Forbidden for url: {host}/reports"] = (
+ "Checkout.com denied access to reports. Please check that your access key has the reports scope."
+ )
+ errors[f"403 Client Error: Forbidden for url: {host}/payments/search"] = (
+ "Checkout.com denied access to payments search. Please check that your access key has the payments scope."
+ )
+ errors[f"403 Client Error: Forbidden for url: {host}/payments/pay_"] = (
+ "Checkout.com denied access to payment details. Please check that your access key has the gateway scope."
+ )
+ errors[f"403 Client Error: Forbidden for url: {host}/customers"] = (
+ "Checkout.com denied access to customers. Please check that your access key has the vault scope."
+ )
+ errors[f"403 Client Error: Forbidden for url: {host}/instruments"] = (
+ "Checkout.com denied access to instruments. Please check that your access key has the vault scope."
+ )
+ return errors
@property
def get_source_config(self) -> SourceConfig:
@@ -71,9 +130,11 @@ class CheckoutComSource(ResumableSource[CheckoutComSourceConfig, CheckoutComResu
name=SchemaExternalDataSourceType.CHECKOUT_COM,
category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
label="Checkout.com",
- caption="""Enter your Checkout.com API access keys to pull your disputes data into the PostHog Data warehouse.
+ caption="""Enter your Checkout.com API access keys to pull your payments data into the PostHog Data warehouse.
-Create an access key in the [Checkout.com dashboard](https://dashboard.checkout.com/) under Settings > Access keys with the `disputes` scope. Bulk payment data isn't listable via the API (it ships as report files), so this source currently syncs disputes.""",
+Create an access key in the [Checkout.com dashboard](https://dashboard.checkout.com/) under Settings > Access keys. Grant it the scopes for the tables you want to sync: `disputes`, `reports`, `payments` (search), `gateway` (payment actions), and `vault` (customers and instruments).
+
+Payments, payment actions, customers and instruments sync from the payments search API. Financial reporting data (financial actions, payouts, balances) syncs from your generated report files: each report type available for your account becomes a table. If no report tables show up, set up scheduled reports in your Checkout.com dashboard first.""",
iconPath="/static/services/checkout_com.png",
docsUrl="https://posthog.com/docs/cdp/sources/checkout-com",
releaseStatus=ReleaseStatus.ALPHA,
@@ -106,6 +167,14 @@ Create an access key in the [Checkout.com dashboard](https://dashboard.checkout.
placeholder="",
secret=True,
),
+ SourceFieldInputConfig(
+ name="start_date",
+ label="Start date",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="2024-01-01",
+ secret=False,
+ ),
],
),
)
@@ -126,8 +195,50 @@ Create an access key in the [Checkout.com dashboard](https://dashboard.checkout.
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # Disputes support a server-side `from` filter on last_update.
- return build_endpoint_schemas(ENDPOINTS, {"disputes": _DISPUTES_INCREMENTAL_FIELDS}, names)
+ # Disputes support a server-side `from` filter on last_update; the reports
+ # tables filter on report creation time and the payments tables on payment
+ # request time. Boundary re-reads on those inclusive range filters make append
+ # unsafe, so everything except disputes is merge-only.
+ schemas = build_endpoint_schemas(
+ (*ENDPOINTS, REPORTS_METADATA_ENDPOINT, *PAYMENTS_ENDPOINTS),
+ {
+ "disputes": _DISPUTES_INCREMENTAL_FIELDS,
+ REPORTS_METADATA_ENDPOINT: _REPORTS_INCREMENTAL_FIELDS,
+ **_PAYMENTS_INCREMENTAL_FIELDS,
+ },
+ None,
+ merge_only=(REPORTS_METADATA_ENDPOINT, *PAYMENTS_ENDPOINTS),
+ descriptions={
+ REPORTS_METADATA_ENDPOINT: "Generated report files available for your account.",
+ **_PAYMENTS_ENDPOINT_DESCRIPTIONS,
+ },
+ )
+
+ # One table per report type the account generates. Discovery needs the API, so
+ # the credential-free path (public docs, placeholder configs) stays static, and
+ # any discovery failure degrades to the static catalog instead of breaking the
+ # schema listing.
+ if config.client_id and config.client_secret:
+ try:
+ discovered = discover_report_types(config.environment, config.client_id, config.client_secret)
+ except Exception:
+ logger.exception("Checkout.com report type discovery failed", team_id=team_id)
+ discovered = {}
+ for table_name in sorted(discovered):
+ schemas.append(
+ SourceSchema(
+ name=table_name,
+ supports_incremental=True,
+ supports_append=False,
+ incremental_fields=_REPORT_ROWS_INCREMENTAL_FIELDS,
+ description=f'Rows from your generated "{discovered[table_name]}" report files.',
+ )
+ )
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [schema for schema in schemas if schema.name in names_set]
+ return schemas
def validate_credentials(
self,
@@ -150,13 +261,42 @@ Create an access key in the [Checkout.com dashboard](https://dashboard.checkout.
resumable_source_manager: ResumableSourceManager[CheckoutComResumeConfig],
inputs: SourceInputs,
) -> SourceResponse:
- return checkout_com_source(
+ if inputs.schema_name in ENDPOINTS:
+ return checkout_com_source(
+ environment=config.environment,
+ client_id=config.client_id,
+ client_secret=config.client_secret,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ 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,
+ )
+
+ if inputs.schema_name in PAYMENTS_ENDPOINTS:
+ return checkout_com_payments_source(
+ environment=config.environment,
+ client_id=config.client_id,
+ client_secret=config.client_secret,
+ schema_name=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ start_date=config.start_date,
+ 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,
+ )
+
+ return checkout_com_reports_source(
environment=config.environment,
client_id=config.client_id,
client_secret=config.client_secret,
- endpoint=inputs.schema_name,
- team_id=inputs.team_id,
- job_id=inputs.job_id,
+ schema_name=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
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_payments.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_payments.py
new file mode 100644
index 000000000000..386c1adb1393
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_payments.py
@@ -0,0 +1,389 @@
+from typing import Any, Optional
+
+import pytest
+from freezegun import freeze_time
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.checkout_com import (
+ CheckoutComResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.payments import (
+ checkout_com_payments_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+PAGE_LIMIT_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.payments.SEARCH_PAGE_LIMIT"
+)
+LOOKUP_BUDGET_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.payments.MAX_FANOUT_LOOKUPS_PER_SYNC"
+)
+SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.reports.make_tracked_session"
+)
+
+NOW = "2024-03-01T00:00:00Z"
+
+
+class _FakeResponse:
+ def __init__(self, status_code: int = 200, json_data: Any = None) -> None:
+ self.status_code = status_code
+ self._json_data = json_data
+
+ @property
+ def ok(self) -> bool:
+ return self.status_code < 400
+
+ def json(self) -> Any:
+ return self._json_data
+
+ def raise_for_status(self) -> None:
+ if not self.ok:
+ raise Exception(f"{self.status_code} Client Error for url")
+
+
+class _FakeSession:
+ """Replays queued search (POST) and lookup (GET) responses, recording each request."""
+
+ def __init__(
+ self,
+ search_responses: Optional[list[_FakeResponse]] = None,
+ lookup_responses: Optional[list[_FakeResponse]] = None,
+ ) -> None:
+ self._search_responses = list(search_responses or [])
+ self._lookup_responses = list(lookup_responses or [])
+ self.searches: list[dict[str, Any]] = []
+ self.lookups: list[dict[str, Any]] = []
+
+ def post(self, url: str, **kwargs: Any) -> _FakeResponse:
+ self.searches.append({"url": url, **kwargs})
+ if not self._search_responses:
+ raise AssertionError(f"unexpected search request to {url}")
+ return self._search_responses.pop(0)
+
+ def get(self, url: str, **kwargs: Any) -> _FakeResponse:
+ self.lookups.append({"url": url, **kwargs})
+ if not self._lookup_responses:
+ raise AssertionError(f"unexpected lookup request to {url}")
+ return self._lookup_responses.pop(0)
+
+
+class _FakeManager(ResumableSourceManager[CheckoutComResumeConfig]):
+ """In-memory stand-in for the Redis-backed manager (no `super().__init__`)."""
+
+ def __init__(self, resume_state: Optional[CheckoutComResumeConfig] = None) -> None:
+ self._resume_state = resume_state
+ self.saved_states: list[CheckoutComResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._resume_state is not None
+
+ def load_state(self) -> Optional[CheckoutComResumeConfig]:
+ return self._resume_state
+
+ def save_state(self, data: CheckoutComResumeConfig) -> None:
+ self.saved_states.append(data)
+
+
+def _payment(
+ payment_id: str,
+ requested_on: str,
+ customer_id: Optional[str] = None,
+ source_id: Optional[str] = None,
+) -> dict[str, Any]:
+ payment: dict[str, Any] = {
+ "id": payment_id,
+ "requested_on": requested_on,
+ "amount": 1000,
+ "currency": "USD",
+ "approved": True,
+ "status": "Captured",
+ "_links": {"self": {"href": f"https://api.checkout.com/payments/{payment_id}"}},
+ }
+ if customer_id is not None:
+ payment["customer"] = {"id": customer_id, "email": "[email protected]"}
+ if source_id is not None:
+ payment["source"] = {"id": source_id, "type": "card"}
+ return payment
+
+
+def _search_page(payments: list[dict[str, Any]]) -> _FakeResponse:
+ return _FakeResponse(json_data={"total_count": len(payments), "data": payments})
+
+
+def _rows(source_response) -> list[dict[str, Any]]:
+ return [row for chunk in source_response.items() for row in chunk]
+
+
+def _source(
+ schema_name: str,
+ manager: Optional[_FakeManager] = None,
+ start_date: Optional[str] = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+):
+ return checkout_com_payments_source(
+ environment="production",
+ client_id="ack_id",
+ client_secret="secret",
+ schema_name=schema_name,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager or _FakeManager(),
+ start_date=start_date,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+
+
+@freeze_time(NOW)
+class TestPaymentsWindowWalking:
+ @mock.patch(PAGE_LIMIT_PATCH, 2)
+ @mock.patch(SESSION_PATCH)
+ def test_full_page_subdivides_window_and_yields_ascending(self, mock_make_session):
+ # The full-range page comes back full (== limit), so the range splits in half;
+ # each half fits in one page and is provably complete.
+ session = _FakeSession(
+ search_responses=[
+ _search_page(
+ [
+ _payment("pay_2", "2024-02-29T18:00:00Z"),
+ _payment("pay_1", "2024-02-29T06:00:00Z"),
+ ]
+ ),
+ _search_page([_payment("pay_1", "2024-02-29T06:00:00Z")]),
+ _search_page([_payment("pay_2", "2024-02-29T18:00:00Z")]),
+ ]
+ )
+ mock_make_session.side_effect = [session]
+ manager = _FakeManager()
+
+ rows = _rows(_source("payments", manager=manager, start_date="2024-02-29"))
+
+ assert [row["id"] for row in rows] == ["pay_1", "pay_2"]
+ assert all("_links" not in row for row in rows)
+ assert [(s["json"]["from"], s["json"]["to"]) for s in session.searches] == [
+ ("2024-02-29T00:00:00Z", "2024-03-01T00:00:00Z"),
+ ("2024-02-29T00:00:00Z", "2024-02-29T12:00:00Z"),
+ ("2024-02-29T12:00:00Z", "2024-03-01T00:00:00Z"),
+ ]
+ assert all(s["json"]["limit"] == 2 and s["auth"] is not None for s in session.searches)
+ # Each completed window checkpoints its end, ascending.
+ assert [state.search_window_to for state in manager.saved_states] == [
+ "2024-02-29T12:00:00Z",
+ "2024-03-01T00:00:00Z",
+ ]
+
+ @pytest.mark.parametrize(
+ "start_date, should_use_incremental_field, last_value, expected_from",
+ [
+ (None, False, None, "2023-03-02T00:00:00Z"),
+ ("2024-01-01", False, None, "2024-01-01T00:00:00Z"),
+ ("2024-01-01", True, "2024-02-01T00:00:00Z", "2024-02-01T00:00:00Z"),
+ ],
+ )
+ @mock.patch(SESSION_PATCH)
+ def test_range_start_resolution(
+ self, mock_make_session, start_date, should_use_incremental_field, last_value, expected_from
+ ):
+ session = _FakeSession(search_responses=[_search_page([])])
+ mock_make_session.side_effect = [session]
+
+ rows = _rows(
+ _source(
+ "payments",
+ start_date=start_date,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ )
+ )
+
+ assert rows == []
+ assert session.searches[0]["json"]["from"] == expected_from
+ assert session.searches[0]["json"]["to"] == NOW
+
+ @mock.patch(SESSION_PATCH)
+ def test_resume_checkpoint_wins_over_watermark(self, mock_make_session):
+ session = _FakeSession(search_responses=[_search_page([])])
+ mock_make_session.side_effect = [session]
+ manager = _FakeManager(CheckoutComResumeConfig(search_window_to="2024-02-15T00:00:00Z"))
+
+ _rows(
+ _source(
+ "payments",
+ manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-02-01T00:00:00Z",
+ )
+ )
+
+ assert session.searches[0]["json"]["from"] == "2024-02-15T00:00:00Z"
+
+ @mock.patch(PAGE_LIMIT_PATCH, 1)
+ @mock.patch(SESSION_PATCH)
+ def test_full_page_at_minimum_window_yields_with_error(self, mock_make_session):
+ # One-second range that still fills a page: subdivision can't go further, so the
+ # window yields what it has and the truncation is loud instead of silent.
+ session = _FakeSession(search_responses=[_search_page([_payment("pay_1", "2024-02-29T23:59:59Z")])])
+ mock_make_session.side_effect = [session]
+ logger = mock.MagicMock()
+
+ response = checkout_com_payments_source(
+ environment="production",
+ client_id="ack_id",
+ client_secret="secret",
+ schema_name="payments",
+ logger=logger,
+ resumable_source_manager=_FakeManager(),
+ start_date="2024-02-29T23:59:59Z",
+ )
+ rows = _rows(response)
+
+ assert [row["id"] for row in rows] == ["pay_1"]
+ assert len(session.searches) == 1
+ logger.error.assert_called_once()
+
+
+@freeze_time(NOW)
+class TestPaymentActionsFanout:
+ @pytest.mark.parametrize(
+ "actions_payload",
+ [
+ {"items": [{"id": "act_1", "type": "Capture", "response_code": "10000"}]},
+ [{"id": "act_1", "type": "Capture", "response_code": "10000"}],
+ {"data": [{"id": "act_1", "type": "Capture", "response_code": "10000"}]},
+ ],
+ )
+ @mock.patch(SESSION_PATCH)
+ def test_fetches_actions_per_payment_and_tolerates_wrapper_shapes(self, mock_make_session, actions_payload):
+ session = _FakeSession(
+ search_responses=[_search_page([_payment("pay_1", "2024-02-29T06:00:00Z")])],
+ lookup_responses=[_FakeResponse(json_data=actions_payload)],
+ )
+ mock_make_session.side_effect = [session]
+
+ rows = _rows(_source("payment_actions"))
+
+ assert rows == [
+ {
+ "id": "act_1",
+ "type": "Capture",
+ "response_code": "10000",
+ "payment_id": "pay_1",
+ "payment_requested_on": "2024-02-29T06:00:00Z",
+ }
+ ]
+ assert session.lookups == [
+ {
+ "url": "https://api.checkout.com/payments/pay_1/actions",
+ "auth": mock.ANY,
+ "timeout": mock.ANY,
+ }
+ ]
+
+ @mock.patch(LOOKUP_BUDGET_PATCH, 1)
+ @mock.patch(SESSION_PATCH)
+ def test_lookup_budget_stops_cleanly_without_checkpointing(self, mock_make_session):
+ session = _FakeSession(
+ search_responses=[
+ _search_page(
+ [
+ _payment("pay_1", "2024-02-29T06:00:00Z"),
+ _payment("pay_2", "2024-02-29T18:00:00Z"),
+ ]
+ )
+ ],
+ lookup_responses=[_FakeResponse(json_data={"items": [{"id": "act_1"}]})],
+ )
+ mock_make_session.side_effect = [session]
+ manager = _FakeManager()
+ logger = mock.MagicMock()
+
+ response = checkout_com_payments_source(
+ environment="production",
+ client_id="ack_id",
+ client_secret="secret",
+ schema_name="payment_actions",
+ logger=logger,
+ resumable_source_manager=manager,
+ )
+ rows = _rows(response)
+
+ # Only the budgeted lookup ran, the interrupted window is not checkpointed (the
+ # next run re-covers it), and the stop is loud.
+ assert [row["id"] for row in rows] == ["act_1"]
+ assert len(session.lookups) == 1
+ assert manager.saved_states == []
+ logger.warning.assert_called_once()
+
+
+@freeze_time(NOW)
+class TestReferencedRecordFanout:
+ @pytest.mark.parametrize(
+ "schema_name, record_id, url",
+ [
+ ("customers", "cus_1", "https://api.checkout.com/customers/cus_1"),
+ ("instruments", "src_1", "https://api.checkout.com/instruments/src_1"),
+ ],
+ )
+ @mock.patch(SESSION_PATCH)
+ def test_fetches_each_referenced_record_once(self, mock_make_session, schema_name, record_id, url):
+ # Two payments reference the same record; a third has no fetchable reference
+ # (a one-off token is not a vault instrument, a missing customer is skipped).
+ payments = [
+ _payment("pay_1", "2024-02-29T06:00:00Z", customer_id="cus_1", source_id="src_1"),
+ _payment("pay_2", "2024-02-29T07:00:00Z", customer_id="cus_1", source_id="src_1"),
+ _payment("pay_3", "2024-02-29T08:00:00Z", source_id="tok_1"),
+ ]
+ session = _FakeSession(
+ search_responses=[_search_page(payments)],
+ lookup_responses=[_FakeResponse(json_data={"id": record_id, "_links": {}})],
+ )
+ mock_make_session.side_effect = [session]
+
+ rows = _rows(_source(schema_name))
+
+ assert rows == [{"id": record_id, "payment_requested_on": "2024-02-29T06:00:00Z"}]
+ assert [lookup["url"] for lookup in session.lookups] == [url]
+
+ @mock.patch(SESSION_PATCH)
+ def test_deleted_record_is_skipped_and_sync_continues(self, mock_make_session):
+ payments = [
+ _payment("pay_1", "2024-02-29T06:00:00Z", customer_id="cus_gone"),
+ _payment("pay_2", "2024-02-29T07:00:00Z", customer_id="cus_2"),
+ ]
+ session = _FakeSession(
+ search_responses=[_search_page(payments)],
+ lookup_responses=[_FakeResponse(status_code=404), _FakeResponse(json_data={"id": "cus_2"})],
+ )
+ mock_make_session.side_effect = [session]
+ manager = _FakeManager()
+
+ rows = _rows(_source("customers", manager=manager))
+
+ assert [row["id"] for row in rows] == ["cus_2"]
+ # A deleted record doesn't fail the window; it still checkpoints.
+ assert [state.search_window_to for state in manager.saved_states] == [NOW]
+
+
+class TestCheckoutComPaymentsSourceResponse:
+ @pytest.mark.parametrize(
+ "schema_name, primary_keys, partition_keys",
+ [
+ ("payments", ["id"], ["requested_on"]),
+ ("payment_actions", ["payment_id", "id"], ["payment_requested_on"]),
+ ("customers", ["id"], None),
+ ("instruments", ["id"], None),
+ ],
+ )
+ def test_response_metadata(self, schema_name, primary_keys, partition_keys):
+ response = _source(schema_name)
+
+ assert response.name == schema_name
+ assert response.primary_keys == primary_keys
+ assert response.partition_keys == partition_keys
+ # Windows walk oldest-first, so ascending watermark commits are safe.
+ assert response.sort_mode == "asc"
+
+ def test_unknown_schema_raises(self):
+ with pytest.raises(ValueError):
+ _source("nope")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_reports.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_reports.py
new file mode 100644
index 000000000000..15cf2cf405d6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_reports.py
@@ -0,0 +1,490 @@
+import io
+from datetime import UTC, datetime
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.checkout_com import (
+ CheckoutComResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.reports import (
+ MAX_DISCOVERY_PAGES,
+ CheckoutComReportsListingError,
+ _parse_report_file_rows,
+ checkout_com_reports_source,
+ discover_report_types,
+ report_type_table_name,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.reports.make_tracked_session"
+)
+
+
+class _FakeRaw:
+ """Stand-in for `response.raw`: a readable byte stream the file path streams CSV off."""
+
+ def __init__(self, data: bytes) -> None:
+ self._buffer = io.BytesIO(data)
+ self.decode_content = False
+
+ def read(self, *args: Any, **kwargs: Any) -> bytes:
+ return self._buffer.read(*args, **kwargs)
+
+ def readable(self) -> bool:
+ return True
+
+
+class _FakeResponse:
+ def __init__(
+ self,
+ status_code: int = 200,
+ json_data: Optional[dict[str, Any]] = None,
+ text: str = "",
+ headers: Optional[dict[str, str]] = None,
+ ) -> None:
+ self.status_code = status_code
+ self._json_data = json_data if json_data is not None else {}
+ self.raw = _FakeRaw(text.encode())
+ self.headers = headers or {}
+ self.closed = False
+
+ @property
+ def ok(self) -> bool:
+ return self.status_code < 400
+
+ def json(self) -> dict[str, Any]:
+ return self._json_data
+
+ def raise_for_status(self) -> None:
+ if not self.ok:
+ raise Exception(f"{self.status_code} Client Error for url")
+
+ def close(self) -> None:
+ self.closed = True
+
+
+class _FakeSession:
+ """Replays a queued list of responses and records each request's URL and kwargs."""
+
+ def __init__(self, responses: Optional[list[_FakeResponse]] = None) -> None:
+ self._responses = list(responses or [])
+ self.requests: list[dict[str, Any]] = []
+
+ def get(self, url: str, **kwargs: Any) -> _FakeResponse:
+ self.requests.append({"url": url, **kwargs})
+ if not self._responses:
+ raise AssertionError(f"unexpected request to {url}")
+ return self._responses.pop(0)
+
+
+class _FakeManager(ResumableSourceManager[CheckoutComResumeConfig]):
+ """In-memory stand-in for the Redis-backed manager (no `super().__init__`)."""
+
+ def __init__(self, resume_state: Optional[CheckoutComResumeConfig] = None) -> None:
+ self._resume_state = resume_state
+ self.saved_states: list[CheckoutComResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._resume_state is not None
+
+ def load_state(self) -> Optional[CheckoutComResumeConfig]:
+ return self._resume_state
+
+ def save_state(self, data: CheckoutComResumeConfig) -> None:
+ self.saved_states.append(data)
+
+
+def _report(
+ report_id: str,
+ created_on: str,
+ report_type: str = "FinancialActions",
+ files: Optional[list[dict[str, Any]]] = None,
+) -> dict[str, Any]:
+ return {
+ "id": report_id,
+ "created_on": created_on,
+ "last_modified_on": created_on,
+ "type": report_type,
+ "description": "Financial Actions by Payout ID",
+ "account": {"client_id": "cli_1", "entity_id": "ent_1"},
+ "tags": [],
+ "from": "2024-01-01T00:00:00Z",
+ "to": "2024-01-02T00:00:00Z",
+ "files": files if files is not None else [],
+ "_links": {"self": {"href": f"https://api.checkout.com/reports/{report_id}"}},
+ }
+
+
+def _csv_file(file_id: str) -> dict[str, Any]:
+ return {
+ "id": file_id,
+ "filename": f"{file_id}.csv",
+ "format": "CSV",
+ "_links": {"self": {"href": f"https://api.checkout.com/files/{file_id}"}},
+ }
+
+
+def _listing(reports: list[dict[str, Any]], next_token: Optional[str] = None) -> _FakeResponse:
+ links: dict[str, Any] = {"self": {"href": "https://api.checkout.com/reports"}}
+ if next_token:
+ links["next"] = {"href": f"https://api.checkout.com/reports?pagination_token={next_token}"}
+ return _FakeResponse(json_data={"count": len(reports), "limit": 100, "data": reports, "_links": links})
+
+
+def _rows(source_response) -> list[dict[str, Any]]:
+ return [row for chunk in source_response.items() for row in chunk]
+
+
+def _source(
+ schema_name: str,
+ manager: Optional[_FakeManager] = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+):
+ return checkout_com_reports_source(
+ environment="production",
+ client_id="ack_id",
+ client_secret="secret",
+ schema_name=schema_name,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager or _FakeManager(),
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+
+
+class TestReportTypeTableName:
+ @pytest.mark.parametrize(
+ "report_type, expected",
+ [
+ ("FinancialActions", "financial_actions_report"),
+ ("Financial Actions", "financial_actions_report"),
+ ("Payments", "payments_report"),
+ ("Balances", "balances_report"),
+ ("", None),
+ ("!!!", None),
+ ],
+ )
+ def test_maps_api_types_to_stable_table_names(self, report_type, expected):
+ assert report_type_table_name(report_type) == expected
+
+
+class TestParseReportFileRows:
+ def test_parses_rows_with_metadata_and_skips_malformed_lines(self):
+ text = "Action ID,Payment ID,Report ID\nact_1,pay_1,csv_value\n\nact_2,pay_2\nact_3,pay_3,csv_value\n"
+ logger = mock.MagicMock()
+ metadata = {"report_id": "rpt_1", "file_id": "file_1"}
+
+ rows = list(_parse_report_file_rows(io.StringIO(text), metadata, logger))
+
+ assert rows == [
+ # The CSV's own `Report ID` column loses to the injected metadata, which
+ # carries the dedupe key.
+ {
+ "action_id": "act_1",
+ "payment_id": "pay_1",
+ "report_id": "rpt_1",
+ "file_id": "file_1",
+ "file_row_index": 0,
+ },
+ {
+ "action_id": "act_3",
+ "payment_id": "pay_3",
+ "report_id": "rpt_1",
+ "file_id": "file_1",
+ "file_row_index": 1,
+ },
+ ]
+ logger.warning.assert_called_once()
+
+ def test_empty_file_yields_nothing(self):
+ assert list(_parse_report_file_rows(io.StringIO(""), {}, mock.MagicMock())) == []
+
+
+class TestReportsMetadataTable:
+ @mock.patch(SESSION_PATCH)
+ def test_paginates_sorts_ascending_and_strips_links(self, mock_make_session):
+ # Pages arrive newest-first to prove the source re-sorts before yielding.
+ api_session = _FakeSession(
+ [
+ _listing([_report("rpt_2", "2024-02-01T00:00:00Z")], next_token="tok_1"),
+ _listing([_report("rpt_1", "2024-01-01T00:00:00Z")]),
+ ]
+ )
+ mock_make_session.side_effect = [api_session]
+
+ rows = _rows(_source("reports"))
+
+ assert [row["id"] for row in rows] == ["rpt_1", "rpt_2"]
+ assert api_session.requests[1]["params"]["pagination_token"] == "tok_1"
+ assert all("_links" not in row for row in rows)
+ assert all(kwargs.get("auth") is not None for kwargs in api_session.requests)
+
+ @mock.patch(SESSION_PATCH)
+ def test_missing_data_key_yields_nothing(self, mock_make_session):
+ api_session = _FakeSession([_FakeResponse(json_data={"count": 0})])
+ mock_make_session.side_effect = [api_session]
+
+ assert _rows(_source("reports")) == []
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.reports.MAX_LIST_PAGES", 2
+ )
+ @mock.patch(SESSION_PATCH)
+ def test_sync_fails_loudly_when_listing_exceeds_page_cap(self, mock_make_session):
+ api_session = _FakeSession(
+ [_listing([_report(f"rpt_{page}", "2024-01-01T00:00:00Z")], next_token=f"tok_{page}") for page in range(3)]
+ )
+ mock_make_session.side_effect = [api_session]
+ manager = _FakeManager()
+
+ # A partial listing must not produce rows: yielding would advance the
+ # incremental watermark past the reports that were never listed.
+ with pytest.raises(CheckoutComReportsListingError):
+ _rows(_source("reports", manager=manager))
+ assert manager.saved_states == []
+
+
+class TestReportFileSync:
+ @mock.patch(SESSION_PATCH)
+ def test_syncs_matching_reports_and_follows_redirect_without_credentials(self, mock_make_session):
+ csv_text = 'Action ID,Amount\nact_1,"multi\nline"\nact_2,20\n'
+ api_session = _FakeSession(
+ [
+ _listing(
+ [
+ _report("rpt_other", "2024-01-01T00:00:00Z", report_type="Payments"),
+ _report(
+ "rpt_1",
+ "2024-02-01T00:00:00Z",
+ files=[
+ _csv_file("file_1"),
+ {"id": "file_2", "filename": "file_2.xlsx", "format": "XLSX"},
+ ],
+ ),
+ ]
+ ),
+ _FakeResponse(
+ status_code=302,
+ headers={
+ "Location": "https://files.example.com/signed?X-Amz-Credential=AKIA%2F1&X-Amz-Signature=sig123"
+ },
+ ),
+ ]
+ )
+ file_session = _FakeSession([_FakeResponse(text=csv_text)])
+ mock_make_session.side_effect = [api_session, file_session]
+ manager = _FakeManager()
+ logger = mock.MagicMock()
+
+ response = checkout_com_reports_source(
+ environment="production",
+ client_id="ack_id",
+ client_secret="secret",
+ schema_name="financial_actions_report",
+ logger=logger,
+ resumable_source_manager=manager,
+ )
+ rows = _rows(response)
+
+ assert rows == [
+ {
+ "action_id": "act_1",
+ "amount": "multi\nline",
+ "report_id": "rpt_1",
+ "report_created_on": "2024-02-01T00:00:00Z",
+ "report_from": "2024-01-01T00:00:00Z",
+ "report_to": "2024-01-02T00:00:00Z",
+ "report_entity_id": "ent_1",
+ "file_id": "file_1",
+ "file_row_index": 0,
+ },
+ {
+ "action_id": "act_2",
+ "amount": "20",
+ "report_id": "rpt_1",
+ "report_created_on": "2024-02-01T00:00:00Z",
+ "report_from": "2024-01-01T00:00:00Z",
+ "report_to": "2024-01-02T00:00:00Z",
+ "report_entity_id": "ent_1",
+ "file_id": "file_1",
+ "file_row_index": 1,
+ },
+ ]
+ # The bearer-authenticated session never follows the redirect; the signed
+ # storage URL is fetched by a separate session with no credentials attached.
+ file_request = api_session.requests[1]
+ assert file_request["url"] == "https://api.checkout.com/reports/rpt_1/files/file_1"
+ assert file_request["auth"] is not None
+ assert file_request["stream"] is True
+ assert file_session.requests == [
+ {
+ "url": "https://files.example.com/signed?X-Amz-Credential=AKIA%2F1&X-Amz-Signature=sig123",
+ "stream": True,
+ "timeout": mock.ANY,
+ }
+ ]
+ # The signed URL's raw query values are in the file session's redaction set, so
+ # the replayable download credentials never appear in request logs.
+ file_session_redactions = mock_make_session.call_args_list[1].kwargs["redact_values"]
+ assert "sig123" in file_session_redactions
+ assert "AKIA%2F1" in file_session_redactions
+ # The XLSX file is skipped with a warning, and the report checkpoints once
+ # after its files are fully yielded.
+ logger.warning.assert_called_once()
+ assert manager.saved_states == [
+ CheckoutComResumeConfig(report_created_on="2024-02-01T00:00:00Z", report_id="rpt_1")
+ ]
+
+ @mock.patch(SESSION_PATCH)
+ def test_direct_file_response_without_redirect_parses(self, mock_make_session):
+ api_session = _FakeSession(
+ [
+ _listing([_report("rpt_1", "2024-02-01T00:00:00Z", files=[_csv_file("file_1")])]),
+ _FakeResponse(text="Action ID\nact_1\n"),
+ ]
+ )
+ mock_make_session.side_effect = [api_session]
+
+ rows = _rows(_source("financial_actions_report"))
+
+ assert [row["action_id"] for row in rows] == ["act_1"]
+ # No redirect means no separate download session is ever built.
+ assert mock_make_session.call_count == 1
+
+ @pytest.mark.parametrize("location", [None, "http://files.example.com/signed"])
+ @mock.patch(SESSION_PATCH)
+ def test_non_https_redirect_location_raises(self, mock_make_session, location):
+ headers = {"Location": location} if location else {}
+ api_session = _FakeSession(
+ [
+ _listing([_report("rpt_1", "2024-02-01T00:00:00Z", files=[_csv_file("file_1")])]),
+ _FakeResponse(status_code=302, headers=headers),
+ ]
+ )
+ mock_make_session.side_effect = [api_session]
+
+ with pytest.raises(ValueError):
+ _rows(_source("financial_actions_report"))
+
+ @pytest.mark.parametrize(
+ "should_use_incremental_field, last_value, expected",
+ [
+ (True, datetime(2024, 1, 2, tzinfo=UTC), "2024-01-02T00:00:00Z"),
+ (True, None, None),
+ (False, datetime(2024, 1, 2, tzinfo=UTC), None),
+ ],
+ )
+ @mock.patch(SESSION_PATCH)
+ def test_incremental_watermark_becomes_created_after(
+ self, mock_make_session, should_use_incremental_field, last_value, expected
+ ):
+ api_session = _FakeSession([_listing([])])
+ mock_make_session.side_effect = [api_session]
+
+ _rows(
+ _source(
+ "financial_actions_report",
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ )
+ )
+
+ assert api_session.requests[0]["params"].get("created_after") == expected
+
+ @mock.patch(SESSION_PATCH)
+ def test_resume_fast_forwards_listing_and_skips_completed_report(self, mock_make_session):
+ api_session = _FakeSession(
+ [
+ _listing(
+ [
+ _report("rpt_done", "2024-02-01T00:00:00Z", files=[_csv_file("file_done")]),
+ _report("rpt_next", "2024-02-02T00:00:00Z", files=[_csv_file("file_next")]),
+ ]
+ ),
+ _FakeResponse(text="Action ID\nact_9\n"),
+ ]
+ )
+ mock_make_session.side_effect = [api_session]
+ manager = _FakeManager(CheckoutComResumeConfig(report_created_on="2024-02-01T00:00:00Z", report_id="rpt_done"))
+
+ rows = _rows(
+ _source(
+ "financial_actions_report",
+ manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ )
+ )
+
+ # The checkpoint wins over the older incremental watermark, and the already
+ # completed boundary report is not re-downloaded.
+ assert api_session.requests[0]["params"]["created_after"] == "2024-02-01T00:00:00Z"
+ assert [row["report_id"] for row in rows] == ["rpt_next"]
+ assert manager.saved_states == [
+ CheckoutComResumeConfig(report_created_on="2024-02-02T00:00:00Z", report_id="rpt_next")
+ ]
+
+
+class TestDiscoverReportTypes:
+ @mock.patch(SESSION_PATCH)
+ def test_dedupes_types_and_skips_unusable_ones(self, mock_make_session):
+ api_session = _FakeSession(
+ [
+ _listing(
+ [
+ _report("rpt_1", "2024-01-01T00:00:00Z", report_type="FinancialActions"),
+ _report("rpt_2", "2024-01-02T00:00:00Z", report_type="FinancialActions"),
+ _report("rpt_3", "2024-01-03T00:00:00Z", report_type="Payments"),
+ _report("rpt_4", "2024-01-04T00:00:00Z", report_type=""),
+ ]
+ )
+ ]
+ )
+ mock_make_session.side_effect = [api_session]
+
+ assert discover_report_types("production", "ack_id", "secret") == {
+ "financial_actions_report": "FinancialActions",
+ "payments_report": "Payments",
+ }
+
+ @mock.patch(SESSION_PATCH)
+ def test_discovery_is_bounded_to_max_pages(self, mock_make_session):
+ api_session = _FakeSession(
+ [
+ _listing([_report(f"rpt_{page}", "2024-01-01T00:00:00Z")], next_token=f"tok_{page}")
+ for page in range(MAX_DISCOVERY_PAGES + 5)
+ ]
+ )
+ mock_make_session.side_effect = [api_session]
+
+ discover_report_types("production", "ack_id", "secret")
+
+ assert len(api_session.requests) == MAX_DISCOVERY_PAGES
+
+
+class TestCheckoutComReportsSourceResponse:
+ @pytest.mark.parametrize(
+ "schema_name, primary_keys, partition_keys",
+ [
+ ("reports", ["id"], ["created_on"]),
+ ("financial_actions_report", ["file_id", "file_row_index"], ["report_created_on"]),
+ ],
+ )
+ def test_response_metadata(self, schema_name, primary_keys, partition_keys):
+ response = _source(schema_name)
+
+ assert response.name == schema_name
+ assert response.primary_keys == primary_keys
+ assert response.partition_keys == partition_keys
+ assert response.partition_mode == "datetime"
+ # Reports are re-sorted oldest-first before yielding, so ascending watermark
+ # commits are safe.
+ assert response.sort_mode == "asc"
+
+ def test_unknown_schema_raises(self):
+ with pytest.raises(ValueError):
+ _source("nope")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_source.py
index e983f3d82f53..c036c1d93fc7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_source.py
@@ -16,6 +16,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+DISCOVER_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.source.discover_report_types"
+)
+_STATIC_SCHEMAS = ["disputes", "reports", "payments", "payment_actions", "customers", "instruments"]
+
class TestCheckoutComSource:
def setup_method(self):
@@ -36,7 +41,7 @@ class TestCheckoutComSource:
assert config.iconPath == "/static/services/checkout_com.png"
field_names = [f.name for f in config.fields]
- assert field_names == ["environment", "client_id", "client_secret"]
+ assert field_names == ["environment", "client_id", "client_secret", "start_date"]
def test_environment_field_is_a_select_with_default(self):
config = self.source.get_source_config
@@ -61,6 +66,8 @@ class TestCheckoutComSource:
f"HTTP 401 from the OAuth2 token endpoint: invalid_client {OAUTH2_PERMANENT_ERROR_MARKER}",
f"HTTP 400 from the OAuth2 token endpoint {OAUTH2_PERMANENT_ERROR_MARKER}",
"403 Client Error: Forbidden for url: https://api.checkout.com/disputes?limit=250",
+ "403 Client Error: Forbidden for url: https://api.checkout.com/reports?limit=100",
+ "403 Client Error: Forbidden for url: https://api.sandbox.checkout.com/reports/rpt_1/files/file_1",
],
)
def test_non_retryable_errors_match_auth_failures(self, observed_error):
@@ -75,21 +82,79 @@ class TestCheckoutComSource:
"401 Client Error: Unauthorized for url: https://api.checkout.com/disputes",
# Transient token-endpoint errors (429/5xx) carry no marker and stay retryable.
"HTTP 429 from the OAuth2 token endpoint",
+ # An expired signed report-file URL is a different host and must stay retryable.
+ "403 Client Error: Forbidden for url: https://checkout-reports.s3.amazonaws.com/file_1",
],
)
def test_non_retryable_errors_does_not_match_unrelated(self, other_error):
non_retryable_errors = self.source.get_non_retryable_errors()
assert not any(key in other_error for key in non_retryable_errors)
- def test_get_schemas(self):
+ @mock.patch(DISCOVER_PATCH)
+ def test_get_schemas_static_catalog(self, mock_discover):
+ mock_discover.return_value = {}
+
schemas = self.source.get_schemas(self.config, self.team_id)
- assert [s.name for s in schemas] == ["disputes"]
+ assert [s.name for s in schemas] == _STATIC_SCHEMAS
assert all(schema.supports_incremental for schema in schemas)
- assert [f["field"] for f in schemas[0].incremental_fields] == ["last_update"]
+ cursors = {s.name: [f["field"] for f in s.incremental_fields] for s in schemas}
+ assert cursors == {
+ "disputes": ["last_update"],
+ "reports": ["created_on"],
+ "payments": ["requested_on"],
+ "payment_actions": ["payment_requested_on"],
+ "customers": ["payment_requested_on"],
+ "instruments": ["payment_requested_on"],
+ }
+
+ @mock.patch(DISCOVER_PATCH)
+ def test_get_schemas_appends_discovered_report_tables(self, mock_discover):
+ mock_discover.return_value = {"payments_report": "Payments", "financial_actions_report": "FinancialActions"}
+
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert [s.name for s in schemas] == [*_STATIC_SCHEMAS, "financial_actions_report", "payments_report"]
+ report_table = next(s for s in schemas if s.name == "financial_actions_report")
+ assert report_table.supports_incremental is True
+ # Boundary re-reads on the inclusive `created_after` filter make append unsafe.
+ assert report_table.supports_append is False
+ assert [f["field"] for f in report_table.incremental_fields] == ["report_created_on"]
+ mock_discover.assert_called_once_with("production", "ack_id", "secret")
+
+ @mock.patch(DISCOVER_PATCH)
+ def test_get_schemas_without_credentials_never_discovers(self, mock_discover):
+ config = CheckoutComSourceConfig(environment="production", client_id="", client_secret="")
+
+ schemas = self.source.get_schemas(config, self.team_id)
+
+ # The credential-free path serves public docs and placeholder configs, so it
+ # must never reach the API.
+ mock_discover.assert_not_called()
+ assert [s.name for s in schemas] == _STATIC_SCHEMAS
+
+ @mock.patch(DISCOVER_PATCH)
+ def test_get_schemas_discovery_failure_degrades_to_static(self, mock_discover):
+ mock_discover.side_effect = Exception("boom")
+
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert [s.name for s in schemas] == _STATIC_SCHEMAS
+
+ @pytest.mark.parametrize(
+ "names, expected",
+ [
+ (["nope"], []),
+ (["financial_actions_report"], ["financial_actions_report"]),
+ ],
+ )
+ @mock.patch(DISCOVER_PATCH)
+ def test_get_schemas_names_filter_spans_static_and_discovered(self, mock_discover, names, expected):
+ mock_discover.return_value = {"financial_actions_report": "FinancialActions"}
+
+ schemas = self.source.get_schemas(self.config, self.team_id, names=names)
- def test_get_schemas_filtered_unknown_name_returns_empty(self):
- assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+ assert [s.name for s in schemas] == expected
@pytest.mark.parametrize(
"mock_return, expected_valid, expected_message",
@@ -153,3 +218,51 @@ class TestCheckoutComSource:
self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
assert mock_co_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ @pytest.mark.parametrize("schema_name", ["reports", "financial_actions_report"])
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.source.checkout_com_reports_source"
+ )
+ def test_source_for_pipeline_routes_report_schemas(self, mock_reports_source, schema_name):
+ inputs = mock.MagicMock()
+ inputs.schema_name = schema_name
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_reports_source.assert_called_once()
+ kwargs = mock_reports_source.call_args.kwargs
+ assert kwargs["environment"] == "production"
+ assert kwargs["client_id"] == "ack_id"
+ assert kwargs["client_secret"] == "secret"
+ assert kwargs["schema_name"] == schema_name
+ assert kwargs["logger"] is inputs.logger
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05Z"
+
+ @pytest.mark.parametrize("schema_name", ["payments", "payment_actions", "customers", "instruments"])
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.source.checkout_com_payments_source"
+ )
+ def test_source_for_pipeline_routes_payments_schemas(self, mock_payments_source, schema_name):
+ config = CheckoutComSourceConfig(
+ environment="production", client_id="ack_id", client_secret="secret", start_date="2024-01-01"
+ )
+ inputs = mock.MagicMock()
+ inputs.schema_name = schema_name
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(config, manager, inputs)
+
+ mock_payments_source.assert_called_once()
+ kwargs = mock_payments_source.call_args.kwargs
+ assert kwargs["schema_name"] == schema_name
+ assert kwargs["start_date"] == "2024-01-01"
+ assert kwargs["logger"] is inputs.logger
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05Z"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/checkoutcom.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/checkoutcom.py
index 32774383d6ae..2573dbaabdf8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/checkoutcom.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/checkoutcom.py
@@ -11,3 +11,4 @@ class CheckoutComSourceConfig(config.Config):
client_id: str
client_secret: str
environment: Literal["production", "sandbox"] = config.value(default="production")
+ start_date: str | None = None