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 bill_com source (#73770)

Tom Owersb62d4ab6394e
diff --git a/frontend/public/services/bill_com.png b/frontend/public/services/bill_com.png
index 02417a6a3a19..51aae256ffc9 100644
Binary files a/frontend/public/services/bill_com.png and b/frontend/public/services/bill_com.png differ
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 6e011a943555..2b6f15da9d9a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -95,6 +95,7 @@ the row lists both.
| bettermode | HTTP (GraphQL) | requests | ✅ |
| bigmailer | HTTP | requests | ✅ |
| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |
+| bill_com | HTTP | requests | ✅ |
| bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |
| bitbucket | HTTP | requests | ✅ |
| bitrise | HTTP | requests | ✅ |
@@ -801,7 +802,6 @@ doesn't conflict with concurrent PRs.
- beehiiv
- bigcommerce
- bigeye
-- bill_com
- billomat
- bing_webmaster_tools
- bitly
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/bill_com.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/bill_com.py
new file mode 100644
index 000000000000..d5d86eaaf0db
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/bill_com.py
@@ -0,0 +1,285 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bill_com.settings import (
+ BILL_COM_ENDPOINTS,
+ CREATED_TIME_FIELD,
+ UPDATED_TIME_FIELD,
+)
+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.common.typings import SourceResponse
+
+# BILL runs the sandbox on a separate host, and a developer key is issued per environment.
+BILL_COM_HOSTS = {
+ "production": "https://gateway.prod.bill.com/connect",
+ "sandbox": "https://gateway.stage.bill.com/connect",
+}
+# `max` is capped at 100 by the API (default 20).
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class BillComResumeConfig:
+ next_page: str
+
+
+class BillComAuthError(Exception):
+ """Sign-in was rejected — the credentials are wrong, not a transient failure."""
+
+
+def base_url(environment: str) -> str:
+ host = BILL_COM_HOSTS.get(environment)
+ if host is None:
+ raise ValueError(f"Invalid BILL environment: {environment}")
+ return host
+
+
+def format_incremental_value(value: Any) -> str:
+ """Format a cursor value as the ISO 8601 UTC date-time BILL's `filters` param expects."""
+ if isinstance(value, datetime):
+ dt = value
+ elif isinstance(value, date):
+ dt = datetime.combine(value, datetime.min.time())
+ else:
+ return str(value)
+
+ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+
+
+def error_message(response: requests.Response) -> str:
+ """Pull the human-readable text out of BILL's error bodies.
+
+ Failures arrive either as the gateway's `{"message": ...}` or as the API's
+ `[{"message": ..., "code": ...}]` list.
+ """
+ try:
+ body = response.json()
+ except ValueError:
+ return response.text[:200]
+
+ if isinstance(body, list) and body:
+ first = body[0]
+ if isinstance(first, dict):
+ return str(first.get("message") or first.get("detail") or first)
+ if isinstance(body, dict):
+ return str(body.get("message") or body)
+ return str(body)[:200]
+
+
+class BillComClient:
+ """Session-authenticated BILL v3 client.
+
+ BILL has no bearer token: `POST /v3/login` exchanges the developer key plus the org sign-in for
+ a `sessionId` that rides every subsequent request as a header. The session expires after 35
+ minutes of inactivity, so a 401 mid-sync means "sign in again", not "bad credentials".
+ """
+
+ def __init__(
+ self,
+ *,
+ username: str,
+ password: str,
+ organization_id: str,
+ dev_key: str,
+ environment: str,
+ api_version: str,
+ ) -> None:
+ self._username = username
+ self._password = password
+ self._organization_id = organization_id
+ self._dev_key = dev_key
+ self._api_root = f"{base_url(environment)}/{api_version}"
+ self._session_id: Optional[str] = None
+ # capture=False keeps requests metered and logged but excludes them from HTTP sample
+ # capture: BILL responses carry raw financial records (bank accounts, routing numbers,
+ # payments, invoices, customers, vendors) and the login exchange returns a freshly minted
+ # session ID in a generic field — content the name-based scrubbers can't reliably redact.
+ self._session = make_tracked_session(redact_values=(password, dev_key), capture=False)
+
+ @property
+ def api_root(self) -> str:
+ return self._api_root
+
+ @property
+ def session_id(self) -> Optional[str]:
+ return self._session_id
+
+ def login(self) -> str:
+ response = self._session.post(
+ f"{self._api_root}/login",
+ json={
+ "username": self._username,
+ "password": self._password,
+ "organizationId": self._organization_id,
+ "devKey": self._dev_key,
+ },
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ if response.status_code in (400, 401, 403):
+ raise BillComAuthError(f"BILL sign-in failed: {error_message(response)}")
+ response.raise_for_status()
+
+ session_id = response.json().get("sessionId")
+ if not session_id:
+ raise BillComAuthError("BILL sign-in did not return a session ID")
+
+ self._session_id = str(session_id)
+ return self._session_id
+
+ def _get(self, path: str, params: dict[str, Any]) -> requests.Response:
+ return self._session.get(
+ f"{self._api_root}{path}",
+ params=params,
+ headers={"sessionId": self._session_id or "", "devKey": self._dev_key},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ def list_page(self, path: str, params: dict[str, Any]) -> dict[str, Any]:
+ if self._session_id is None:
+ self.login()
+
+ response = self._get(path, params)
+ if response.status_code == 401:
+ # The 35-minute inactivity expiry can bite a long sync; one re-login covers it.
+ self.login()
+ response = self._get(path, params)
+
+ response.raise_for_status()
+ body = response.json()
+ return body if isinstance(body, dict) else {}
+
+
+def build_params(
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+ incremental_field: Optional[str],
+) -> dict[str, Any]:
+ """Build the `max`/`sort`/`filters` query params shared by every BILL list endpoint.
+
+ Sorting on the cursor field ascending is what makes `sort_mode="asc"` true, so the pipeline can
+ advance its watermark after each page. Full-refresh syncs still sort (on the stable
+ `createdTime`) so pagination can't skip or repeat rows as records are written mid-sync.
+ """
+ cursor_field = CREATED_TIME_FIELD
+ if should_use_incremental_field:
+ cursor_field = (
+ incremental_field if incremental_field in (CREATED_TIME_FIELD, UPDATED_TIME_FIELD) else UPDATED_TIME_FIELD
+ )
+
+ params: dict[str, Any] = {"max": PAGE_SIZE, "sort": f"{cursor_field}:asc"}
+
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ params["filters"] = f"{cursor_field}:gte:{format_incremental_value(db_incremental_field_last_value)}"
+
+ return params
+
+
+def get_rows(
+ client: BillComClient,
+ endpoint: str,
+ params: dict[str, Any],
+ resumable_source_manager: ResumableSourceManager[BillComResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ config = BILL_COM_ENDPOINTS[endpoint]
+
+ page: Optional[str] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and resume.next_page:
+ page = resume.next_page
+
+ while True:
+ request_params = dict(params)
+ if page:
+ request_params["page"] = page
+
+ body = client.list_page(config.path, request_params)
+ results = body.get("results") or []
+ if results:
+ yield results
+
+ next_page = str(body.get("nextPage") or "")
+ if not next_page:
+ resumable_source_manager.clear_state()
+ return
+ if next_page == page:
+ # A repeated cursor would page forever; treat it as the end of the list.
+ logger.warning(f"BILL returned a repeated page cursor for {endpoint}, stopping pagination")
+ resumable_source_manager.clear_state()
+ return
+
+ # Saved after the page is yielded, so a crash re-yields the last page (merge dedupes on the
+ # primary key) instead of skipping it.
+ resumable_source_manager.save_state(BillComResumeConfig(next_page=next_page))
+ page = next_page
+
+
+def validate_credentials(
+ username: str,
+ password: str,
+ organization_id: str,
+ dev_key: str,
+ environment: str,
+ api_version: str,
+) -> tuple[bool, Optional[str]]:
+ try:
+ client = BillComClient(
+ username=username,
+ password=password,
+ organization_id=organization_id,
+ dev_key=dev_key,
+ environment=environment,
+ api_version=api_version,
+ )
+ client.login()
+ except (BillComAuthError, ValueError) as e:
+ return False, str(e)
+ except Exception:
+ return False, "Could not reach BILL. Please check your credentials and try again."
+
+ return True, None
+
+
+def bill_com_source(
+ username: str,
+ password: str,
+ organization_id: str,
+ dev_key: str,
+ environment: str,
+ api_version: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BillComResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
+) -> SourceResponse:
+ client = BillComClient(
+ username=username,
+ password=password,
+ organization_id=organization_id,
+ dev_key=dev_key,
+ environment=environment,
+ api_version=api_version,
+ )
+ params = build_params(should_use_incremental_field, db_incremental_field_last_value, incremental_field)
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(client, endpoint, params, resumable_source_manager, logger),
+ primary_keys=["id"],
+ partition_mode="datetime",
+ partition_format="month",
+ # `createdTime` never changes, so partitions don't get rewritten on every sync.
+ partition_keys=[CREATED_TIME_FIELD],
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/canonical_descriptions.py
new file mode 100644
index 000000000000..10ea2617926d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/canonical_descriptions.py
@@ -0,0 +1,347 @@
+"""Canonical, documentation-sourced descriptions for BILL v3 endpoints and columns.
+
+Sourced from the official BILL v3 API description (https://developer.bill.com/openapi/bill-v3-api.json).
+Keyed by the endpoint names in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name` of a
+synced BILL table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Every BILL object carries these; merged into each entry rather than repeated.
+_COMMON_COLUMNS = {
+ "id": "BILL-generated unique identifier for the object.",
+ "createdTime": "Date and time the object was created, as an ISO 8601 date-time.",
+ "updatedTime": "Date and time the object was last updated, as an ISO 8601 date-time.",
+ "archived": "Set as true if the object is archived.",
+}
+
+_CLASSIFICATION_DOCS_URL = "https://developer.bill.com/reference/api-reference-overview"
+
+
+def _columns(**overrides: str) -> dict[str, str]:
+ return {**_COMMON_COLUMNS, **overrides}
+
+
+def _classification(label: str, prefix: str) -> dict[str, str]:
+ return _columns(
+ id=f"BILL-generated ID of the {label}. The value begins with `{prefix}`.",
+ name=f"{label.capitalize()} name.",
+ shortName=f"{label.capitalize()} short name.",
+ description=f"{label.capitalize()} description.",
+ parentId=f"BILL-generated ID of the parent {label}, set when this {label} is a child object.",
+ )
+
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "bills": {
+ "description": "An accounts payable bill your organization owes a vendor.",
+ "docs_url": "https://developer.bill.com/reference/listbills",
+ "columns": _columns(
+ id="BILL-generated ID of the bill. The value begins with `00n`.",
+ vendorId="BILL-generated ID of the vendor the bill is owed to. The value begins with `009`.",
+ vendorName="Vendor name.",
+ amount="Bill total amount. For a bill in an international currency, this value is in the local currency.",
+ fundingAmount="Bill total amount in USD.",
+ paidAmount="Bill paid amount: the sum of all cleared payments and any credit applied to the bill.",
+ dueAmount="Bill due amount, after subtracting applied credits, scheduled payments, and cleared payments.",
+ scheduledAmount="Vendor payment amount that is pending clearance.",
+ creditAmount="Credit amount applied to the bill.",
+ exchangeRate="Exchange rate applied to a bill in an international currency.",
+ description="Bill description.",
+ dueDate="Bill due date, in `yyyy-MM-dd` format.",
+ paymentTermId="BILL-generated ID of the payment term applied to the bill.",
+ invoice="Vendor invoice details, including the invoice number and date.",
+ billLineItems="Bill line item details.",
+ payFromChartOfAccountId="BILL-generated ID of the chart of accounts used to pay the bill. The value begins with `0ca`.",
+ paymentStatus="Payment status of the bill.",
+ approvalStatus="Approval status of the bill.",
+ purchaseOrderNumber="Purchase order number linked with the bill.",
+ createdBy="BILL-generated ID of the user that created the bill. The value begins with `006`.",
+ recordStatus="Record status of the bill.",
+ classifications="Accounting classifications applied to the bill (chart of accounts, department, location, job, item).",
+ ),
+ },
+ "payments": {
+ "description": "A payment sent to a vendor to settle one or more bills.",
+ "docs_url": "https://developer.bill.com/reference/listpayments",
+ "columns": _columns(
+ id="BILL-generated ID of the payment. The value begins with `stp`.",
+ vendorId="BILL-generated ID of the vendor being paid. The value begins with `009`.",
+ vendorName="Vendor name.",
+ billId="BILL-generated ID of the bill being paid. The value begins with `00n`.",
+ billPayments="Bill payments the payment is applied to. Each bill payment ID begins with `blp`.",
+ description="Payment description, included in the check memo or bank descriptor.",
+ processDate="Date BILL starts processing the payment and withdrawing funds, in `yyyy-MM-dd` format.",
+ fundingAccount="Funding account the payment is sent from.",
+ amount="Payment amount. For a payment in an international currency, this value is in the local currency.",
+ fundingAmount="Payment amount in USD.",
+ processingOptions="Payment processing options, such as the delivery speed.",
+ transactionNumber="Payment transaction reference used as an external identifier.",
+ confirmationNumber="BILL-generated bill payment confirmation value.",
+ status="Payment status.",
+ exchangeRate="Exchange rate applied to a payment in an international currency.",
+ onlinePayment="True when the payment was made with BILL; false when it was made outside BILL and recorded.",
+ disbursementType="How the payment is disbursed to the vendor.",
+ disbursementStatus="Disbursement status of the payment.",
+ remittanceEmail="Remittance email address set for the vendor.",
+ voidInfo="Void request details for the payment.",
+ createdBy="BILL-generated ID of the user that created the payment. The value begins with `006`.",
+ cancelRequestSubmitted="True when a request to cancel the payment has been submitted.",
+ ),
+ },
+ "vendors": {
+ "description": "A vendor your organization pays through BILL.",
+ "docs_url": "https://developer.bill.com/reference/listvendors",
+ "columns": _columns(
+ id="BILL-generated ID of the vendor. The value begins with `009`.",
+ name="Vendor name.",
+ shortName="Vendor short name.",
+ accountNumber="Your account number with the vendor, shown on the check memo or electronic payment record.",
+ accountType="Vendor account type, such as business or individual.",
+ email="Vendor email address.",
+ phone="Vendor phone number.",
+ address="Vendor address.",
+ paymentInformation="Vendor payment details, including the payment method.",
+ rppsId="BILL-generated ID of the verified national vendor, when the vendor is one.",
+ bankAccountStatus="Status of the vendor bank account used for electronic payments.",
+ recurringPayments="True when the vendor has recurring payments enabled.",
+ billCurrency="Currency used for bills from this vendor.",
+ balance="Outstanding balance owed to the vendor.",
+ autoPay="Automatic payment settings for the vendor.",
+ networkStatus="Status of the vendor's connection in the BILL network.",
+ paymentNetworkId="Vendor Payment Network ID (PNI), unique per vendor with a BILL account.",
+ ),
+ },
+ "vendor_credits": {
+ "description": "A credit issued by a vendor that can be applied against bill payments.",
+ "docs_url": "https://developer.bill.com/reference/listvendorcredits",
+ "columns": _columns(
+ id="BILL-generated ID of the vendor credit. The value begins with `vcr`.",
+ vendorId="BILL-generated ID of the vendor that issued the credit. The value begins with `009`.",
+ referenceNumber="User-generated vendor credit number.",
+ creditDate="Date the vendor credit was issued, in `yyyy-MM-dd` format.",
+ description="Vendor credit description.",
+ amount="Vendor credit amount.",
+ appliedAmount="Vendor credit amount already applied.",
+ status="Vendor credit status.",
+ applyToChartOfAccountId="BILL-generated ID of the chart of accounts used when the credit is applied. The value begins with `0ca`.",
+ applyToBankAccountId="BILL-generated ID of the bank account used when the credit is applied. The value begins with `bac`.",
+ vendorCreditLineItems="Vendor credit line item details.",
+ usage="Details of where the vendor credit has been used.",
+ ),
+ },
+ "recurring_bills": {
+ "description": "A template that generates bills for a vendor on a repeating schedule.",
+ "docs_url": "https://developer.bill.com/reference/listrecurringbills",
+ "columns": _columns(
+ id="BILL-generated ID of the recurring bill. The value begins with `btp`.",
+ vendorId="BILL-generated ID of the vendor. The value begins with `009`.",
+ description="Recurring bill description.",
+ schedule="Schedule the recurring bill is generated on.",
+ recurringBillLineItems="Recurring bill line item details.",
+ processingOptions="Processing options applied to generated bills.",
+ paymentInformation="Payment details used for generated bills.",
+ ),
+ },
+ "invoices": {
+ "description": "An accounts receivable invoice your organization issued to a customer.",
+ "docs_url": "https://developer.bill.com/reference/listinvoices",
+ "columns": _columns(
+ id="BILL-generated ID of the invoice. The value begins with `00e`.",
+ invoiceNumber="User-generated invoice number, auto-generated when not set.",
+ invoiceDate="Invoice creation date, in `yyyy-MM-dd` format.",
+ dueDate="Invoice due date, in `yyyy-MM-dd` format.",
+ customerId="BILL-generated ID of the customer being invoiced. The value begins with `0cu`.",
+ paymentTermId="BILL-generated ID of the payment term applied to the invoice.",
+ totalAmount="Invoice total amount.",
+ dueAmount="Invoice due amount, after subtracting applied credits, scheduled payments, and cleared payments.",
+ scheduledAmount="Customer payment amount that is pending clearance.",
+ creditAmount="Credit amount applied to the invoice.",
+ status="Invoice status.",
+ exchangeRate="Exchange rate applied to the invoice.",
+ invoiceLineItems="Invoice line item details.",
+ payToChartOfAccountId="BILL-generated ID of the chart of accounts for the invoice payment. The value begins with `0ca`.",
+ payments="Payments received against the invoice.",
+ classifications="Accounting classifications applied to the invoice.",
+ salesTaxItemId="BILL-generated ID of the sales tax item applied to taxable line items. The value begins with `0ii`.",
+ salesTaxTotal="Invoice sales tax amount.",
+ salesTaxPercentage="Invoice sales tax percentage.",
+ enableCardPayment="True when the card payment option is enabled for the invoice.",
+ convenienceFee="Convenience fee charged for paying the invoice by card.",
+ invoicePdfId="BILL-generated ID of the invoice PDF. The value begins with `att`.",
+ createdBy="BILL-generated ID of the user that created the invoice. The value begins with `006`.",
+ recordStatus="Record status of the invoice.",
+ ),
+ },
+ "customers": {
+ "description": "A customer your organization invoices through BILL.",
+ "docs_url": "https://developer.bill.com/reference/listcustomers",
+ "columns": _columns(
+ id="BILL-generated ID of the customer. The value begins with `0cu`.",
+ name="Customer name.",
+ companyName="Customer company name.",
+ contact="Primary contact details for the customer.",
+ email="Customer email address.",
+ phone="Customer phone number.",
+ fax="Customer fax number.",
+ description="Customer description.",
+ invoiceCurrency="Currency used for invoices to this customer.",
+ accountType="Customer account type, such as business or individual.",
+ paymentTermId="BILL-generated ID of the payment term, setting how many days the customer has to clear an invoice.",
+ accountNumber="Customer account number, shown on customer invoices.",
+ billingAddress="Customer billing address.",
+ shippingAddress="Customer shipping address.",
+ balance="Outstanding balance owed by the customer.",
+ hasBankAccount="True when the customer bank account has been added.",
+ authorizedToCharge="True when your organization is authorized to charge the customer for invoices.",
+ ),
+ },
+ "receivable_payments": {
+ "description": "A payment received from a customer against one or more invoices.",
+ "docs_url": "https://developer.bill.com/reference/listreceivablepayments",
+ "columns": _columns(
+ id="BILL-generated ID of the received payment. The value begins with `0rp`.",
+ customerId="BILL-generated ID of the customer that paid. The value begins with `0cu`.",
+ invoicePayments="Invoice payments the received payment is applied to.",
+ description="Received payment description.",
+ paymentDate="Date funds are withdrawn from the customer bank account.",
+ fundingAccount="Account the payment was received from.",
+ receivablesAccount="Account the received payment is deposited into.",
+ amount="Received payment amount, in the local currency for international payments.",
+ unappliedAmount="Received payment amount not yet applied to an invoice, such as an overpayment.",
+ convenienceFeeAmount="Convenience fee charged to the customer.",
+ receivablesType="Type of received payment.",
+ status="Received payment status.",
+ referenceNumber="Received payment reference number.",
+ onlinePayment="True when the payment was received with BILL; false when received outside BILL and recorded.",
+ ),
+ },
+ "credit_memos": {
+ "description": "A credit issued to a customer that can be applied against invoices.",
+ "docs_url": "https://developer.bill.com/reference/listcreditmemos",
+ "columns": _columns(
+ id="BILL-generated ID of the credit memo. The value begins with `ccr`.",
+ customerId="BILL-generated ID of the customer the credit was issued to. The value begins with `0cu`.",
+ referenceNumber="User-generated credit memo number.",
+ creditDate="Date the credit memo was issued, in `yyyy-MM-dd` format.",
+ description="Credit memo description.",
+ salesTaxItemId="BILL-generated ID of the sales tax item applied to taxable line items. The value begins with `0ii`.",
+ payToChartOfAccountId="BILL-generated ID of the chart of accounts used when the credit memo is applied. The value begins with `0ca`.",
+ payToBankAccountId="BILL-generated ID of the bank account used when the credit memo is applied. The value begins with `bac`.",
+ amount="Credit memo amount.",
+ appliedAmount="Credit memo amount already applied to invoices.",
+ salesTaxTotal="Credit memo sales tax amount.",
+ salesTaxPercentage="Credit memo sales tax percentage.",
+ status="Credit memo status.",
+ creditMemoLineItems="Credit memo line item details.",
+ classifications="Accounting classifications applied to the credit memo.",
+ usage="Details of where the credit memo has been used.",
+ ),
+ },
+ "recurring_invoices": {
+ "description": "A template that generates customer invoices on a repeating schedule.",
+ "docs_url": "https://developer.bill.com/reference/listrecurringinvoices",
+ "columns": _columns(
+ id="BILL-generated ID of the recurring invoice. The value begins with `rit`.",
+ customerId="BILL-generated ID of the customer. The value begins with `0cu`.",
+ paymentTermId="BILL-generated ID of the payment term applied to generated invoices.",
+ description="Recurring invoice description.",
+ schedule="Schedule the recurring invoice is generated on.",
+ recurringInvoiceLineItems="Recurring invoice line item details.",
+ classifications="Accounting classifications applied to generated invoices.",
+ sendEmail="True when an email is sent to the customer each time an invoice is created.",
+ ),
+ },
+ "bank_accounts": {
+ "description": "A bank account your organization funds BILL payments from.",
+ "docs_url": "https://developer.bill.com/reference/listbankaccounts",
+ "columns": _columns(
+ id="BILL-generated ID of the bank account. The value begins with `bac`.",
+ status="Bank account verification status.",
+ routingNumber="Bank routing number.",
+ accountNumber="Bank account number.",
+ nameOnAccount="Full name on the bank account.",
+ type="Bank account type, such as checking or savings.",
+ ownerType="Whether the account is owned by a business or an individual.",
+ bankName="Bank name.",
+ accessToAdmins="True when all users with the administrator role can access the account.",
+ default="Whether the account is the default for payments.",
+ chartOfAccountId="BILL-generated ID of the chart of accounts for the bank account. The value begins with `0ca`.",
+ createdBy="BILL-generated ID of the user that created the bank account. The value begins with `006`.",
+ ),
+ },
+ "chart_of_accounts": {
+ "description": "A chart of accounts entry used to categorize bills, invoices, and payments.",
+ "docs_url": "https://developer.bill.com/reference/listclassificationchartofaccounts",
+ "columns": _columns(
+ id="BILL-generated ID of the chart of accounts. The value begins with `0ca`.",
+ name="Chart of accounts name.",
+ description="Chart of accounts description.",
+ parentId="BILL-generated ID of the parent chart of accounts, set when this entry is a child object.",
+ account="Account details, including the account number and type.",
+ ),
+ },
+ "accounting_classes": {
+ "description": "An accounting class used to categorize transactions.",
+ "docs_url": _CLASSIFICATION_DOCS_URL,
+ "columns": _classification("accounting class", "cls"),
+ },
+ "departments": {
+ "description": "A department used to categorize transactions.",
+ "docs_url": _CLASSIFICATION_DOCS_URL,
+ "columns": _classification("department", "0de"),
+ },
+ "employees": {
+ "description": "An employee used to categorize transactions.",
+ "docs_url": _CLASSIFICATION_DOCS_URL,
+ "columns": _columns(
+ id="BILL-generated ID of the employee. The value begins with `emp`.",
+ firstName="Employee first name.",
+ lastName="Employee last name.",
+ shortName="Employee short name.",
+ parentId="BILL-generated ID of the parent employee, set when this employee is a child object.",
+ ),
+ },
+ "items": {
+ "description": "An item that can be added as a line item on bills and invoices.",
+ "docs_url": _CLASSIFICATION_DOCS_URL,
+ "columns": _columns(
+ id="BILL-generated ID of the item. The value begins with `0ii`.",
+ type="Item type, such as service, product, or sales tax.",
+ name="Item name.",
+ shortName="Item short name.",
+ description="Item description.",
+ parentId="BILL-generated ID of the parent item, set when this item is a child object.",
+ price="Item price.",
+ expenseChartOfAccountId="BILL-generated ID of the chart of accounts used when the item appears on bills or purchases.",
+ purchaseDescription="Item description used when the item appears on bills or purchases.",
+ purchaseCost="Item purchase cost set in your accounting system.",
+ chartOfAccountId="BILL-generated ID of the chart of accounts for the item. The value begins with `0ca`.",
+ taxable="True when the item is taxable.",
+ percentage="Item tax percentage.",
+ ),
+ },
+ "jobs": {
+ "description": "A job used to categorize transactions.",
+ "docs_url": _CLASSIFICATION_DOCS_URL,
+ "columns": _classification("job", "job"),
+ },
+ "locations": {
+ "description": "A location used to categorize transactions.",
+ "docs_url": _CLASSIFICATION_DOCS_URL,
+ "columns": _classification("location", "loc"),
+ },
+ "users": {
+ "description": "A user in your BILL organization.",
+ "docs_url": "https://developer.bill.com/reference/listorganizationusers",
+ "columns": _columns(
+ id="BILL-generated ID of the user. The value begins with `006`.",
+ firstName="User first name.",
+ lastName="User last name.",
+ email="User email address.",
+ role="Role assigned to the user in the organization.",
+ ),
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/settings.py
new file mode 100644
index 000000000000..2b4e9728ef75
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/settings.py
@@ -0,0 +1,61 @@
+from dataclasses import dataclass
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+# BILL v3 list endpoints, taken from the published OpenAPI description
+# (https://developer.bill.com/openapi/bill-v3-api.json). Every one of them shares the same
+# response envelope (`{"results": [...], "nextPage": ..., "prevPage": ...}`), the same
+# `max`/`page`/`sort`/`filters` query params, and returns objects carrying `id`, `createdTime`,
+# and `updatedTime`.
+#
+# The `/v3/spend/*` resources are deliberately excluded: BILL Spend & Expense is a separate API
+# surface authenticated with its own API token rather than the session login used here.
+
+CREATED_TIME_FIELD = "createdTime"
+UPDATED_TIME_FIELD = "updatedTime"
+
+
+@dataclass(frozen=True)
+class BillComEndpointConfig:
+ name: str
+ path: str
+
+
+def _endpoint(name: str, path: str) -> BillComEndpointConfig:
+ return BillComEndpointConfig(name=name, path=path)
+
+
+BILL_COM_ENDPOINTS: dict[str, BillComEndpointConfig] = {
+ # Accounts payable
+ "bills": _endpoint("bills", "/bills"),
+ "payments": _endpoint("payments", "/payments"),
+ "vendors": _endpoint("vendors", "/vendors"),
+ "vendor_credits": _endpoint("vendor_credits", "/vendor-credits"),
+ "recurring_bills": _endpoint("recurring_bills", "/recurringbills"),
+ # Accounts receivable
+ "invoices": _endpoint("invoices", "/invoices"),
+ "customers": _endpoint("customers", "/customers"),
+ "receivable_payments": _endpoint("receivable_payments", "/receivable-payments"),
+ "credit_memos": _endpoint("credit_memos", "/credit-memos"),
+ "recurring_invoices": _endpoint("recurring_invoices", "/recurring-invoices"),
+ # Organization, funding, and accounting classifications
+ "bank_accounts": _endpoint("bank_accounts", "/funding-accounts/banks"),
+ "chart_of_accounts": _endpoint("chart_of_accounts", "/classifications/chart-of-accounts"),
+ "accounting_classes": _endpoint("accounting_classes", "/classifications/accounting-classes"),
+ "departments": _endpoint("departments", "/classifications/departments"),
+ "employees": _endpoint("employees", "/classifications/employees"),
+ "items": _endpoint("items", "/classifications/items"),
+ "jobs": _endpoint("jobs", "/classifications/jobs"),
+ "locations": _endpoint("locations", "/classifications/locations"),
+ "users": _endpoint("users", "/users"),
+}
+
+ENDPOINTS: tuple[str, ...] = tuple(BILL_COM_ENDPOINTS.keys())
+
+# `filters=updatedTime:gte:<value>` is a real server-side filter on every list endpoint, so all
+# endpoints sync incrementally. `updatedTime` is listed first so it becomes the default cursor —
+# it catches edits to older records that `createdTime` would miss.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: [incremental_field(UPDATED_TIME_FIELD), incremental_field(CREATED_TIME_FIELD)] for name in ENDPOINTS
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/source.py
index 47bff59b9c4c..fbaccfcb9631 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/source.py
@@ -1,13 +1,36 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.bill_com.bill_com import (
+ BillComResumeConfig,
+ bill_com_source,
+ validate_credentials as validate_bill_com_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bill_com.settings import (
+ 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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.billcom import (
BillComSourceConfig,
)
@@ -15,18 +38,144 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BillComSource(SimpleSource[BillComSourceConfig]):
+class BillComSource(ResumableSource[BillComSourceConfig, BillComResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ supported_versions = ("v3",)
+ default_version = "v3"
+ api_docs_url = "https://developer.bill.com/reference/api-reference-overview"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BILLCOM
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "BILL sign-in failed": "BILL could not sign you in. Please check your email, password, organization ID, and developer key.",
+ "BILL sign-in did not return a session ID": "BILL did not start an API session. Please check your developer key and try again.",
+ "401 Client Error: Unauthorized for url: https://gateway": "Your BILL API session could not be renewed. Please check your credentials and reconnect.",
+ "403 Client Error: Forbidden for url: https://gateway": "Your BILL user does not have access to this data. Please check the user's permissions and try again.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.bill_com.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.BILL_COM,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
label="BILL (formerly Bill.com)",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["bill.com", "accounts payable", "accounts receivable", "ap", "ar"],
+ caption="""Connect BILL to pull your accounts payable and receivable data into the PostHog Data warehouse.
+
+Create a developer key in your [BILL developer account](https://developer.bill.com/docs/bill-keys-tokens), then enter the email and password you sign in with, your organization ID, and that developer key. PostHog uses them to start an API session for each sync.
+
+BILL Spend & Expense data is not included — it uses a separate API token.""",
iconPath="/static/services/bill_com.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/bill-com",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="username",
+ label="Email",
+ type=SourceFieldInputConfigType.EMAIL,
+ required=True,
+ placeholder="[email protected]",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="password",
+ label="Password",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="organization_id",
+ label="Organization ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="dev_key",
+ label="Developer key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="environment",
+ label="Environment",
+ required=True,
+ defaultValue="production",
+ options=[
+ SourceFieldSelectConfigOption(label="Production", value="production"),
+ SourceFieldSelectConfigOption(label="Sandbox", value="sandbox"),
+ ],
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: BillComSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: BillComSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_bill_com_credentials(
+ username=config.username,
+ password=config.password,
+ organization_id=config.organization_id,
+ dev_key=config.dev_key,
+ environment=config.environment,
+ api_version=self.resolve_api_version(api_version),
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BillComResumeConfig]:
+ return ResumableSourceManager[BillComResumeConfig](inputs, BillComResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BillComSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BillComResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return bill_com_source(
+ username=config.username,
+ password=config.password,
+ organization_id=config.organization_id,
+ dev_key=config.dev_key,
+ environment=config.environment,
+ api_version=self.resolve_api_version(inputs.api_version),
+ 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,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/tests/test_bill_com.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/tests/test_bill_com.py
new file mode 100644
index 000000000000..1c77d2b44511
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/tests/test_bill_com.py
@@ -0,0 +1,384 @@
+from collections.abc import Iterable
+from datetime import UTC, date, datetime
+from typing import Any, Optional, cast
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bill_com.bill_com import (
+ PAGE_SIZE,
+ BillComAuthError,
+ BillComClient,
+ BillComResumeConfig,
+ base_url,
+ bill_com_source,
+ build_params,
+ error_message,
+ format_incremental_value,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bill_com.settings import BILL_COM_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.bill_com.bill_com"
+
+
+class _FakeManager(ResumableSourceManager[BillComResumeConfig]):
+ def __init__(self, state: Optional[BillComResumeConfig] = None) -> None:
+ self.state = state
+ self.saved: list[BillComResumeConfig] = []
+ self.cleared = False
+
+ def can_resume(self) -> bool:
+ return self.state is not None
+
+ def load_state(self) -> Optional[BillComResumeConfig]:
+ return self.state
+
+ def save_state(self, data: BillComResumeConfig) -> None:
+ self.saved.append(data)
+
+ def clear_state(self) -> None:
+ self.cleared = True
+
+
+def _response(status: int = 200, body: Any = None, text: str = "") -> mock.MagicMock:
+ response = mock.MagicMock(spec=requests.Response)
+ response.status_code = status
+ response.text = text
+ if isinstance(body, Exception):
+ response.json.side_effect = body
+ else:
+ response.json.return_value = body
+ if status >= 400:
+ response.raise_for_status.side_effect = requests.HTTPError(f"{status} Client Error", response=response)
+ return response
+
+
+def _client(session: mock.MagicMock, environment: str = "production") -> BillComClient:
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ return BillComClient(
+ username="[email protected]",
+ password="pw",
+ organization_id="org-1",
+ dev_key="dev-key",
+ environment=environment,
+ api_version="v3",
+ )
+
+
+class TestBillCom:
+ @pytest.mark.parametrize(
+ "environment, expected",
+ [
+ ("production", "https://gateway.prod.bill.com/connect"),
+ ("sandbox", "https://gateway.stage.bill.com/connect"),
+ ],
+ )
+ def test_base_url_per_environment(self, environment: str, expected: str) -> None:
+ assert base_url(environment) == expected
+
+ def test_base_url_rejects_unknown_environment(self) -> None:
+ with pytest.raises(ValueError):
+ base_url("evil")
+
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 3, 1, 12, 30, 15, 250000, tzinfo=UTC), "2026-03-01T12:30:15.250Z"),
+ (datetime(2026, 3, 1, 12, 30, 15), "2026-03-01T12:30:15.000Z"),
+ (date(2026, 3, 1), "2026-03-01T00:00:00.000Z"),
+ ("2026-03-01T00:00:00.000Z", "2026-03-01T00:00:00.000Z"),
+ ],
+ )
+ def test_format_incremental_value(self, value: Any, expected: str) -> None:
+ assert format_incremental_value(value) == expected
+
+ @pytest.mark.parametrize(
+ "body, text, expected",
+ [
+ ([{"message": "Invalid credentials", "code": "BDC_1105"}], "", "Invalid credentials"),
+ ({"message": "Unauthorized"}, "", "Unauthorized"),
+ (ValueError("not json"), "<html>502</html>", "<html>502</html>"),
+ ],
+ )
+ def test_error_message_reads_both_error_envelopes(self, body: Any, text: str, expected: str) -> None:
+ assert error_message(_response(body=body, text=text)) == expected
+
+ @pytest.mark.parametrize(
+ "should_use_incremental_field, last_value, incremental_field, expected_sort, expected_filters",
+ [
+ (False, None, None, "createdTime:asc", None),
+ # A last value only filters when the sync is actually incremental.
+ (False, datetime(2026, 3, 1, tzinfo=UTC), "updatedTime", "createdTime:asc", None),
+ (True, None, "updatedTime", "updatedTime:asc", None),
+ (
+ True,
+ datetime(2026, 3, 1, tzinfo=UTC),
+ "updatedTime",
+ "updatedTime:asc",
+ "updatedTime:gte:2026-03-01T00:00:00.000Z",
+ ),
+ (
+ True,
+ datetime(2026, 3, 1, tzinfo=UTC),
+ "createdTime",
+ "createdTime:asc",
+ "createdTime:gte:2026-03-01T00:00:00.000Z",
+ ),
+ # An unsupported cursor field falls back to the one BILL can filter on.
+ (
+ True,
+ datetime(2026, 3, 1, tzinfo=UTC),
+ "id",
+ "updatedTime:asc",
+ "updatedTime:gte:2026-03-01T00:00:00.000Z",
+ ),
+ ],
+ )
+ def test_build_params(
+ self,
+ should_use_incremental_field: bool,
+ last_value: Any,
+ incremental_field: Optional[str],
+ expected_sort: str,
+ expected_filters: Optional[str],
+ ) -> None:
+ params = build_params(should_use_incremental_field, last_value, incremental_field)
+
+ assert params["max"] == PAGE_SIZE
+ assert params["sort"] == expected_sort
+ assert params.get("filters") == expected_filters
+
+ def test_login_posts_credentials_and_stores_session_id(self) -> None:
+ session = mock.MagicMock()
+ session.post.return_value = _response(body={"sessionId": "sess-1", "organizationId": "org-1"})
+ client = _client(session)
+
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ assert client.login() == "sess-1"
+
+ assert client.session_id == "sess-1"
+ assert session.post.call_args.args[0] == "https://gateway.prod.bill.com/connect/v3/login"
+ assert session.post.call_args.kwargs["json"] == {
+ "username": "[email protected]",
+ "password": "pw",
+ "organizationId": "org-1",
+ "devKey": "dev-key",
+ }
+
+ @pytest.mark.parametrize("status", [400, 401, 403])
+ def test_login_rejects_bad_credentials_without_retrying(self, status: int) -> None:
+ session = mock.MagicMock()
+ session.post.return_value = _response(status=status, body=[{"message": "Invalid credentials"}])
+ client = _client(session)
+
+ with pytest.raises(BillComAuthError, match="Invalid credentials"):
+ client.login()
+
+ def test_login_without_session_id_raises(self) -> None:
+ session = mock.MagicMock()
+ session.post.return_value = _response(body={"organizationId": "org-1"})
+ client = _client(session)
+
+ with pytest.raises(BillComAuthError, match="did not return a session ID"):
+ client.login()
+
+ def test_no_bill_traffic_is_ever_sample_captured(self) -> None:
+ # Track every tracked session built during a sign-in + data request, tagging each with the
+ # kwargs it was created with, so we can prove no BILL traffic ever feeds HTTP sample capture.
+ created: list[tuple[dict[str, Any], mock.MagicMock]] = []
+
+ def _make(**kwargs: Any) -> mock.MagicMock:
+ session = mock.MagicMock()
+ session.post.return_value = _response(body={"sessionId": "sess-secret"})
+ session.get.return_value = _response(body={"results": [{"id": "00n1"}]})
+ created.append((kwargs, session))
+ return session
+
+ with mock.patch(f"{_MODULE}.make_tracked_session", side_effect=_make):
+ client = BillComClient(
+ username="[email protected]",
+ password="pw",
+ organization_id="org-1",
+ dev_key="dev-key",
+ environment="production",
+ api_version="v3",
+ )
+ client.login()
+ client.list_page("/invoices", {})
+
+ # BILL responses carry the freshly minted session ID and raw financial records that no
+ # name-based scrubber would recognise, so every session used for BILL traffic must be
+ # excluded from capture.
+ assert created, "no tracked session was built"
+ assert all(kwargs.get("capture", True) is False for kwargs, _ in created)
+
+ def test_list_page_signs_in_lazily_and_sends_session_headers(self) -> None:
+ session = mock.MagicMock()
+ session.post.return_value = _response(body={"sessionId": "sess-1"})
+ session.get.return_value = _response(body={"results": [{"id": "00n1"}]})
+ client = _client(session)
+
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ body = client.list_page("/bills", {"max": PAGE_SIZE})
+
+ assert body == {"results": [{"id": "00n1"}]}
+ assert session.post.call_count == 1
+ assert session.get.call_args.args[0] == "https://gateway.prod.bill.com/connect/v3/bills"
+ assert session.get.call_args.kwargs["headers"] == {"sessionId": "sess-1", "devKey": "dev-key"}
+
+ def test_list_page_signs_in_again_when_the_session_expires(self) -> None:
+ session = mock.MagicMock()
+ session.post.return_value = _response(body={"sessionId": "sess-2"})
+ session.get.side_effect = [_response(status=401, body={"message": "Unauthorized"}), _response(body={})]
+ client = _client(session)
+
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ client.list_page("/bills", {})
+
+ # One sign-in to start the session, one to replace the expired one.
+ assert session.post.call_count == 2
+ assert session.get.call_count == 2
+
+ def test_list_page_raises_on_other_errors(self) -> None:
+ session = mock.MagicMock()
+ session.post.return_value = _response(body={"sessionId": "sess-1"})
+ session.get.return_value = _response(status=403, body=[{"message": "Forbidden"}])
+ client = _client(session)
+
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ with pytest.raises(requests.HTTPError):
+ client.list_page("/bills", {})
+
+ assert session.post.call_count == 1
+
+ def test_get_rows_paginates_and_checkpoints_after_each_page(self) -> None:
+ client = mock.MagicMock(spec=BillComClient)
+ client.list_page.side_effect = [
+ {"results": [{"id": "00n1"}], "nextPage": "cursor-2"},
+ {"results": [{"id": "00n2"}], "nextPage": "cursor-3"},
+ {"results": [{"id": "00n3"}]},
+ ]
+ manager = _FakeManager()
+
+ pages = list(get_rows(client, "bills", {"max": PAGE_SIZE}, manager, mock.MagicMock()))
+
+ assert pages == [[{"id": "00n1"}], [{"id": "00n2"}], [{"id": "00n3"}]]
+ assert [call.args[1].get("page") for call in client.list_page.call_args_list] == [None, "cursor-2", "cursor-3"]
+ assert [state.next_page for state in manager.saved] == ["cursor-2", "cursor-3"]
+ assert manager.cleared is True
+
+ def test_get_rows_resumes_from_saved_cursor(self) -> None:
+ client = mock.MagicMock(spec=BillComClient)
+ client.list_page.return_value = {"results": [{"id": "00n9"}]}
+ manager = _FakeManager(BillComResumeConfig(next_page="cursor-7"))
+
+ pages = list(get_rows(client, "bills", {"max": PAGE_SIZE}, manager, mock.MagicMock()))
+
+ assert pages == [[{"id": "00n9"}]]
+ assert client.list_page.call_args.args[1]["page"] == "cursor-7"
+
+ def test_get_rows_stops_on_a_repeated_cursor(self) -> None:
+ client = mock.MagicMock(spec=BillComClient)
+ client.list_page.side_effect = [
+ {"results": [{"id": "00n1"}], "nextPage": "cursor-2"},
+ {"results": [{"id": "00n2"}], "nextPage": "cursor-2"},
+ ]
+ manager = _FakeManager()
+
+ pages = list(get_rows(client, "bills", {}, manager, mock.MagicMock()))
+
+ assert pages == [[{"id": "00n1"}], [{"id": "00n2"}]]
+ assert client.list_page.call_count == 2
+
+ def test_get_rows_yields_nothing_for_an_empty_endpoint(self) -> None:
+ client = mock.MagicMock(spec=BillComClient)
+ client.list_page.return_value = {"results": [], "nextPage": None}
+ manager = _FakeManager()
+
+ assert list(get_rows(client, "vendors", {}, manager, mock.MagicMock())) == []
+ assert manager.saved == []
+ assert manager.cleared is True
+
+ @pytest.mark.parametrize("endpoint", sorted(BILL_COM_ENDPOINTS))
+ def test_get_rows_requests_each_endpoints_documented_path(self, endpoint: str) -> None:
+ client = mock.MagicMock(spec=BillComClient)
+ client.list_page.return_value = {"results": []}
+
+ list(get_rows(client, endpoint, {}, _FakeManager(), mock.MagicMock()))
+
+ assert client.list_page.call_args.args[0] == BILL_COM_ENDPOINTS[endpoint].path
+
+ @pytest.mark.parametrize(
+ "login_response, expected",
+ [
+ (_response(body={"sessionId": "sess-1"}), (True, None)),
+ (
+ _response(status=401, body=[{"message": "Invalid credentials"}]),
+ (False, "BILL sign-in failed: Invalid credentials"),
+ ),
+ ],
+ )
+ def test_validate_credentials(self, login_response: mock.MagicMock, expected: tuple[bool, Optional[str]]) -> None:
+ session = mock.MagicMock()
+ session.post.return_value = login_response
+
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ assert validate_credentials("[email protected]", "pw", "org-1", "dev-key", "production", "v3") == expected
+
+ def test_validate_credentials_rejects_an_unknown_environment_without_a_request(self) -> None:
+ session = mock.MagicMock()
+
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials("[email protected]", "pw", "org-1", "dev-key", "evil", "v3")
+
+ assert is_valid is False
+ assert message is not None and "Invalid BILL environment" in message
+ session.post.assert_not_called()
+
+ def test_validate_credentials_maps_transport_failures_to_a_friendly_message(self) -> None:
+ session = mock.MagicMock()
+ session.post.side_effect = requests.ConnectionError("boom")
+
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials("[email protected]", "pw", "org-1", "dev-key", "production", "v3")
+
+ assert is_valid is False
+ assert message == "Could not reach BILL. Please check your credentials and try again."
+
+ def test_bill_com_source_response_shape(self) -> None:
+ session = mock.MagicMock()
+ session.post.return_value = _response(body={"sessionId": "sess-1"})
+ session.get.return_value = _response(body={"results": [{"id": "00n1", "createdTime": "2026-03-01T00:00:00Z"}]})
+ manager = _FakeManager()
+
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ response = bill_com_source(
+ username="[email protected]",
+ password="pw",
+ organization_id="org-1",
+ dev_key="dev-key",
+ environment="production",
+ api_version="v3",
+ endpoint="bills",
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 1, tzinfo=UTC),
+ incremental_field="updatedTime",
+ )
+
+ assert response.name == "bills"
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == "asc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["createdTime"]
+
+ pages = list(cast("Iterable[Any]", response.items()))
+
+ assert pages == [[{"id": "00n1", "createdTime": "2026-03-01T00:00:00Z"}]]
+ assert session.get.call_args.kwargs["params"]["filters"] == "updatedTime:gte:2026-03-01T00:00:00.000Z"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/tests/test_bill_com_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/tests/test_bill_com_source.py
new file mode 100644
index 000000000000..e806fd9b3bc2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bill_com/tests/test_bill_com_source.py
@@ -0,0 +1,177 @@
+from typing import Optional
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bill_com.bill_com import BillComResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.bill_com.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bill_com.source import BillComSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.billcom import (
+ BillComSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.bill_com.source"
+
+
+class TestBillComSource:
+ def setup_method(self) -> None:
+ self.source = BillComSource()
+ self.team_id = 123
+ self.config = BillComSourceConfig(
+ username="[email protected]",
+ password="pw",
+ organization_id="org-1",
+ dev_key="dev-key",
+ environment="production",
+ )
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.BILLCOM
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "BillCom"
+ assert config.label == "BILL (formerly Bill.com)"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/bill_com.png"
+ assert [field.name for field in config.fields] == [
+ "username",
+ "password",
+ "organization_id",
+ "dev_key",
+ "environment",
+ ]
+
+ @pytest.mark.parametrize("field_name", ["password", "dev_key"])
+ def test_credential_fields_are_secret_passwords(self, field_name: str) -> None:
+ field = next(
+ f
+ for f in self.source.get_source_config.fields
+ if isinstance(f, SourceFieldInputConfig) and f.name == field_name
+ )
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_environment_field_defaults_to_production(self) -> None:
+ field = next(f for f in self.source.get_source_config.fields if f.name == "environment")
+ assert isinstance(field, SourceFieldSelectConfig)
+ assert field.defaultValue == "production"
+ assert {option.value for option in field.options} == {"production", "sandbox"}
+
+ def test_api_version_is_pinned_to_the_path_the_source_calls(self) -> None:
+ assert self.source.supported_versions == ("v3",)
+ assert self.source.default_version == "v3"
+ assert self.source.resolve_api_version(None) == "v3"
+
+ def test_get_schemas_are_incremental_on_update_and_create_times(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ assert all(schema.supports_incremental for schema in schemas)
+ assert all(
+ [f["field"] for f in schema.incremental_fields] == ["updatedTime", "createdTime"] for schema in schemas
+ )
+
+ def test_get_schemas_needs_no_credentials(self) -> None:
+ # The endpoint catalog is static, so the public docs can render the table list.
+ assert self.source.lists_tables_without_credentials is True
+
+ @pytest.mark.parametrize("names, expected", [(["bills"], ["bills"]), (["nope"], []), (None, list(ENDPOINTS))])
+ def test_get_schemas_filtered_by_names(self, names: Optional[list[str]], expected: list[str]) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=names)
+ assert [schema.name for schema in schemas] == expected
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions) == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "BILL sign-in failed: Invalid credentials",
+ "401 Client Error: Unauthorized for url: https://gateway.prod.bill.com/connect/v3/bills",
+ "403 Client Error: Forbidden for url: https://gateway.prod.bill.com/connect/v3/users",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "500 Server Error for url: https://gateway.prod.bill.com/connect/v3/bills",
+ "429 Client Error: Too Many Requests for url: https://gateway.prod.bill.com/connect/v3/bills",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_transient_failures(self, other_error: str) -> None:
+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())
+
+ @pytest.mark.parametrize(
+ "validate_result",
+ [(True, None), (False, "BILL sign-in failed: Invalid credentials")],
+ )
+ @mock.patch(f"{_MODULE}.validate_bill_com_credentials")
+ def test_validate_credentials(
+ self, mock_validate: mock.MagicMock, validate_result: tuple[bool, Optional[str]]
+ ) -> None:
+ mock_validate.return_value = validate_result
+
+ assert self.source.validate_credentials(self.config, self.team_id) == validate_result
+ mock_validate.assert_called_once_with(
+ username="[email protected]",
+ password="pw",
+ organization_id="org-1",
+ dev_key="dev-key",
+ environment="production",
+ api_version="v3",
+ )
+
+ def test_get_resumable_source_manager_is_bound_to_the_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert manager._data_class is BillComResumeConfig
+
+ @mock.patch(f"{_MODULE}.bill_com_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "bills"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-03-01T00:00:00.000Z"
+ inputs.incremental_field = "updatedTime"
+ inputs.api_version = None
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["username"] == "[email protected]"
+ assert kwargs["dev_key"] == "dev-key"
+ assert kwargs["environment"] == "production"
+ assert kwargs["api_version"] == "v3"
+ assert kwargs["endpoint"] == "bills"
+ assert kwargs["incremental_field"] == "updatedTime"
+ assert kwargs["db_incremental_field_last_value"] == "2026-03-01T00:00:00.000Z"
+ assert kwargs["resumable_source_manager"] is manager
+
+ @mock.patch(f"{_MODULE}.bill_com_source")
+ def test_source_for_pipeline_drops_the_cursor_on_a_full_refresh(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "vendors"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-03-01T00:00:00.000Z"
+ inputs.api_version = None
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_every_endpoint_advertises_incremental_fields(self) -> None:
+ assert set(INCREMENTAL_FIELDS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/billcom.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/billcom.py
index 4a840cc8415b..5fb40a1a089e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/billcom.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/billcom.py
@@ -1,9 +1,15 @@
# This file is automatically generated from `SourceRegistry.get_all_sources()`
# Do not edit manually - run `pnpm generate:source-configs` to regenerate.
+from typing import Literal
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
@config.config
class BillComSourceConfig(config.Config):
- pass
+ username: str
+ password: str
+ organization_id: str
+ dev_key: str
+ environment: Literal["production", "sandbox"] = config.value(default="production")