: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse-sources): add adyen stores, payment instruments and legal entities (#116121)
Tom Owersfc32948eb860
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.mdindex 1dfca85e43c4..7ce0f3de38de 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@@ -206,14 +206,14 @@ Note: NextRoll splits reporting into a separate GraphQL Reporting API (https://a## Adyen — gaps-Today (7): `AccountHolders`, `BalanceAccounts`, `Companies`, `MerchantAccounts`, `SettlementDetailReports`, `Transactions`, `Transfers`+Today (10): `AccountHolders`, `BalanceAccounts`, `Companies`, `LegalEntities`, `MerchantAccounts`, `PaymentInstruments`, `SettlementDetailReports`, `Stores`, `Transactions`, `Transfers`Diffed against: <https://raw.githubusercontent.com/Adyen/adyen-openapi/main/json/BalancePlatformService-v2.json>-- [ ] `Legal entities (Legal Entity API v4, GET /legalEntities/{id})` — resolve legalEntityId in account holders to business identity and verification information (high)-- [ ] `Payment instruments (Balance Platform API v2, GET /balanceAccounts/{id}/paymentInstruments)` — resolve payment instrument references in transactions and transfers to cards, account details, and status (high)-- [ ] `Stores (Management API v3, GET /stores)` — resolve store identifiers in settlement reports and compare payment outcomes across physical locations (high)-- [ ] `Disputes (Transaction API v4, GET /disputes)` — measure issuing dispute rates, disputed amounts, and outcomes alongside card transactions (high)+- [x] `Legal entities (Legal Entity API v4, GET /legalEntities/{id})` — resolve legalEntityId in account holders to business identity and verification information (high). Added as `LegalEntities` (one lookup per distinct account holder `legalEntityId`; full refresh; off by default).+- [x] `Payment instruments (Balance Platform API v2, GET /balanceAccounts/{id}/paymentInstruments)` — resolve payment instrument references in transactions and transfers to cards, account details, and status (high). Added as `PaymentInstruments` (fan-out over balance accounts; full refresh).+- [x] `Stores (Management API v3, GET /stores)` — resolve store identifiers in settlement reports and compare payment outcomes across physical locations (high). Added as `Stores` (full refresh).+- [ ] `Disputes (Transaction API v4, GET /disputes)` — measure issuing dispute rates, disputed amounts, and outcomes alongside card transactions (high); skipped, the Raise Disputes v4 spec contradicts itself on pagination and response shape, and the dispute object has no timestamp to sync on- [ ] `Grants (Transfers API v4, GET /grants)` — analyze capital financing balances and repayment obligations alongside transfers (medium)- [ ] `Managed payout executions (Balance Platform API v2, GET /balanceAccounts/{balanceAccountId}/payoutSchedules/{id}/executions)` — track scheduled payout attempts and outcomes beyond completed transfers (medium)- [ ] `Terminals (Management API v3, GET /terminals)` — analyze terminal inventory and allocation across merchants and stores (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/adyen.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/adyen.pyindex 12b1df9bf6ba..60365bb4e636 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/adyen.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/adyen.py@@ -30,12 +30,14 @@ ADYEN_HOSTS: dict[str, dict[str, str]] = {"configuration": "https://balanceplatform-api-test.adyen.com/bcl/v2","management": "https://management-test.adyen.com/v3","reports": "https://ca-test.adyen.com",+ "legal_entity": "https://kyc-test.adyen.com/lem/v4",},"live": {"transfers": "https://balanceplatform-api-live.adyen.com/btl/v4","configuration": "https://balanceplatform-api-live.adyen.com/bcl/v2","management": "https://management-live.adyen.com/v3","reports": "https://ca-live.adyen.com",+ "legal_entity": "https://kyc-live.adyen.com/lem/v4",},}@@ -395,31 +397,94 @@ def _iter_page_number_pages(manager.save_state(AdyenResumeConfig(page_number=page_number))+def _parent_endpoint(config: AdyenEndpointConfig) -> AdyenEndpointConfig:+ parent = ADYEN_ENDPOINTS[config.parent] if config.parent else None+ if parent is None:+ raise AdyenConfigurationError(f"Adyen endpoint {config.name} has no parent endpoint configured.")+ return parent+++def _collect_ids(+ session: requests.Session,+ config: AdyenEndpointConfig,+ environment: Optional[str],+ balance_platform: str,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[AdyenResumeConfig],+ field: str = "id",+) -> list[str]:+ """Distinct `field` values across an offset-paginated endpoint, walking its own parents first."""+ host = base_url(environment, config.api)+ if config.pagination == "fanout_offset":+ paths = [+ config.path.format(parent_id=parent_id)+ for parent_id in _collect_ids(+ session, _parent_endpoint(config), environment, balance_platform, logger, manager+ )+ ]+ else:+ paths = [config.path.format(balance_platform=balance_platform)]++ ids: dict[str, None] = {}+ for path in paths:+ for page in _iter_offset_pages(session, host, path, config.data_key, logger):+ for item in page:+ value = item.get(field)+ # The id is interpolated into the next request path, so only accept plain identifiers.+ if isinstance(value, str) and _IDENTIFIER_RE.match(value):+ ids[value] = None+ # Nothing has been yielded yet, so resuming here loses no rows.+ manager.safe_point()+ return list(ids)++def _iter_fanout_pages(session: requests.Session,config: AdyenEndpointConfig,- host: str,+ environment: Optional[str],balance_platform: str,logger: FilteringBoundLogger,manager: ResumableSourceManager[AdyenResumeConfig],start_parent_index: int,) -> Iterator[list[dict[str, Any]]]:- parent = ADYEN_ENDPOINTS[config.parent] if config.parent else None- if parent is None:- raise AdyenConfigurationError(f"Adyen endpoint {config.name} has no parent endpoint configured.")-- parent_path = parent.path.format(balance_platform=balance_platform)- parent_ids: list[str] = []- for page in _iter_offset_pages(session, host, parent_path, parent.data_key, logger):- parent_ids.extend(str(item["id"]) for item in page if item.get("id"))+ parent_ids = _collect_ids(+ session, _parent_endpoint(config), environment, balance_platform, logger, manager, config.parent_field+ )+ host = base_url(environment, config.api)for index, parent_id in enumerate(parent_ids):if index < start_parent_index:continuechild_path = config.path.format(parent_id=parent_id)- for page in _iter_offset_pages(session, host, child_path, config.data_key, logger):- yield page+ yield from _iter_offset_pages(session, host, child_path, config.data_key, logger)manager.save_state(AdyenResumeConfig(parent_index=index + 1))+ # Many parents have no children, and a long run of empty requests needs a hand-off point.+ manager.safe_point()+++def _iter_fanout_objects(+ session: requests.Session,+ config: AdyenEndpointConfig,+ environment: Optional[str],+ balance_platform: str,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[AdyenResumeConfig],+ start_parent_index: int,+) -> Iterator[list[dict[str, Any]]]:+ parent_ids = _collect_ids(+ session, _parent_endpoint(config), environment, balance_platform, logger, manager, config.parent_field+ )+ host = base_url(environment, config.api)++ for index, parent_id in enumerate(parent_ids):+ if index < start_parent_index:+ continue+ payload = _request(session, f"{host}{config.path.format(parent_id=parent_id)}", logger).json()+ manager.save_state(AdyenResumeConfig(parent_index=index + 1))+ if isinstance(payload, dict) and payload.get("id"):+ yield [payload]+ else:+ manager.safe_point()def _iter_report_batches(@@ -522,11 +587,12 @@ def get_rows()return- if config.pagination == "fanout_offset":+ if config.pagination in ("fanout_offset", "fanout_object"):platform = _require_identifier(balance_platform, "Balance platform ID")start_parent_index = resume.parent_index if resume is not None and resume.parent_index is not None else 0- yield from _iter_fanout_pages(- session, config, host, platform, logger, resumable_source_manager, start_parent_index+ iter_fanout = _iter_fanout_pages if config.pagination == "fanout_offset" else _iter_fanout_objects+ yield from iter_fanout(+ session, config, environment, platform, logger, resumable_source_manager, start_parent_index)returndiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/canonical_descriptions.pyindex a4b3a8fc0278..1073c6887c8e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/canonical_descriptions.py@@ -72,6 +72,59 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"timeZone": "Time zone of the balance account.",},},+ "PaymentInstruments": {+ "description": "A card or business account issued against a balance account in your balance platform.",+ "docs_url": "https://docs.adyen.com/api-explorer/balanceplatform/2/get/balanceAccounts/(id)/paymentInstruments",+ "columns": {+ "id": "Unique identifier of the payment instrument.",+ "balanceAccountId": "Unique identifier of the balance account the payment instrument is linked to.",+ "bankAccount": "Bank account details, for payment instruments of type bankAccount.",+ "card": "Card details such as brand, form factor and last four digits, for payment instruments of type card.",+ "description": "Your description of the payment instrument.",+ "issuingCountryCode": "Two-character ISO code of the country where the payment instrument is issued.",+ "paymentInstrumentGroupId": "Unique identifier of the payment instrument group the payment instrument belongs to.",+ "reference": "Your reference for the payment instrument.",+ "replacedById": "Unique identifier of the payment instrument that replaced this one.",+ "replacementOfId": "Unique identifier of the payment instrument this one replaces.",+ "status": "Status of the payment instrument: active, inactive, suspended or closed.",+ "statusReason": "Reason the payment instrument has its current status.",+ "type": "Type of payment instrument: card or bankAccount.",+ },+ },+ "LegalEntities": {+ "description": "The legal entity behind an account holder: an individual, organization, sole proprietorship or trust.",+ "docs_url": "https://docs.adyen.com/api-explorer/legalentity/4/get/legalEntities/(id)",+ "columns": {+ "id": "Unique identifier of the legal entity.",+ "type": "Type of legal entity: individual, organization, soleProprietorship, trust or unincorporatedPartnership.",+ "capabilities": "Capabilities requested for the legal entity, with their verification status.",+ "entityAssociations": "Other legal entities linked to this one, such as owners, signatories or directors.",+ "individual": "Details of the person, for legal entities of type individual.",+ "organization": "Details of the organization, for legal entities of type organization.",+ "soleProprietorship": "Details of the sole proprietorship, for legal entities of type soleProprietorship.",+ "trust": "Details of the trust, for legal entities of type trust.",+ "problems": "Verification errors on the legal entity that you need to resolve.",+ "reference": "Your reference for the legal entity.",+ "transferInstruments": "Transfer instruments, such as bank accounts, linked to the legal entity.",+ "verificationDeadlines": "Deadlines by which capabilities need verification before Adyen disables them.",+ },+ },+ "Stores": {+ "description": "A physical store location belonging to a merchant account.",+ "docs_url": "https://docs.adyen.com/api-explorer/Management/3/get/stores",+ "columns": {+ "id": "Unique identifier of the store.",+ "merchantId": "Unique identifier of the merchant account the store belongs to.",+ "reference": "Your reference for the store.",+ "description": "Your description of the store.",+ "address": "Address of the store.",+ "businessLineIds": "Business lines the store is linked to.",+ "externalReferenceId": "Reference for the store in your own systems.",+ "phoneNumber": "Phone number of the store.",+ "shopperStatement": "Text shown on the shopper's bank statement for payments at the store.",+ "status": "Status of the store: active, inactive or closed.",+ },+ },"Companies": {"description": "A company account your API credential can access.","docs_url": "https://docs.adyen.com/api-explorer/Management/3/get/companies",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/settings.pyindex a00b9ac83a64..4029cf3395e4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/settings.py@@ -4,16 +4,17 @@ from typing import Literalfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_fieldfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType-# Adyen splits its read APIs across three hosts with independent versions, so each endpoint+# Adyen splits its read APIs across several hosts with independent versions, so each endpoint# names the API it belongs to rather than sharing one base URL.-AdyenApi = Literal["transfers", "configuration", "management", "reports"]+AdyenApi = Literal["transfers", "configuration", "management", "reports", "legal_entity"]# `cursor` — Transfers API `_links.next` with an opaque `cursor` query param.# `offset` — Configuration API `offset`/`limit`.# `page` — Management API `pageNumber`/`pageSize`.# `fanout_offset` — offset pagination per parent id resolved from another endpoint.+# `fanout_object` — one single-object GET per parent id resolved from another endpoint.# `report_batch` — no pagination: walk sequential report batch numbers, one CSV file each.-AdyenPagination = Literal["cursor", "offset", "page", "fanout_offset", "report_batch"]+AdyenPagination = Literal["cursor", "offset", "page", "fanout_offset", "fanout_object", "report_batch"]@dataclass(frozen=True)@@ -30,8 +31,11 @@ class AdyenEndpointConfig:partition_key: str | None = Nonerequires_balance_platform: bool = Falserequires_merchant_account: bool = False- # Fan-out children: the endpoint whose row ids fill the `{parent_id}` placeholder.+ # Fan-out children: the endpoint whose rows fill the `{parent_id}` placeholder, and the field+ # read from each parent row.parent: str | None = None+ parent_field: str = "id"+ sync_by_default: bool = Truedescription: str = ""@@ -57,6 +61,31 @@ ADYEN_ENDPOINTS: dict[str, AdyenEndpointConfig] = {requires_balance_platform=True,description="Balance accounts holding funds for each account holder in your balance platform.",),+ "PaymentInstruments": AdyenEndpointConfig(+ name="PaymentInstruments",+ api="configuration",+ path="/balanceAccounts/{parent_id}/paymentInstruments",+ primary_key=("id",),+ pagination="fanout_offset",+ data_key="paymentInstruments",+ parent="BalanceAccounts",+ requires_balance_platform=True,+ description="Cards and business accounts issued against each balance account, with their status.",+ ),+ "LegalEntities": AdyenEndpointConfig(+ name="LegalEntities",+ api="legal_entity",+ path="/legalEntities/{parent_id}",+ primary_key=("id",),+ pagination="fanout_object",+ parent="AccountHolders",+ parent_field="legalEntityId",+ requires_balance_platform=True,+ # Needs a Legal Entity Management API role most credentials lack, and the rows carry+ # personal identity data, so the table is opt-in.+ sync_by_default=False,+ description="Legal entities behind your account holders, with their business identity and verification status.",+ ),"Companies": AdyenEndpointConfig(name="Companies",api="management",@@ -75,6 +104,15 @@ ADYEN_ENDPOINTS: dict[str, AdyenEndpointConfig] = {data_key="data",description="Merchant accounts your API credential can access, with their processing configuration.",),+ "Stores": AdyenEndpointConfig(+ name="Stores",+ api="management",+ path="/stores",+ primary_key=("id",),+ pagination="page",+ data_key="data",+ description="Physical store locations across the merchant accounts your API credential can access.",+ ),"SettlementDetailReports": AdyenEndpointConfig(name="SettlementDetailReports",api="reports",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/source.pyindex 68b84b57e4e0..6e97895dd537 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/source.py@@ -38,9 +38,10 @@ CAPTION = """Connect your Adyen account to sync payments data into the PostHog DCreate an API credential in your Adyen Customer Area under **Developers > API credentials**, then paste its API key below. Which tables you can sync depends on what that credential can reach:-- **Transactions, transfers, account holders and balance accounts** need an Adyen for Platforms or Adyen Issuing integration. Add your balance platform ID too.+- **Transactions, transfers, account holders, balance accounts and payment instruments** need an Adyen for Platforms or Adyen Issuing integration. Add your balance platform ID too.+- **Legal entities** also need the balance platform ID, plus a Legal Entity Management API role on the credential.- **Settlement detail reports** need a merchant account and the **Merchant Report Download** role. Adyen only creates these files once you turn on the settlement details report in your Customer Area.-- **Companies and merchant accounts** come from the Management API and need an account read role.+- **Companies, merchant accounts and stores** come from the Management API and need an account read role.Pick the environment that matches where you created the API key — a test key won't work against live."""@@ -91,7 +92,8 @@ class AdyenSource(ResumableSource[AdyenSourceConfig, AdyenResumeConfig]):has_platform = bool((config.balance_platform or "").strip())has_merchant = bool((config.merchant_account or "").strip())should_sync_default = {- name: (has_platform or not endpoint.requires_balance_platform)+ name: endpoint.sync_by_default+ and (has_platform or not endpoint.requires_balance_platform)and (has_merchant or not endpoint.requires_merchant_account)for name, endpoint in ADYEN_ENDPOINTS.items()}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/tests/test_adyen.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/tests/test_adyen.pyindex 2ed8dff5c466..5d821e75fb34 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/tests/test_adyen.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/tests/test_adyen.py@@ -140,6 +140,7 @@ class TestHosts:("test_configuration", "test", "configuration", "https://balanceplatform-api-test.adyen.com/bcl/v2"),("live_management", "live", "management", "https://management-live.adyen.com/v3"),("test_reports", "test", "reports", "https://ca-test.adyen.com"),+ ("live_legal_entity", "live", "legal_entity", "https://kyc-live.adyen.com/lem/v4"),# An unrecognised environment can never retarget the API key at another host.("unknown_falls_back_to_live", "evil.example.com", "management", "https://management-live.adyen.com/v3"),("none_falls_back_to_live", None, "reports", "https://ca-live.adyen.com"),@@ -458,6 +459,52 @@ class TestFanout:assert [row["id"] for row in rows] == ["BA2"]assert "AH2" in session.requested_urls[1]+ def test_payment_instruments_walk_account_holders_then_balance_accounts(self) -> None:+ session = _FakeSession(+ [+ _FakeResponse(json_data={"accountHolders": [{"id": "AH1"}, {"id": "AH2"}]}),+ _FakeResponse(json_data={"balanceAccounts": [{"id": "BA1"}]}),+ # A malformed id from the response must never reach a request path.+ _FakeResponse(json_data={"balanceAccounts": [{"id": "BA2"}, {"id": "../x"}]}),+ _FakeResponse(json_data={"hasNext": False, "paymentInstruments": []}),+ _FakeResponse(json_data={"hasNext": False, "paymentInstruments": [{"id": "PI1"}]}),+ ]+ )+ manager = _FakeManager()++ rows = _drain(session, "PaymentInstruments", manager, balance_platform="BP123")++ assert [row["id"] for row in rows] == ["PI1"]+ assert [urlparse(url).path for url in session.requested_urls[3:]] == [+ "/bcl/v2/balanceAccounts/BA1/paymentInstruments",+ "/bcl/v2/balanceAccounts/BA2/paymentInstruments",+ ]+ assert manager.saved_states == [AdyenResumeConfig(parent_index=1), AdyenResumeConfig(parent_index=2)]++ def test_legal_entities_are_fetched_once_per_distinct_id_from_the_kyc_host(self) -> None:+ session = _FakeSession(+ [+ _FakeResponse(+ json_data={+ "accountHolders": [+ {"id": "AH1", "legalEntityId": "LE1"},+ {"id": "AH2"},+ {"id": "AH3", "legalEntityId": "LE1"},+ {"id": "AH4", "legalEntityId": "LE2"},+ ]+ }+ ),+ _FakeResponse(json_data={"id": "LE2", "type": "organization"}),+ ]+ )+ manager = _FakeManager(AdyenResumeConfig(parent_index=1))++ rows = _drain(session, "LegalEntities", manager, balance_platform="BP123")++ assert rows == [{"id": "LE2", "type": "organization"}]+ assert session.requested_urls[1] == "https://kyc-test.adyen.com/lem/v4/legalEntities/LE2"+ assert manager.saved_states == [AdyenResumeConfig(parent_index=2)]+class TestReportBatches:def _report(self, rows: str) -> _FakeResponse:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/tests/test_adyen_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/tests/test_adyen_source.pyindex 8dd544e4f302..eabbb143d84e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/tests/test_adyen_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/tests/test_adyen_source.py@@ -39,15 +39,24 @@ class TestAdyenSource:@parameterized.expand([- ("both_identifiers", "BP123", "ACME", set(ENDPOINTS)),+ ("both_identifiers", "BP123", "ACME", set(ENDPOINTS) - {"LegalEntities"}),("platform_only","BP123",None,- {"Transactions", "Transfers", "AccountHolders", "BalanceAccounts", "Companies", "MerchantAccounts"},+ {+ "Transactions",+ "Transfers",+ "AccountHolders",+ "BalanceAccounts",+ "PaymentInstruments",+ "Companies",+ "MerchantAccounts",+ "Stores",+ },),- ("merchant_only", None, "ACME", {"SettlementDetailReports", "Companies", "MerchantAccounts"}),- ("neither", None, " ", {"Companies", "MerchantAccounts"}),+ ("merchant_only", None, "ACME", {"SettlementDetailReports", "Companies", "MerchantAccounts", "Stores"}),+ ("neither", None, " ", {"Companies", "MerchantAccounts", "Stores"}),])def test_tables_needing_a_missing_identifier_start_unselected(