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): add mercury statement, treasury and merchant tables (#115056)

Tom Owers4eb5ef895544
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 c8de11e9e4df..9fba3599581b 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
@@ -5529,14 +5529,14 @@ Note: The reference is a static HTML tree; the full endpoint list is readable fr
## Mercury — gaps
-Today (11): `Accounts`, `Cards`, `Categories`, `CreditAccounts`, `Customers`, `Events`, `Invoices`, `Recipients`, `Transactions`, `TreasuryAccounts`, `Users`
+Today (15): `AccountStatements`, `Accounts`, `Cards`, `Categories`, `CreditAccounts`, `Customers`, `Events`, `Invoices`, `Merchants`, `Recipients`, `Transactions`, `TreasuryAccounts`, `TreasuryStatements`, `TreasuryTransactions`, `Users`
Diffed against: <https://docs.mercury.com/reference/getaccounts>
-- [ ] `merchants (GET /api/v1/merchants)` — lookup table that resolves the merchant IDs already carried on synced Transactions (high)
-- [ ] `account statements (GET /api/v1/account/{accountId}/statements)` — period-level opening/closing balances for reconciliation against Accounts (high)
-- [ ] `treasury transactions (GET /api/v1/treasury/{treasuryId}/transactions)` — we sync TreasuryAccounts but none of their activity, so treasury yield/flows are unqueryable (high)
-- [ ] `treasury statements (GET /api/v1/treasury/{treasuryId}/statements)` — period balances for treasury accounts (medium)
+- [x] `merchants (GET /api/v1/merchants)` — lookup table that resolves the merchant IDs already carried on synced Transactions (high). Added as `Merchants`. The endpoint lists priority merchants for card spend controls, so its IDs resolve `merchantLock` on Cards rather than Transactions.
+- [x] `account statements (GET /api/v1/account/{accountId}/statements)` — period-level opening/closing balances for reconciliation against Accounts (high). Added as `AccountStatements` (fan-out over `Accounts`). The API returns only the ending balance per period.
+- [x] `treasury transactions (GET /api/v1/treasury/{treasuryId}/transactions)` — we sync TreasuryAccounts but none of their activity, so treasury yield/flows are unqueryable (high). Added as `TreasuryTransactions` (fan-out over `TreasuryAccounts`).
+- [x] `treasury statements (GET /api/v1/treasury/{treasuryId}/statements)` — period balances for treasury accounts (medium). Added as `TreasuryStatements` (fan-out over `TreasuryAccounts`). Rows are statement documents (monthly statements, trade confirmations, tax forms) with no balance fields.
- [ ] `send money approval requests (GET /api/v1/request-send-money)` — approval state/transition history for outbound payments (medium)
- [ ] `recipient invites (GET /api/v1/recipient-invites)` — pending recipient onboarding state alongside synced Recipients (low)
- [ ] `SAFE requests (GET /api/v1/safes)` — fundraising SAFE request records (low)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/canonical_descriptions.py
index c348731f74e7..0c72559964eb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/canonical_descriptions.py
@@ -3,6 +3,24 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
)
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "AccountStatements": {
+ "description": "A monthly statement for a Mercury bank account, with the period's ending balance and the transactions it covers.",
+ "docs_url": "https://docs.mercury.com/reference/getaccountstatements",
+ "columns": {
+ "id": "Unique identifier for the account statement.",
+ "accountId": "The Mercury account this statement belongs to.",
+ "startDate": "Start of the period covered by the statement.",
+ "endDate": "End of the period covered by the statement.",
+ "endingBalance": "Account balance at the end of the statement period, in dollars.",
+ "accountNumber": "Bank account number printed on the statement.",
+ "routingNumber": "Bank routing number printed on the statement.",
+ "companyLegalName": "Legal name of the company on the statement.",
+ "companyLegalAddress": "Legal address of the company on the statement.",
+ "ein": "Employer identification number on the statement, if any.",
+ "downloadUrl": "URL to download the statement PDF.",
+ "transactions": "IDs and timestamps of the transactions included in the statement.",
+ },
+ },
"Accounts": {
"description": "A bank account (checking or savings) in your Mercury organization, including balances and routing details.",
"docs_url": "https://docs.mercury.com/reference/getaccounts",
@@ -117,6 +135,14 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"slug": "Unique identifier used to build public payment URLs for this invoice.",
},
},
+ "Merchants": {
+ "description": "A priority merchant that can be used in card spend controls such as merchant locking.",
+ "docs_url": "https://docs.mercury.com/reference/listmerchants",
+ "columns": {
+ "id": "Unique identifier for the merchant.",
+ "name": "Name of the merchant.",
+ },
+ },
"Recipients": {
"description": "A payment recipient saved in your Mercury organization, with routing and payment method details.",
"docs_url": "https://docs.mercury.com/reference/getrecipients",
@@ -178,6 +204,38 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"netReturns": "Monthly net return breakdown with dividend and fee details.",
},
},
+ "TreasuryStatements": {
+ "description": "A document for a Mercury treasury account, such as a monthly statement, trade confirmation, or tax form.",
+ "docs_url": "https://docs.mercury.com/reference/gettreasurystatements",
+ "columns": {
+ "id": "Unique identifier for the statement.",
+ "accountId": "The treasury account this statement belongs to.",
+ "documentType": "Type of document, such as MonthlyStatement, TradeConfirmation, or a tax form.",
+ "description": "Human-readable description of the statement.",
+ "periodStart": "Start of the period covered by the statement.",
+ "periodEnd": "End of the period covered by the statement.",
+ "creationDate": "Date the custodian created the statement.",
+ "createdAt": "When the statement record was created.",
+ "updatedAt": "When the statement record was last updated.",
+ "downloadUrl": "URL to download the statement PDF.",
+ },
+ },
+ "TreasuryTransactions": {
+ "description": "A ledger entry on a Mercury treasury account, such as a deposit, withdrawal, dividend, interest payment, or fee.",
+ "docs_url": "https://docs.mercury.com/reference/gettreasurytransactions",
+ "columns": {
+ "id": "Unique identifier for the treasury transaction.",
+ "accountId": "The treasury account this transaction belongs to.",
+ "type": "Kind of treasury transaction, such as depositComplete, dividendPosted, or interestPosted.",
+ "amount": "Transaction amount, in dollars.",
+ "balance": "Treasury account balance after this transaction, in dollars.",
+ "canonicalDay": "Day the transaction applies to.",
+ "description": "Description of the transaction.",
+ "security": "Security involved in the transaction, if any.",
+ "details": "Extra details such as trade action, sweep direction, and counterparty account IDs.",
+ "additionalDetails": "Free-text additional details about the transaction, if any.",
+ },
+ },
"Users": {
"description": "A user in your Mercury organization.",
"docs_url": "https://docs.mercury.com/reference/getusers",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/mercury.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/mercury.py
index 47cc9e7a22dd..85b6ef18aed6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/mercury.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/mercury.py
@@ -1,26 +1,32 @@
import dataclasses
from datetime import UTC, date, datetime
-from typing import Any, Optional
+from typing import Any, Optional, cast
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
JSONResponseCursorPaginator,
SinglePagePaginator,
)
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,
EndpointResource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.mercury.settings import (
- DEFAULT_PAGE_SIZE,
MERCURY_BASE_URL,
MERCURY_ENDPOINTS,
+ MercuryEndpointConfig,
)
@@ -50,12 +56,31 @@ def format_incremental_value(value: Any) -> str | None:
return str(value)[:10]
+def _paginator(config: MercuryEndpointConfig) -> BasePaginator:
+ if not config.paginated:
+ return SinglePagePaginator()
+ return JSONResponseCursorPaginator(cursor_path=config.cursor_path, cursor_param=config.cursor_param)
+
+
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": MERCURY_BASE_URL,
+ "auth": {
+ "type": "bearer",
+ "token": api_key,
+ },
+ "headers": {
+ "Accept": "application/json",
+ },
+ }
+
+
def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:
config = MERCURY_ENDPOINTS[name]
params: dict[str, Any] = {}
if config.paginated:
- params["limit"] = DEFAULT_PAGE_SIZE
+ params["limit"] = config.page_size
# Explicit ascending order so cursor pages arrive oldest-first and the incremental
# watermark only ever advances.
params["order"] = "asc"
@@ -72,9 +97,7 @@ def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResou
"path": config.path,
"data_selector": config.data_selector,
"params": params,
- "paginator": JSONResponseCursorPaginator(cursor_path="page.nextPage", cursor_param="start_after")
- if config.paginated
- else SinglePagePaginator(),
+ "paginator": _paginator(config),
}
resource: EndpointResource = {
@@ -105,17 +128,12 @@ def mercury_source(
db_incremental_field_last_value: Optional[Any],
should_use_incremental_field: bool = False,
) -> Resource:
+ endpoint_config = MERCURY_ENDPOINTS[endpoint]
+ if endpoint_config.fanout is not None:
+ return _dependent_resource(api_key, endpoint_config, endpoint_config.fanout, team_id, job_id)
+
config: RESTAPIConfig = {
- "client": {
- "base_url": MERCURY_BASE_URL,
- "auth": {
- "type": "bearer",
- "token": api_key,
- },
- "headers": {
- "Accept": "application/json",
- },
- },
+ "client": _client_config(api_key),
"resource_defaults": {},
"resources": [get_resource(endpoint, should_use_incremental_field)],
}
@@ -142,6 +160,36 @@ def mercury_source(
)
+def _dependent_resource(
+ api_key: str, config: MercuryEndpointConfig, fanout: DependentEndpointConfig, team_id: int, job_id: str
+) -> Resource:
+ parent_config = MERCURY_ENDPOINTS[fanout.parent_name]
+ # The per-account children have no server-side time filter, so they are always full refresh.
+ # They carry no resume state: one saved cursor cannot address both the parent and child pages.
+ return cast(
+ Resource,
+ build_dependent_resource(
+ endpoint_configs=MERCURY_ENDPOINTS,
+ child_endpoint=config.name,
+ fanout=fanout,
+ client_config=_client_config(api_key),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ child_params_extra={"order": "asc"},
+ parent_endpoint_extra={
+ "paginator": _paginator(parent_config),
+ "data_selector": parent_config.data_selector,
+ },
+ child_endpoint_extra={
+ "paginator": _paginator(config),
+ "data_selector": config.data_selector,
+ },
+ ),
+ )
+
+
def check_credentials(api_key: str) -> int:
"""Probe the cheapest authenticated endpoint and return the HTTP status code."""
response = make_tracked_session(redact_values=(api_key,)).get(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/settings.py
index f1577180de60..d17e0aebc3f4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/settings.py
@@ -1,5 +1,8 @@
-from dataclasses import dataclass
+from dataclasses import dataclass, field
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.types import IncrementalField
@@ -20,7 +23,7 @@ class MercuryEndpointConfig:
name: str
path: str
data_selector: str
- primary_key: str = "id"
+ primary_keys: tuple[str, ...] = ("id",)
# Stable datetime field used for Delta partitioning; None disables partitioning.
partition_key: str | None = None
# Cursor-paginated endpoints accept limit/order/start_after; /credit returns one page.
@@ -29,9 +32,34 @@ class MercuryEndpointConfig:
timestamp_columns: tuple[str, ...] = ()
# Server-side query param mapped from the user's incremental field, when the API has one.
incremental_param: str | None = None
+ # Body path of the next-page cursor and the query param it is sent back in.
+ cursor_path: str = "page.nextPage"
+ cursor_param: str = "start_after"
+ page_size: int = DEFAULT_PAGE_SIZE
+ # Per-account child endpoints, fanned out over a parent account listing.
+ fanout: DependentEndpointConfig | None = None
+ # Required by the shared fan-out helper; fan-out children here have no server-side time filter.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: str | None = None
MERCURY_ENDPOINTS: dict[str, MercuryEndpointConfig] = {
+ "AccountStatements": MercuryEndpointConfig(
+ name="AccountStatements",
+ path="/account/{accountId}/statements",
+ data_selector="statements",
+ # Statement rows do not carry their account id, so it is copied in from the parent row.
+ primary_keys=("accountId", "id"),
+ partition_key="startDate",
+ timestamp_columns=("startDate", "endDate"),
+ fanout=DependentEndpointConfig(
+ parent_name="Accounts",
+ resolve_param="accountId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "accountId"},
+ ),
+ ),
"Accounts": MercuryEndpointConfig(
name="Accounts",
path="/accounts",
@@ -78,6 +106,11 @@ MERCURY_ENDPOINTS: dict[str, MercuryEndpointConfig] = {
partition_key="createdAt",
timestamp_columns=("createdAt", "updatedAt", "canceledAt"),
),
+ "Merchants": MercuryEndpointConfig(
+ name="Merchants",
+ path="/merchants",
+ data_selector="data",
+ ),
"Recipients": MercuryEndpointConfig(
name="Recipients",
path="/recipients",
@@ -98,11 +131,40 @@ MERCURY_ENDPOINTS: dict[str, MercuryEndpointConfig] = {
data_selector="accounts",
timestamp_columns=("createdAt",),
),
+ "TreasuryStatements": MercuryEndpointConfig(
+ name="TreasuryStatements",
+ path="/treasury/{treasuryId}/statements",
+ data_selector="statements",
+ primary_keys=("accountId", "id"),
+ partition_key="createdAt",
+ timestamp_columns=("createdAt", "updatedAt", "creationDate"),
+ fanout=DependentEndpointConfig(
+ parent_name="TreasuryAccounts",
+ resolve_param="treasuryId",
+ resolve_field="id",
+ include_from_parent=[],
+ ),
+ ),
+ "TreasuryTransactions": MercuryEndpointConfig(
+ name="TreasuryTransactions",
+ path="/treasury/{treasuryId}/transactions",
+ data_selector="transactions",
+ primary_keys=("accountId", "id"),
+ # Unlike the other list endpoints, this one pages with an integer `cursor` in the body.
+ cursor_path="cursor",
+ cursor_param="cursor",
+ fanout=DependentEndpointConfig(
+ parent_name="TreasuryAccounts",
+ resolve_param="treasuryId",
+ resolve_field="id",
+ include_from_parent=[],
+ ),
+ ),
"Users": MercuryEndpointConfig(
name="Users",
path="/users",
data_selector="users",
- primary_key="userId",
+ primary_keys=("userId",),
),
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/source.py
index 412bf67cc3d8..25ec66f82585 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/source.py
@@ -17,7 +17,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch
SourceSchema,
build_endpoint_schemas,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
+ SourceInputs,
+ SourceResponse,
+ TDataType,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mercury import (
MercurySourceConfig,
)
@@ -108,6 +112,10 @@ class MercurySource(ResumableSource[MercurySourceConfig, MercuryResumeConfig]):
inputs: SourceInputs,
) -> SourceResponse:
endpoint_config = MERCURY_ENDPOINTS[inputs.schema_name]
+ # Derived from settings because fan-out child resources carry no `columns` hint of their own.
+ column_hints: dict[str, TDataType | None] | None = (
+ dict.fromkeys(endpoint_config.timestamp_columns, "timestamp") or None
+ )
resource = mercury_source(
api_key=config.api_key,
endpoint=inputs.schema_name,
@@ -124,8 +132,8 @@ class MercurySource(ResumableSource[MercurySourceConfig, MercuryResumeConfig]):
return SourceResponse(
name=resource.name,
items=lambda: resource,
- primary_keys=[endpoint_config.primary_key],
- column_hints=resource.column_hints,
+ primary_keys=list(endpoint_config.primary_keys),
+ column_hints=column_hints,
partition_count=1,
partition_size=1,
partition_mode="datetime",
@@ -137,8 +145,8 @@ class MercurySource(ResumableSource[MercurySourceConfig, MercuryResumeConfig]):
return SourceResponse(
name=resource.name,
items=lambda: resource,
- primary_keys=[endpoint_config.primary_key],
- column_hints=resource.column_hints,
+ primary_keys=list(endpoint_config.primary_keys),
+ column_hints=column_hints,
sort_mode="asc",
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/tests/test_mercury.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/tests/test_mercury.py
index 13e6badf289d..bbbc3a3bf016 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/tests/test_mercury.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mercury/tests/test_mercury.py
@@ -148,3 +148,96 @@ class TestMercurySourceResumeBehavior:
assert sent_params[0]["start"] == "2026-01-02"
assert sent_params[0]["order"] == "asc"
+
+
+class TestMercuryFanoutEndpoints:
+ @pytest.mark.parametrize(
+ (
+ "endpoint",
+ "parent_body",
+ "child_bodies",
+ "expected_paths",
+ "cursor_param",
+ "expected_cursors",
+ "expected_rows",
+ ),
+ [
+ (
+ "AccountStatements",
+ {"accounts": [{"id": "acc-1"}, {"id": "acc-2"}], "page": {"nextPage": None}},
+ [
+ {"statements": [{"id": "s1"}], "page": {"nextPage": "s1"}},
+ {"statements": [{"id": "s2"}], "page": {}},
+ {"statements": [{"id": "s3"}], "page": {"nextPage": None}},
+ ],
+ ["/account/acc-1/statements", "/account/acc-1/statements", "/account/acc-2/statements"],
+ "start_after",
+ [None, "s1", None],
+ [
+ {"id": "s1", "accountId": "acc-1"},
+ {"id": "s2", "accountId": "acc-1"},
+ {"id": "s3", "accountId": "acc-2"},
+ ],
+ ),
+ (
+ "TreasuryTransactions",
+ {"accounts": [{"id": "tr-1"}, {"id": "tr-2"}], "page": {"nextPage": None}},
+ [
+ {"transactions": [{"id": "t1", "accountId": "tr-1"}], "cursor": 7},
+ {"transactions": [{"id": "t2", "accountId": "tr-1"}], "cursor": None},
+ {"transactions": [{"id": "t3", "accountId": "tr-2"}]},
+ ],
+ ["/treasury/tr-1/transactions", "/treasury/tr-1/transactions", "/treasury/tr-2/transactions"],
+ "cursor",
+ [None, 7, None],
+ [
+ {"id": "t1", "accountId": "tr-1"},
+ {"id": "t2", "accountId": "tr-1"},
+ {"id": "t3", "accountId": "tr-2"},
+ ],
+ ),
+ ],
+ )
+ def test_walks_child_pages_for_each_parent_account(
+ self,
+ endpoint: str,
+ parent_body: dict[str, Any],
+ child_bodies: list[dict[str, Any]],
+ expected_paths: list[str],
+ cursor_param: str,
+ expected_cursors: list[Any],
+ expected_rows: list[dict[str, Any]],
+ ) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ responses = iter([_make_http_response(parent_body), *(_make_http_response(b) for b in child_bodies)])
+ sent: list[tuple[str, dict[str, Any]]] = []
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent.append((request.url, dict(request.params or {})))
+ return next(responses)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ resource = mercury_source(
+ api_key="test-token",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=None,
+ )
+ rows = [row for page in cast(Iterable[Any], resource) for row in page]
+
+ child_requests = sent[1:]
+ assert [url.split("/api/v1", 1)[1] for url, _ in child_requests] == expected_paths
+ assert [params.get(cursor_param) for _, params in child_requests] == expected_cursors
+ assert all(params["order"] == "asc" for _, params in child_requests)
+ assert rows == expected_rows
+ manager.save_state.assert_not_called()