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 invoiced import source (#69348)

Tom Owers2d3bfa8caffe
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 8328dd76929a..74e05dcf1d75 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -196,6 +196,7 @@ the row lists both.
| instatus | HTTP | requests | ✅ |
| intercom | HTTP | requests + `rest_source.RESTClient` | ✅ |
| intruder | HTTP | requests | ✅ |
+| invoiced | HTTP | requests | ✅ |
| invoiceninja | HTTP | requests | ✅ |
| ip2whois | HTTP | requests | ✅ |
| iterable | HTTP | requests | ✅ |
@@ -552,7 +553,6 @@ doesn't conflict with concurrent PRs.
- instagram
- instantly
- interzoid
-- invoiced
- jamf_pro
- jobber
- judgeme_reviews
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 8f75f5c02c58..e9db61243cb0 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
@@ -1749,7 +1749,7 @@ class IntruderSourceConfig(config.Config):
@config.config
class InvoicedSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/canonical_descriptions.py
new file mode 100644
index 000000000000..4cbbd7390a76
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/canonical_descriptions.py
@@ -0,0 +1,185 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Invoiced API docs (https://developer.invoiced.com/api).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "customers": {
+ "description": "A customer you bill in Invoiced, holding contact, address, payment, and collections settings.",
+ "docs_url": "https://developer.invoiced.com/api/customers",
+ "columns": {
+ "id": "The customer's unique ID.",
+ "name": "Customer name.",
+ "number": "A unique ID to help tie the customer to your external systems.",
+ "email": "Email address.",
+ "type": "Organization type, company or person.",
+ "autopay": "Whether AutoPay is enabled.",
+ "payment_terms": "Payment terms when AutoPay is off, e.g. NET 30.",
+ "currency": "3-letter ISO currency code.",
+ "country": "Two-letter ISO country code.",
+ "credit_hold": "When true, the customer is on credit hold.",
+ "credit_limit": "Customer credit limit.",
+ "taxable": "Whether the customer is taxable.",
+ "parent_customer": "Parent customer ID, if any.",
+ "created_at": "UNIX timestamp when created.",
+ "updated_at": "UNIX timestamp when last updated.",
+ },
+ },
+ "invoices": {
+ "description": "An invoice issued to a customer, with line items, totals, payment state, and collection status.",
+ "docs_url": "https://developer.invoiced.com/api/invoices",
+ "columns": {
+ "id": "The invoice's unique ID.",
+ "customer": "Customer ID the invoice belongs to.",
+ "number": "The reference number assigned to the invoice.",
+ "status": "Invoice state: draft, not_sent, sent, viewed, past_due, pending, paid, or voided.",
+ "draft": "When true, the invoice is a draft; when false, it is outstanding.",
+ "closed": "When true, the invoice is closed and considered bad debt.",
+ "paid": "Whether the invoice has been paid in full.",
+ "currency": "3-letter ISO currency code.",
+ "date": "Invoice date (UNIX timestamp).",
+ "due_date": "Date payment is due by (UNIX timestamp).",
+ "payment_terms": "Payment terms for the invoice, e.g. NET 30.",
+ "subscription": "Subscription ID if the invoice came from a subscription.",
+ "subtotal": "Invoice subtotal.",
+ "total": "Invoice total.",
+ "balance": "Balance owed.",
+ "attempt_count": "Number of payment attempts.",
+ "created_at": "UNIX timestamp when created.",
+ "updated_at": "UNIX timestamp when last updated.",
+ },
+ },
+ "payments": {
+ "description": "A payment received from a customer, with the amounts applied to invoices, estimates, or credit balances.",
+ "docs_url": "https://developer.invoiced.com/api/payments",
+ "columns": {
+ "id": "The payment's unique ID.",
+ "customer": "Associated customer ID, if any.",
+ "date": "Payment date (UNIX timestamp).",
+ "currency": "3-letter ISO currency code.",
+ "amount": "Payment amount.",
+ "balance": "Unapplied amount remaining.",
+ "method": "Payment instrument used, e.g. ach, check, credit_card, wire_transfer.",
+ "reference": "Reference number, e.g. a check number.",
+ "source": "Source of the payment.",
+ "voided": "Whether the payment was voided.",
+ "matched": "When true, there is a CashMatch suggestion.",
+ "applied_to": "List of payment applications describing how the payment was applied.",
+ "created_at": "UNIX timestamp when created.",
+ "updated_at": "UNIX timestamp when last updated.",
+ },
+ },
+ "credit_notes": {
+ "description": "A credit note issued against a customer's invoice, reducing the amount owed.",
+ "docs_url": "https://developer.invoiced.com/api/credit-notes",
+ "columns": {
+ "id": "The credit note's unique ID.",
+ "customer": "Customer ID the credit note belongs to.",
+ "number": "The reference number assigned to the credit note.",
+ "status": "Credit note state: draft, open, paid, closed, or voided.",
+ "draft": "When true, the credit note is a draft; when false, it is outstanding.",
+ "closed": "When true, the credit note is closed and considered bad debt.",
+ "paid": "Whether the credit note has been paid in full.",
+ "currency": "3-letter ISO currency code.",
+ "date": "Credit note date (UNIX timestamp).",
+ "subtotal": "Credit note subtotal.",
+ "total": "Credit note total.",
+ "balance": "Balance owed.",
+ "created_at": "UNIX timestamp when created.",
+ "updated_at": "UNIX timestamp when last updated.",
+ },
+ },
+ "estimates": {
+ "description": "An estimate (quote) sent to a customer, optionally convertible into an invoice.",
+ "docs_url": "https://developer.invoiced.com/api/estimates",
+ "columns": {
+ "id": "The estimate's unique ID.",
+ "customer": "Customer ID the estimate belongs to.",
+ "invoice": "Invoice ID the estimate was converted into, if any.",
+ "number": "The reference number assigned to the estimate.",
+ "status": "Estimate state: draft, not_sent, sent, approved, invoiced, declined, or voided.",
+ "approved": "Whether the estimate was approved.",
+ "currency": "3-letter ISO currency code.",
+ "date": "Estimate date (UNIX timestamp).",
+ "expiration_date": "Estimate expiration date (UNIX timestamp).",
+ "deposit": "Up-front deposit required.",
+ "deposit_paid": "Whether the deposit has been paid in full.",
+ "subtotal": "Estimate subtotal.",
+ "total": "Estimate total.",
+ "created_at": "UNIX timestamp when created.",
+ "updated_at": "UNIX timestamp when last updated.",
+ },
+ },
+ "subscriptions": {
+ "description": "A recurring billing subscription that bills a customer for a plan on a fixed schedule.",
+ "docs_url": "https://developer.invoiced.com/api/subscriptions",
+ "columns": {
+ "id": "The subscription's unique ID.",
+ "customer": "Associated customer ID.",
+ "plan": "Plan ID the subscription bills for.",
+ "status": "Subscription status: not_started, active, past_due, finished, or canceled.",
+ "quantity": "Plan quantity, defaults to 1.",
+ "start_date": "UNIX timestamp the subscription starts (or started).",
+ "period_start": "Start of the current billing period (UNIX timestamp).",
+ "period_end": "End of the current billing period (UNIX timestamp).",
+ "cancel_at_period_end": "When true, the subscription cancels at the end of the current billing period.",
+ "canceled_at": "UNIX timestamp the subscription was canceled.",
+ "paused": "Whether the subscription is paused.",
+ "recurring_total": "Total recurring amount, including taxes.",
+ "mrr": "Monthly recurring revenue (MRR).",
+ "created_at": "UNIX timestamp when created.",
+ "updated_at": "UNIX timestamp when last updated.",
+ },
+ },
+ "items": {
+ "description": "A catalog item — a reusable product or service that can be added to invoices as a line item.",
+ "docs_url": "https://developer.invoiced.com/api/items",
+ "columns": {
+ "id": "The item's unique ID.",
+ "name": "Item name.",
+ "type": "Optional line item type, used to group line items in reporting.",
+ "currency": "3-letter ISO currency code.",
+ "unit_cost": "Unit cost or rate.",
+ "description": "Optional description.",
+ "taxable": "Excludes the amount from taxes when false.",
+ "discountable": "Excludes the amount from discounts when false.",
+ "gl_account": "General ledger account code.",
+ "created_at": "UNIX timestamp when created.",
+ "updated_at": "UNIX timestamp when last updated.",
+ },
+ },
+ "plans": {
+ "description": "A billing plan describing the price and billing interval used by subscriptions.",
+ "docs_url": "https://developer.invoiced.com/api/plans",
+ "columns": {
+ "id": "The plan's unique ID.",
+ "name": "Plan name.",
+ "catalog_item": "Item ID the plan belongs to.",
+ "currency": "3-letter ISO currency code.",
+ "amount": "Plan amount; not applicable when the pricing mode is custom.",
+ "pricing_mode": "Pricing mode: per_unit, volume, tiered, or custom.",
+ "quantity_type": "Quantity type: constant or usage.",
+ "interval": "Billing frequency: day, week, month, or year.",
+ "interval_count": "Number of intervals between each subscription billing, defaults to 1.",
+ "created_at": "UNIX timestamp when created.",
+ "updated_at": "UNIX timestamp when last updated.",
+ },
+ },
+ "coupons": {
+ "description": "A coupon that applies a fixed or percentage discount to invoices or subscriptions.",
+ "docs_url": "https://developer.invoiced.com/api/coupons",
+ "columns": {
+ "id": "The coupon's unique ID.",
+ "name": "Coupon name.",
+ "currency": "3-letter ISO currency code.",
+ "value": "Discount amount.",
+ "is_percent": "When true, the value is a percentage.",
+ "exclusive": "When true, no other coupons can be used simultaneously.",
+ "expiration_date": "Date the coupon expires (UNIX timestamp).",
+ "max_redemptions": "Maximum number of times the coupon can be used.",
+ "created_at": "UNIX timestamp when created.",
+ "updated_at": "UNIX timestamp when last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/invoiced.py b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/invoiced.py
new file mode 100644
index 000000000000..56005905824e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/invoiced.py
@@ -0,0 +1,220 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import quote, urlencode, urlsplit
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from urllib3.util.retry import Retry
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+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
+from products.warehouse_sources.backend.temporal.data_imports.sources.invoiced.settings import INVOICED_ENDPOINTS
+
+INVOICED_BASE_URL = "https://api.invoiced.com"
+INVOICED_HOST = "api.invoiced.com"
+# List endpoints paginate GitHub-style (page/per_page + Link header) in pages of up to 100.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+# Cheap list endpoint used to confirm an API key is genuine. Invoiced API keys are
+# account-wide, so one probe validates access to every list endpoint.
+DEFAULT_PROBE_PATH = "/customers"
+
+
+class InvoicedRetryableError(Exception):
+ pass
+
+
+class InvoicedUntrustedURLError(Exception):
+ """A pagination URL (resumed or upstream) pointed somewhere other than the Invoiced API."""
+
+
+def _validate_pagination_url(url: str) -> str:
+ """Pin every authenticated request to the Invoiced API origin.
+
+ Both resumed `next_url` values (loaded from Redis) and upstream `Link` header URLs are followed
+ verbatim with the customer's API key installed as HTTP Basic auth. Validating the scheme and host
+ keeps a poisoned resume state or a hostile upstream response from retargeting the request at
+ another host and leaking the key (SSRF). Returns the URL unchanged when it is trusted.
+ """
+ parts = urlsplit(url)
+ if not (parts.scheme == "https" and parts.netloc == INVOICED_HOST):
+ raise InvoicedUntrustedURLError(f"Refusing to follow pagination URL outside {INVOICED_BASE_URL}")
+ return url
+
+
+class InvoicedResumeConfig:
+ # Full URL of the next page, taken verbatim from the Link header's rel="next". It carries
+ # the original request's per_page/sort/updated_after params, so a crashed sync resumes from
+ # the page after the last one yielded; merge dedupes the re-pulled page on `id`.
+ next_url: str | None = None
+
+
+def _get_session(api_key: str) -> requests.Session:
+ # Invoiced authenticates via HTTP Basic with the API key as the username and a blank password.
+ # `allow_redirects=False` stops a redirect response from sending the API key to another host, and
+ # `retry=Retry(total=0)` disables the adapter's built-in retries — `_fetch_page` already retries
+ # 429/5xx via tenacity, so the adapter default would stack a second retry layer.
+ session = make_tracked_session(
+ headers={"Accept": "application/json"},
+ redact_values=(api_key,),
+ allow_redirects=False,
+ retry=Retry(total=0),
+ )
+ session.auth = (api_key, "")
+ return session
+
+
+def _to_unix_timestamp(value: Any) -> int:
+ """Convert an incremental cursor to the UNIX epoch integer `updated_after` expects."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return int(dt.timestamp())
+ if isinstance(value, date):
+ return int(datetime(value.year, value.month, value.day, tzinfo=UTC).timestamp())
+ return int(value)
+
+
+def _build_initial_url(
+ path: str,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> str:
+ # An explicit ascending updated_at sort keeps page traversal deterministic and lets the
+ # pipeline checkpoint the incremental watermark per batch (sort_mode="asc"). `sort` is
+ # documented on every list endpoint we sync ("Column to sort by, i.e. name asc").
+ params: dict[str, Any] = {"per_page": PAGE_SIZE, "sort": "updated_at asc"}
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ params["updated_after"] = _to_unix_timestamp(db_incremental_field_last_value)
+ return f"{INVOICED_BASE_URL}{path}?{urlencode(params, quote_via=quote)}"
+
+
+@retry(
+ retry=retry_if_exception_type((InvoicedRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ logger: FilteringBoundLogger,
+) -> tuple[list[dict[str, Any]], Optional[str]]:
+ # `url` is already absolute — either the initial endpoint URL or a verbatim Link rel="next",
+ # so we never re-send query params (they're baked into the pagination URL).
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Invoiced enforces rate limits via 429 with no published numeric limits; back off and retry.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise InvoicedRetryableError(f"Invoiced API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Invoiced API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ data = response.json()
+ # List endpoints return a top-level JSON array; pagination lives in the Link header.
+ if not isinstance(data, list):
+ raise InvoicedRetryableError(f"Invoiced returned an unexpected payload for {url}: {type(data).__name__}")
+
+ next_url = response.links.get("next", {}).get("url")
+ return data, next_url
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InvoicedResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = INVOICED_ENDPOINTS[endpoint]
+ session = _get_session(api_key)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume and resume.next_url:
+ # Resume state comes from Redis — validate before sending the API key to it.
+ url: Optional[str] = _validate_pagination_url(resume.next_url)
+ logger.debug(f"Invoiced: resuming {endpoint} from {url}")
+ else:
+ url = _build_initial_url(config.path, should_use_incremental_field, db_incremental_field_last_value)
+
+ while url:
+ items, next_url = _fetch_page(session, url, logger)
+ if items:
+ yield items
+
+ # No Link rel="next" means we've reached the last page.
+ if not next_url:
+ break
+
+ # The upstream-supplied next-page URL is followed verbatim with the API key — pin it to the
+ # Invoiced API so a hostile response can't retarget the authenticated request.
+ url = _validate_pagination_url(next_url)
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(InvoicedResumeConfig(next_url=url))
+
+
+def invoiced_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InvoicedResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = INVOICED_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,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ # Rows are requested with an explicit `sort=updated_at asc` (see _build_initial_url).
+ sort_mode="asc",
+ )
+
+
+def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single endpoint to validate the API key.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = _get_session(api_key)
+ try:
+ response = session.get(f"{INVOICED_BASE_URL}{path}", params={"per_page": 1}, timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to Invoiced: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Invoiced returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ status, message = check_access(api_key)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Invoiced API key"
+ return False, message or "Could not validate Invoiced API key"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/settings.py
new file mode 100644
index 000000000000..1e48e599eaed
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/settings.py
@@ -0,0 +1,43 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class InvoicedEndpointConfig:
+ path: str
+ # Invoiced object IDs are unique per resource within an account (integers for documents,
+ # user-assigned strings for catalog objects like items/plans/coupons), so `id` is a safe
+ # primary key for every top-level list endpoint.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# Invoiced REST API top-level list endpoints (https://developer.invoiced.com/api). Every one of
+# these documents a server-side `updated_after` UNIX-timestamp filter, so `updated_at` is a
+# genuine incremental cursor across the board.
+INVOICED_ENDPOINTS: dict[str, InvoicedEndpointConfig] = {
+ "customers": InvoicedEndpointConfig(path="/customers"),
+ "invoices": InvoicedEndpointConfig(path="/invoices"),
+ "payments": InvoicedEndpointConfig(path="/payments"),
+ "credit_notes": InvoicedEndpointConfig(path="/credit_notes"),
+ "estimates": InvoicedEndpointConfig(path="/estimates"),
+ "subscriptions": InvoicedEndpointConfig(path="/subscriptions"),
+ "items": InvoicedEndpointConfig(path="/items"),
+ "plans": InvoicedEndpointConfig(path="/plans"),
+ "coupons": InvoicedEndpointConfig(path="/coupons"),
+}
+
+ENDPOINTS = tuple(INVOICED_ENDPOINTS.keys())
+
+# Invoiced represents timestamps as UNIX epoch integers (`updated_at` in responses,
+# `updated_after` as the matching request filter).
+_UPDATED_AT_INCREMENTAL_FIELD: IncrementalField = {
+ "label": "updated_at",
+ "type": IncrementalFieldType.Integer,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.Integer,
+}
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ endpoint: [_UPDATED_AT_INCREMENTAL_FIELD] for endpoint in ENDPOINTS
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/source.py
index 0949ff28bd2e..eb97ba9506e3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/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.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 InvoicedSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.invoiced.invoiced import (
+ InvoicedResumeConfig,
+ invoiced_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.invoiced.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ INVOICED_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class InvoicedSource(SimpleSource[InvoicedSourceConfig]):
+class InvoicedSource(ResumableSource[InvoicedSourceConfig, InvoicedResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.INVOICED
@@ -24,7 +48,92 @@ class InvoicedSource(SimpleSource[InvoicedSourceConfig]):
name=SchemaExternalDataSourceType.INVOICED,
category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
label="Invoiced",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Invoiced API key to pull your accounts receivable and billing data into the PostHog Data warehouse.
+
+You can create an API key under **Settings → Developers → API Keys** in [Invoiced](https://www.invoiced.com). The key grants read access to your customers, invoices, payments, credit notes, estimates, subscriptions, and billing catalog.
+""",
iconPath="/static/services/invoiced.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/invoiced",
+ keywords=["billing", "invoicing", "accounts receivable"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.invoiced.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.invoiced.com": "Your Invoiced API key is invalid or has been revoked. Generate a new key under Settings → Developers → API Keys, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.invoiced.com": "Your Invoiced API key does not have access to this data. Check the key's permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: InvoicedSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every list endpoint documents a server-side `updated_after` UNIX-timestamp filter, so
+ # each schema advertises `updated_at` as a genuine incremental cursor.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=True,
+ supports_append=True,
+ incremental_fields=INCREMENTAL_FIELDS[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: InvoicedSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # Invoiced API keys are account-wide, so a single probe validates access to every schema.
+ return validate_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[InvoicedResumeConfig]:
+ return ResumableSourceManager[InvoicedResumeConfig](inputs, InvoicedResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: InvoicedSourceConfig,
+ resumable_source_manager: ResumableSourceManager[InvoicedResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in INVOICED_ENDPOINTS:
+ raise ValueError(f"Unknown Invoiced schema '{inputs.schema_name}'")
+
+ return invoiced_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,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/tests/test_invoiced.py b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/tests/test_invoiced.py
new file mode 100644
index 000000000000..826efafc8fcb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/tests/test_invoiced.py
@@ -0,0 +1,219 @@
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.invoiced.invoiced import (
+ INVOICED_BASE_URL,
+ PAGE_SIZE,
+ InvoicedResumeConfig,
+ InvoicedUntrustedURLError,
+ _to_unix_timestamp,
+ _validate_pagination_url,
+ get_rows,
+ invoiced_source,
+ validate_credentials,
+)
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.invoiced.invoiced"
+
+
+def _make_manager(resume_state: InvoicedResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _response(items: Any, next_url: str | None = None, status_code: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = items
+ resp.status_code = status_code
+ resp.ok = status_code < 400
+ resp.links = {"next": {"url": next_url}} if next_url else {}
+ return resp
+
+
+class TestToUnixTimestamp:
+ @parameterized.expand(
+ [
+ ("aware_datetime", datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), 1704164645),
+ ("naive_datetime_assumed_utc", datetime(2024, 1, 2, 3, 4, 5), 1704164645),
+ ("date", date(2024, 1, 2), 1704153600),
+ ("int", 1700000000, 1700000000),
+ ("numeric_string", "1700000000", 1700000000),
+ ]
+ )
+ def test_converts_to_epoch_seconds(self, _name: str, value: Any, expected: int) -> None:
+ assert _to_unix_timestamp(value) == expected
+
+
+class TestGetRows:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_paginates_via_link_header_and_saves_state_after_yield(self, mock_session: mock.MagicMock) -> None:
+ page_two_url = f"{INVOICED_BASE_URL}/customers?page=2&per_page={PAGE_SIZE}"
+ mock_session.return_value.get.side_effect = [
+ _response([{"id": 1}, {"id": 2}], next_url=page_two_url),
+ _response([{"id": 3}]),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("api-key", "customers", mock.MagicMock(), manager))
+
+ assert batches == [[{"id": 1}, {"id": 2}], [{"id": 3}]]
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0].next_url == page_two_url
+ # The second request follows the Link rel="next" URL verbatim.
+ assert mock_session.return_value.get.call_args_list[1].args[0] == page_two_url
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_incremental_request_includes_updated_after_and_sort(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response([])
+
+ manager = _make_manager()
+ list(
+ get_rows(
+ "api-key",
+ "invoices",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1700000000,
+ )
+ )
+
+ url = mock_session.return_value.get.call_args.args[0]
+ query = parse_qs(urlparse(url).query)
+ assert urlparse(url).path == "/invoices"
+ assert query["updated_after"] == ["1700000000"]
+ assert query["sort"] == ["updated_at asc"]
+ assert query["per_page"] == [str(PAGE_SIZE)]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_full_refresh_omits_updated_after(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response([])
+
+ manager = _make_manager()
+ list(get_rows("api-key", "customers", mock.MagicMock(), manager))
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert "updated_after" not in parse_qs(urlparse(url).query)
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_resumes_from_saved_next_url(self, mock_session: mock.MagicMock) -> None:
+ saved_url = f"{INVOICED_BASE_URL}/customers?page=7&per_page={PAGE_SIZE}"
+ mock_session.return_value.get.return_value = _response([])
+
+ manager = _make_manager(InvoicedResumeConfig(next_url=saved_url))
+ list(get_rows("api-key", "customers", mock.MagicMock(), manager))
+
+ assert mock_session.return_value.get.call_args.args[0] == saved_url
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_empty_response_stops_without_saving_state(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response([])
+
+ manager = _make_manager()
+ batches = list(get_rows("api-key", "customers", mock.MagicMock(), manager))
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_authenticates_with_api_key_as_basic_auth_username(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response([])
+
+ list(get_rows("api-key", "customers", mock.MagicMock(), _make_manager()))
+
+ assert mock_session.return_value.auth == ("api-key", "")
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_hostile_upstream_next_url_is_rejected(self, mock_session: mock.MagicMock) -> None:
+ # An upstream Link header pointing at another host must abort before the API key is sent
+ # there, and the poisoned URL must not be persisted as resume state.
+ mock_session.return_value.get.return_value = _response(
+ [{"id": 1}], next_url="https://evil.example.com/customers"
+ )
+
+ manager = _make_manager()
+ with pytest.raises(InvoicedUntrustedURLError):
+ list(get_rows("api-key", "customers", mock.MagicMock(), manager))
+ manager.save_state.assert_not_called()
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_hostile_resumed_next_url_is_rejected(self, mock_session: mock.MagicMock) -> None:
+ # A poisoned resume state from Redis must never be requested with the API key.
+ manager = _make_manager(InvoicedResumeConfig(next_url="https://evil.example.com/customers"))
+ with pytest.raises(InvoicedUntrustedURLError):
+ list(get_rows("api-key", "customers", mock.MagicMock(), manager))
+ mock_session.return_value.get.assert_not_called()
+
+
+class TestValidatePaginationUrl:
+ @parameterized.expand(
+ [
+ ("first_page", f"{INVOICED_BASE_URL}/customers?per_page=100"),
+ ("next_page", f"{INVOICED_BASE_URL}/customers?per_page=100&page=2"),
+ ("other_endpoint", f"{INVOICED_BASE_URL}/invoices?page=3"),
+ ]
+ )
+ def test_trusted_urls_pass_through(self, _name: str, url: str) -> None:
+ assert _validate_pagination_url(url) == url
+
+ @parameterized.expand(
+ [
+ ("foreign_host", "https://evil.example.com/customers"),
+ ("subdomain_lookalike", "https://api.invoiced.com.evil.example.com/customers"),
+ ("http_scheme", "http://api.invoiced.com/customers"),
+ ("metadata_endpoint", "http://169.254.169.254/latest/meta-data/"),
+ ]
+ )
+ def test_untrusted_urls_raise(self, _name: str, url: str) -> None:
+ with pytest.raises(InvoicedUntrustedURLError):
+ _validate_pagination_url(url)
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("unauthorized", 401),
+ ("forbidden", 403),
+ ]
+ )
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_auth_failure_maps_to_invalid_key(self, _name: str, status_code: int, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response({}, status_code=status_code)
+ assert validate_credentials("bad-key") == (False, "Invalid Invoiced API key")
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_valid_key(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response([])
+ assert validate_credentials("good-key") == (True, None)
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_unexpected_status_returns_message(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _response({}, status_code=500)
+ ok, message = validate_credentials("key")
+ assert ok is False
+ assert message == "Invoiced returned HTTP 500"
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_connection_error_returns_message(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ ok, message = validate_credentials("key")
+ assert ok is False
+ assert message is not None and "Could not connect to Invoiced" in message
+
+
+class TestInvoicedSourceResponse:
+ def test_response_metadata(self) -> None:
+ response = invoiced_source("api-key", "invoices", mock.MagicMock(), _make_manager())
+
+ assert response.name == "invoices"
+ assert response.primary_keys == ["id"]
+ # Rows are requested with an explicit ascending updated_at sort.
+ assert response.sort_mode == "asc"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/tests/test_invoiced_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/tests/test_invoiced_source.py
new file mode 100644
index 000000000000..c68aac51391d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiced/tests/test_invoiced_source.py
@@ -0,0 +1,147 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+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 InvoicedSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.invoiced.invoiced import InvoicedResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.invoiced.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.invoiced.source import InvoicedSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestInvoicedSource:
+ def setup_method(self) -> None:
+ self.source = InvoicedSource()
+ self.team_id = 123
+ self.config = InvoicedSourceConfig(api_key="invoiced-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.INVOICED
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Invoiced"
+ assert config.label == "Invoiced"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/invoiced"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret
+ # field an editor could retarget to reuse a preserved key against another host.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_incremental(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is True for s in schemas)
+ assert all(s.supports_append is True for s in schemas)
+ assert all([f["field"] for f in s.incremental_fields] == ["updated_at"] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["invoices"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "invoices"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://api.invoiced.com/customers?per_page=100",
+ ),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.invoiced.com/invoices?per_page=100"),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ (
+ "server_error",
+ "500 Server Error: Internal Server Error for url: https://api.invoiced.com/customers",
+ ),
+ (
+ "rate_limited",
+ "429 Client Error: Too Many Requests for url: https://api.invoiced.com/invoices",
+ ),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.invoiced.source.validate_credentials")
+ def test_validate_credentials_delegates_with_api_key(self, mock_validate: mock.MagicMock) -> None:
+ # The status-to-message mapping lives in invoiced.validate_credentials; here we only assert
+ # the source probes with the configured key and returns the delegate's verdict unchanged.
+ mock_validate.return_value = (False, "Invalid Invoiced API key")
+ result = self.source.validate_credentials(self.config, self.team_id)
+ mock_validate.assert_called_once_with("invoiced-key")
+ assert result == (False, "Invalid Invoiced API key")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is InvoicedResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.invoiced.source.invoiced_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "invoices"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1700000000
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "invoiced-key"
+ assert kwargs["endpoint"] == "invoices"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1700000000
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.invoiced.source.invoiced_source")
+ def test_source_for_pipeline_drops_cursor_on_full_refresh(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "customers"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1700000000
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["should_use_incremental_field"] is False
+ assert kwargs["db_incremental_field_last_value"] is None
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Invoiced schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)