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(warehouse-sources): add mollie balance, profile and mandate tables (#115454)

Tom Owers6d75b57dad18
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 9cdeae1a853b..e8be954667c9 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
@@ -5674,10 +5674,10 @@ Today (7): `chargebacks`, `customers`, `payment_links`, `payments`, `refunds`, `
Diffed against: <https://raw.githubusercontent.com/mollie/openapi/main/specs.yaml>
-- [ ] `/v2/balances/{balanceId}/transactions` — per-transaction ledger of every movement (payment, refund, fee, payout) — the reconciliation fact table (high)
-- [ ] `/v2/balances` — balance accounts that transactions and settlements roll up to; lookup for balanceId (high)
-- [ ] `/v2/profiles` — lookup resolving the profileId carried on payments, payment links and methods (high)
-- [ ] `/v2/customers/{customerId}/mandates` — SEPA/card mandates that subscriptions and recurring payments reference (high)
+- [x] `/v2/balances/{balanceId}/transactions` — per-transaction ledger of every movement (payment, refund, fee, payout) — the reconciliation fact table (high)
+- [x] `/v2/balances` — balance accounts that transactions and settlements roll up to; lookup for balanceId (high)
+- [x] `/v2/profiles` — lookup resolving the profileId carried on payments, payment links and methods (high)
+- [x] `/v2/customers/{customerId}/mandates` — SEPA/card mandates that subscriptions and recurring payments reference (high)
- [ ] `/v2/payouts` — bank payouts of settled funds — needed to tie settlements to money received (high)
- [ ] `/v2/payments/{paymentId}/captures` — capture events on authorized payments; without them captured vs authorized amounts can't be split (medium)
- [ ] `/v2/invoices` — Mollie's own invoices to the merchant (fees charged) for cost analysis (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/canonical_descriptions.py
index 3f41efa8c11d..156a17788142 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/canonical_descriptions.py
@@ -117,4 +117,62 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
expiresAt="Time at which the payment link expires, in ISO 8601 format.",
),
},
+ "balances": {
+ "description": "A Mollie balance account. Payments, refunds, fees and payouts are booked to a balance.",
+ "docs_url": "https://docs.mollie.com/reference/get-balance",
+ "columns": _columns(
+ currency="ISO 4217 currency code of the balance.",
+ description="Description or name of the balance, used to denote its purpose.",
+ status="Status of the balance: active or inactive.",
+ transferFrequency="How often the available amount is transferred to the transfer destination.",
+ transferThreshold="Minimum available amount required before an automatic transfer is made.",
+ transferReference="Transfer reference included in all transfers for this balance.",
+ transferDestination="Destination the available amount is automatically transferred to.",
+ availableAmount="Amount directly available on the balance, as a value/currency object.",
+ pendingAmount="Amount that is queued to be added to the balance, as a value/currency object.",
+ ),
+ },
+ "balance_transactions": {
+ "description": "A single movement of funds on a Mollie balance, such as a payment, refund, chargeback, fee or settlement.",
+ "docs_url": "https://docs.mollie.com/reference/list-balance-transactions",
+ "columns": _columns(
+ balanceId="Identifier of the balance the transaction was booked to.",
+ type="Type of transaction, for example payment, refund, chargeback or outgoing-transfer.",
+ resultAmount="Final amount moved to or from the balance after deductions. Negative when funds leave the balance.",
+ initialAmount="Amount to be moved to or from the balance, excluding deductions.",
+ deductions="Total amount of deductions (such as fees) withheld from the movement.",
+ deductionDetails="Breakdown of the deductions withheld from the movement, by deduction type.",
+ context="Extra context about the event that triggered the transaction, such as the related payment ID.",
+ ),
+ },
+ "profiles": {
+ "description": "A Mollie payment profile (website or app) that payments, payment links and payment methods belong to.",
+ "docs_url": "https://docs.mollie.com/reference/get-profile",
+ "columns": _columns(
+ name="Name of the profile, usually the website or app name.",
+ website="URL of the profile's website or app.",
+ email="Email address associated with the profile.",
+ phone="Phone number associated with the profile.",
+ businessCategory="Industry the profile's trade name or brand is associated with.",
+ status="Verification status of the profile: unverified, verified, or blocked.",
+ review="Present when changes to the profile are pending review by Mollie.",
+ ),
+ },
+ "mandates": {
+ "description": "A customer's authorization (mandate) that lets you charge their account or card for recurring payments.",
+ "docs_url": "https://docs.mollie.com/reference/get-mandate",
+ "columns": _columns(
+ customerId="Identifier of the customer the mandate is linked to.",
+ method="Payment method of the mandate, such as directdebit, creditcard or paypal.",
+ consumerName="The customer's name.",
+ consumerAccount="The customer's IBAN or card number details.",
+ consumerBic="The BIC of the customer's bank.",
+ consumerEmail="The customer's email address.",
+ details="Payment method specific details of the mandate.",
+ signatureDate="Date the mandate was signed, in YYYY-MM-DD format.",
+ mandateReference="Custom reference for the mandate.",
+ scopes="Use cases the mandate is eligible for.",
+ status="Status of the mandate: valid, pending, or invalid.",
+ ),
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/mollie.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/mollie.py
index 98d112951445..ea18221d2feb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/mollie.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/mollie.py
@@ -1,4 +1,5 @@
import dataclasses
+from collections.abc import Callable, Iterable
from typing import Any, Optional
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
@@ -6,24 +7,46 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
RESTAPIConfig,
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 (
JSONResponsePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.sources.mollie.settings import MOLLIE_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.mollie.settings import (
+ MOLLIE_ENDPOINTS,
+ MollieEndpointConfig,
+)
MOLLIE_BASE_URL = "https://api.mollie.com/v2"
-# Mollie list pages cap at 250 items.
-PAGE_SIZE = 250
[email protected](frozen=True)
class MollieResumeConfig:
# Mollie paginates via the HAL `_links.next.href` URL, which is
# self-contained (ID-anchored `from` cursor), so the URL is all we persist.
- next_url: str
+ next_url: Optional[str] = None
+ # Nested endpoints store the `build_dependent_resource` checkpoint instead: which parents
+ # finished and where the current one stopped.
+ fanout_state: Optional[dict[str, Any]] = None
+
+
+def _source_response(endpoint: str, config: MollieEndpointConfig, items: Callable[[], Iterable[Any]]) -> SourceResponse:
+ return SourceResponse(
+ name=endpoint,
+ items=items,
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[config.partition_key],
+ sort_mode="asc",
+ )
def mollie_source(
@@ -35,22 +58,50 @@ def mollie_source(
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
config = MOLLIE_ENDPOINTS[endpoint]
+ client_config: ClientConfig = {
+ "base_url": MOLLIE_BASE_URL,
+ # Bearer is supplied via the framework auth config so its value is redacted from logs
+ # and raised error messages.
+ "auth": {"type": "bearer", "token": api_key},
+ # Mollie paginates via the HAL `_links.next.href` URL, which is self-contained.
+ "paginator": JSONResponsePaginator(next_url_path="_links.next.href"),
+ }
+
+ resume: Optional[MollieResumeConfig] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+
+ if config.fanout is not None:
+ parent_config = MOLLIE_ENDPOINTS[config.fanout.parent_name]
+
+ def save_fanout_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state:
+ resumable_source_manager.save_state(MollieResumeConfig(fanout_state=state))
+
+ child = build_dependent_resource(
+ endpoint_configs=MOLLIE_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=config.fanout,
+ client_config=client_config,
+ parent_endpoint_extra={"data_selector": f"_embedded.{parent_config.embedded_key}"},
+ child_endpoint_extra={"data_selector": f"_embedded.{config.embedded_key}"},
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ resume_hook=save_fanout_checkpoint,
+ initial_paginator_state=resume.fanout_state if resume else None,
+ )
+ return _source_response(endpoint, config, lambda: child)
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": MOLLIE_BASE_URL,
- # Bearer is supplied via the framework auth config so its value is redacted from logs
- # and raised error messages.
- "auth": {"type": "bearer", "token": api_key},
- # Mollie paginates via the HAL `_links.next.href` URL, which is self-contained.
- "paginator": JSONResponsePaginator(next_url_path="_links.next.href"),
- },
+ "client": client_config,
"resources": [
{
"name": endpoint,
"endpoint": {
"path": config.path,
- "params": {"limit": PAGE_SIZE},
+ "params": {"limit": config.page_size},
# Rows live under the HAL `_embedded.<key>` object. A missing block is a
# legitimate empty page (yield nothing), not an error, so no data_selector_required.
"data_selector": f"_embedded.{config.embedded_key}",
@@ -60,10 +111,8 @@ def mollie_source(
}
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:
- initial_paginator_state = {"next_url": resume.next_url}
+ if resume is not None and resume.next_url:
+ initial_paginator_state = {"next_url": resume.next_url}
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
# Save state AFTER yielding a page so a crash re-yields the last page (merge dedupes on
@@ -80,17 +129,7 @@ def mollie_source(
initial_paginator_state=initial_paginator_state,
)
- return SourceResponse(
- name=endpoint,
- items=lambda: resource,
- primary_keys=[config.primary_key],
- partition_count=1,
- partition_size=1,
- partition_mode="datetime",
- partition_format="month",
- partition_keys=[config.partition_key],
- sort_mode="asc",
- )
+ return _source_response(endpoint, config, lambda: resource)
def validate_credentials(api_key: str) -> bool:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/settings.py
index 39d39da82531..ca5b0906dee2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/settings.py
@@ -1,15 +1,27 @@
-from dataclasses import dataclass
+from dataclasses import dataclass, field
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
-@dataclass
+# Mollie list pages cap at 250 items.
+PAGE_SIZE = 250
+
+
+@dataclass(frozen=True)
class MollieEndpointConfig:
name: str
path: str
# Key the rows live under inside the HAL `_embedded` object.
embedded_key: str
- primary_key: str = "id"
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
# Every Mollie resource carries an immutable createdAt.
partition_key: str = "createdAt"
+ page_size: int = PAGE_SIZE
+ incremental_fields: list[str] = field(default_factory=list)
+ default_incremental_field: str | None = None
+ # Set for endpoints nested under a parent resource (e.g. /customers/{customerId}/mandates).
+ fanout: DependentEndpointConfig | None = None
# No Mollie v2 list endpoint supports created/updated-since filtering — only an
@@ -52,6 +64,45 @@ MOLLIE_ENDPOINTS: dict[str, MollieEndpointConfig] = {
path="/payment-links",
embedded_key="payment_links",
),
+ # Balances, balance transactions, settlements and profiles are organization-level resources:
+ # Mollie serves them only to access tokens, never to a profile API key.
+ "balances": MollieEndpointConfig(
+ name="balances",
+ path="/balances",
+ embedded_key="balances",
+ ),
+ "balance_transactions": MollieEndpointConfig(
+ name="balance_transactions",
+ path="/balances/{balanceId}/transactions",
+ embedded_key="balance_transactions",
+ # Transaction rows don't carry their balance id, so it comes from the parent row.
+ primary_keys=["balanceId", "id"],
+ fanout=DependentEndpointConfig(
+ parent_name="balances",
+ resolve_param="balanceId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "balanceId"},
+ ),
+ ),
+ "profiles": MollieEndpointConfig(
+ name="profiles",
+ path="/profiles",
+ embedded_key="profiles",
+ ),
+ "mandates": MollieEndpointConfig(
+ name="mandates",
+ path="/customers/{customerId}/mandates",
+ embedded_key="mandates",
+ primary_keys=["customerId", "id"],
+ fanout=DependentEndpointConfig(
+ parent_name="customers",
+ resolve_param="customerId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "customerId"},
+ ),
+ ),
}
ENDPOINTS = tuple(MOLLIE_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/source.py
index 5817c3a2ab41..a8a4d27afd83 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/source.py
@@ -59,7 +59,9 @@ class MollieSource(ResumableSource[MollieSourceConfig, MollieResumeConfig]):
label="Mollie",
caption="""Enter your Mollie API key to pull your Mollie payments data into the PostHog Data warehouse.
-You can find your API key in the [Mollie dashboard](https://my.mollie.com/dashboard/developers/api-keys) under Developers > API keys. Use a live key (`live_...`) for production data — test keys only return test-mode data.""",
+You can find your API key in the [Mollie dashboard](https://my.mollie.com/dashboard/developers/api-keys) under Developers > API keys. Use a live key (`live_...`) for production data — test keys only return test-mode data.
+
+The balances, balance transactions, settlements and profiles tables are organization-level data that Mollie only shares with an [organization access token](https://docs.mollie.com/docs/authentication). To sync them, connect an access token (`access_...`) that is scoped to your payment profile and has read permissions for those resources.""",
iconPath="/static/services/mollie.png",
docsUrl="https://posthog.com/docs/cdp/sources/mollie",
releaseStatus=ReleaseStatus.GA,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/tests/test_mollie.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/tests/test_mollie.py
index b26e81390989..96d743c0d893 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/tests/test_mollie.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mollie/tests/test_mollie.py
@@ -132,6 +132,62 @@ class TestPagination:
assert rows == []
+class TestFanOut:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_mandates_walk_every_customer_and_carry_customer_id(self, MockSession) -> None:
+ session = MockSession.return_value
+ child_next = "https://api.mollie.com/v2/customers/cst_1/mandates?from=mdt_2&limit=250"
+ urls, _params = _wire(
+ session,
+ [
+ _response("customers", [{"id": "cst_1"}, {"id": "cst_2"}]),
+ _response("mandates", [{"id": "mdt_1"}], next_url=child_next),
+ _response("mandates", [{"id": "mdt_2"}]),
+ _response("mandates", [{"id": "mdt_3"}]),
+ ],
+ )
+
+ manager = _make_manager()
+ source = _source("mandates", manager)
+ rows = _rows(source)
+
+ assert [(r["customerId"], r["id"]) for r in rows] == [
+ ("cst_1", "mdt_1"),
+ ("cst_1", "mdt_2"),
+ ("cst_2", "mdt_3"),
+ ]
+ assert all("_customers_id" not in r for r in rows)
+ assert source.primary_keys == ["customerId", "id"]
+ assert urls[1].endswith("/customers/cst_1/mandates")
+ assert urls[2] == child_next
+ assert urls[3].endswith("/customers/cst_2/mandates")
+ last_state = manager.save_state.call_args.args[0]
+ assert last_state.next_url is None
+ assert last_state.fanout_state["completed"] == ["/customers/cst_1/mandates", "/customers/cst_2/mandates"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resume_skips_balances_already_finished(self, MockSession) -> None:
+ session = MockSession.return_value
+ urls, _params = _wire(
+ session,
+ [
+ _response("balances", [{"id": "bal_1"}, {"id": "bal_2"}]),
+ _response("balance_transactions", [{"id": "baltr_9"}]),
+ ],
+ )
+
+ manager = _make_manager(
+ MollieResumeConfig(
+ fanout_state={"completed": ["/balances/bal_1/transactions"], "current": None, "child_state": None}
+ )
+ )
+ rows = _rows(_source("balance_transactions", manager))
+
+ assert [(r["balanceId"], r["id"]) for r in rows] == [("bal_2", "baltr_9")]
+ assert len(urls) == 2
+ assert urls[1].endswith("/balances/bal_2/transactions")
+
+
class TestRetries:
@mock.patch("tenacity.nap.time.sleep", return_value=None)
@mock.patch(CLIENT_SESSION_PATCH)