: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(data-warehouse): add gocardless creditors, balances and payout items tables (#112585)
Tom Owersa37509fd48cb
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 ac358303bd0e..5ed3ba165c5b 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@@ -3692,10 +3692,10 @@ Today (7): `customers`, `events`, `mandates`, `payments`, `payouts`, `refunds`,Diffed against: <https://developer.gocardless.com/api-reference/>-- [ ] `payout_items (/payouts/{id}/items)` — line items that reconcile each payout to its underlying payments, refunds and fees - the core payout reconciliation join (high)-- [ ] `customer_bank_accounts` — lookup resolving the customer_bank_account IDs carried on every mandate and payment we already sync (high)-- [ ] `creditors` — lookup resolving the creditor ID on payments, payouts and mandates (high)-- [ ] `balances` — current available/pending funds per creditor - the headline treasury metric (medium)+- [x] `payout_items (/payouts/{id}/items)` — line items that reconcile each payout to its underlying payments, refunds and fees - the core payout reconciliation join (high)+- [x] `customer_bank_accounts` — lookup resolving the customer_bank_account IDs carried on every mandate and payment we already sync (high)+- [x] `creditors` — lookup resolving the creditor ID on payments, payouts and mandates (high)+- [x] `balances` — current available/pending funds per creditor - the headline treasury metric (medium)- [ ] `instalment_schedules` — payment plans that group the individual payments we sync (medium)- [ ] `billing_requests` — the modern checkout/mandate-setup funnel object, needed to measure setup conversion (medium)- [ ] `payment_account_transactions` — transaction ledger for embedded payment accounts (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gocardless/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gocardless/canonical_descriptions.pyindex d0a9a76a9602..71c5d398d1d4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gocardless/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gocardless/canonical_descriptions.py@@ -112,4 +112,53 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {links="Related resources the event concerns (payment, mandate, subscription, etc.).",),},+ "customer_bank_accounts": {+ "description": "A customer's bank account that payments are collected from.",+ "docs_url": "https://developer.gocardless.com/api-reference/#core-endpoints-customer-bank-accounts",+ "columns": _columns(+ account_holder_name="Name of the account holder, as known by the bank.",+ account_number_ending="Last two digits of the account number.",+ account_type="Type of bank account, for countries that need it (savings or checking).",+ bank_name="Name of the bank the account is held with.",+ country_code="ISO 3166-1 two-letter country code of the bank account.",+ currency="ISO 4217 three-letter currency code of the bank account.",+ enabled="Whether the bank account can be used for new mandates.",+ links="Related resources (customer).",+ ),+ },+ "creditors": {+ "description": "The entity, usually your organisation, that payments are collected on behalf of.",+ "docs_url": "https://developer.gocardless.com/api-reference/#core-endpoints-creditors",+ "columns": _columns(+ name="Name of the creditor.",+ creditor_type="Type of business of the creditor (e.g. company, individual, charity).",+ country_code="ISO 3166-1 two-letter country code of the creditor's address.",+ verification_status="State of the creditor's verification (successful, in_review, or action_required).",+ scheme_identifiers="Scheme identifiers the creditor collects payments under.",+ links="Related resources, including the default payout bank account per currency.",+ ),+ },+ "balances": {+ "description": "A snapshot of a creditor's funds held by GoCardless, one row per balance type and currency.",+ "docs_url": "https://developer.gocardless.com/api-reference/#core-endpoints-balances",+ "columns": {+ "creditor_id": "ID of the creditor the balance belongs to.",+ "balance_type": "Type of balance (e.g. confirmed_funds, pending_payouts, pending_payments_submitted).",+ "amount": "Balance amount, in the smallest currency unit.",+ "currency": "ISO 4217 three-letter currency code of the balance.",+ "last_updated_at": "Time the balance was last updated (ISO 8601).",+ "links": "Related resources (creditor).",+ },+ },+ "payout_items": {+ "description": "A line item of a payout: a payment, refund, fee, or other amount that makes up the payout total.",+ "docs_url": "https://developer.gocardless.com/api-reference/#core-endpoints-payout-items",+ "columns": {+ "payout_id": "ID of the payout this item belongs to.",+ "type": "Type of item (e.g. payment_paid_out, payment_failed, refund, gocardless_fee, app_fee).",+ "amount": "Amount of the item, in the smallest currency unit, as a string.",+ "taxes": "Taxes applied to a fee item, with amount, currency, and tax rate.",+ "links": "Related resources (payment, mandate, refund).",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gocardless/gocardless.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gocardless/gocardless.pyindex 858e8700858b..e5d8c3b833b0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gocardless/gocardless.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gocardless/gocardless.py@@ -1,6 +1,7 @@import dataclasses-from datetime import UTC, date, datetime-from typing import Any, Optional+from collections.abc import Iterable+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional, castfrom urllib.parse import urlencodefrom requests import Response@@ -10,13 +11,20 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resRESTAPIConfig,rest_api_resource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (JSONResponseCursorPaginator,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse-from products.warehouse_sources.backend.temporal.data_imports.sources.gocardless.settings import GOCARDLESS_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.gocardless.settings import (+ GOCARDLESS_ENDPOINTS,+ PAGE_SIZE,+)GOCARDLESS_HOSTS = {"live": "https://api.gocardless.com",@@ -24,11 +32,9 @@ GOCARDLESS_HOSTS = {}# Every request must pin an API version via this header.GOCARDLESS_VERSION = "2015-07-06"-# GoCardless list pages cap at 500 items.-PAGE_SIZE = 500[email protected](frozen=True)class GoCardlessResumeConfig:# GoCardless cursor pagination: `after=<id>` from meta.cursors.after; the# static params are deterministically rebuilt from job inputs on resume.@@ -84,6 +90,59 @@ def validate_credentials(environment: str, access_token: str) -> bool:return ok+def _client_config(base_url: str, access_token: str) -> ClientConfig:+ return {+ "base_url": base_url,+ # Auth (Bearer) is supplied via the framework auth config so its value is redacted+ # from logs and raised errors; only the non-secret version header is set here.+ "headers": {"GoCardless-Version": GOCARDLESS_VERSION},+ "auth": {"type": "bearer", "token": access_token},+ "paginator": GoCardlessCursorPaginator(),+ # Cursor pagination stays on the base host; pin every request (including a seeded+ # resume cursor) to it so a spoofed response can't redirect the token off-host.+ "allowed_hosts": [],+ }+++def _fanout_source(base_url: str, access_token: str, endpoint: str, team_id: int, job_id: str) -> SourceResponse:+ config = GOCARDLESS_ENDPOINTS[endpoint]+ assert config.fanout is not None+ fanout = config.fanout+ parent_config = GOCARDLESS_ENDPOINTS[fanout.parent_name]++ if config.parent_created_within_days is not None:+ cutoff = datetime.now(UTC) - timedelta(days=config.parent_created_within_days)+ fanout = dataclasses.replace(+ fanout, parent_params={**fanout.parent_params, "created_at[gte]": _format_created_at(cutoff)}+ )++ dependent_resource = cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=GOCARDLESS_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=fanout,+ client_config=_client_config(base_url, access_token),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ should_use_incremental_field=False,+ parent_endpoint_extra={"paginator": GoCardlessCursorPaginator(), "data_selector": parent_config.data_key},+ child_endpoint_extra={"paginator": GoCardlessCursorPaginator(), "data_selector": config.data_key},+ ),+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: dependent_resource,+ primary_keys=[config.primary_key] if config.primary_key else None,+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ )++def gocardless_source(environment: str,access_token: str,@@ -96,6 +155,9 @@ def gocardless_source(config = GOCARDLESS_ENDPOINTS[endpoint]base_url = _base_url(environment)+ if config.fanout is not None:+ return _fanout_source(base_url, access_token, endpoint, team_id, job_id)+params: dict[str, Any] = {"limit": PAGE_SIZE}if config.incremental_fields and db_incremental_field_last_value is not None:# `gte` re-fetches the boundary row (merge dedupes on primary key) so@@ -103,17 +165,7 @@ def gocardless_source(params["created_at[gte]"] = _format_created_at(db_incremental_field_last_value)rest_config: RESTAPIConfig = {- "client": {- "base_url": base_url,- # Auth (Bearer) is supplied via the framework auth config so its value is redacted- # from logs and raised errors; only the non-secret version header is set here.- "headers": {"GoCardless-Version": GOCARDLESS_VERSION},- "auth": {"type": "bearer", "token": access_token},- "paginator": GoCardlessCursorPaginator(),- # Cursor pagination stays on the base host; pin every request (including a seeded- # resume cursor) to it so a spoofed response can't redirect the token off-host.- "allowed_hosts": [],- },+ "client": _client_config(base_url, access_token),"resources": [{"name": endpoint,@@ -152,12 +204,12 @@ def gocardless_source(return SourceResponse(name=endpoint,items=lambda: resource,- primary_keys=[config.primary_key],+ primary_keys=[config.primary_key] if config.primary_key else None,partition_count=1,partition_size=1,- partition_mode="datetime",- partition_format="month",- partition_keys=[config.partition_key],+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,# GoCardless lists are reverse-chronological with no sort param; the# pipeline commits desc-sort watermarks only when a run completes.sort_mode="desc" if config.incremental_fields else "asc",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gocardless/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gocardless/settings.pyindex 93aabfefb1d6..a4a34fe7ac1b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gocardless/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gocardless/settings.py@@ -1,18 +1,31 @@from dataclasses import dataclass, field+from typing import Optional+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+# GoCardless list pages cap at 500 items.+PAGE_SIZE = 500-@dataclass++@dataclass(frozen=True)class GoCardlessEndpointConfig:name: strpath: str# Key the rows live under in the response body (GoCardless wraps per resource).data_key: str- primary_key: str = "id"+ # None for resources with no id, which only ever sync as a full replace.+ primary_key: Optional[str] = "id"incremental_fields: list[IncrementalField] = field(default_factory=list)- # Every GoCardless resource carries an immutable created_at.- partition_key: str = "created_at"+ # Immutable created_at on every resource that has one; None for resources without it.+ partition_key: Optional[str] = "created_at"+ page_size: int = PAGE_SIZE+ default_incremental_field: Optional[str] = None+ fanout: Optional[DependentEndpointConfig] = None+ # Bounds the fan-out parent listing to rows created in the last N days.+ parent_created_within_days: Optional[int] = None# GoCardless list endpoints filter only on created_at (no updated_at), and core@@ -64,6 +77,52 @@ GOCARDLESS_ENDPOINTS: dict[str, GoCardlessEndpointConfig] = {},],),+ "customer_bank_accounts": GoCardlessEndpointConfig(+ name="customer_bank_accounts",+ path="/customer_bank_accounts",+ data_key="customer_bank_accounts",+ ),+ "creditors": GoCardlessEndpointConfig(+ name="creditors",+ path="/creditors",+ data_key="creditors",+ ),+ # /balances requires a creditor filter, so it fans out over creditors. A balance row has no+ # id or created_at; it is a point-in-time snapshot, so it is replaced on every sync.+ "balances": GoCardlessEndpointConfig(+ name="balances",+ path="/balances?creditor={creditor}",+ data_key="balances",+ primary_key=None,+ partition_key=None,+ fanout=DependentEndpointConfig(+ parent_name="creditors",+ resolve_param="creditor",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "creditor_id"},+ ),+ ),+ # /payout_items requires a payout filter and has no id or created_at, so it fans out over+ # payouts and syncs as a full replace. GoCardless serves items only for payouts created in+ # the last 6 months and answers 410 Gone for older ones, so the parent listing is bounded+ # to that window and a boundary 410 is skipped rather than failing the table.+ "payout_items": GoCardlessEndpointConfig(+ name="payout_items",+ path="/payout_items?payout={payout}",+ data_key="payout_items",+ primary_key=None,+ partition_key=None,+ fanout=DependentEndpointConfig(+ parent_name="payouts",+ resolve_param="payout",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "payout_id"},+ child_response_actions=[{"status_code": 410, "action": "ignore"}],+ ),+ parent_created_within_days=186,+ ),}ENDPOINTS = tuple(GOCARDLESS_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gocardless/tests/test_gocardless.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gocardless/tests/test_gocardless.pyindex 1d9389348d33..14fab0c30b06 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gocardless/tests/test_gocardless.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gocardless/tests/test_gocardless.py@@ -1,7 +1,7 @@import json-from datetime import UTC, date, datetime+from datetime import UTC, date, datetime, timedeltafrom typing import Any-from urllib.parse import urlparse+from urllib.parse import parse_qs, urlparseimport pytestfrom unittest import mock@@ -28,6 +28,13 @@ GOCARDLESS_SESSION_PATCH = ()+def _status_response(status_code: int) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = b'{"error": {"code": %d}}' % status_code+ return resp++def _response(data_key: str, items: list[dict[str, Any]], after: str | None = None) -> Response:body = {data_key: items, "meta": {"cursors": {"before": None, "after": after}, "limit": 500}}resp = Response()@@ -258,6 +265,63 @@ class TestPagination:manager.save_state.assert_not_called()+class TestFanout:+ @pytest.mark.parametrize(+ "endpoint, parent_key, parent_id, resolve_param, injected_key",+ [+ ("payout_items", "payouts", "PO1", "payout", "payout_id"),+ ("balances", "creditors", "CR1", "creditor", "creditor_id"),+ ],+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_child_is_fetched_per_parent_with_parent_id_injected(+ self, MockSession, endpoint, parent_key, parent_id, resolve_param, injected_key+ ):+ session = MockSession.return_value+ params, urls = _wire(+ session,+ [+ _response(parent_key, [{"id": parent_id}]),+ _response(endpoint, [{"type": "a", "amount": "1"}], after="X1"),+ _response(endpoint, [{"type": "b", "amount": "2"}]),+ ],+ )++ rows = _run(session, "live", endpoint, _make_manager())++ assert urlparse(urls[1]).path == f"/{endpoint}"+ assert parse_qs(urlparse(urls[1]).query) == {resolve_param: [parent_id]}+ assert params[2]["after"] == "X1"+ assert [r["type"] for r in rows] == ["a", "b"]+ assert all(r[injected_key] == parent_id for r in rows)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_payout_items_skips_payouts_past_the_retention_window(self, MockSession):+ session = MockSession.return_value+ params, _ = _wire(+ session,+ [+ _response("payouts", [{"id": "PO_OLD"}, {"id": "PO_NEW"}]),+ _status_response(410),+ _response("payout_items", [{"type": "payment_paid_out", "amount": "100"}]),+ ],+ )++ rows = _run(session, "live", "payout_items", _make_manager())++ assert [r["payout_id"] for r in rows] == ["PO_NEW"]+ assert params[0]["created_at[gte]"] > _format_created_at(datetime.now(UTC) - timedelta(days=187))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_balances_lists_every_creditor(self, MockSession):+ session = MockSession.return_value+ params, _ = _wire(session, [_response("creditors", [{"id": "CR1"}]), _response("balances", [])])++ _run(session, "live", "balances", _make_manager())++ assert "created_at[gte]" not in params[0]++class TestGoCardlessSourceResponse:@pytest.mark.parametrize("endpoint", list(ENDPOINTS))def test_response_metadata_per_endpoint(self, endpoint):@@ -272,6 +336,10 @@ class TestGoCardlessSourceResponse:)assert response.name == endpoint+ if config.primary_key is None:+ assert response.primary_keys is None+ assert response.partition_keys is None+ returnassert response.primary_keys == [config.primary_key]assert response.partition_mode == "datetime"assert response.partition_keys == ["created_at"]@@ -284,4 +352,4 @@ class TestGoCardlessSourceResponse:@pytest.mark.parametrize("config", list(GOCARDLESS_ENDPOINTS.values()))def test_partition_keys_are_stable_creation_fields(self, config):- assert config.partition_key == "created_at"+ assert config.partition_key in ("created_at", None)