: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 airwallex disputes, credit notes and subscription items (#116123)
Tom Owerse5ef9e9d5b0c
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 dd66d236aad1..cc74be1ffffe 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@@ -356,22 +356,22 @@ Note: AirOps has repositioned around AI search visibility; the entire brand-kit## Airwallex — gaps-Today (13): `Beneficiaries`, `BillingCustomers`, `Customers`, `Deposits`, `FinancialTransactions`, `GlobalAccounts`, `Invoices`, `PaymentAttempts`, `PaymentIntents`, `Refunds`, `Settlements`, `Subscriptions`, `Transfers`+Today (16): `Beneficiaries`, `BillingCustomers`, `CreditNotes`, `Customers`, `Deposits`, `FinancialTransactions`, `GlobalAccounts`, `Invoices`, `PaymentAttempts`, `PaymentDisputes`, `PaymentIntents`, `Refunds`, `Settlements`, `SubscriptionItems`, `Subscriptions`, `Transfers`Diffed against: <https://raw.githubusercontent.com/airwallex/airwallex-openapi/main/openapi/client-api/latest/airwallex-openapi-latest.json>-- [ ] `Subscription items (GET /api/v1/billing/subscriptions/{id}/items)` — provides quantities and prices needed to calculate recurring revenue from synced subscriptions (high)+- [x] `Subscription items (GET /api/v1/billing/subscriptions/{id}/items)` — provides quantities and prices needed to calculate recurring revenue from synced subscriptions (high)- [ ] `Invoice line items (GET /api/v1/billing/invoices/{id}/line_items)` — allocates synced invoice revenue to products, quantities, discounts, and taxes (high)- [ ] `Products and prices (GET /api/v1/billing/products; GET /api/v1/billing/prices)` — provides the billing catalog and price terms for revenue analysis (high)-- [ ] `Credit notes (GET /api/v1/billing/credit_notes)` — reconciles invoice credits with net revenue and customer balances (high)-- [ ] `Payment disputes (GET /api/v1/pa/payment_disputes)` — links chargebacks to synced payment intents and attempts for loss analysis (high)+- [x] `Credit notes (GET /api/v1/billing/credit_notes)` — reconciles invoice credits with net revenue and customer balances (high)+- [x] `Payment disputes (GET /api/v1/pa/payment_disputes)` — links chargebacks to synced payment intents and attempts for loss analysis (high)- [ ] `Meter summaries (GET /api/v1/billing/meters/{id}/summaries)` — measures billable usage for metered subscriptions (high)- [ ] `Conversions (GET /api/v1/fx/conversions)` — measures currency conversion volume, execution rates, and settlement timing (medium)- [ ] `Balance history (GET /api/v1/balances/history)` — tracks historical cash balances by currency for treasury reports (medium)- [ ] `Card transactions (GET /api/v1/issuing/card_transactions)` — provides merchant and card spend details beyond account ledger entries (medium)- [ ] `Bills and expenses (GET /api/v1/spend/bills; GET /api/v1/spend/expenses)` — measures supplier liabilities and business expenses alongside payments (medium)-Note: Diffed all collection GET paths in Airwallex's official OpenAPI spec, including nested billing resources. Invoice and subscription list responses omit their line items. Items require requests for each parent; meter summaries also need meter discovery and time ranges. Sensitive card details, tokens, webhooks, and account configuration were excluded.+Note: Diffed all collection GET paths in Airwallex's official OpenAPI spec, including nested billing resources. Invoice and subscription list responses omit their line items. Items require requests for each parent; meter summaries also need meter discovery and time ranges. Sensitive card details, tokens, webhooks, and account configuration were excluded. Meter summaries stay out: the endpoint computes a usage aggregate on request for one billing customer and a caller-chosen time range, so it has no stored rows to sync.## Aiven — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/airwallex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/airwallex.pyindex 1e64f19052d9..ec60ef96bf94 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/airwallex.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/airwallex.py@@ -15,13 +15,18 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.httfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,rest_api_resource,+ rest_api_resources,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import AuthConfigBasefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (BasePaginator,JSONResponseCursorPaginator,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpoint+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -56,6 +61,9 @@ class AirwallexResumeConfig:# `page_after` token. Exactly one is set, matching the endpoint's pagination style.page_num: Optional[int] = Nonecursor: Optional[str] = None+ # Framework fan-out snapshot ({"completed": [...], "current": ..., "child_state": ...}) for+ # per-parent child lists such as subscription items.+ fanout_state: Optional[dict[str, Any]] = Nonedef _to_iso8601(value: Any) -> Optional[str]:@@ -234,7 +242,7 @@ def _make_drop_map(drop_fields: tuple[str, ...]) -> Any:def _build_endpoint(config: AirwallexEndpointConfig, should_use_incremental_field: bool) -> Endpoint:endpoint: Endpoint = {"path": config.path,- "params": {"page_size": config.page_size},+ "params": {config.page_size_param: config.page_size},"data_selector": "items",# A missing `items` key means the response shape changed; fail loud rather than syncing 0 rows."data_selector_required": True,@@ -258,6 +266,72 @@ def _build_endpoint(config: AirwallexEndpointConfig, should_use_incremental_fielreturn endpoint+def _client_config(client_id: str, api_key: str, base_url: str, api_version: str) -> ClientConfig:+ return {+ "base_url": base_url,+ "headers": {+ "Accept": "application/json",+ # Pinning the version keeps response shapes stable when Airwallex ships a new one.+ "x-api-version": api_version,+ },+ "auth": AirwallexAuth(client_id, api_key, base_url),+ }+++def _fanout_resource(+ config: AirwallexEndpointConfig,+ client_config: ClientConfig,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[AirwallexResumeConfig],+) -> Resource:+ """Walk the parent list and fetch the child list for each parent row.++ The parent list is re-fetched each run. A resumed run skips parents already done and resumes+ the one in progress from its saved cursor.+ """+ assert config.fanout_parent is not None+ parent_config = AIRWALLEX_ENDPOINTS[config.fanout_parent]++ child_endpoint = _build_endpoint(config, should_use_incremental_field=False)+ child_endpoint["params"] = {+ **(child_endpoint.get("params") or {}),+ "id": {"type": "resolve", "resource": parent_config.name, "field": "id"},+ }++ rest_config: RESTAPIConfig = {+ "client": client_config,+ "resource_defaults": {},+ "resources": [+ {+ "name": parent_config.name,+ "endpoint": _build_endpoint(parent_config, should_use_incremental_field=False),+ },+ {"name": config.name, "endpoint": child_endpoint},+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.fanout_state:+ initial_paginator_state = resume.fanout_state++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state is not None:+ resumable_source_manager.save_state(AirwallexResumeConfig(fanout_state=state))++ resources = rest_api_resources(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+ return next(resource for resource in resources if getattr(resource, "name", None) == config.name)++def airwallex_source(client_id: str,api_key: str,@@ -273,16 +347,14 @@ def airwallex_source(config = AIRWALLEX_ENDPOINTS[endpoint]base_url = base_url_for(environment)+ client_config = _client_config(client_id, api_key, base_url, api_version)++ if config.fanout_parent is not None:+ fanout_resource = _fanout_resource(config, client_config, team_id, job_id, resumable_source_manager)+ return _source_response(config, fanout_resource)+rest_config: RESTAPIConfig = {- "client": {- "base_url": base_url,- "headers": {- "Accept": "application/json",- # Pinning the version keeps response shapes stable when Airwallex ships a new one.- "x-api-version": api_version,- },- "auth": AirwallexAuth(client_id, api_key, base_url),- },+ "client": client_config,"resource_defaults": {},"resources": [{@@ -326,8 +398,12 @@ def airwallex_source(initial_paginator_state=initial_paginator_state,)+ return _source_response(config, resource)+++def _source_response(config: AirwallexEndpointConfig, resource: Resource) -> SourceResponse:return SourceResponse(- name=endpoint,+ name=config.name,items=lambda: resource,primary_keys=config.primary_keys,# Airwallex documents an order for only one of its list endpoints, and that one isdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/canonical_descriptions.pyindex 8b4d89b098ad..0dfd86fe208d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/canonical_descriptions.py@@ -349,4 +349,85 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"updated_at": "Time when the billing customer was last updated.",},},+ "PaymentDisputes": {+ "description": "Disputes and chargebacks raised against payments, with their stage, status, and due date.",+ "docs_url": "https://www.airwallex.com/docs/api/payments/payment_disputes/list",+ "columns": {+ "accept_details": "Further details on why the client is accepting the Payment Dispute event.",+ "acquirer_reference_number": "The acquirer reference number of original payment.",+ "ai_dispute_automation": "Information about AI dispute automation, including recommendation and current status.",+ "amount": "Payment Dispute amount.",+ "card_brand": "The card brand of original payment, applicable when payment_method_type is `CARD`.",+ "challenge_details": "The challenge data submitted at each stage.",+ "connected_account_id": "Account identifier of the connected account.",+ "created_at": "Time at which this Payment Dispute was created.",+ "currency": "Payment Dispute currency.",+ "customer_id": "The customer unique identifier of original payment.",+ "customer_name": "The customer name of original payment.",+ "due_at": "Payment Dispute due date.",+ "id": "Payment Dispute unique identifier.",+ "issuer_comment": "The issuer's comment on Payment Dispute.",+ "issuer_documents": "The issuer's documents on Payment Dispute.",+ "merchant_order_id": "The order unique identifier of original payment.",+ "metadata": "A set of key-value pairs attached to the dispute by the merchant.",+ "mode": "Payment Dispute mode, one of `ALLOCATION` or `COLLABORATION`.",+ "payment_attempt_id": "Payment Attempt unique identifier.",+ "payment_intent_id": "Payment Intent unique identifier.",+ "payment_method_type": "The payment method type of original payment.",+ "reason": "Payment Dispute reason.",+ "refunds": "The Refunds of original payment.",+ "stage": "Payment Dispute stage, one of `RFI`, `PRE_CHARGEBACK`, `CHARGEBACK`, `PRE_ARBITRATION`, `ARBITRATION`.",+ "status": "Payment Dispute status.",+ "transaction_type": "The transaction type of the original transaction, one of `PAYMENT` or `REFUND`.",+ "updated_at": "Last time at which this Payment Dispute was updated or operated on.",+ },+ },+ "CreditNotes": {+ "description": "Credit notes issued against billing invoices, as refunds, adjustments, or out-of-band credits.",+ "docs_url": "https://www.airwallex.com/docs/api/billing/credit_notes/list",+ "columns": {+ "adjustment_amount": "Amount credited to decrease the amount of an unpaid invoice.",+ "billing_customer_id": "ID of the Billing Customer.",+ "created_at": "Time when this credit note was created.",+ "currency": "The currency of the credit note (in 3-letter ISO-4217 format).",+ "custom_reason": "An explanation for issuing the credit note when the reason enum is set to `OTHER`.",+ "e_invoicing_document_id": "The ID of the E-Invoicing Document associated with this Credit Note.",+ "finalized_at": "Time at which the credit note was finalized.",+ "id": "ID of the Credit Note object.",+ "invoice_id": "ID of the Invoice.",+ "memo": "Customer-facing text that appears on the credit note PDF.",+ "metadata": "A set of key-value pairs that you can attach to this object for storing additional information.",+ "number": "A unique number that identifies this particular credit note and appears on the PDF of the credit note and its associated invoice.",+ "out_of_band_amount": "Amount credited outside of Airwallex.",+ "pdf_url": "The link to download the PDF for the credit note.",+ "reason": "Reason for issuing this credit note.",+ "refund_amount": "Amount credited with refund.",+ "refund_status": "Status of the refund, one of `CREATED`, `SUCCEEDED` or `FAILED`.",+ "status": "Status of the credit note, one of `DRAFT`, `FINALIZED`, and `VOIDED`.",+ "total_amount": "The total amount of the credit note, including tax.",+ "total_discount_amounts": "The aggregate amounts calculated per discount across all credit note line items and the credit note.",+ "total_tax_amount": "The aggregate amounts calculated per tax rate for all line items.",+ "type": "The type of the credit note, one of: `BEFORE_PAYMENT`, `AFTER_PAYMENT`.",+ "updated_at": "Time when this credit note was last updated.",+ "voided_at": "Time at which the credit note was voided.",+ },+ },+ "SubscriptionItems": {+ "description": "The prices and quantities each billing subscription is subscribed to.",+ "docs_url": "https://www.airwallex.com/docs/api/billing/subscription_items/list",+ "columns": {+ "applied_discounts": "List of the discounts that are applied to the Subscription Item.",+ "created_at": "Time when the Subscription Item was created.",+ "current_period_ends_at": "The end time of the current period that the subscription item has been invoiced for.",+ "current_period_starts_at": "The start time of the current period that the subscription item has been invoiced for.",+ "id": "ID of the Subscription Item object.",+ "metadata": "A set of string key-value pairs that you can attach to this object for storing additional information.",+ "price": "Price subscribed by the customer.",+ "quantity": "The quantity of the product.",+ "rate_card_version": "The pinned Rate Card Version on a Subscription Item, including the associated Rate Card.",+ "subscription_id": "ID of the Subscription object that this Subscription Item belongs to.",+ "tax_percent": "The effective tax percent of this subscription item.",+ "updated_at": "Time when the Subscription Item was updated.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/settings.pyindex a7de9a593275..a521ed6ef9d3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/settings.py@@ -25,6 +25,11 @@ class AirwallexEndpointConfig:primary_keys: list[str] = field(default_factory=lambda: ["id"])partition_key: Optional[str] = "created_at"page_size: int = 500+ # Most list endpoints take `page_size`; payment disputes take `size`.+ page_size_param: str = "page_size"+ supports_incremental: bool = True+ # Parent endpoint whose `id` fills the `{id}` placeholder in `path`, for per-parent child lists.+ fanout_parent: Optional[str] = None# Fields stripped from every row before it lands in the warehouse (e.g. a live client secret).drop_fields: tuple[str, ...] = ()@@ -121,10 +126,37 @@ AIRWALLEX_ENDPOINTS: dict[str, AirwallexEndpointConfig] = {path="/api/v1/billing/billing_customers",pagination="cursor",),+ # Disputes move through stages and statuses long after creation, so the cursor tracks+ # `updated_at` to pick those changes up.+ "PaymentDisputes": AirwallexEndpointConfig(+ name="PaymentDisputes",+ path="/api/v1/pa/payment_disputes",+ pagination="cursor",+ start_param="from_updated_at",+ cursor_field="updated_at",+ page_size_param="size",+ ),+ "CreditNotes": AirwallexEndpointConfig(+ name="CreditNotes",+ path="/api/v1/billing/credit_notes",+ pagination="cursor",+ ),+ # Items are listed per subscription and take no time filter, so this is full refresh only.+ # Item ids are only documented within their subscription, so the key carries the parent id.+ "SubscriptionItems": AirwallexEndpointConfig(+ name="SubscriptionItems",+ path="/api/v1/billing/subscriptions/{id}/items",+ pagination="cursor",+ primary_keys=["subscription_id", "id"],+ supports_incremental=False,+ fanout_parent="Subscriptions",+ ),}ENDPOINTS = tuple(AIRWALLEX_ENDPOINTS.keys())INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {- name: _incremental_field(config.cursor_field) for name, config in AIRWALLEX_ENDPOINTS.items()+ name: _incremental_field(config.cursor_field)+ for name, config in AIRWALLEX_ENDPOINTS.items()+ if config.supports_incremental}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex.pyindex c912e62e7d7a..7374d5c0ffd8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex.py@@ -171,19 +171,20 @@ class TestAirwallexTransport:@parameterized.expand([- ("FinancialTransactions", "from_created_at"),- ("Settlements", "from_settled_at"),- ("Beneficiaries", "from_date"),- ("Invoices", "from_created_at"),+ ("FinancialTransactions", "created_at", "from_created_at"),+ ("Settlements", "settled_at", "from_settled_at"),+ ("Beneficiaries", "created_at", "from_date"),+ ("Invoices", "created_at", "from_created_at"),+ ("PaymentDisputes", "updated_at", "from_updated_at"),])- def test_incremental_uses_the_endpoints_own_filter_name(self, endpoint: str, param: str) -> None:+ def test_incremental_uses_the_endpoints_own_filter_name(self, endpoint: str, field: str, param: str) -> None:# Airwallex names this filter differently per endpoint, and sends 200 while ignoring a name# it does not know, so a wrong name silently full-scans every run.result = _driver().run(endpoint,[_login_response(), _page([{"id": "1"}], has_more=False)],- incremental_field="settled_at" if endpoint == "Settlements" else "created_at",+ incremental_field=field,db_incremental_field_last_value=datetime(2021, 1, 1, tzinfo=UTC),)@@ -215,6 +216,64 @@ class TestAirwallexTransport:assert [row["id"] for row in result.rows] == ["1", "2"]assert result.params("page") == [None, None, "cur1"]+ @parameterized.expand([("PaymentDisputes", "size", "page_size"), ("CreditNotes", "page_size", "size")])+ def test_page_size_rides_the_endpoints_own_param(self, endpoint: str, param: str, unused: str) -> None:+ # An unknown size param is ignored, so disputes would fall back to 10 rows per page.+ result = _driver().run(endpoint, [_login_response(), _page([{"id": "1"}])])++ assert result.raised is None+ assert result.requests[1].param(param) == "500"+ assert result.requests[1].param(unused) is None++ def test_subscription_items_fan_out_over_every_subscription(self) -> None:+ result = _driver().run(+ "SubscriptionItems",+ [+ _login_response(),+ _page([{"id": "sub_1"}, {"id": "sub_2"}]),+ _page([{"id": "si_1", "subscription_id": "sub_1"}], page_after="cur1"),+ _page([{"id": "si_2", "subscription_id": "sub_1"}]),+ _page([{"id": "si_1", "subscription_id": "sub_2"}]),+ ],+ )++ assert result.raised is None+ assert result.paths[1:] == [+ "/api/v1/billing/subscriptions",+ "/api/v1/billing/subscriptions/sub_1/items",+ "/api/v1/billing/subscriptions/sub_1/items",+ "/api/v1/billing/subscriptions/sub_2/items",+ ]+ assert result.params("page")[2:] == [None, "cur1", None]+ assert [(row["subscription_id"], row["id"]) for row in result.rows] == [+ ("sub_1", "si_1"),+ ("sub_1", "si_2"),+ ("sub_2", "si_1"),+ ]+ assert result.response is not None+ # Item ids are only documented as unique within a subscription.+ assert result.response.primary_keys == ["subscription_id", "id"]++ def test_subscription_items_resume_skips_finished_subscriptions(self) -> None:+ result = _driver().run(+ "SubscriptionItems",+ [+ _login_response(),+ _page([{"id": "sub_1"}, {"id": "sub_2"}]),+ _page([{"id": "si_1", "subscription_id": "sub_2"}]),+ ],+ resume_state=AirwallexResumeConfig(+ fanout_state={+ "completed": ["/api/v1/billing/subscriptions/sub_1/items"],+ "current": None,+ "child_state": None,+ }+ ),+ )++ assert result.raised is None+ assert result.paths[1:] == ["/api/v1/billing/subscriptions", "/api/v1/billing/subscriptions/sub_2/items"]+def test_page_number_paginator_stops_at_the_api_cap(self) -> None:# page_num is capped at 2000; walking past it would request pages the API rejects.paginator = AirwallexPageNumberPaginator(page_num=MAX_PAGE_NUM, endpoint="FinancialTransactions")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex_source.pyindex 97d2651cde07..480a4ed5444b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex_source.py@@ -21,6 +21,7 @@ class TestAirwallexSource:("settlements_track_settled_at", "Settlements", "settled_at"),("beneficiaries_track_created_at", "Beneficiaries", "created_at"),("transactions_track_created_at", "FinancialTransactions", "created_at"),+ ("disputes_track_updated_at", "PaymentDisputes", "updated_at"),])def test_incremental_cursor_matches_the_field_the_filter_bounds(