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): implement chargedesk import source (#66755)

Tom Owers76fbd93f88d0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 2e712df8d488..48faa06865fc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -72,6 +72,7 @@ the row lists both.
| campaign_monitor | HTTP | requests | ✅ |
| canny | HTTP | requests | ✅ |
| chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| chargedesk | HTTP | requests | ✅ |
| checkout_com | HTTP | requests | ✅ |
| coda | HTTP | requests | ✅ |
| coingecko | HTTP | requests | ✅ |
@@ -328,7 +329,6 @@ doesn't conflict with concurrent PRs.
- cart_com
- castor_edc
- chameleon
-- chargedesk
- chargify
- chatwoot
- chift
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.py
new file mode 100644
index 000000000000..ce52e7531f0d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/canonical_descriptions.py
@@ -0,0 +1,98 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Sourced from the official ChargeDesk API docs (https://chargedesk.com/api-docs). Keyed by the endpoint
+# name returned by `get_schemas`. Any field not listed here falls back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "charges": {
+ "description": "Individual charges, payments, invoices and refunds synced from your connected payment gateway.",
+ "docs_url": "https://chargedesk.com/api-docs#charges",
+ "columns": {
+ "charge_id": "Unique identifier for the charge.",
+ "amount": "The amount of the charge in decimal format (e.g. '34.00').",
+ "amount_refunded": "The portion of the charge that has been refunded, in decimal format.",
+ "added_tax": "Tax added to the charge amount, in decimal format.",
+ "currency": "Three-letter ISO currency code the charge was made in.",
+ "customer_id": "Identifier of the customer the charge belongs to.",
+ "customer_email": "Email address of the customer the charge belongs to.",
+ "customer_name": "Name of the customer the charge belongs to.",
+ "subscription_id": "Identifier of the subscription this charge was generated from, if any.",
+ "product_id": "Identifier of the product this charge is for, if any.",
+ "description": "Free-text description of what the charge is for.",
+ "is_paid": "Whether the charge has been paid.",
+ "status": "Current status of the charge (e.g. 'paid', 'refunded', 'failed').",
+ "occurred": "Unix epoch seconds when the charge occurred.",
+ "payment_method": "Payment method used (e.g. 'Credit').",
+ "payment_method_brand": "Card brand or payment method brand (e.g. 'Visa').",
+ "last_4_digits": "Last four digits of the payment card, if applicable.",
+ "transaction_id": "Transaction identifier from the underlying payment gateway.",
+ "metadata": "Arbitrary key/value metadata set on the charge.",
+ },
+ },
+ "customers": {
+ "description": "Customers who have been charged or imported into ChargeDesk from your payment gateway.",
+ "docs_url": "https://chargedesk.com/api-docs#customers",
+ "columns": {
+ "customer_id": "Unique identifier shared by all charges from the same customer.",
+ "name": "Full name of the customer.",
+ "first_name": "First name of the customer.",
+ "email": "Primary email address of the customer.",
+ "username": "Username associated with the customer.",
+ "phone": "Phone number of the customer.",
+ "company": "ChargeDesk company the customer belongs to.",
+ "customer_company": "Company name supplied for the customer.",
+ "country": "Two-letter country code of the customer.",
+ "billing_address": "Billing address of the customer.",
+ "shipping_address": "Shipping address of the customer.",
+ "tax_number": "Tax/VAT number recorded for the customer.",
+ "delinquent": "Whether the customer has an unpaid or past-due balance.",
+ "first_seen": "Unix epoch seconds when the customer was first created in ChargeDesk.",
+ "metadata": "Arbitrary key/value metadata set on the customer.",
+ },
+ },
+ "subscriptions": {
+ "description": "Recurring subscriptions synced from your connected payment gateway.",
+ "docs_url": "https://chargedesk.com/api-docs#subscriptions",
+ "columns": {
+ "subscription_id": "Unique identifier shared by all charges for this subscription.",
+ "customer_id": "Identifier of the customer the subscription belongs to.",
+ "product_id": "Identifier of the product the subscription is for.",
+ "amount": "Recurring amount of the subscription in decimal format.",
+ "currency": "Three-letter ISO currency code of the subscription.",
+ "quantity": "Number of units the subscription bills for.",
+ "interval": "Billing interval unit (e.g. 'month').",
+ "interval_count": "Number of intervals between billings.",
+ "status": "Current status of the subscription (e.g. 'active', 'canceled').",
+ "first_seen": "Unix epoch seconds when the subscription was created.",
+ "current_period_start": "Unix epoch seconds of the start of the current billing period.",
+ "current_period_end": "Unix epoch seconds of the end of the current billing period.",
+ "canceled_at": "Unix epoch seconds when the subscription was canceled, or 0 if active.",
+ "ended_at": "Unix epoch seconds when the subscription ended, or 0 if still running.",
+ "trial_start": "Unix epoch seconds when the trial started, or 0 if no trial.",
+ "trial_end": "Unix epoch seconds when the trial ends, or 0 if no trial.",
+ "trial_period_days": "Length of the trial period in days.",
+ "metadata": "Arbitrary key/value metadata set on the subscription.",
+ },
+ },
+ "products": {
+ "description": "Products created or imported into ChargeDesk that charges and subscriptions reference.",
+ "docs_url": "https://chargedesk.com/api-docs#products",
+ "columns": {
+ "product_id": "Unique identifier shared by all charges for the same product.",
+ "name": "Name of the product as shown to customers.",
+ "description": "Description of what the product is.",
+ "amount": "Default amount charged for the product.",
+ "currency": "Three-letter ISO currency code of the product.",
+ "quantity": "Default quantity charged for the product.",
+ "interval": "Billing interval unit for recurring products.",
+ "interval_count": "Number of intervals between billings for recurring products.",
+ "chargeable": "Whether the product can currently be charged.",
+ "taxable": "Whether tax applies to the product.",
+ "trial_period_days": "Default trial period length in days.",
+ "status": "Status of the product.",
+ "url": "URL with more information about the product.",
+ "first_seen": "Unix epoch seconds when the product was first created.",
+ },
+ },
+}
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.mdx
new file mode 100644
index 000000000000..264fa3b3f22a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/chargedesk.mdx
@@ -0,0 +1,53 @@
+---
+title: Linking ChargeDesk as a source
+sidebar: Docs
+showTitle: true
+availability: { free: full, selfServe: full, enterprise: full }
+sourceId: Chargedesk
+---
+
+import SourceSetupIntro from '../_snippets/source-setup-intro.mdx'
+import SyncModes from '../_snippets/sync-modes.mdx'
+import TroubleshootingLink from '../_snippets/dw-troubleshooting-link.mdx'
+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.
+
+## Prerequisites
+
+Before connecting, you need:
+
+- A ChargeDesk account with at least one connected payment gateway.
+- API access enabled for the company you want to sync.
+- A secret API key for that company.
+
+Each company in ChargeDesk has its own secret key. Create one under **Setup → API / Webhooks → Issue New Key**. The key is used as the username for HTTP Basic authentication (the password is left empty), so a single secret key grants read access to all of that company's data.
+
+## Adding a data source
+
+<SourceSetupIntro />
+
+When prompted, enter your ChargeDesk **secret API key**. That's the only credential required.
+
+## Sync modes
+
+<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.
+
+## Configuration
+
+<SourceParameters />
+
+## Supported tables
+
+<SourceTables />
+
+## Troubleshooting
+
+- **Invalid or revoked key:** if syncs fail with an authentication error, issue a new secret key in **Setup → API / Webhooks** and reconnect the source.
+- **API access not enabled:** make sure API access is turned on for the specific company whose key you used — keys are scoped per company.
+
+<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/chargedesk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/chargedesk.py
new file mode 100644
index 000000000000..0c5ceb07bc10
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/chargedesk.py
@@ -0,0 +1,307 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.chargedesk.settings import (
+ CHARGEDESK_ENDPOINTS,
+ ChargedeskEndpointConfig,
+)
+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.resumable import ResumableSourceManager
+
+CHARGEDESK_BASE_URL = "https://api.chargedesk.com/v1"
+
+# ChargeDesk doesn't document rate limits, so retry transient failures with capped exponential backoff.
+MAX_ATTEMPTS = 5
+
+
+class ChargedeskRetryableError(Exception):
+ pass
+
+
+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.
+ offset: int = 0
+ window_max: int | None = None
+ # Which pass we were in when state was saved. An incremental sync against a newest-first API runs an
+ # "earliest" backfill (rows older than what we have) followed by a "latest" pass (rows newer than the
+ # 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"
+
+
+def _auth(api_key: str) -> tuple[str, str]:
+ # HTTP Basic with the secret key as the username and an empty password.
+ return (api_key, "")
+
+
+@retry(
+ retry=retry_if_exception_type((ChargedeskRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ auth: tuple[str, str],
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict:
+ response = session.get(url, auth=auth, params=params, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ChargedeskRetryableError(f"ChargeDesk API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"ChargeDesk API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _iter_pages(
+ session: requests.Session,
+ auth: tuple[str, str],
+ cfg: ChargedeskEndpointConfig,
+ logger: FilteringBoundLogger,
+ *,
+ min_value: int | None,
+ start_offset: int,
+ start_window_max: int | None,
+) -> Iterator[tuple[list[dict], tuple[int, int | None] | None]]:
+ """Page through a ChargeDesk list endpoint by offset.
+
+ Yields ``(page_items, resume_state)`` where ``resume_state`` is the ``(offset, window_max)`` to resume
+ from to fetch the *next* page, or ``None`` when this is the terminal page. Results come back newest
+ first, so once the offset nears the API's hard cap we reset it to 0 and pin ``[max]`` to the oldest row
+ we just saw (the boundary row is re-fetched and deduped on the primary key by the merge).
+ """
+ url = f"{CHARGEDESK_BASE_URL}{cfg.path}"
+ offset = start_offset
+ window_max = start_window_max
+
+ while True:
+ params: dict[str, Any] = {"count": cfg.page_size, "offset": offset}
+ if min_value is not None:
+ params[f"{cfg.filter_param}[min]"] = min_value
+ if window_max is not None:
+ params[f"{cfg.filter_param}[max]"] = window_max
+
+ data = _fetch_page(session, url, auth, params, logger)
+ items = data.get("data", [])
+
+ # A short page (fewer rows than requested) means there's nothing after it in this window.
+ if len(items) < cfg.page_size:
+ yield items, None
+ return
+
+ next_offset = offset + cfg.page_size
+ next_window_max = window_max
+
+ if next_offset + cfg.page_size > cfg.max_offset:
+ oldest_ts = items[-1].get(cfg.timestamp_field)
+ if not isinstance(oldest_ts, int):
+ # Can't shift the window without a timestamp to anchor it, and stepping past the cap would
+ # 400. Surface it rather than silently dropping the tail.
+ logger.warning(
+ f"ChargeDesk: {cfg.name} hit the offset cap ({cfg.max_offset}) but the last row has no "
+ f"usable '{cfg.timestamp_field}' to continue from; stopping pagination for this window."
+ )
+ yield items, None
+ return
+ if oldest_ts == window_max:
+ # The whole offset window collapsed onto a single timestamp: more than `max_offset` rows
+ # share `oldest_ts`, so re-pinning `[max]` to the same value would re-fetch this exact page
+ # forever (offset can't advance past the cap). Surface it and stop rather than spin until
+ # Temporal kills the activity. The unreachable tail is a hard limitation of an offset+`[max]`
+ # API when a single timestamp exceeds the offset cap.
+ logger.warning(
+ f"ChargeDesk: {cfg.name} has more than {cfg.max_offset} rows at {cfg.timestamp_field}="
+ f"{oldest_ts}; the offset cap prevents fetching the rest of this timestamp, stopping "
+ f"pagination for this window."
+ )
+ yield items, None
+ return
+ logger.debug(f"ChargeDesk: {cfg.name} reached offset cap, shifting {cfg.filter_param}[max] to {oldest_ts}")
+ next_offset = 0
+ next_window_max = oldest_ts
+
+ yield items, (next_offset, next_window_max)
+ offset = next_offset
+ window_max = next_window_max
+
+
+def _run_pass(
+ session: requests.Session,
+ auth: tuple[str, str],
+ cfg: ChargedeskEndpointConfig,
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ resumable_source_manager: "ResumableSourceManager[ChargedeskResumeConfig]",
+ *,
+ phase: str,
+ min_value: int | None,
+ start_offset: int,
+ start_window_max: int | None,
+) -> Iterator[Any]:
+ """Batch a single pass's pages, yielding tables and saving resume state at page boundaries.
+
+ State is saved only after a whole page has been batched and a table yielded, so a crash re-fetches
+ from the next page rather than skipping the unyielded tail of a partially consumed page.
+ """
+ for items, resume_state in _iter_pages(
+ session,
+ auth,
+ cfg,
+ logger,
+ min_value=min_value,
+ start_offset=start_offset,
+ start_window_max=start_window_max,
+ ):
+ for item in items:
+ batcher.batch(item)
+
+ if batcher.should_yield():
+ yield batcher.get_table()
+ if resume_state is not None:
+ resumable_source_manager.save_state(
+ ChargedeskResumeConfig(offset=resume_state[0], window_max=resume_state[1], phase=phase)
+ )
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: "ResumableSourceManager[ChargedeskResumeConfig]",
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ db_incremental_field_earliest_value: Any = None,
+) -> Iterator[Any]:
+ cfg = CHARGEDESK_ENDPOINTS[endpoint]
+ auth = _auth(api_key)
+ # Redact the secret key from logged URLs / captured samples — it rides in the Basic auth header.
+ session = make_tracked_session(redact_values=(api_key,))
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ incremental = should_use_incremental_field and cfg.supports_incremental
+ no_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(
+ session,
+ auth,
+ cfg,
+ logger,
+ batcher,
+ 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(
+ session,
+ auth,
+ cfg,
+ logger,
+ batcher,
+ resumable_source_manager,
+ phase="earliest",
+ min_value=None,
+ start_offset=start_offset,
+ start_window_max=window_max,
+ )
+
+ 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(
+ session,
+ auth,
+ cfg,
+ logger,
+ batcher,
+ resumable_source_manager,
+ phase="latest",
+ min_value=int(db_incremental_field_last_value),
+ start_offset=start_offset,
+ start_window_max=window_max,
+ )
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def chargedesk_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: "ResumableSourceManager[ChargedeskResumeConfig]",
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ db_incremental_field_earliest_value: Optional[Any] = None,
+) -> SourceResponse:
+ cfg = CHARGEDESK_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ db_incremental_field_earliest_value=db_incremental_field_earliest_value,
+ ),
+ primary_keys=cfg.primary_keys,
+ # ChargeDesk list endpoints return rows newest first (offset 0 is the most recent; the docs
+ # recommend paginating earlier with `[max]`). Matches the newest-first contract Stripe uses.
+ sort_mode="desc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="week",
+ partition_keys=[cfg.timestamp_field],
+ )
+
+
+def validate_credentials(api_key: str) -> bool:
+ # A single company secret key grants full read access (ChargeDesk has no per-resource scopes), so one
+ # cheap probe against /charges confirms the key is genuine.
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(
+ f"{CHARGEDESK_BASE_URL}/charges",
+ auth=_auth(api_key),
+ params={"count": 1},
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
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.py
new file mode 100644
index 000000000000..7fd49a4c357d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/settings.py
@@ -0,0 +1,88 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class ChargedeskEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str]
+ # Response column holding a stable epoch-second creation timestamp. Used for partitioning, for the
+ # incremental watermark, and as the upper bound when window-shifting past the offset cap. Never a
+ # mutable "last edited" field — those rewrite partitions on every sync.
+ timestamp_field: str
+ # 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
+ # 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
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ page_size: int = 500 # documented maximum for the `count` param
+ supports_incremental: bool = True
+
+
+def _epoch_incremental_field(field_name: str) -> IncrementalField:
+ # ChargeDesk timestamps are Unix epoch seconds stored as integers, so the merge cursor is compared
+ # as an integer even though it represents a datetime.
+ return {
+ "label": field_name,
+ "type": IncrementalFieldType.DateTime,
+ "field": field_name,
+ "field_type": IncrementalFieldType.Integer,
+ }
+
+
+CHARGEDESK_ENDPOINTS: dict[str, ChargedeskEndpointConfig] = {
+ "charges": ChargedeskEndpointConfig(
+ name="charges",
+ path="/charges",
+ primary_keys=["charge_id"],
+ timestamp_field="occurred",
+ filter_param="occurred",
+ max_offset=50000,
+ incremental_fields=[_epoch_incremental_field("occurred")],
+ ),
+ "customers": ChargedeskEndpointConfig(
+ name="customers",
+ path="/customers",
+ primary_keys=["customer_id"],
+ timestamp_field="first_seen",
+ filter_param="first_seen",
+ max_offset=50000,
+ incremental_fields=[_epoch_incremental_field("first_seen")],
+ ),
+ "subscriptions": ChargedeskEndpointConfig(
+ name="subscriptions",
+ path="/subscriptions",
+ primary_keys=["subscription_id"],
+ timestamp_field="first_seen",
+ # Subscriptions expose `created[min]/created[max]` server-side, but the only timestamp on the row
+ # is `first_seen` (the creation time). They track the same moment, so we watermark on `first_seen`
+ # and send its value as `created[min]`.
+ filter_param="created",
+ max_offset=10000,
+ incremental_fields=[_epoch_incremental_field("first_seen")],
+ ),
+ "products": ChargedeskEndpointConfig(
+ name="products",
+ path="/products",
+ primary_keys=["product_id"],
+ timestamp_field="first_seen",
+ filter_param="created",
+ max_offset=10000,
+ # Products are a small, mutable catalog with no useful append-only cursor, so we full-refresh them
+ # every sync (matching the canonical Airbyte connector). The `created[*]` filter still bounds the
+ # window-shift when an account somehow has more than 10,000 products.
+ supports_incremental=False,
+ ),
+}
+
+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
+}
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.py
index 7123d5435e0e..f7feb15097a3 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
@@ -1,19 +1,43 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.chargedesk.chargedesk import (
+ ChargedeskResumeConfig,
+ chargedesk_source,
+ validate_credentials as validate_chargedesk_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.chargedesk.settings import (
+ CHARGEDESK_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ChargedeskSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ChargedeskSource(SimpleSource[ChargedeskSourceConfig]):
+class ChargedeskSource(ResumableSource[ChargedeskSourceConfig, ChargedeskResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CHARGEDESK
@@ -24,7 +48,94 @@ class ChargedeskSource(SimpleSource[ChargedeskSourceConfig]):
name=SchemaExternalDataSourceType.CHARGEDESK,
category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
label="Chargedesk",
- iconPath="/static/services/chargedesk.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your ChargeDesk secret API key to automatically pull your ChargeDesk data into the PostHog Data warehouse.
+
+Each company has its own secret key. Create one in your ChargeDesk account under **Setup → API / Webhooks → Issue New Key**, and make sure API access is enabled for the company.""",
+ iconPath="/static/services/chargedesk.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/chargedesk",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="Secret API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="sk_...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.chargedesk.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # A bad or disabled secret key surfaces as a requests HTTPError when `_fetch_page` calls
+ # `raise_for_status()`. Retrying can't fix a credential problem, so stop the sync. Match the
+ # stable status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.chargedesk.com": "Your ChargeDesk secret API key is invalid or has been revoked. Issue a new key in your ChargeDesk account (Setup → API / Webhooks) and reconnect.",
+ "403 Client Error: Forbidden for url: https://api.chargedesk.com": "Your ChargeDesk secret API key does not have API access enabled. Enable API access for the company in your ChargeDesk account and reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: ChargedeskSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ cfg = CHARGEDESK_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=cfg.supports_incremental,
+ supports_append=cfg.supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: ChargedeskSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_chargedesk_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid ChargeDesk secret API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ChargedeskResumeConfig]:
+ return ResumableSourceManager[ChargedeskResumeConfig](inputs, ChargedeskResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ChargedeskSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ChargedeskResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return chargedesk_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ db_incremental_field_earliest_value=inputs.db_incremental_field_earliest_value
+ if inputs.should_use_incremental_field
+ else None,
)
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.py
new file mode 100644
index 000000000000..03f682e3d415
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/tests/test_chargedesk.py
@@ -0,0 +1,325 @@
+import json
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.sources.chargedesk import chargedesk
+from products.warehouse_sources.backend.temporal.data_imports.sources.chargedesk.chargedesk import (
+ ChargedeskResumeConfig,
+ _iter_pages,
+ _run_pass,
+ chargedesk_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.chargedesk.settings import (
+ CHARGEDESK_ENDPOINTS,
+ ChargedeskEndpointConfig,
+)
+
+
+def _cfg(**overrides: Any) -> ChargedeskEndpointConfig:
+ base: dict[str, Any] = {
+ "name": "charges",
+ "path": "/charges",
+ "primary_keys": ["charge_id"],
+ "timestamp_field": "occurred",
+ "filter_param": "occurred",
+ "max_offset": 50000,
+ "page_size": 2,
+ }
+ base.update(overrides)
+ return ChargedeskEndpointConfig(**base)
+
+
+class _FakeResponse:
+ def __init__(self, payload: dict, status: int = 200):
+ self._payload = payload
+ self.status_code = status
+ self.ok = 200 <= status < 300
+ self.text = json.dumps(payload)
+
+ def json(self) -> dict:
+ return self._payload
+
+ def raise_for_status(self) -> None:
+ if not self.ok:
+ response = requests.Response()
+ response.status_code = self.status_code
+ raise requests.HTTPError(f"{self.status_code} Client Error", response=response)
+
+
+class _PagedSession:
+ """Fake session that slices a fixed (newest-first) dataset by offset, honoring [min]/[max] filters."""
+
+ def __init__(self, rows: list[dict], filter_param: str = "occurred", ts_field: str = "occurred"):
+ self.rows = rows
+ self.filter_param = filter_param
+ self.ts_field = ts_field
+ self.calls: list[dict] = []
+
+ def get(self, url: str, auth: Any = None, params: dict | None = None, timeout: Any = None) -> _FakeResponse:
+ params = params or {}
+ self.calls.append(params)
+ mn = params.get(f"{self.filter_param}[min]")
+ mx = params.get(f"{self.filter_param}[max]")
+ selected = [
+ r for r in self.rows if (mn is None or r[self.ts_field] >= mn) and (mx is None or r[self.ts_field] <= mx)
+ ]
+ offset = params["offset"]
+ count = params["count"]
+ page = selected[offset : offset + count]
+ return _FakeResponse({"count": count, "offset": offset, "data": page})
+
+
+class _FakeManager:
+ def __init__(self, state: ChargedeskResumeConfig | None = None):
+ self._state = state
+ self.saved: list[ChargedeskResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> ChargedeskResumeConfig | None:
+ return self._state
+
+ def save_state(self, state: ChargedeskResumeConfig) -> None:
+ self.saved.append(state)
+
+
+def _charges(ids_and_ts: list[tuple[str, int]]) -> list[dict]:
+ # Newest first, matching ChargeDesk's default list ordering.
+ return [{"charge_id": cid, "occurred": ts} for cid, ts in ids_and_ts]
+
+
+class TestIterPages:
+ def test_single_short_page_is_terminal(self) -> None:
+ session = _PagedSession(_charges([("a", 30), ("b", 20)]))
+ cfg = _cfg(page_size=5)
+ results = list(
+ _iter_pages(session, ("k", ""), cfg, MagicMock(), min_value=None, start_offset=0, start_window_max=None) # type: ignore[arg-type]
+ )
+
+ assert len(results) == 1
+ items, resume_state = results[0]
+ assert [r["charge_id"] for r in items] == ["a", "b"]
+ assert resume_state is None # short page -> no next page
+
+ def test_multi_page_offsets_and_termination(self) -> None:
+ session = _PagedSession(_charges([("a", 50), ("b", 40), ("c", 30), ("d", 20), ("e", 10)]))
+ cfg = _cfg(page_size=2)
+ results = list(
+ _iter_pages(session, ("k", ""), cfg, MagicMock(), min_value=None, start_offset=0, start_window_max=None) # type: ignore[arg-type]
+ )
+
+ # 5 rows / page_size 2 => full pages [a,b],[c,d] then terminal short page [e]
+ all_ids = [r["charge_id"] for items, _ in results for r in items]
+ assert all_ids == ["a", "b", "c", "d", "e"]
+ # offsets requested are 0, 2, 4
+ assert [c["offset"] for c in session.calls] == [0, 2, 4]
+ assert results[-1][1] is None # last page terminal
+ assert results[0][1] == (2, None) # resume from offset 2 next
+
+ def test_window_shift_at_offset_cap(self) -> None:
+ # max_offset=2 forces a window shift after the first full page (offset would step to 2; 2+2 > 2).
+ session = _PagedSession(_charges([("a", 50), ("b", 40), ("c", 30), ("d", 20)]))
+ cfg = _cfg(page_size=2, max_offset=2)
+ results = list(
+ _iter_pages(session, ("k", ""), cfg, MagicMock(), min_value=None, start_offset=0, start_window_max=None) # type: ignore[arg-type]
+ )
+
+ # First page [a,b]; cap hit -> shift occurred[max] to oldest seen (40), reset offset 0.
+ first_items, first_resume = results[0]
+ assert [r["charge_id"] for r in first_items] == ["a", "b"]
+ assert first_resume == (0, 40)
+ # Subsequent calls carry occurred[max]=40 and start at offset 0.
+ shifted_calls = [c for c in session.calls if c.get("occurred[max]") == 40]
+ assert shifted_calls and shifted_calls[0]["offset"] == 0
+ # Every row is still surfaced (boundary row b re-fetched, deduped downstream on primary key).
+ all_ids = [r["charge_id"] for items, _ in results for r in items]
+ assert set(all_ids) == {"a", "b", "c", "d"}
+
+ def test_stops_when_offset_cap_window_collapses_to_one_timestamp(self) -> None:
+ # More rows than the offset cap can reach all share the same timestamp. Re-pinning [max] to that
+ # timestamp would re-fetch the same page forever; pagination must terminate instead of spinning.
+ session = _PagedSession(_charges([("a", 100), ("b", 100), ("c", 100), ("d", 100)]))
+ cfg = _cfg(page_size=2, max_offset=2)
+ results = list(
+ _iter_pages(session, ("k", ""), cfg, MagicMock(), min_value=None, start_offset=0, start_window_max=None) # type: ignore[arg-type]
+ )
+
+ # Terminates (the final page carries no resume state) rather than looping indefinitely.
+ assert results[-1][1] is None
+ # It shifted [max] to 100 exactly once, then stopped on the next identical-timestamp page.
+ assert sum(1 for c in session.calls if c.get("occurred[max]") == 100) >= 1
+
+ def test_min_filter_passed_through(self) -> None:
+ session = _PagedSession(_charges([("a", 50), ("b", 40), ("c", 30)]))
+ cfg = _cfg(page_size=5)
+ list(_iter_pages(session, ("k", ""), cfg, MagicMock(), min_value=35, start_offset=0, start_window_max=None)) # type: ignore[arg-type]
+ assert session.calls[0]["occurred[min]"] == 35
+
+ def test_filter_param_differs_from_timestamp_field(self) -> None:
+ # Subscriptions filter on `created` but the row timestamp column is `first_seen`.
+ rows = [{"subscription_id": "s1", "first_seen": 100}, {"subscription_id": "s2", "first_seen": 50}]
+ session = _PagedSession(rows, filter_param="created", ts_field="first_seen")
+ cfg = _cfg(
+ name="subscriptions",
+ path="/subscriptions",
+ primary_keys=["subscription_id"],
+ timestamp_field="first_seen",
+ filter_param="created",
+ page_size=5,
+ )
+ list(_iter_pages(session, ("k", ""), cfg, MagicMock(), min_value=60, start_offset=0, start_window_max=None)) # type: ignore[arg-type]
+ assert session.calls[0]["created[min]"] == 60
+
+
+class TestRunPass:
+ def test_saves_state_after_yielding_each_batch(self) -> None:
+ session = _PagedSession(_charges([("a", 50), ("b", 40), ("c", 30), ("d", 20), ("e", 10)]))
+ cfg = _cfg(page_size=2)
+ manager = _FakeManager()
+ batcher = Batcher(logger=MagicMock(), chunk_size=2, chunk_size_bytes=10**9)
+
+ tables = list(
+ _run_pass(
+ session, # type: ignore[arg-type]
+ ("k", ""),
+ cfg,
+ MagicMock(),
+ batcher,
+ manager, # type: ignore[arg-type]
+ phase="full",
+ min_value=None,
+ start_offset=0,
+ start_window_max=None,
+ )
+ )
+
+ # chunk_size=2 -> a batch yields after each 2-row page that has a following page.
+ assert len(tables) >= 1
+ assert manager.saved # state persisted after yielding
+ # Saved offsets advance and stay tagged with the current phase.
+ assert all(s.phase == "full" for s in manager.saved)
+ assert manager.saved[0].offset == 2
+
+
+class TestGetRows:
+ def _collect(self, gen: Any) -> list[dict]:
+ return [row for table in gen for row in table.to_pylist()]
+
+ def test_full_scan_when_not_incremental(self) -> None:
+ session = _PagedSession(_charges([("a", 50), ("b", 40), ("c", 30)]))
+ manager = _FakeManager()
+ with patch.object(chargedesk, "make_tracked_session", return_value=session):
+ rows = self._collect(
+ get_rows("k", "charges", MagicMock(), manager, should_use_incremental_field=False) # type: ignore[arg-type]
+ )
+ assert {r["charge_id"] for r in rows} == {"a", "b", "c"}
+ # No incremental filters on a full scan.
+ assert all("occurred[min]" not in c for c in session.calls)
+
+ def test_latest_pass_uses_min_filter(self) -> None:
+ session = _PagedSession(_charges([("a", 50), ("b", 40)]))
+ manager = _FakeManager()
+ with patch.object(chargedesk, "make_tracked_session", return_value=session):
+ self._collect(
+ get_rows(
+ "k",
+ "charges",
+ MagicMock(),
+ manager, # type: ignore[arg-type]
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=45,
+ db_incremental_field_earliest_value=None,
+ )
+ )
+ assert session.calls[0]["occurred[min]"] == 45
+
+ def test_earliest_pass_then_latest_pass(self) -> None:
+ session = _PagedSession(_charges([("a", 50), ("b", 40), ("c", 30), ("d", 20)]))
+ manager = _FakeManager()
+ with patch.object(chargedesk, "make_tracked_session", return_value=session):
+ self._collect(
+ get_rows(
+ "k",
+ "charges",
+ MagicMock(),
+ manager, # type: ignore[arg-type]
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=50,
+ db_incremental_field_earliest_value=20,
+ )
+ )
+ # Earliest backfill runs first with occurred[max]=20, then latest with occurred[min]=50.
+ assert session.calls[0].get("occurred[max]") == 20
+ assert any(c.get("occurred[min]") == 50 for c in session.calls)
+
+ def test_incremental_ignored_for_full_refresh_endpoint(self) -> None:
+ session = _PagedSession([{"product_id": "p1", "first_seen": 10}], filter_param="created", ts_field="first_seen")
+ manager = _FakeManager()
+ with patch.object(chargedesk, "make_tracked_session", return_value=session):
+ self._collect(
+ get_rows(
+ "k",
+ "products",
+ MagicMock(),
+ manager, # type: ignore[arg-type]
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=5,
+ )
+ )
+ # products is full-refresh only, so the [min] filter must never be sent.
+ assert all("created[min]" not in c for c in session.calls)
+
+ def test_resume_from_saved_full_state(self) -> None:
+ session = _PagedSession(_charges([("a", 50), ("b", 40), ("c", 30), ("d", 20)]))
+ manager = _FakeManager(state=ChargedeskResumeConfig(offset=2, window_max=None, phase="full"))
+ with patch.object(chargedesk, "make_tracked_session", return_value=session):
+ self._collect(
+ get_rows("k", "charges", MagicMock(), manager, should_use_incremental_field=False) # type: ignore[arg-type]
+ )
+ # First fetch resumes from the saved offset, not 0.
+ assert session.calls[0]["offset"] == 2
+
+
+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:
+ session = MagicMock()
+ session.get.return_value = _FakeResponse({}, status=status)
+ with patch.object(chargedesk, "make_tracked_session", return_value=session):
+ assert validate_credentials("k") is expected
+
+ def test_network_error_is_invalid(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with patch.object(chargedesk, "make_tracked_session", return_value=session):
+ assert validate_credentials("k") is False
+
+
+class TestChargedeskSource:
+ @parameterized.expand(list(CHARGEDESK_ENDPOINTS.keys()))
+ def test_source_response_shape(self, endpoint: str) -> None:
+ cfg = CHARGEDESK_ENDPOINTS[endpoint]
+ response = chargedesk_source("k", endpoint, MagicMock(), MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == cfg.primary_keys
+ # ChargeDesk returns rows newest-first.
+ assert response.sort_mode == "desc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [cfg.timestamp_field]
+
+ def test_primary_keys_are_resource_specific(self) -> None:
+ assert chargedesk_source("k", "charges", MagicMock(), MagicMock()).primary_keys == ["charge_id"]
+ assert chargedesk_source("k", "customers", MagicMock(), MagicMock()).primary_keys == ["customer_id"]
+
+
+if __name__ == "__main__":
+ pytest.main([__file__])
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.py
new file mode 100644
index 000000000000..2b146de4cf0d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chargedesk/tests/test_chargedesk_source.py
@@ -0,0 +1,158 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.chargedesk import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.chargedesk.chargedesk import (
+ ChargedeskResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.chargedesk.source import ChargedeskSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ChargedeskSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config() -> ChargedeskSourceConfig:
+ return ChargedeskSourceConfig(api_key="sk_test")
+
+
+class TestChargedeskSourceConfig:
+ def test_source_type(self) -> None:
+ assert ChargedeskSource().source_type == ExternalDataSourceType.CHARGEDESK
+
+ def test_get_source_config(self) -> None:
+ config = ChargedeskSource().get_source_config
+ assert config.name == SchemaExternalDataSourceType.CHARGEDESK
+ assert config.category == DataWarehouseSourceCategory.PAYMENTS___BILLING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/chargedesk"
+
+ def test_single_secret_api_key_field(self) -> None:
+ fields = ChargedeskSource().get_source_config.fields
+ assert len(fields) == 1
+ api_key_field = fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ # The secret key must be stored as a password/secret, never plain text.
+ assert api_key_field.secret is True
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static catalog, so the public docs can render the table list.
+ assert ChargedeskSource.lists_tables_without_credentials is True
+
+
+class TestGetSchemas:
+ def test_lists_all_four_resources(self) -> None:
+ schemas = ChargedeskSource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == {"charges", "customers", "subscriptions", "products"}
+
+ def test_incremental_resources_advertise_incremental(self) -> None:
+ schemas = {s.name: s for s in ChargedeskSource().get_schemas(_config(), team_id=1)}
+ for name in ("charges", "customers", "subscriptions"):
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].incremental_fields
+
+ def test_products_is_full_refresh_only(self) -> None:
+ schemas = {s.name: s for s in ChargedeskSource().get_schemas(_config(), team_id=1)}
+ assert schemas["products"].supports_incremental is False
+ assert schemas["products"].incremental_fields == []
+
+ def test_incremental_fields_use_resource_timestamp(self) -> None:
+ schemas = {s.name: s for s in ChargedeskSource().get_schemas(_config(), team_id=1)}
+ assert schemas["charges"].incremental_fields[0]["field"] == "occurred"
+ # 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"
+
+ def test_names_filter(self) -> None:
+ schemas = ChargedeskSource().get_schemas(_config(), team_id=1, names=["charges"])
+ assert [s.name for s in schemas] == ["charges"]
+
+
+class TestValidateCredentials:
+ def test_valid_key(self) -> None:
+ with patch.object(source_module, "validate_chargedesk_credentials", return_value=True):
+ ok, error = ChargedeskSource().validate_credentials(_config(), team_id=1)
+ assert ok is True
+ assert error is None
+
+ def test_invalid_key(self) -> None:
+ with patch.object(source_module, "validate_chargedesk_credentials", return_value=False):
+ ok, error = ChargedeskSource().validate_credentials(_config(), team_id=1)
+ assert ok is False
+ assert error is not None
+
+
+class TestNonRetryableErrors:
+ def test_auth_errors_are_non_retryable(self) -> None:
+ errors = ChargedeskSource().get_non_retryable_errors()
+ assert any(key.startswith("401") for key in errors)
+ assert any(key.startswith("403") for key in errors)
+
+
+class TestResumableManager:
+ def test_returns_manager_bound_to_resume_config(self) -> None:
+ inputs = MagicMock()
+ manager = ChargedeskSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is ChargedeskResumeConfig
+
+
+class TestSourceForPipeline:
+ def _inputs(self, **overrides: Any) -> MagicMock:
+ inputs = MagicMock()
+ inputs.schema_name = "charges"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1000
+ inputs.db_incremental_field_earliest_value = 500
+ for key, value in overrides.items():
+ setattr(inputs, key, value)
+ return inputs
+
+ def test_plumbs_incremental_values_through(self) -> None:
+ captured: dict[str, Any] = {}
+
+ def _fake_source(**kwargs: Any) -> str:
+ captured.update(kwargs)
+ return "response"
+
+ with patch.object(source_module, "chargedesk_source", side_effect=_fake_source):
+ ChargedeskSource().source_for_pipeline(_config(), MagicMock(), self._inputs())
+
+ assert captured["endpoint"] == "charges"
+ assert captured["api_key"] == "sk_test"
+ assert captured["db_incremental_field_last_value"] == 1000
+ assert captured["db_incremental_field_earliest_value"] == 500
+
+ def test_non_incremental_run_passes_no_watermark(self) -> None:
+ captured: dict[str, Any] = {}
+
+ def _fake_source(**kwargs: Any) -> str:
+ captured.update(kwargs)
+ return "response"
+
+ with patch.object(source_module, "chargedesk_source", side_effect=_fake_source):
+ ChargedeskSource().source_for_pipeline(
+ _config(), MagicMock(), self._inputs(should_use_incremental_field=False)
+ )
+
+ assert captured["db_incremental_field_last_value"] is None
+ assert captured["db_incremental_field_earliest_value"] is None
+
+
+class TestCanonicalDescriptions:
+ def test_covers_every_resource(self) -> None:
+ descriptions = ChargedeskSource().get_canonical_descriptions()
+ assert {"charges", "customers", "subscriptions", "products"} <= set(descriptions)
+
+
+if __name__ == "__main__":
+ pytest.main([__file__])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 955b3b7c97f8..5bfb024c2ee0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -597,7 +597,7 @@ class ChargebeeSourceConfig(config.Config):
@config.config
class ChargedeskSourceConfig(config.Config):
- pass
+ api_key: str
@config.config