: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(chargedesk): add line item, activity and cancellation tables (#102239)
Tom Owers11252cca8b2e
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 d4e830d35d5a..04e6da8432ea 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@@ -1327,13 +1327,13 @@ Note: Chameleon's published OpenAPI at developers.chameleon.io/api-reference/ope## Chargedesk — gaps-Today (4): `charges`, `customers`, `products`, `subscriptions`+Today (7): `activity_log`, `charge_items`, `charges`, `customers`, `products`, `subscription_cancellations`, `subscriptions`Diffed against: <https://chargedesk.com/api-docs>-- [ ] `GET /v1/charges/{CHARGE_ID}/items` — charge line items - the product/quantity breakdown behind every charge we already sync (high)-- [ ] `GET /v1/log/cancellations` — subscription cancellation log with reasons and timestamps, the core churn dataset (high)-- [ ] `GET /v1/log/activity` — the account-wide activity/state-change history across charges, customers and subscriptions (high)+- [x] `GET /v1/charges/{CHARGE_ID}/items` — charge line items - the product/quantity breakdown behind every charge we already sync (high)+- [x] `GET /v1/log/cancellations` — subscription cancellation log with reasons and timestamps, the core churn dataset (high)+- [x] `GET /v1/log/activity` — the account-wide activity/state-change history across charges, customers and subscriptions (high)Note: Full endpoint list extracted from the single-page api-docs HTML. Only three additional GET-listable analytical resources exist; agents are POST/DELETE only (no list endpoint), /v1/customers/grouped is just an aggregated view of customers we already sync, and gateway/\* plus webhooks are actions and plumbing.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/canonical_descriptions.pyindex ce52e7531f0d..983b17a32d9f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/canonical_descriptions.py@@ -95,4 +95,59 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"first_seen": "Unix epoch seconds when the product was first created.",},},+ "charge_items": {+ "description": "Line items behind each charge: the products, quantities and unit prices that make up the charge amount.",+ "docs_url": "https://chargedesk.com/api-docs#charges-items",+ "columns": {+ "charge_id": "Identifier of the charge the line item belongs to.",+ "charge_occurred": "Unix epoch seconds when the parent charge occurred.",+ "ord": "Position of the line item within its charge, starting at 0.",+ "description": "Description of the line item as shown on receipts and invoices.",+ "raw_description": "Unformatted description of the line item.",+ "quantity": "Number of units billed on the line item.",+ "unit_price": "Price of a single unit.",+ "amount": "Total amount for the line item, excluding tax.",+ "amount_with_tax": "Total amount for the line item, including tax.",+ "amount_refundable": "Portion of the line item that can still be refunded.",+ "currency": "Three-letter ISO currency code of the line item.",+ "product_id": "Identifier of the product the line item is for, if any.",+ "taxable": "Whether tax applies to the line item.",+ },+ },+ "activity_log": {+ "description": "History of actions taken on charges, customers, subscriptions and products, including who or what triggered each one.",+ "docs_url": "https://chargedesk.com/api-docs#logs-agent-activity",+ "columns": {+ "log_id": "Hash of the log row's contents. ChargeDesk returns no identifier, so this keys the table.",+ "object_type": "Type of object the action was taken on ('charge', 'customer', 'subscription' or 'product').",+ "object_id": "Identifier of the object the action was taken on.",+ "action_type": "Action that was taken (e.g. 'refund').",+ "action_reason": "Reason given for the action.",+ "action_params": "Parameters the action was performed with.",+ "event": "Event name for the action (e.g. 'charge-refund').",+ "description": "Human-readable summary of what happened.",+ "sub_description": "Additional detail about what happened.",+ "source": "Where the action came from (e.g. 'web').",+ "ip": "IP address the action came from.",+ "company": "ChargeDesk company the action belongs to.",+ "context": "Context the action was taken in.",+ "params": "Raw parameters recorded with the log entry.",+ "occurred": "Unix epoch seconds when the action occurred.",+ },+ },+ "subscription_cancellations": {+ "description": "Customer-initiated subscription cancellations, pauses and reactivations, with the reason each customer gave.",+ "docs_url": "https://chargedesk.com/api-docs#logs-subscription-cancellations",+ "columns": {+ "log_id": "Hash of the log row's contents. ChargeDesk returns no identifier, so this keys the table.",+ "action": "What the customer asked for: 'cancel', 'pause', 'reactivate', or 'support' when the request went to support instead of being actioned.",+ "reason": "Reason the customer gave for the request.",+ "method": "How the cancellation was applied (e.g. 'at_period_end').",+ "subscription_id": "Identifier of the subscription the request was for.",+ "customer_id": "Identifier of the customer who made the request.",+ "email": "Email address of the customer who made the request.",+ "ip": "IP address the request came from.",+ "occurred": "Unix epoch seconds when the request was made.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/chargedesk.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/chargedesk.mdxindex 264fa3b3f22a..5c5a81f0101e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/chargedesk.mdx+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/chargedesk.mdx@@ -13,7 +13,7 @@ import AlphaRelease from '../_snippets/alpha-release.mdx'<AlphaRelease />-[ChargeDesk](https://chargedesk.com) is a billing-support tool that layers customer support workflows on top of payment gateways like Stripe, Braintree, and PayPal. Linking ChargeDesk as a source syncs your charges, customers, subscriptions, and products into the PostHog data warehouse, where you can join them with product analytics, build revenue insights, and power SQL queries.+[ChargeDesk](https://chargedesk.com) is a billing-support tool that layers customer support workflows on top of payment gateways like Stripe, Braintree, and PayPal. Linking ChargeDesk as a source syncs your charges, charge line items, customers, subscriptions, products, subscription cancellations, and account activity into the PostHog data warehouse, where you can join them with product analytics, build revenue insights, and power SQL queries.## Prerequisites@@ -35,7 +35,11 @@ When prompted, enter your ChargeDesk **secret API key**. That's the only credent<SyncModes />-Charges, customers, and subscriptions support incremental sync using ChargeDesk's server-side time-range filters, so ongoing syncs only fetch new records. Products are small and mutable, so they are full-refreshed on every sync.+Every table except products supports incremental sync using ChargeDesk's server-side time-range filters, so ongoing syncs only fetch new records. Products are small and mutable, so they are full-refreshed on every sync.++Charge items are not selected by default. ChargeDesk returns line items one charge at a time and allows 60 API requests a minute, so the first sync of an account with a lot of charges is slow. Select the table when you need the per-item breakdown of your charges.++The activity log and subscription cancellations tables carry no identifier of their own, so each row is keyed by `log_id`, a hash of the row's contents.## Configurationdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/chargedesk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/chargedesk.pyindex 125e915aa162..405fb339b32d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/chargedesk.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/chargedesk.py@@ -1,7 +1,9 @@+import hashlibimport dataclassesfrom collections.abc import Iteratorfrom typing import Any, Optional+import orjsonfrom requests import Request, Responsefrom requests.auth import HTTPBasicAuthfrom structlog.types import FilteringBoundLogger@@ -15,15 +17,25 @@ 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 BasePaginator+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ IncrementalConfig,+)from 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 SourceResponseCHARGEDESK_BASE_URL = "https://api.chargedesk.com/v1"+# A stalled read would hold the import worker for the whole activity, and the fan-out over charges+# makes one request per charge, so every request gets a finite (connect, read) bound.+REQUEST_TIMEOUT_SECONDS: tuple[float, float] = (10.0, 60.0)[email protected](frozen=True)class ChargedeskResumeConfig:# ChargeDesk has no opaque page cursor — pagination is purely `offset` within a `[max]`-bounded window,# so resuming only needs the next offset and the current upper time bound.@@ -34,6 +46,9 @@ class ChargedeskResumeConfig:# watermark); "full" is the first/full-refresh scan. Tracking the phase lets a resume pick up the right# pass instead of restarting the whole sync.phase: str = "full"+ # Opaque per-parent checkpoint for a fan-out endpoint, whose pagination is the parent walk rather+ # than an offset of its own. Round-tripped into the framework's `initial_paginator_state`.+ fanout_state: dict[str, Any] | None = Noneclass ChargedeskOffsetWindowPaginator(BasePaginator):@@ -149,6 +164,45 @@ class ChargedeskOffsetWindowPaginator(BasePaginator):return f"ChargedeskOffsetWindowPaginator(offset={self.offset}, window_max={self.window_max})"+def _client_config(api_key: str, paginator: Optional[BasePaginator] = None) -> ClientConfig:+ config: ClientConfig = {+ "base_url": CHARGEDESK_BASE_URL,+ # HTTP Basic with the secret key as the username and an empty password.+ "auth": {"type": "http_basic", "username": api_key, "password": ""},+ "request_timeout": REQUEST_TIMEOUT_SECONDS,+ }+ if paginator is not None:+ config["paginator"] = paginator+ return config+++def _with_synthetic_ids(pages: Iterator[list[dict[str, Any]]], column: str) -> Iterator[list[dict[str, Any]]]:+ """Key rows that carry no identifier by a hash of their own contents.++ The log endpoints return no id, so a row re-read at a window boundary would land as a second+ row. Hashing the whole row makes that re-read merge onto itself, and collapses the+ indistinguishable duplicates one page can hold.+ """+ for page in pages:+ rows: list[dict[str, Any]] = []+ seen: set[str] = set()+ for raw_row in page:+ row = {key: value for key, value in raw_row.items() if key != column}+ row_id = hashlib.sha256(orjson.dumps(row, option=orjson.OPT_SORT_KEYS, default=str)).hexdigest()+ if row_id in seen:+ continue+ seen.add(row_id)+ row[column] = row_id+ rows.append(row)+ yield rows+++def _no_child_window(_incremental_field: str) -> Optional[IncrementalConfig]:+ # A fan-out child endpoint takes no params of its own, so its cursor is bound by the window on+ # the parent walk instead of by a filter on the child request.+ return None++def _run_pass(api_key: str,cfg: ChargedeskEndpointConfig,@@ -173,12 +227,7 @@ def _run_pass(params[f"{cfg.filter_param}[min]"] = min_valuerest_config: RESTAPIConfig = {- "client": {- "base_url": CHARGEDESK_BASE_URL,- # HTTP Basic with the secret key as the username and an empty password.- "auth": {"type": "http_basic", "username": api_key, "password": ""},- "paginator": ChargedeskOffsetWindowPaginator(cfg, logger=logger),- },+ "client": _client_config(api_key, ChargedeskOffsetWindowPaginator(cfg, logger=logger)),"resources": [{"name": cfg.name,@@ -211,6 +260,62 @@ def _run_pass(yield from resource+def _run_fanout_pass(+ api_key: str,+ cfg: ChargedeskEndpointConfig,+ team_id: int,+ job_id: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: "ResumableSourceManager[ChargedeskResumeConfig]",+ *,+ phase: str,+ min_value: int | None,+ window_max: int | None,+ start_state: dict[str, Any] | None,+ incremental: bool,+) -> Iterator[list[dict[str, Any]]]:+ """Run a single pass over an endpoint reached by fanning out across its parent list endpoint.++ The child endpoint accepts no parameters, so the pass is windowed on the parent walk: the+ parent's own `[min]`/`[max]` filters and offset cap decide which parents get a child request.+ Resume state here is the framework's per-parent checkpoint, so a resumed pass skips the parents+ it already fetched rather than paying for them again.+ """+ assert cfg.fanout is not None+ parent_cfg = CHARGEDESK_ENDPOINTS[cfg.fanout.parent_name]++ fanout = cfg.fanout+ if min_value is not None:+ fanout = dataclasses.replace(fanout, parent_params={f"{parent_cfg.filter_param}[min]": min_value})++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state:+ resumable_source_manager.save_state(ChargedeskResumeConfig(phase=phase, fanout_state=dict(state)))++ yield from build_dependent_resource(+ endpoint_configs=CHARGEDESK_ENDPOINTS,+ child_endpoint=cfg.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,+ should_use_incremental_field=incremental,+ incremental_field=cfg.default_incremental_field,+ incremental_config_factory=_no_child_window,+ # `count` and `offset` come from the parent's paginator; the child endpoint documents neither.+ page_size_param=None,+ parent_endpoint_extra={+ "paginator": ChargedeskOffsetWindowPaginator(parent_cfg, logger=logger, window_max=window_max),+ "data_selector": "data",+ },+ child_endpoint_extra={"paginator": "single_page", "data_selector": "items"},+ resume_hook=save_checkpoint,+ initial_paginator_state=start_state,+ )++def get_rows(api_key: str,endpoint: str,@@ -229,61 +334,50 @@ def get_rows(incremental = should_use_incremental_field and cfg.supports_incrementalno_watermark = db_incremental_field_last_value is None and db_incremental_field_earliest_value is None- if not incremental or no_watermark:- start_offset, window_max = (- (resume.offset, resume.window_max) if resume and resume.phase == "full" else (0, None)- )- yield from _run_pass(- api_key,- cfg,- team_id,- job_id,- logger,- resumable_source_manager,- phase="full",- min_value=None,- start_offset=start_offset,- start_window_max=window_max,- )- else:- # Newest-first incremental: first walk older rows we don't have yet (bounded by the earliest value- # we've synced), then the rows newer than our watermark. Skip the earliest pass entirely if a resume- # tells us we already finished it.- if db_incremental_field_earliest_value is not None and (resume is None or resume.phase == "earliest"):- if resume is not None and resume.phase == "earliest":- start_offset, window_max = resume.offset, resume.window_max- else:- start_offset, window_max = 0, int(db_incremental_field_earliest_value)- yield from _run_pass(+ def run_pass(*, phase: str, min_value: int | None, window_max: int | None) -> Iterator[list[dict[str, Any]]]:+ resumed = resume if resume is not None and resume.phase == phase else None+ if cfg.fanout is not None:+ pages = _run_fanout_pass(api_key,cfg,team_id,job_id,logger,resumable_source_manager,- phase="earliest",- min_value=None,- start_offset=start_offset,- start_window_max=window_max,+ phase=phase,+ min_value=min_value,+ window_max=window_max,+ start_state=resumed.fanout_state if resumed is not None else None,+ incremental=incremental,)-- if db_incremental_field_last_value is not None:- if resume is not None and resume.phase == "latest":- start_offset, window_max = resume.offset, resume.window_max- else:- start_offset, window_max = 0, None- yield from _run_pass(+ else:+ pages = _run_pass(api_key,cfg,team_id,job_id,logger,resumable_source_manager,- phase="latest",- min_value=int(db_incremental_field_last_value),- start_offset=start_offset,- start_window_max=window_max,+ phase=phase,+ min_value=min_value,+ start_offset=resumed.offset if resumed is not None else 0,+ start_window_max=resumed.window_max if resumed is not None else window_max,)+ if cfg.synthetic_id_column is not None:+ pages = _with_synthetic_ids(pages, cfg.synthetic_id_column)+ return pages++ if not incremental or no_watermark:+ yield from run_pass(phase="full", min_value=None, window_max=None)+ else:+ # Newest-first incremental: first walk older rows we don't have yet (bounded by the earliest value+ # we've synced), then the rows newer than our watermark. Skip the earliest pass entirely if a resume+ # tells us we already finished it.+ if db_incremental_field_earliest_value is not None and (resume is None or resume.phase == "earliest"):+ yield from run_pass(phase="earliest", min_value=None, window_max=int(db_incremental_field_earliest_value))++ if db_incremental_field_last_value is not None:+ yield from run_pass(phase="latest", min_value=int(db_incremental_field_last_value), window_max=None)def chargedesk_source(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/settings.pyindex 7fd49a4c357d..d2a787c3f9c6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/settings.py@@ -1,9 +1,15 @@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.types import IncrementalField, IncrementalFieldType+# Column holding the content hash that keys the log endpoints, neither of which returns an id.+LOG_ID_COLUMN = "log_id"-@dataclass++@dataclass(frozen=True)class ChargedeskEndpointConfig:name: strpath: str@@ -15,14 +21,28 @@ class ChargedeskEndpointConfig:# Base name of the bracketed server-side range filter (e.g. `occurred` -> occurred[min]/occurred[max]).# This is NOT always the same as `timestamp_field`: subscriptions/products filter on `created` but the# only timestamp the response carries is `first_seen`.- filter_param: str+ # A fan-out child sends no list request of its own, so it leaves this and `max_offset` unset and the+ # parent endpoint's values bound the walk instead.+ filter_param: str = ""# The API rejects an `offset` past this value (charges/customers cap at 50,000, subscriptions/products- # at 10,000). When pagination approaches it we reset the offset and tighten the `[max]` time window to- # the oldest row seen so far, as the docs recommend.- max_offset: int+ # and the logs at 10,000). When pagination approaches it we reset the offset and tighten the `[max]`+ # time window to the oldest row seen so far, as the docs recommend.+ max_offset: int = 0incremental_fields: list[IncrementalField] = field(default_factory=list)page_size: int = 500 # documented maximum for the `count` paramsupports_incremental: bool = True+ # Set on an endpoint reached by fanning out over a parent list endpoint, one child request per+ # parent row.+ fanout: DependentEndpointConfig | None = None+ # Set on an endpoint whose rows carry no identifier. Each row gets a deterministic hash of its+ # own contents in this column, so a row re-read at a window boundary merges onto itself.+ synthetic_id_column: str | None = None+ # Cleared for a table too expensive to sync unless the user asks for it.+ should_sync_default: bool = True++ @property+ def default_incremental_field(self) -> str | None:+ return self.incremental_fields[0]["field"] if self.incremental_fields else Nonedef _epoch_incremental_field(field_name: str) -> IncrementalField:@@ -79,6 +99,45 @@ CHARGEDESK_ENDPOINTS: dict[str, ChargedeskEndpointConfig] = {# window-shift when an account somehow has more than 10,000 products.supports_incremental=False,),+ "charge_items": ChargedeskEndpointConfig(+ name="charge_items",+ path="/charges/{charge_id}/items",+ # `ord` is the item's position within its own charge, so the charge id has to be part of the key.+ primary_keys=["charge_id", "ord"],+ # Items carry no timestamp; the parent charge's `occurred` rides along and dates the row.+ timestamp_field="charge_occurred",+ incremental_fields=[_epoch_incremental_field("charge_occurred")],+ # One request per charge against an API that allows 60 a minute, so syncing the breakdown is an+ # explicit choice rather than something every connection pays for.+ should_sync_default=False,+ fanout=DependentEndpointConfig(+ parent_name="charges",+ resolve_param="charge_id",+ resolve_field="charge_id",+ include_from_parent=["charge_id", "occurred"],+ parent_field_renames={"charge_id": "charge_id", "occurred": "charge_occurred"},+ ),+ ),+ "activity_log": ChargedeskEndpointConfig(+ name="activity_log",+ path="/log/activity",+ primary_keys=[LOG_ID_COLUMN],+ timestamp_field="occurred",+ filter_param="occurred",+ max_offset=10000,+ incremental_fields=[_epoch_incremental_field("occurred")],+ synthetic_id_column=LOG_ID_COLUMN,+ ),+ "subscription_cancellations": ChargedeskEndpointConfig(+ name="subscription_cancellations",+ path="/log/cancellations",+ primary_keys=[LOG_ID_COLUMN],+ timestamp_field="occurred",+ filter_param="occurred",+ max_offset=10000,+ incremental_fields=[_epoch_incremental_field("occurred")],+ synthetic_id_column=LOG_ID_COLUMN,+ ),}ENDPOINTS = tuple(CHARGEDESK_ENDPOINTS.keys())@@ -86,3 +145,5 @@ ENDPOINTS = tuple(CHARGEDESK_ENDPOINTS.keys())INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: cfg.incremental_fields for name, cfg in CHARGEDESK_ENDPOINTS.items() if cfg.supports_incremental}++SHOULD_SYNC_DEFAULT: dict[str, bool] = {name: cfg.should_sync_default for name, cfg in CHARGEDESK_ENDPOINTS.items()}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/source.pyindex eaa2ea56f80b..82c48afc76ee 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/source.py@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.chargedeskfrom products.warehouse_sources.backend.temporal.data_imports.sources.chargedesk.settings import (ENDPOINTS,INCREMENTAL_FIELDS,+ SHOULD_SYNC_DEFAULT,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (@@ -96,7 +97,7 @@ Each company has its own secret key. Create one in your ChargeDesk account underforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, should_sync_default=SHOULD_SYNC_DEFAULT)def validate_credentials(self,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/tests/test_chargedesk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/tests/test_chargedesk.pyindex 7a53b6ef4f8c..761fa9c591f6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/tests/test_chargedesk.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/tests/test_chargedesk.py@@ -23,11 +23,14 @@ CHARGEDESK_SESSION_PATCH = ()-def _small_charges_cfg(**overrides: Any) -> dict[str, Any]:- """CHARGEDESK_ENDPOINTS override shrinking the charges page size (and optionally the offset cap)+def _small_cfg(endpoint: str, **overrides: Any) -> dict[str, Any]:+ """CHARGEDESK_ENDPOINTS override shrinking an endpoint's page size (and optionally the offset cap)so pagination/window-shift behavior is testable with a handful of rows."""- base = dataclasses.replace(CHARGEDESK_ENDPOINTS["charges"], **{"page_size": 2, **overrides})- return {"charges": base}+ return {endpoint: dataclasses.replace(CHARGEDESK_ENDPOINTS[endpoint], **{"page_size": 2, **overrides})}+++def _small_charges_cfg(**overrides: Any) -> dict[str, Any]:+ return _small_cfg("charges", **overrides)def _response(items: list[dict[str, Any]]) -> Response:@@ -37,6 +40,14 @@ def _response(items: list[dict[str, Any]]) -> Response:return resp+def _items_response(items: list[dict[str, Any]]) -> Response:+ # The charge items endpoint answers with two arrays; only `items` is synced.+ resp = Response()+ resp.status_code = 200+ resp._content = json.dumps({"items": items, "taxes": []}).encode()+ return resp++def _charges(ids_and_ts: list[tuple[str, int]]) -> list[dict[str, Any]]:# Newest first, matching ChargeDesk's default list ordering.return [{"charge_id": cid, "occurred": ts} for cid, ts in ids_and_ts]@@ -67,6 +78,20 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,return param_snapshots+def _wire_requests(session: mock.MagicMock, responses: list[Response]) -> list[tuple[str, dict[str, Any]]]:+ """Like `_wire`, but snapshots each request's URL alongside its params at send time."""+ session.headers = {}+ snapshots: list[tuple[str, dict[str, Any]]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append((request.url, dict(request.params or {})))+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots++def _source(endpoint: str = "charges",manager: mock.MagicMock | None = None,@@ -364,6 +389,121 @@ class TestResume:assert "occurred[max]" not in params[0]+class TestChargeItemsFanout:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_fans_out_over_charges_and_carries_parent_fields(self, MockSession) -> None:+ session = MockSession.return_value+ requests = _wire_requests(+ session,+ [+ _response(_charges([("a", 30), ("b", 20)])),+ _items_response([{"ord": 0, "amount": 12}]),+ _items_response([{"ord": 0, "amount": 5}, {"ord": 1, "amount": 7}]),+ ],+ )++ rows = _rows(_source(endpoint="charge_items"))++ assert [url for url, _params in requests[1:]] == [+ "https://api.chargedesk.com/v1/charges/a/items",+ "https://api.chargedesk.com/v1/charges/b/items",+ ]+ # The parent's id and timestamp ride along under the names the table keys and partitions on.+ assert [(r["charge_id"], r["ord"], r["charge_occurred"]) for r in rows] == [+ ("a", 0, 30),+ ("b", 0, 20),+ ("b", 1, 20),+ ]+ # The child endpoint documents no paging params, so none are sent.+ assert all(params == {} for _url, params in requests[1:])++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_bounds_the_parent_walk(self, MockSession) -> None:+ session = MockSession.return_value+ requests = _wire_requests(+ session,+ [_response(_charges([("a", 60)])), _items_response([{"ord": 0}])],+ )++ _rows(+ _source(+ endpoint="charge_items",+ should_use_incremental_field=True,+ db_incremental_field_last_value=50,+ )+ )++ # The child takes no filters, so the watermark has to narrow the parent listing instead.+ assert requests[0][1]["occurred[min]"] == 50+ assert requests[1][1] == {}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_checkpoints_each_completed_parent(self, MockSession) -> None:+ session = MockSession.return_value+ _wire_requests(+ session,+ [+ _response(_charges([("a", 30), ("b", 20)])),+ _items_response([{"ord": 0}]),+ _items_response([{"ord": 0}]),+ ],+ )++ manager = _make_manager()+ _rows(_source(endpoint="charge_items", manager=manager))++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved[-1].phase == "full"+ assert saved[-1].fanout_state["completed"] == ["/charges/a/items", "/charges/b/items"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resume_skips_parents_already_fetched(self, MockSession) -> None:+ session = MockSession.return_value+ requests = _wire_requests(+ session,+ [_response(_charges([("a", 30), ("b", 20)])), _items_response([{"ord": 0}])],+ )++ manager = _make_manager(+ ChargedeskResumeConfig(+ phase="full",+ fanout_state={"completed": ["/charges/a/items"], "current": None, "child_state": None},+ )+ )+ _rows(_source(endpoint="charge_items", manager=manager))++ # Only the parent that hadn't been fetched costs a request on the resumed run.+ assert [url for url, _params in requests[1:]] == ["https://api.chargedesk.com/v1/charges/b/items"]+++class TestSyntheticLogIds:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_indistinguishable_rows_collapse_within_a_page(self, MockSession) -> None:+ session = MockSession.return_value+ entry = {"object_type": "charge", "object_id": "a", "event": "charge-refund", "occurred": 100}+ _wire(session, [_response([entry, dict(entry), {**entry, "event": "charge-void"}])])++ rows = _rows(_source(endpoint="activity_log"))++ assert [r["event"] for r in rows] == ["charge-refund", "charge-void"]+ assert len({r["log_id"] for r in rows}) == 2++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_row_reread_on_a_later_page_keeps_its_id(self, MockSession) -> None:+ session = MockSession.return_value+ first = {"subscription_id": "s1", "action": "cancel", "occurred": 100}+ boundary = {"subscription_id": "s2", "action": "pause", "occurred": 90}+ _wire(session, [_response([first, boundary]), _response([boundary])])++ with mock.patch.dict(CHARGEDESK_ENDPOINTS, _small_cfg("subscription_cancellations")):+ rows = _rows(_source(endpoint="subscription_cancellations"))++ ids = [r["log_id"] for r in rows if r["subscription_id"] == "s2"]+ # The window-shift re-read has to merge onto the row it already synced, not land beside it.+ assert len(ids) == 2+ assert ids[0] == ids[1]++class TestValidateCredentials:@parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])def test_status_mapping(self, _name: str, status: int, expected: bool) -> None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/tests/test_chargedesk_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/tests/test_chargedesk_source.pyindex 706b715267f2..ae7b69f0dccc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/tests/test_chargedesk_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/tests/test_chargedesk_source.py@@ -37,6 +37,14 @@ class TestGetSchemas:# Customers/subscriptions track the creation timestamp column that the row actually carries.assert schemas["customers"].incremental_fields[0]["field"] == "first_seen"assert schemas["subscriptions"].incremental_fields[0]["field"] == "first_seen"+ # Charge items carry no timestamp of their own; the parent charge's dates the row.+ assert schemas["charge_items"].incremental_fields[0]["field"] == "charge_occurred"++ def test_charge_items_is_not_selected_by_default(self) -> None:+ # Syncing it costs one request per charge against a 60-requests-a-minute API.+ schemas = {s.name: s for s in ChargedeskSource().get_schemas(_config(), team_id=1)}+ assert schemas["charge_items"].should_sync_default is False+ assert schemas["charges"].should_sync_default is Trueclass TestValidateCredentials: