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(checkout_com): sync the financial actions settlement ledger (#102229)

Tom Owers246356f2593b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 6f159c01ef92..29b89af34fa3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -1443,23 +1443,23 @@ and `projects.applicationIds`.
Note: docs.checkmarx.com now redirects the API reference to Stoplight; I pulled the full operation tree from https://checkmarx.stoplight.io/api/v1/projects/cHJqOjE5ODM2OQ==/table-of-contents (project 198369) and read every GET operation from it. The gap concentration is in triage state history and the small lookup tables that decode the ids on scan_results.
-## CheckoutCom — **thin**
+## CheckoutCom — adequate
-Today (1): `disputes`
+Today (7 + one table per report type the account generates): `disputes`, `payments`, `payment_actions`, `financial_actions`, `customers`, `instruments`, `reports`
Diffed against: <https://api-reference.checkout.com/v1/swagger.yaml>
-- [ ] `POST /payments/search` — the bulk payments surface (beta, paginated) - payments are the whole point of the integration and are entirely missing (high)
-- [ ] `GET /financial-actions` — the settlement ledger: captures, refunds, chargebacks and fees per payment; reconciliation is impossible without it (high)
-- [ ] `GET /payments/{id}/actions` — per-payment action history (authorize, capture, void, refund) with response codes - the transition history behind decline analysis (high)
-- [ ] `GET /reports and GET /reports/{id}/files/{fileId}` — the settlement and payments report files Checkout.com itself points finance teams at for reconciliation (high)
+- [x] `POST /payments/search` — the bulk payments surface (beta, paginated) - payments are the whole point of the integration and are entirely missing (high)
+- [x] `GET /financial-actions` — the settlement ledger: captures, refunds, chargebacks and fees per payment; reconciliation is impossible without it (high)
+- [x] `GET /payments/{id}/actions` — per-payment action history (authorize, capture, void, refund) with response codes - the transition history behind decline analysis (high)
+- [x] `GET /reports and GET /reports/{id}/files/{fileId}` — the settlement and payments report files Checkout.com itself points finance teams at for reconciliation (high)
- [ ] `GET /balances/{id}` — per-currency-account balances for an entity, needed for payout and float reporting (medium)
- [ ] `GET /issuing/transactions` — card issuing transaction fact table for anyone using Issuing (medium)
- [ ] `GET /disputes/{dispute_id}/evidence (and /evidence/submitted, /schemefiles)` — evidence submitted per dispute; win-rate analysis needs it alongside the disputes already synced (medium)
- [ ] `GET /accounts/entities/{id}/payment-instruments and /accounts/entities/{entityId}/members` — platform sub-entity payout instruments and members, the dimension tables for marketplace reporting (low)
- [ ] `GET /forex/rates` — indicative FX rates for normalizing multi-currency volume (requires processing_channel_id and currency pairs) (low)
-Note: Official OpenAPI 3.0.1 (2.8 MB, 173 paths) is served at api-reference.checkout.com/v1/swagger.yaml. The source implementation comments that "Checkout.com has no list-all-payments endpoint - bulk payment data only exists via report files", but the current spec does expose POST /payments/search (beta, cursor-paginated) and GET /financial-actions as real bulk surfaces, so that constraint is out of date. Only `disputes` is synced today, out of a payments API - this is a small fraction of the vendor's queryable surface.
+Note: Official OpenAPI 3.0.1 (2.8 MB, 173 paths) is served at api-reference.checkout.com/v1/swagger.yaml. `POST /payments/search` is the only server-side payments listing (`GET /payments` looks up by reference only) and takes no page cursor, so `payments` walks the time range and splits any window that fills a page. `GET /financial-actions` is not a bulk listing either — it requires a `payment_id` or a single `action_id` — so `financial_actions` fans out per payment over those same windows, as `payment_actions`, `customers` and `instruments` already do. `GET /reports` plus `GET /reports/{id}/files/{fileId}` back the `reports` table and one parsed table per report type the account generates, which is where the bulk settlement and payments files land.
## Churnkey — adequate
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 1cac9718a1fb..0e80bf5aee44 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
@@ -102,6 +102,39 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"payment_requested_on": "Request time of the parent payment. Used as the incremental sync cursor.",
},
},
+ "financial_actions": {
+ "description": "A financial action against your balances for a payment: a capture, refund, chargeback or fee, with its amount breakdown.",
+ "docs_url": "https://api-reference.checkout.com/#operation/getFinancialActions",
+ "columns": {
+ "action_id": "Unique identifier of the financial action impacting your balances.",
+ "action_type": "Type of action processed (e.g. Authorization, Capture, Refund, Chargeback, Pay to card).",
+ "entity_id": "Identifier of the entity the payment was processed for.",
+ "sub_entity_id": "Identifier of the sub-entity the payment was processed for.",
+ "currency_account_id": "Identifier of the currency account the action amount was charged to.",
+ "payment_method": "Payment method associated with the financial action.",
+ "processing_channel_id": "Identifier of the processing channel configuration used.",
+ "mid": "Optional merchant ID used to segment payments traffic with card schemes.",
+ "response_code": "Response code of the payment request.",
+ "response_description": "Description of the payment request response code.",
+ "region": "Region where the payment occurred (Domestic, International, Intra, IntraEEA, IntraEuropean_SEPA).",
+ "card_type": "Card type used to make the payment (CREDIT, DEBIT, PREPAID, CHARGE).",
+ "card_category": "Card category used to make the payment (CONSUMER or COMMERCIAL).",
+ "issuer_country": "Two-letter ISO country code where the payment is processed.",
+ "merchant_category_code": "ISO 18245 four-digit code classifying the goods or services you provide.",
+ "fx_trade_id": "Identifier of the foreign exchange trade executed for this action.",
+ "acquirer_reference_number": "Number assigned to the transaction as it moves between the merchant bank and the cardholder's bank.",
+ "account_funding_transaction": "Whether the transaction debited funds to fund a non-merchant account, such as loading a prepaid card.",
+ "scheme_fx_adjustment_eligible": "Whether the transaction honors the scheme exchange rate applicable at authorization for both authorization and settlement movements.",
+ "processed_on": "Time at which the action was processed and impacted your balances.",
+ "requested_on": "Time at which the gateway request for the action was made.",
+ "breakdown": "Breakdown of the amounts and fees within this financial action, with the currencies and FX rates applied.",
+ "bin": "Bank identification number of the card's issuing institution.",
+ "issuing_bank": "Bank that issued the card used to make the payment.",
+ "payment_type": "Type of card payment where the cardholder is not present (Regular, Recurring, MOTO, Installment, Unscheduled).",
+ "payment_id": "Identifier of the payment this financial action belongs to.",
+ "payment_requested_on": "Request time of the parent payment. Used as the incremental sync cursor, so actions added after the payment synced appear on a full refresh rather than the next incremental run.",
+ },
+ },
"customers": {
"description": "A customer record referenced by your payments.",
"docs_url": "https://api-reference.checkout.com/#tag/Customers",
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
index 86bf4b355b32..0614ea232e1e 100644
--- 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
@@ -1,4 +1,4 @@
-"""Checkout.com payments, payment actions, customers and instruments.
+"""Checkout.com payments, payment actions, financial 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
@@ -19,9 +19,17 @@ report the schema ``Completed`` while the table stayed where it was. Each fully-
window is also checkpointed in Redis, so a retry within the same job resumes where
the budget ran out.
-``payment_actions``, ``customers`` and ``instruments`` have no listing
-endpoints at all, so their syncs walk the same payment windows and fan out per
-referenced record. The search response references a customer by email alone
+``payment_actions``, ``financial_actions``, ``customers`` and ``instruments``
+have no listing endpoints at all, so their syncs walk the same payment windows
+and fan out per referenced record. ``GET /financial-actions`` requires a
+``payment_id`` (or a single ``action_id``), so the settlement ledger (captures,
+refunds, chargebacks and their fee breakdowns) is fetched per payment and
+paginated with ``pagination_token``. It takes no time filter, so there is no
+action-level cursor available: the table advances on the parent payment's request
+time like the other fan-out tables, and an action added after its payment synced
+(a later refund or chargeback) appears on a full refresh rather than the next
+incremental run. The regenerated FinancialActions report table covers late
+adjustments without one, which is why both surfaces are worth syncing. The search response references a customer by email alone
(its ``customer`` object carries no ``cus_`` id) and describes a card source
without an instrument id, so customers are fetched via ``GET
/customers/{identifier}`` (the endpoint accepts an email) and instruments via
@@ -48,6 +56,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_c
)
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.reports import (
_make_api_session,
+ _next_pagination_token,
_strip_links,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import OAuth2Auth
@@ -58,7 +67,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
SourceResponse,
)
-PAYMENTS_ENDPOINTS = ("payments", "payment_actions", "customers", "instruments")
+PAYMENTS_ENDPOINTS = ("payments", "payment_actions", "financial_actions", "customers", "instruments")
# The search endpoint caps `limit` at 1000.
SEARCH_PAGE_LIMIT = 1000
@@ -95,6 +104,11 @@ MAX_FANOUT_LOOKUPS_PER_SYNC = 10_000
# and never re-read, so raising could not backfill the nulls anyway.
MAX_CUSTOMER_ID_LOOKUPS_PER_SYNC = 10_000
FANOUT_CHUNK_SIZE = 500
+# The financial actions listing caps `limit` at 100 and pages with `pagination_token`.
+FINANCIAL_ACTIONS_PAGE_LIMIT = 100
+# One payment's ledger is a handful of actions; this only bounds a pathological response
+# (or a `next` token that never advances) rather than any realistic payment.
+MAX_FINANCIAL_ACTIONS_PAGES_PER_PAYMENT = 50
# Bucket count for the md5(id) partitioning of `payments` (see
# checkout_com_payments_source): enough buckets to keep each per-partition merge small
# on multi-million-row accounts, matching the count other id-hashed sources use.
@@ -117,6 +131,9 @@ FANOUT_INCREMENTAL_FIELD = "payment_requested_on"
SYNC_BUDGET_EXCEEDED_MARKER = "Checkout.com sync fell behind"
# Stable marker so the source can map an id-less run to a customer-facing error.
UNRESOLVED_REFERENCES_MARKER = "Checkout.com payments reference records without a usable identifier"
+# Stable marker so the source can map an unroutable financial actions endpoint to a
+# customer-facing error instead of syncing an empty ledger.
+FINANCIAL_ACTIONS_UNAVAILABLE_MARKER = "Checkout.com financial actions are not available for this account"
class CheckoutComSyncBudgetExceeded(Exception):
@@ -142,6 +159,17 @@ class CheckoutComUnresolvedReferencesError(Exception):
"""
+class CheckoutComFinancialActionsUnavailableError(Exception):
+ """Every financial actions lookup in a run answered 404, and nothing landed.
+
+ The endpoint documents no 404 for a payment that simply has none yet — it returns an
+ empty ``data`` array — so a 404 on every payment means the route is not served for
+ this account rather than that the ledger is empty. Raised rather than returned: a
+ settlement table reporting `Completed` while holding nothing is the failure that makes
+ reconciliation quietly wrong.
+ """
+
+
class _SyncBudget:
"""Counts API calls for one sync and says when to stop cleanly."""
@@ -188,6 +216,13 @@ class _FanoutRunState:
instrument_ids_by_card: dict[_CardIdentity, Optional[str]] = dataclasses.field(default_factory=dict)
unresolvable_references: int = 0
rows_landed: int = 0
+ # Counted separately from `rows_landed`, which the customers/instruments path owns:
+ # these two decide whether an empty financial actions run is an unroutable endpoint
+ # (every lookup 404'd) or an account that genuinely has no settled payments yet.
+ # `served` counts answered lookups rather than rows, because a payment with no actions
+ # yet answers 200 with an empty `data` array — that proves the route works.
+ financial_actions_missing: int = 0
+ financial_actions_served: int = 0
def _to_datetime(value: Any) -> datetime | None:
@@ -364,6 +399,80 @@ def _payment_actions_rows(
return rows
+def _financial_actions_page(
+ session: requests.Session,
+ auth: OAuth2Auth,
+ api_base: str,
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> Optional[dict[str, Any]]:
+ """One page of ``GET /financial-actions``; ``None`` means the endpoint answered 404.
+
+ Unlike the other fan-out lookups, a 404 here does not mean "this record is gone", so
+ it is reported rather than skipped (see CheckoutComFinancialActionsUnavailableError).
+ """
+ response = session.get(f"{api_base}/financial-actions", params=params, 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}, "
+ f"url={api_base}/financial-actions, body={_error_details(response)}"
+ )
+ response.raise_for_status()
+ payload = response.json()
+ return payload if isinstance(payload, dict) else {}
+
+
+def _financial_actions_rows(
+ session: requests.Session,
+ auth: OAuth2Auth,
+ api_base: str,
+ payment: dict[str, Any],
+ logger: FilteringBoundLogger,
+ budget: _SyncBudget,
+ state: _FanoutRunState,
+) -> list[dict[str, Any]]:
+ payment_id = str(payment.get("id") or "")
+ params: dict[str, Any] = {"payment_id": payment_id, "limit": FINANCIAL_ACTIONS_PAGE_LIMIT}
+ rows: list[dict[str, Any]] = []
+ pagination_token: Optional[str] = None
+ for _ in range(MAX_FINANCIAL_ACTIONS_PAGES_PER_PAYMENT):
+ if not budget.take_lookup():
+ return rows
+ page_params = dict(params)
+ if pagination_token:
+ page_params["pagination_token"] = pagination_token
+ payload = _financial_actions_page(session, auth, api_base, page_params, logger)
+ if payload is None:
+ state.financial_actions_missing += 1
+ return rows
+ state.financial_actions_served += 1
+ data = payload.get("data")
+ if not isinstance(data, list):
+ return rows
+ for action in data:
+ if not isinstance(action, dict):
+ continue
+ 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.
+ # `payment_id` is also a documented field of the action itself, so this only
+ # normalizes it to the payment the row was fetched for.
+ row["payment_id"] = payment_id
+ row["payment_requested_on"] = payment.get("requested_on")
+ rows.append(row)
+ next_token = _next_pagination_token(payload)
+ if not next_token or next_token == pagination_token:
+ return rows
+ pagination_token = next_token
+ logger.error(
+ "Checkout.com financial actions paging cap reached for a payment; later actions may be missing",
+ payment_id=payment_id,
+ )
+ return rows
+
+
def _customer_email(customer: dict[str, Any]) -> Optional[str]:
email = str(customer.get("email") or "").strip()
return email if "@" in email else None
@@ -695,6 +804,13 @@ def _get_rows(
if not budget.take_lookup():
break
chunk.extend(_payment_actions_rows(session, auth, hosts["api"], payment, logger))
+ elif schema_name == "financial_actions":
+ if not str(payment.get("id") or ""):
+ continue
+ # Budget is taken per page inside, since one payment can paginate.
+ chunk.extend(_financial_actions_rows(session, auth, hosts["api"], payment, logger, budget, state))
+ if budget.exhausted:
+ break
else:
row = (
_customer_row(session, auth, hosts["api"], payment, logger, budget, state)
@@ -719,6 +835,13 @@ def _get_rows(
if chunk:
latest_yielded = _latest_incremental_value(schema_name, chunk, latest_yielded)
yield chunk
+ # Checked before the budget branch, so an unroutable endpoint reports its own cause
+ # rather than the generic falling-behind message a row-less run would otherwise raise.
+ if state.financial_actions_missing and not state.financial_actions_served:
+ raise CheckoutComFinancialActionsUnavailableError(
+ f"{FINANCIAL_ACTIONS_UNAVAILABLE_MARKER}: every financial actions lookup in this run "
+ f"({state.financial_actions_missing} payment(s)) returned 404, so no settlement data could be read"
+ )
if budget.exhausted:
advanced = latest_yielded is not None and (watermark is None or latest_yielded > watermark)
if should_use_incremental_field and advanced:
@@ -780,6 +903,16 @@ def checkout_com_payments_source(
partition_mode = "datetime"
partition_format = "month"
partition_count = 1
+ elif schema_name == "financial_actions":
+ # `action_id` is documented as the id of the action impacting your balances, but
+ # not as globally unique, so the payment it was fetched for is part of the key.
+ # The fee `breakdown` stays nested here — the FinancialActions *report* flattens it
+ # and keys on (action_id, breakdown_type); the API returns one row per action.
+ primary_keys = ["payment_id", "action_id"]
+ partition_keys = ["payment_requested_on"]
+ partition_mode = "datetime"
+ partition_format = "month"
+ partition_count = 1
else:
# Customers and instruments are point lookups keyed by their own id; they
# carry no stable creation timestamp to partition on.
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 9ed209a61569..b8b00abf7281 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
@@ -20,6 +20,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_c
)
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.payments import (
FANOUT_INCREMENTAL_FIELD,
+ FINANCIAL_ACTIONS_UNAVAILABLE_MARKER,
PAYMENTS_ENDPOINTS,
PAYMENTS_INCREMENTAL_FIELD,
SYNC_BUDGET_EXCEEDED_MARKER,
@@ -71,6 +72,7 @@ _REPORT_ROWS_INCREMENTAL_FIELDS: list[IncrementalField] = [incremental_field("re
_PAYMENTS_INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
"payments": [incremental_field(PAYMENTS_INCREMENTAL_FIELD)],
"payment_actions": [incremental_field(FANOUT_INCREMENTAL_FIELD)],
+ "financial_actions": [incremental_field(FANOUT_INCREMENTAL_FIELD)],
"customers": [incremental_field(FANOUT_INCREMENTAL_FIELD)],
"instruments": [incremental_field(FANOUT_INCREMENTAL_FIELD)],
}
@@ -78,6 +80,7 @@ _PAYMENTS_INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
_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.",
+ "financial_actions": "Settlement ledger entries for each payment: captures, refunds, chargebacks and fee breakdowns. Actions added after a payment syncs need a full refresh to appear.",
"customers": "Customer records referenced by your payments.",
"instruments": "Stored payment instruments referenced by your payments.",
}
@@ -113,6 +116,14 @@ class CheckoutComSource(ResumableSource[CheckoutComSourceConfig, CheckoutComResu
"identifier, so the referenced records can't be fetched and this table can't be filled. "
"Re-enable syncing to skip those payments and continue with newer ones."
),
+ # Checkout.com documents the financial actions endpoint on a per-account base
+ # URL, so an account not served on the standard host 404s every lookup no
+ # matter how often it retries.
+ FINANCIAL_ACTIONS_UNAVAILABLE_MARKER: (
+ "Checkout.com returned no financial actions for any of your payments. Financial actions may not be "
+ "enabled for your account. Sync the financial actions report table instead, or contact "
+ "Checkout.com support to enable the financial actions API."
+ ),
}
for host in ("https://api.checkout.com", "https://api.sandbox.checkout.com"):
errors[f"403 Client Error: Forbidden for url: {host}/disputes"] = (
@@ -133,6 +144,9 @@ class CheckoutComSource(ResumableSource[CheckoutComSourceConfig, CheckoutComResu
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}/financial-actions"] = (
+ "Checkout.com denied access to financial actions. Please check that your access key has the financial-actions 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."
)
@@ -170,9 +184,9 @@ class CheckoutComSource(ResumableSource[CheckoutComSourceConfig, CheckoutComResu
label="Checkout.com",
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. Grant it the scopes for the tables you want to sync: `disputes`, `reports`, `payments` (search), `gateway` (payment actions and instruments), and `vault` (customers and instruments).
+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 instruments), `financial-actions` (the settlement ledger), and `vault` (customers and instruments).
-Payments, payment actions, customers and instruments sync from the payments search API. It reaches back 90 days by default. Set a start date to sync more history. 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.""",
+Payments, payment actions, financial actions, customers and instruments sync from the payments search API. It reaches back 90 days by default. Set a start date to sync more history. 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,
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
index c8de803ea875..6f3bebc066e9 100644
--- 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
@@ -16,8 +16,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_c
CheckoutComResumeConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.payments import (
+ FINANCIAL_ACTIONS_UNAVAILABLE_MARKER,
SYNC_BUDGET_EXCEEDED_MARKER,
UNRESOLVED_REFERENCES_MARKER,
+ CheckoutComFinancialActionsUnavailableError,
CheckoutComSyncBudgetExceeded,
CheckoutComUnresolvedReferencesError,
checkout_com_payments_source,
@@ -472,6 +474,191 @@ class TestPaymentActionsFanout:
_rows(response)
+def _financial_actions_page(actions: list[dict[str, Any]], next_token: Optional[str] = None) -> _FakeResponse:
+ payload: dict[str, Any] = {"count": len(actions), "limit": 100, "data": actions}
+ if next_token is not None:
+ payload["_links"] = {
+ "next": {
+ "href": f"https://api.checkout.com/financial-actions?payment_id=pay_1&pagination_token={next_token}"
+ }
+ }
+ return _FakeResponse(json_data=payload)
+
+
+def _financial_action(action_id: str) -> dict[str, Any]:
+ return {
+ "action_id": action_id,
+ "payment_id": "pay_1",
+ "action_type": "Capture",
+ "processed_on": "2024-02-29T06:00:01Z",
+ "breakdown": [{"breakdown_type": "Scheme Fixed Fee", "holding_currency": "USD"}],
+ }
+
+
+class TestFinancialActionsFanout:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel(NOW, tick=False):
+ yield
+
+ @mock.patch(SESSION_PATCH)
+ def test_fetches_the_ledger_per_payment_and_keys_it_to_the_payment(self, mock_make_session):
+ session = _FakeSession(
+ search_responses=[_search_page([_payment("pay_1", "2024-02-29T06:00:00Z")])],
+ lookup_responses=[_financial_actions_page([_financial_action("act_1")])],
+ )
+ mock_make_session.side_effect = [session]
+
+ rows = _rows(_source("financial_actions", start_date="2024-02-28"))
+
+ assert rows == [
+ {
+ "action_id": "act_1",
+ "payment_id": "pay_1",
+ "action_type": "Capture",
+ "processed_on": "2024-02-29T06:00:01Z",
+ "breakdown": [{"breakdown_type": "Scheme Fixed Fee", "holding_currency": "USD"}],
+ "payment_requested_on": "2024-02-29T06:00:00Z",
+ }
+ ]
+ assert session.lookups == [
+ {
+ "url": "https://api.checkout.com/financial-actions",
+ "params": {"payment_id": "pay_1", "limit": 100},
+ "auth": mock.ANY,
+ "timeout": mock.ANY,
+ }
+ ]
+
+ @mock.patch(SESSION_PATCH)
+ def test_follows_the_pagination_token_and_stops_on_the_terminal_page(self, mock_make_session):
+ session = _FakeSession(
+ search_responses=[_search_page([_payment("pay_1", "2024-02-29T06:00:00Z")])],
+ lookup_responses=[
+ _financial_actions_page([_financial_action("act_1")], next_token="tok_2"),
+ _financial_actions_page([_financial_action("act_2")]),
+ ],
+ )
+ mock_make_session.side_effect = [session]
+
+ rows = _rows(_source("financial_actions", start_date="2024-02-28"))
+
+ assert [row["action_id"] for row in rows] == ["act_1", "act_2"]
+ # Only the token is carried forward; the next page is rebuilt against our own host.
+ assert [lookup["params"] for lookup in session.lookups] == [
+ {"payment_id": "pay_1", "limit": 100},
+ {"payment_id": "pay_1", "limit": 100, "pagination_token": "tok_2"},
+ ]
+
+ @mock.patch(SESSION_PATCH)
+ def test_a_next_token_that_never_advances_does_not_loop(self, mock_make_session):
+ session = _FakeSession(
+ search_responses=[_search_page([_payment("pay_1", "2024-02-29T06:00:00Z")])],
+ lookup_responses=[
+ _financial_actions_page([_financial_action("act_1")], next_token="tok_2"),
+ _financial_actions_page([_financial_action("act_2")], next_token="tok_2"),
+ ],
+ )
+ mock_make_session.side_effect = [session]
+
+ rows = _rows(_source("financial_actions", start_date="2024-02-28"))
+
+ assert [row["action_id"] for row in rows] == ["act_1", "act_2"]
+ assert len(session.lookups) == 2
+
+ @mock.patch(LOOKUP_BUDGET_PATCH, 1)
+ @mock.patch(SESSION_PATCH)
+ def test_each_page_spends_one_lookup_from_the_run_budget(self, mock_make_session):
+ # The regression this guards: taking the budget once per payment instead of once
+ # per page lets a paginating payment issue unbounded requests inside one lookup.
+ session = _FakeSession(
+ search_responses=[_search_page([_payment("pay_1", "2024-02-29T06:00:00Z")])],
+ lookup_responses=[_financial_actions_page([_financial_action("act_1")], next_token="tok_2")],
+ )
+ mock_make_session.side_effect = [session]
+
+ response = _source(
+ "financial_actions",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=BUDGET_WATERMARK,
+ )
+ rows = _rows(response)
+
+ assert [row["action_id"] for row in rows] == ["act_1"]
+ assert len(session.lookups) == 1
+
+ @mock.patch(SESSION_PATCH)
+ def test_every_lookup_404ing_fails_instead_of_syncing_an_empty_ledger(self, mock_make_session):
+ # A 404 here is not "this payment has no actions" — the endpoint returns an empty
+ # `data` array for that. Reporting Completed over an empty settlement table would
+ # make reconciliation silently wrong.
+ session = _FakeSession(
+ search_responses=[_search_page([_payment("pay_1", "2024-02-29T06:00:00Z")])],
+ lookup_responses=[_FakeResponse(status_code=404)],
+ )
+ mock_make_session.side_effect = [session]
+
+ with pytest.raises(CheckoutComFinancialActionsUnavailableError) as excinfo:
+ _rows(_source("financial_actions", start_date="2024-02-28"))
+
+ assert FINANCIAL_ACTIONS_UNAVAILABLE_MARKER in str(excinfo.value)
+
+ @mock.patch(SESSION_PATCH)
+ def test_a_404_alongside_resolved_actions_is_tolerated(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=[
+ _financial_actions_page([_financial_action("act_1")]),
+ _FakeResponse(status_code=404),
+ ],
+ )
+ mock_make_session.side_effect = [session]
+
+ rows = _rows(_source("financial_actions", start_date="2024-02-28"))
+
+ assert [row["action_id"] for row in rows] == ["act_1"]
+
+ @mock.patch(SESSION_PATCH)
+ def test_an_answered_empty_ledger_beside_a_404_is_tolerated(self, mock_make_session):
+ # A payment with no actions yet answers 200 with an empty `data` array, which proves
+ # the route works. Counting rows instead of answered lookups failed this run as an
+ # unroutable endpoint even though one lookup succeeded.
+ session = _FakeSession(
+ search_responses=[
+ _search_page(
+ [
+ _payment("pay_1", "2024-02-29T06:00:00Z"),
+ _payment("pay_2", "2024-02-29T18:00:00Z"),
+ ]
+ )
+ ],
+ lookup_responses=[
+ _financial_actions_page([]),
+ _FakeResponse(status_code=404),
+ ],
+ )
+ mock_make_session.side_effect = [session]
+
+ assert _rows(_source("financial_actions", start_date="2024-02-28")) == []
+
+ @mock.patch(SESSION_PATCH)
+ def test_an_empty_ledger_across_every_payment_completes(self, mock_make_session):
+ session = _FakeSession(
+ search_responses=[_search_page([_payment("pay_1", "2024-02-29T06:00:00Z")])],
+ lookup_responses=[_financial_actions_page([])],
+ )
+ mock_make_session.side_effect = [session]
+
+ assert _rows(_source("financial_actions", start_date="2024-02-28")) == []
+
+
class TestCustomersFanout:
@pytest.fixture(autouse=True)
def _frozen_clock(self):
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 5d89588073e3..9873f80518df 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
@@ -18,7 +18,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
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"]
+_STATIC_SCHEMAS = [
+ "disputes",
+ "reports",
+ "payments",
+ "payment_actions",
+ "financial_actions",
+ "customers",
+ "instruments",
+]
def _http_error(status: int) -> requests.HTTPError:
@@ -119,6 +127,7 @@ class TestCheckoutComSource:
"reports": ["created_on"],
"payments": ["requested_on"],
"payment_actions": ["payment_requested_on"],
+ "financial_actions": ["payment_requested_on"],
"customers": ["payment_requested_on"],
"instruments": ["payment_requested_on"],
}
@@ -267,7 +276,9 @@ class TestCheckoutComSource:
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"])
+ @pytest.mark.parametrize(
+ "schema_name", ["payments", "payment_actions", "financial_actions", "customers", "instruments"]
+ )
@mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.checkout_com.source.checkout_com_payments_source"
)