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(data-warehouse): add 4 missing tables to the Dodo Payments source (#117155)

Tom Owerscbaca52ed9a2
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 1eb7451f531b..11976a085fc2 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
@@ -3879,10 +3879,10 @@ Today (18): `addons`, `balance_ledger_entries`, `brands`, `credit_entitlements`,
Diffed against: <https://raw.githubusercontent.com/dodopayments/dodopayments-python/main/api.md>
-- [ ] `Payment line items (GET /payments/{payment_id}/line-items)` — attribute payment revenue to products and metered charges absent from payment listings (high)
-- [ ] `Subscription usage history (GET /subscriptions/{subscription_id}/usage-history)` — reconcile billed usage, free allowances, and chargeable units across subscription billing periods (high)
-- [ ] `Payout breakup details (GET /payouts/{payout_id}/breakup/details)` — reconcile settlement line items with imported payments, refunds, and disputes (high)
-- [ ] `Credit entitlement balances (GET /credit-entitlements/{credit_entitlement_id}/balances)` — measure remaining customer credits and overages beyond the entitlement catalog (high)
+- [x] `Payment line items (GET /payments/{payment_id}/line-items)` — attribute payment revenue to products and metered charges absent from payment listings (high)
+- [x] `Subscription usage history (GET /subscriptions/{subscription_id}/usage-history)` — reconcile billed usage, free allowances, and chargeable units across subscription billing periods (high)
+- [x] `Payout breakup details (GET /payouts/{payout_id}/breakup/details)` — reconcile settlement line items with imported payments, refunds, and disputes (high)
+- [x] `Credit entitlement balances (GET /credit-entitlements/{credit_entitlement_id}/balances)` — measure remaining customer credits and overages beyond the entitlement catalog (high)
- [ ] `Credit entitlement ledger (GET /credit-entitlements/{credit_entitlement_id}/balances/{customer_id}/ledger)` — track credit consumption and balance changes by customer and entitlement (high)
- [ ] `Credit entitlement grants (GET /credit-entitlements/{credit_entitlement_id}/balances/{customer_id}/grants)` — analyze granted credits, expiry, and remaining quantities by customer (medium)
- [ ] `Customer wallets (GET /customers/{customer_id}/wallets)` — measure customer wallet balances and prepaid funds by currency (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/canonical_descriptions.py
index bf15d019219c..f2289050f842 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/canonical_descriptions.py
@@ -364,4 +364,65 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updated_at": "Timestamp when the credit entitlement was last modified.",
},
},
+ "payment_line_items": {
+ "description": "Line items of each payment: the products and metered charges the payment was collected for.",
+ "docs_url": f"{_DOCS_ROOT}/payments/retrieve-line-items",
+ "columns": {
+ "payment_id": "Payment the line item belongs to.",
+ "payment_created_at": "Timestamp when the parent payment was created, in UTC.",
+ "currency": "Currency of the parent payment, as an ISO 4217 code.",
+ "items_id": "Identifier of the item the line was charged for.",
+ "name": "Name of the item.",
+ "description": "Description of the item.",
+ "amount": "Amount charged for the item, in the smallest currency unit.",
+ "tax": "Tax charged on the item, in the smallest currency unit.",
+ "refundable_amount": "Part of the amount that can still be refunded, in the smallest currency unit.",
+ },
+ },
+ "subscription_usage_history": {
+ "description": "Metered usage of each usage-based subscription, one row per billing period.",
+ "docs_url": f"{_DOCS_ROOT}/subscriptions/get-usage-history",
+ "columns": {
+ "subscription_id": "Subscription the usage belongs to.",
+ "start_date": "Start date of the billing period.",
+ "end_date": "End date of the billing period.",
+ "meters": (
+ "Usage of each meter in the billing period: meter id and name, consumed units, free "
+ "threshold, chargeable units, price per unit, currency and total price."
+ ),
+ },
+ },
+ "payout_breakup_details": {
+ "description": (
+ "Balance ledger entries settled in each payout, converted into the payout currency at the "
+ "rate the payout settled at."
+ ),
+ "docs_url": f"{_DOCS_ROOT}/payouts/list-breakup-details",
+ "columns": {
+ "payout_id": "Payout the entry was settled in.",
+ "id": "Unique identifier of the balance ledger entry.",
+ "created_at": "Timestamp when the entry was created.",
+ "event_type": "Type of balance ledger event, for example payment, refund, dispute or payment_fees.",
+ "description": "Human-readable description of the transaction.",
+ "reference_object_id": "ID of the related object, for example a payment or refund ID.",
+ "original_amount": "Amount in the original currency, in that currency's smallest unit.",
+ "original_currency": "Original currency, as an ISO 4217 code.",
+ "payout_currency_amount": "Amount converted into the payout currency, in its smallest unit.",
+ "usd_equivalent_amount": "USD equivalent of the original amount, in cents.",
+ },
+ },
+ "credit_entitlement_balances": {
+ "description": "Credit balance of each customer for each credit entitlement.",
+ "docs_url": f"{_DOCS_ROOT}/credit-entitlements/list-balances",
+ "columns": {
+ "id": "Unique identifier of the balance.",
+ "credit_entitlement_id": "Credit entitlement the balance is for.",
+ "customer_id": "Customer the balance belongs to.",
+ "balance": "Remaining credit balance.",
+ "overage": "Credits consumed beyond the balance.",
+ "created_at": "Timestamp when the balance was created.",
+ "updated_at": "Timestamp when the balance was last modified.",
+ "last_transaction_at": "Timestamp of the last credit transaction on the balance.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/dodopayments.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/dodopayments.py
index e42648f0d320..2bc8254adef4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/dodopayments.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/dodopayments.py
@@ -8,11 +8,18 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.htt
from 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.fanout import (
+ rename_parent_fields,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
PageNumberPaginator,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ Endpoint,
+ EndpointResource,
+)
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
@@ -24,9 +31,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.dodopaymen
)
[email protected](frozen=True)
class DodoPaymentsResumeConfig:
- page_number: int
+ # Top-level endpoints resume from the next zero-based page.
+ page_number: int | None = None
+ # Fan-out endpoints resume by parent: the child paths already synced, the one in progress and
+ # its paginator state. See `_make_paginate_dependent_resource` in `common/rest_source`.
+ completed: list[str] | None = None
+ current: str | None = None
+ child_state: dict[str, Any] | None = None
def base_url_for_mode(mode: str) -> str:
@@ -103,8 +116,27 @@ def get_resource(
params["page_size"] = PAGE_SIZE
if should_use_incremental_field and config.start_param and incremental_start_value:
params[config.start_param] = incremental_start_value
+ if config.fanout is not None:
+ params[config.fanout.resolve_param] = {
+ "type": "resolve",
+ "resource": config.fanout.parent_name,
+ "field": config.fanout.resolve_field,
+ }
- return {
+ endpoint_config: Endpoint = {
+ "path": config.path,
+ "params": params,
+ "data_selector": "items",
+ "paginator": DodoPaymentsPaginator() if config.paginated else "single_page",
+ # Every list endpoint wraps its rows in `items`; a body without it is a response
+ # shape change, which should fail loud rather than sync zero rows.
+ "data_selector_required": True,
+ "data_selector_empty_ok": True,
+ }
+ if config.fanout is not None and config.fanout.child_response_actions:
+ endpoint_config["response_actions"] = config.fanout.child_response_actions
+
+ resource: EndpointResource = {
"name": endpoint,
"table_name": endpoint,
"write_disposition": {"disposition": "merge", "strategy": "upsert"}
@@ -112,17 +144,19 @@ def get_resource(
else "replace",
"table_format": "delta",
"primary_key": config.primary_keys,
- "endpoint": {
- "path": config.path,
- "params": params,
- "data_selector": "items",
- "paginator": DodoPaymentsPaginator() if config.paginated else "single_page",
- # Every list endpoint wraps its rows in `items`; a body without it is a response
- # shape change, which should fail loud rather than sync zero rows.
- "data_selector_required": True,
- "data_selector_empty_ok": True,
- },
+ "endpoint": endpoint_config,
}
+ if config.fanout is not None and config.fanout.include_from_parent:
+ resource["include_from_parent"] = config.fanout.include_from_parent
+ return resource
+
+
+def _resume_state(resume: DodoPaymentsResumeConfig, fanout: bool) -> Optional[dict[str, Any]]:
+ if fanout:
+ if not (resume.completed or resume.current):
+ return None
+ return {"completed": resume.completed or [], "current": resume.current, "child_state": resume.child_state}
+ return {"page_number": resume.page_number} if resume.page_number is not None else None
def dodopayments_source(
@@ -161,24 +195,58 @@ def dodopayments_source(
if resumable_source_manager.can_resume():
resume = resumable_source_manager.load_state()
if resume is not None:
- initial_paginator_state = {"page_number": resume.page_number}
+ initial_paginator_state = _resume_state(resume, fanout=config.fanout is not None)
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
# Fires after a page has been yielded, so a crash re-yields that page (the merge dedupes
# on the primary key) instead of skipping it.
- if state and state.get("page_number") is not None:
+ if not state:
+ return
+ if config.fanout is not None:
+ resumable_source_manager.save_state(
+ DodoPaymentsResumeConfig(
+ completed=state.get("completed"),
+ current=state.get("current"),
+ child_state=state.get("child_state"),
+ )
+ )
+ elif state.get("page_number") is not None:
resumable_source_manager.save_state(DodoPaymentsResumeConfig(page_number=int(state["page_number"])))
- resource_iter = rest_api_resource(
- rest_config,
- team_id,
- job_id,
- # The date filter is already baked into the request params above, so the framework's own
- # incremental param injection is intentionally unused.
- db_incremental_field_last_value=None,
- resume_hook=save_checkpoint,
- initial_paginator_state=initial_paginator_state,
- )
+ if config.fanout is None:
+ resource_iter = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ # The date filter is already baked into the request params above, so the framework's own
+ # incremental param injection is intentionally unused.
+ db_incremental_field_last_value=None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+ else:
+ # An incremental child's cursor is a parent field copied onto its rows, so the watermark
+ # filters the parent listing, not the child request.
+ rest_config["resources"].insert(
+ 0,
+ get_resource(
+ config.fanout.parent_name,
+ should_use_incremental_field and bool(config.incremental_fields),
+ incremental_start_value,
+ ),
+ )
+ resources = rest_api_resources(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value=None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+ child = next(r for r in resources if r.name == endpoint)
+ resource_iter = child.add_map(
+ rename_parent_fields(config.fanout.parent_name, config.fanout.parent_field_renames)
+ )
partition_kwargs: dict[str, Any] = {}
if config.partition_key is not None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/settings.py
index 931fb1d107d1..6c1062352180 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/settings.py
@@ -1,5 +1,9 @@
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.rest_source.typing import ResponseAction
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.types import IncrementalField
@@ -20,6 +24,11 @@ PAGE_SIZE = 100
# waiting for against the 240 requests/minute rate limit.
REQUEST_TIMEOUT_SECONDS: tuple[float, float] = (10.0, 60.0)
+# A parent row deleted between the parent listing and its child request returns 404 (the
+# documented "not found" answer of every child endpoint). Skip that parent rather than fail the
+# whole table.
+SKIP_MISSING_PARENT: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]
+
# Rows whose fields get restated after creation re-read a trailing 30 day window on every
# incremental run. Dodo only filters on `created_at` - there is no updated-since filter anywhere
# in the API - so a bare creation cursor would freeze `status`, `dispute_status` and
@@ -33,7 +42,8 @@ class DodoPaymentsEndpointConfig:
path: str
primary_keys: list[str]
# Query param carrying the server-side "created on or after" filter, when the endpoint has
- # one. `None` means the endpoint offers no date filter at all and must be full-refreshed.
+ # one. `None` means the endpoint offers no date filter at all and must be full-refreshed,
+ # unless its fan-out parent has one.
start_param: str | None = None
incremental_fields: list[IncrementalField] = field(default_factory=list)
# Stable creation timestamp used for datetime partitioning. `None` where the resource has no
@@ -44,6 +54,8 @@ class DodoPaymentsEndpointConfig:
# Fields on these resources are restated in place after creation, so incremental runs need
# the trailing re-read window above.
restated: bool = False
+ # Per-parent child endpoints, read once for each row of the parent listing.
+ fanout: DependentEndpointConfig | None = None
DODOPAYMENTS_ENDPOINTS: dict[str, DodoPaymentsEndpointConfig] = {
@@ -126,6 +138,70 @@ DODOPAYMENTS_ENDPOINTS: dict[str, DodoPaymentsEndpointConfig] = {
"license_key_instances": DodoPaymentsEndpointConfig(path="/license_key_instances", primary_keys=["id"]),
"entitlements": DodoPaymentsEndpointConfig(path="/entitlements", primary_keys=["id"]),
"credit_entitlements": DodoPaymentsEndpointConfig(path="/credit-entitlements", primary_keys=["id"]),
+ # Line items take no date filter of their own, so incremental runs filter the parent payment
+ # listing on `created_at_gte` instead. `refundable_amount` drops when a payment is refunded,
+ # hence the re-read window.
+ "payment_line_items": DodoPaymentsEndpointConfig(
+ path="/payments/{payment_id}/line-items",
+ primary_keys=["payment_id", "items_id"],
+ incremental_fields=[incremental_field("payment_created_at")],
+ partition_key="payment_created_at",
+ paginated=False,
+ restated=True,
+ fanout=DependentEndpointConfig(
+ child_response_actions=SKIP_MISSING_PARENT,
+ parent_name="payments",
+ resolve_param="payment_id",
+ resolve_field="payment_id",
+ # The line-items body carries `currency` beside `items`, not on each item, so it comes
+ # from the parent payment instead.
+ include_from_parent=["payment_id", "created_at", "currency"],
+ parent_field_renames={
+ "payment_id": "payment_id",
+ "created_at": "payment_created_at",
+ "currency": "currency",
+ },
+ ),
+ ),
+ # One row per billing period. The current period's usage grows until it closes, so this is
+ # full refresh only.
+ "subscription_usage_history": DodoPaymentsEndpointConfig(
+ path="/subscriptions/{subscription_id}/usage-history",
+ primary_keys=["subscription_id", "start_date"],
+ partition_key="start_date",
+ fanout=DependentEndpointConfig(
+ child_response_actions=SKIP_MISSING_PARENT,
+ parent_name="subscriptions",
+ resolve_param="subscription_id",
+ resolve_field="subscription_id",
+ include_from_parent=["subscription_id"],
+ parent_field_renames={"subscription_id": "subscription_id"},
+ ),
+ ),
+ "payout_breakup_details": DodoPaymentsEndpointConfig(
+ path="/payouts/{payout_id}/breakup/details",
+ primary_keys=["payout_id", "id"],
+ fanout=DependentEndpointConfig(
+ child_response_actions=SKIP_MISSING_PARENT,
+ parent_name="payouts",
+ resolve_param="payout_id",
+ resolve_field="payout_id",
+ include_from_parent=["payout_id"],
+ parent_field_renames={"payout_id": "payout_id"},
+ ),
+ ),
+ # Balance rows already carry `credit_entitlement_id`, so nothing is copied from the parent.
+ "credit_entitlement_balances": DodoPaymentsEndpointConfig(
+ path="/credit-entitlements/{credit_entitlement_id}/balances",
+ primary_keys=["credit_entitlement_id", "id"],
+ fanout=DependentEndpointConfig(
+ child_response_actions=SKIP_MISSING_PARENT,
+ parent_name="credit_entitlements",
+ resolve_param="credit_entitlement_id",
+ resolve_field="id",
+ include_from_parent=[],
+ ),
+ ),
}
ENDPOINTS = tuple(DODOPAYMENTS_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/tests/test_dodopayments.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/tests/test_dodopayments.py
index 658e5b0764cc..07385c3dab20 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/tests/test_dodopayments.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dodopayments/tests/test_dodopayments.py
@@ -153,9 +153,14 @@ class TestSourceResponseMetadata:
class TestEndpointCatalog:
def test_every_incremental_endpoint_declares_a_server_side_filter(self):
- # Without a server-side filter an "incremental" sync would still fetch every page.
+ # Without a server-side filter an "incremental" sync would still fetch every page. A fan-out
+ # child is filtered through its parent listing instead.
for name, config in DODOPAYMENTS_ENDPOINTS.items():
- assert bool(config.incremental_fields) == (config.start_param is not None), name
+ filter_config = DODOPAYMENTS_ENDPOINTS[config.fanout.parent_name] if config.fanout else config
+ if config.incremental_fields:
+ assert filter_config.start_param is not None, name
+ if config.fanout:
+ assert config.start_param is None, name
def test_incremental_cursor_matches_the_partition_key(self):
# The cursor and the partition key must both be creation timestamps that never change.
@@ -163,3 +168,159 @@ class TestEndpointCatalog:
if not config.incremental_fields:
continue
assert [f["field"] for f in config.incremental_fields] == [config.partition_key], name
+
+
+class TestFanout:
+ @pytest.mark.parametrize(
+ "endpoint, parent_row, child_path, child_row, expected_row",
+ [
+ (
+ "payment_line_items",
+ {"payment_id": "pay_1", "created_at": "2024-05-01T00:00:00Z", "currency": "USD", "status": "ok"},
+ "/payments/pay_1/line-items",
+ {"items_id": "pdt_1", "amount": 1000, "tax": 0, "refundable_amount": 1000},
+ {
+ "items_id": "pdt_1",
+ "amount": 1000,
+ "tax": 0,
+ "refundable_amount": 1000,
+ "payment_id": "pay_1",
+ "payment_created_at": "2024-05-01T00:00:00Z",
+ "currency": "USD",
+ },
+ ),
+ (
+ "subscription_usage_history",
+ {"subscription_id": "sub_1", "created_at": "2024-05-01T00:00:00Z"},
+ "/subscriptions/sub_1/usage-history",
+ {"start_date": "2024-05-01T00:00:00Z", "end_date": "2024-06-01T00:00:00Z", "meters": []},
+ {
+ "start_date": "2024-05-01T00:00:00Z",
+ "end_date": "2024-06-01T00:00:00Z",
+ "meters": [],
+ "subscription_id": "sub_1",
+ },
+ ),
+ (
+ "payout_breakup_details",
+ {"payout_id": "po_1", "created_at": "2024-05-01T00:00:00Z"},
+ "/payouts/po_1/breakup/details",
+ {"id": "ble_1", "event_type": "payment", "payout_currency_amount": 500},
+ {"id": "ble_1", "event_type": "payment", "payout_currency_amount": 500, "payout_id": "po_1"},
+ ),
+ (
+ "credit_entitlement_balances",
+ {"id": "cde_1", "name": "Credits"},
+ "/credit-entitlements/cde_1/balances",
+ {"id": "bal_1", "credit_entitlement_id": "cde_1", "customer_id": "cus_1", "balance": "10"},
+ {"id": "bal_1", "credit_entitlement_id": "cde_1", "customer_id": "cus_1", "balance": "10"},
+ ),
+ ],
+ )
+ def test_child_is_read_per_parent_with_parent_fields(
+ self,
+ endpoint: str,
+ parent_row: dict[str, Any],
+ child_path: str,
+ child_row: dict[str, Any],
+ expected_row: dict[str, Any],
+ ) -> None:
+ result = _driver().run(endpoint, [_response([parent_row]), _response([child_row])])
+
+ assert result.raised is None
+ parent_path = "/" + child_path.split("/")[1]
+ assert result.paths == [parent_path, child_path]
+ assert result.rows == [expected_row]
+
+ @pytest.mark.parametrize(
+ "endpoint, parent_row, expected_parent_filter, expected_child_query",
+ [
+ # Line items is a single object, not a page, and filters through the payment listing.
+ (
+ "payment_line_items",
+ {"payment_id": "pay_1", "created_at": "2024-05-01T00:00:00Z", "currency": "USD"},
+ "2024-05-01T10:00:00Z",
+ set(),
+ ),
+ # Usage history has no incremental field, so its parent listing stays unfiltered.
+ ("subscription_usage_history", {"subscription_id": "sub_1"}, None, {"page_size", "page_number"}),
+ ],
+ )
+ def test_incremental_child_filters_the_parent_listing(
+ self,
+ endpoint: str,
+ parent_row: dict[str, Any],
+ expected_parent_filter: str | None,
+ expected_child_query: set[str],
+ ) -> None:
+ result = _driver().run(
+ endpoint,
+ [_response([parent_row]), _response([])],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 5, 1, 10, tzinfo=UTC),
+ )
+
+ assert result.raised is None
+ assert result.requests[0].param("created_at_gte") == expected_parent_filter
+ assert set(result.requests[1].query) == expected_child_query
+
+ def test_paginated_child_walks_every_page_of_each_parent(self) -> None:
+ def periods(count: int, prefix: str) -> ScriptedResponse:
+ return _response([{"start_date": f"{prefix}{i}", "meters": []} for i in range(count)])
+
+ result = _driver().run(
+ "subscription_usage_history",
+ [
+ _response([{"subscription_id": "sub_1"}, {"subscription_id": "sub_2"}]),
+ periods(PAGE_SIZE, "a"),
+ periods(1, "b"),
+ periods(1, "c"),
+ ],
+ )
+
+ assert result.raised is None
+ assert result.paths == [
+ "/subscriptions",
+ "/subscriptions/sub_1/usage-history",
+ "/subscriptions/sub_1/usage-history",
+ "/subscriptions/sub_2/usage-history",
+ ]
+ assert result.params("page_number") == ["0", "0", "1", "0"]
+ assert len(result.rows) == PAGE_SIZE + 2
+ assert result.rows[-1] == {"start_date": "c0", "meters": [], "subscription_id": "sub_2"}
+
+ def test_missing_parent_is_skipped(self) -> None:
+ # A payment removed between the listing and its child request must not fail the table.
+ result = _driver().run(
+ "payment_line_items",
+ [
+ _response(
+ [
+ {"payment_id": "pay_gone", "created_at": "2024-05-01T00:00:00Z", "currency": "USD"},
+ {"payment_id": "pay_2", "created_at": "2024-05-02T00:00:00Z", "currency": "EUR"},
+ ]
+ ),
+ ScriptedResponse(status=404, json={"message": "not found"}),
+ _response([{"items_id": "pdt_1", "amount": 1}]),
+ ],
+ )
+
+ assert result.raised is None
+ assert [(row["payment_id"], row["currency"]) for row in result.rows] == [("pay_2", "EUR")]
+
+ def test_resume_skips_parents_already_synced(self) -> None:
+ result = _driver().run(
+ "payout_breakup_details",
+ [
+ _response([{"payout_id": "po_1"}, {"payout_id": "po_2"}]),
+ _response([{"id": "ble_2"}]),
+ ],
+ resume_state=DodoPaymentsResumeConfig(completed=["/payouts/po_1/breakup/details"]),
+ )
+
+ assert result.raised is None
+ assert result.paths == ["/payouts", "/payouts/po_2/breakup/details"]
+ assert result.rows == [{"id": "ble_2", "payout_id": "po_2"}]
+ assert result.final_state == DodoPaymentsResumeConfig(
+ completed=["/payouts/po_1/breakup/details", "/payouts/po_2/breakup/details"]
+ )