Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add Billomat import source (#84315)

Tom Owersc2467c519895
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.py
index 980e78d7b484..7bafa2852a6f 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py
@@ -525,9 +525,12 @@ def ssh_tunnel_connection_changed(existing: Any, incoming: Any) -> bool:
return any(_coerce(existing.get(key)) != _coerce(incoming.get(key)) for key in _SSH_TUNNEL_CONNECTION_FIELDS)
-# Nested SourceFieldSelectConfig containers (Stripe `auth_method`, Snowflake `auth_type`,
-# ServiceNow `auth_method`) keep their secrets one level down, not at the top level.
-_NESTED_AUTH_CONTAINERS = ("auth_method", "auth_type")
+# Nested containers that keep their secrets one level down, not at the top level: the
+# SourceFieldSelectConfig ones (Stripe `auth_method`, Snowflake `auth_type`, ServiceNow
+# `auth_method`) key their selected branch as `selection`; the SourceFieldSwitchGroupConfig
+# one (Billomat's `registered_app`) keys it as `enabled` instead, but the same carried-over-
+# secret check below applies either way.
+_NESTED_AUTH_CONTAINERS = ("auth_method", "auth_type", "registered_app")
# Secrets the edit form can never re-supply (parsed into the individual fields on create, then
# stripped from API reads and hidden in the edit form), so gating credential re-entry on them would
@@ -1320,10 +1323,11 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
# SSH tunnel is a nested config - deep-merge it so partial updates preserve existing fields
existing_ssh_tunnel = existing_job_inputs.get("ssh_tunnel")
- # Nested SourceFieldSelectConfig containers (e.g. Stripe `auth_method`, Snowflake `auth_type`) need
- # a deep-merge that preserves sensitive fields not explicitly provided. The shallow merge above
- # would otherwise wipe redacted credentials nested inside these containers.
- for container_key in ("auth_method", "auth_type"):
+ # Nested containers (e.g. Stripe `auth_method`, Snowflake `auth_type`, Billomat `registered_app`)
+ # need a deep-merge that preserves sensitive fields not explicitly provided. The shallow merge
+ # above would otherwise wipe redacted credentials nested inside these containers. Same container
+ # list as the host-change gate above, so a merge here always has a matching preserved-credential check.
+ for container_key in _NESTED_AUTH_CONTAINERS:
existing_container = existing_job_inputs.get(container_key)
incoming_container = incoming_job_inputs.get(container_key)
if incoming_container is not None and not isinstance(incoming_container, dict):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/billomat/billomat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/billomat/billomat.py
new file mode 100644
index 000000000000..499d51638b85
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/billomat/billomat.py
@@ -0,0 +1,256 @@
+import dataclasses
+from datetime import date, datetime
+from typing import Any, Optional
+
+from requests import Response
+
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+# Billomat's documented maximum; requesting the largest page size keeps the per-15-minute
+# request budget (300 without a registered app) from being spent on pagination alone.
+_PER_PAGE = 1000
+
+
[email protected](frozen=False)
+class BillomatResumeConfig:
+ next_page: int
+
+
+def _extract_total_count(response: Response) -> Optional[int]:
+ """Read the record `total` Billomat's XML-to-JSON conversion stamps onto the single
+ top-level resource wrapper (e.g. `{"clients": {"client": [...], "total": "12"}}`)."""
+ try:
+ body = response.json()
+ except ValueError:
+ return None
+ if not isinstance(body, dict) or len(body) != 1:
+ return None
+ (wrapper,) = body.values()
+ if not isinstance(wrapper, dict):
+ return None
+ total = wrapper.get("total")
+ try:
+ return int(total) if total is not None else None
+ except (TypeError, ValueError):
+ return None
+
+
+class BillomatPaginator(PageNumberPaginator):
+ """Stops once `page * per_page` covers the response body's `total` record count, so a
+ full sync doesn't pay for one extra empty-page request past the last page of data."""
+
+ def __init__(self, per_page: int, base_page: int = 1, page: Optional[int] = None, page_param: str = "page") -> None:
+ super().__init__(base_page=base_page, page=page, page_param=page_param)
+ self._per_page = per_page
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ fetched_page = self.page
+ super().update_state(response, data)
+ if not self._has_next_page:
+ return
+ total = _extract_total_count(response)
+ if total is not None and fetched_page * self._per_page >= total:
+ self._has_next_page = False
+
+
+def _billomat_headers(api_key: str, app_id: Optional[str], app_secret: Optional[str]) -> dict[str, str]:
+ headers = {"X-BillomatApiKey": api_key, "Accept": "application/json"}
+ if app_id and app_secret:
+ headers["X-AppId"] = app_id
+ headers["X-AppSecret"] = app_secret
+ return headers
+
+
+def _format_date(value: Any) -> Optional[str]:
+ """Billomat's `from`/`to` filters take a bare `YYYY-MM-DD` date, no time component."""
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ value = value.date()
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%d")
+ return str(value)
+
+
+def _incremental_param() -> dict[str, Any]:
+ return {
+ "type": "incremental",
+ "cursor_path": "date",
+ "initial_value": None,
+ "convert": _format_date,
+ }
+
+
+def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:
+ write_disposition = (
+ {
+ "disposition": "merge",
+ "strategy": "upsert",
+ }
+ if should_use_incremental_field
+ else "replace"
+ )
+
+ resources: dict[str, EndpointResource] = {
+ "Clients": {
+ "name": "Clients",
+ "table_name": "clients",
+ "write_disposition": "replace",
+ "endpoint": {
+ "data_selector": '"clients"."client"',
+ "path": "/clients",
+ "params": {
+ "per_page": _PER_PAGE,
+ "order_by": "id ASC",
+ },
+ },
+ "table_format": "delta",
+ },
+ "Suppliers": {
+ "name": "Suppliers",
+ "table_name": "suppliers",
+ "write_disposition": "replace",
+ "endpoint": {
+ "data_selector": '"suppliers"."supplier"',
+ "path": "/suppliers",
+ "params": {
+ "per_page": _PER_PAGE,
+ "order_by": "id ASC",
+ },
+ },
+ "table_format": "delta",
+ },
+ "Invoices": {
+ "name": "Invoices",
+ "table_name": "invoices",
+ "write_disposition": write_disposition,
+ "endpoint": {
+ "data_selector": '"invoices"."invoice"',
+ "path": "/invoices",
+ "params": {
+ "per_page": _PER_PAGE,
+ "order_by": "date ASC",
+ "from": _incremental_param() if should_use_incremental_field else None,
+ },
+ },
+ "table_format": "delta",
+ },
+ "Estimates": {
+ "name": "Estimates",
+ "table_name": "estimates",
+ "write_disposition": write_disposition,
+ "endpoint": {
+ # Billomat's own resource path/element for estimates is "offer" (the public docs
+ # page is titled "Estimates" but the API itself never renamed it).
+ "data_selector": '"offers"."offer"',
+ "path": "/offers",
+ "params": {
+ "per_page": _PER_PAGE,
+ "order_by": "date ASC",
+ "from": _incremental_param() if should_use_incremental_field else None,
+ },
+ },
+ "table_format": "delta",
+ },
+ "CreditNotes": {
+ "name": "CreditNotes",
+ "table_name": "credit_notes",
+ "write_disposition": write_disposition,
+ "endpoint": {
+ "data_selector": '"credit-notes"."credit-note"',
+ "path": "/credit-notes",
+ "params": {
+ "per_page": _PER_PAGE,
+ "order_by": "date ASC",
+ "from": _incremental_param() if should_use_incremental_field else None,
+ },
+ },
+ "table_format": "delta",
+ },
+ "Incomings": {
+ "name": "Incomings",
+ "table_name": "incomings",
+ "write_disposition": write_disposition,
+ "endpoint": {
+ "data_selector": '"incomings"."incoming"',
+ "path": "/incomings",
+ "params": {
+ "per_page": _PER_PAGE,
+ "order_by": "date ASC",
+ "from": _incremental_param() if should_use_incremental_field else None,
+ },
+ },
+ "table_format": "delta",
+ },
+ }
+ return resources[name]
+
+
+def billomat_source(
+ api_key: str,
+ billomat_id: str,
+ app_id: Optional[str],
+ app_secret: Optional[str],
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[BillomatResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+ should_use_incremental_field: bool = False,
+) -> Resource:
+ headers = _billomat_headers(api_key, app_id, app_secret)
+ # `X-AppSecret` isn't carried by any framework auth object (there is none here — the API
+ # key rides as a plain header), so it needs its own redact entry alongside the API key.
+ # allow_redirects=False: a redirect would forward the API key/app secret headers off the validated host.
+ session = make_tracked_session(
+ headers=headers, redact_values=tuple(v for v in (api_key, app_secret) if v), allow_redirects=False
+ )
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"page": resume_config.next_page}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state and state.get("page") is not None:
+ resumable_source_manager.save_state(BillomatResumeConfig(next_page=int(state["page"])))
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": f"https://{billomat_id}.billomat.net/api",
+ "session": session,
+ "paginator": BillomatPaginator(per_page=_PER_PAGE, base_page=1, page=1, page_param="page"),
+ },
+ "resources": [get_resource(endpoint, should_use_incremental_field)],
+ }
+
+ return rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+
+def validate_credentials(api_key: str, billomat_id: str, app_id: Optional[str], app_secret: Optional[str]) -> bool:
+ # allow_redirects=False: a redirect would forward the API key/app secret headers off the validated host.
+ session = make_tracked_session(
+ headers=_billomat_headers(api_key, app_id, app_secret),
+ redact_values=tuple(v for v in (api_key, app_secret) if v),
+ allow_redirects=False,
+ )
+ res = session.get(f"https://{billomat_id}.billomat.net/api/clients?per_page=1")
+ return res.status_code == 200
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/billomat/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/billomat/canonical_descriptions.py
new file mode 100644
index 000000000000..9d1065ce3e21
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/billomat/canonical_descriptions.py
@@ -0,0 +1,128 @@
+"""Canonical, documentation-sourced descriptions for Billomat endpoints and columns.
+
+Sourced from the official Billomat API reference (https://www.billomat.com/en/api/).
+Keyed by the resource names in `settings.py` `ENDPOINTS`, which match the
+`ExternalDataSchema.name` of a synced Billomat table. Columns absent here fall back to LLM
+enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Clients": {
+ "description": "A customer you bill in Billomat.",
+ "docs_url": "https://www.billomat.com/en/api/clients/",
+ "columns": {
+ "id": "Unique identifier for the client.",
+ "created": "Time the client was created.",
+ "archived": "Whether the client has been archived.",
+ "client_number": "Client number shown on documents.",
+ "name": "Company name.",
+ "first_name": "Contact first name.",
+ "last_name": "Contact last name.",
+ "email": "Contact email address.",
+ "phone": "Contact phone number.",
+ "street": "Street address.",
+ "zip": "Postal code.",
+ "city": "City.",
+ "country_code": "ISO 3166 alpha-2 country code.",
+ "vat_number": "VAT registration number.",
+ "bank_iban": "IBAN on file for the client.",
+ "currency_code": "ISO currency code used for the client's documents.",
+ "due_days": "Default number of days given to pay an invoice.",
+ "revenue_gross": "Total gross revenue billed to the client.",
+ "revenue_net": "Total net revenue billed to the client.",
+ },
+ },
+ "Suppliers": {
+ "description": "A vendor you receive bills (incomings) from in Billomat.",
+ "docs_url": "https://www.billomat.com/en/api/suppliers/",
+ "columns": {
+ "id": "Unique identifier for the supplier.",
+ "created": "Time the supplier was created.",
+ "name": "Company name.",
+ "first_name": "Contact first name.",
+ "last_name": "Contact last name.",
+ "email": "Contact email address.",
+ "phone": "Contact phone number.",
+ "street": "Street address.",
+ "city": "City.",
+ "zip": "Postal code.",
+ "country_code": "ISO 3166 alpha-2 country code.",
+ "vat_number": "VAT registration number.",
+ "bank_iban": "IBAN on file for the supplier.",
+ "currency_code": "ISO currency code used for the supplier's documents.",
+ "costs_gross": "Total gross costs billed by the supplier.",
+ "costs_net": "Total net costs billed by the supplier.",
+ },
+ },
+ "Invoices": {
+ "description": "An invoice issued to a client.",
+ "docs_url": "https://www.billomat.com/en/api/invoices/",
+ "columns": {
+ "id": "Unique identifier for the invoice.",
+ "client_id": "Client the invoice was issued to.",
+ "invoice_number": "Invoice number, empty until the invoice is completed.",
+ "status": "Invoice status: DRAFT, OPEN, PAID, OVERDUE or CANCELED.",
+ "date": "Invoice date.",
+ "due_date": "Payment deadline.",
+ "total_gross": "Total amount including tax.",
+ "total_net": "Total amount excluding tax.",
+ "paid_amount": "Amount received so far.",
+ "open_amount": "Outstanding balance.",
+ "currency_code": "ISO currency code.",
+ },
+ },
+ "Estimates": {
+ "description": "An estimate (Billomat calls it an 'offer') sent to a client before an invoice.",
+ "docs_url": "https://www.billomat.com/en/api/estimates/",
+ "columns": {
+ "id": "Unique identifier for the estimate.",
+ "client_id": "Client the estimate was sent to.",
+ "contact_id": "Contact person at the client the estimate was sent to.",
+ "offer_number": "Estimate document number.",
+ "status": "Estimate status: DRAFT, OPEN, WON, LOST, CANCELED or CLEARED.",
+ "date": "Estimate date.",
+ "total_gross": "Total amount including tax.",
+ "total_net": "Total amount excluding tax.",
+ "currency_code": "ISO currency code.",
+ "validity_date": "Date the estimate expires.",
+ },
+ },
+ "CreditNotes": {
+ "description": "A credit note issued to a client, typically against an invoice.",
+ "docs_url": "https://www.billomat.com/en/api/credit-notes/",
+ "columns": {
+ "id": "Unique identifier for the credit note.",
+ "client_id": "Client the credit note was issued to.",
+ "contact_id": "Contact person at the client the credit note was issued to.",
+ "credit_note_number": "Credit note document number.",
+ "date": "Credit note date.",
+ "status": "Credit note status: DRAFT, OPEN or PAID.",
+ "total_gross": "Total amount including tax.",
+ "total_net": "Total amount excluding tax.",
+ "currency_code": "ISO currency code.",
+ "invoice_id": "Invoice the credit note was issued against, if any.",
+ },
+ },
+ "Incomings": {
+ "description": "An incoming bill received from a supplier.",
+ "docs_url": "https://www.billomat.com/en/api/incomings/",
+ "columns": {
+ "id": "Unique identifier for the incoming bill.",
+ "supplier_id": "Supplier the bill was received from.",
+ "number": "Supplier's own document number.",
+ "date": "Bill date.",
+ "due_date": "Payment deadline.",
+ "status": "Bill status: OPEN, PAID or OVERDUE.",
+ "total_gross": "Total amount including tax.",
+ "total_net": "Total amount excluding tax.",
+ "paid_amount": "Amount paid so far.",
+ "open_amount": "Outstanding balance.",
+ "currency_code": "ISO currency code.",
+ "category": "Expense category assigned to the bill.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/billomat/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/billomat/settings.py
new file mode 100644
index 000000000000..7f3acc360ed0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/billomat/settings.py
@@ -0,0 +1,49 @@
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+ENDPOINTS = (
+ "Clients",
+ "Suppliers",
+ "Invoices",
+ "Estimates",
+ "CreditNotes",
+ "Incomings",
+)
+
+# Billomat's `from`/`to` list filters apply to the document `date`, not a last-modified
+# timestamp, so this only catches new documents within a synced date window, not edits to
+# existing ones (the API has no `updated_since`-style filter at all). Clients and Suppliers
+# have no date filter, so they stay full-refresh only.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "Invoices": [
+ {
+ "label": "date",
+ "type": IncrementalFieldType.Date,
+ "field": "date",
+ "field_type": IncrementalFieldType.Date,
+ },
+ ],
+ "Estimates": [
+ {
+ "label": "date",
+ "type": IncrementalFieldType.Date,
+ "field": "date",
+ "field_type": IncrementalFieldType.Date,
+ },
+ ],
+ "CreditNotes": [
+ {
+ "label": "date",
+ "type": IncrementalFieldType.Date,
+ "field": "date",
+ "field_type": IncrementalFieldType.Date,
+ },
+ ],
+ "Incomings": [
+ {
+ "label": "date",
+ "type": IncrementalFieldType.Date,
+ "field": "date",
+ "field_type": IncrementalFieldType.Date,
+ },
+ ],
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/billomat/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/billomat/source.py
index fe88f0f93618..6defc06435ce 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/billomat/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/billomat/source.py
@@ -1,32 +1,214 @@
-from typing import cast
+import re
+from dataclasses import field
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSwitchGroupConfig,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.billomat.billomat import (
+ BillomatResumeConfig,
+ billomat_source,
+ validate_credentials as validate_billomat_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.billomat.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.billomat import (
BillomatSourceConfig,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+# The Billomat ID is interpolated into https://{billomat_id}.billomat.net, so it must be a bare
+# DNS subdomain: alphanumerics and hyphens, starting alphanumeric. This keeps outbound traffic
+# pinned to *.billomat.net (a value with a scheme, dot, or path can't build another host).
+_BILLOMAT_ID_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9-]*$")
+
+
+@frozen
+class _RegisteredAppCredentials:
+ app_id: Optional[str]
+ app_secret: Optional[str] = field(repr=False)
+
+
+def _registered_app_credentials(config: BillomatSourceConfig) -> _RegisteredAppCredentials:
+ registered_app = config.registered_app
+ if registered_app is None or not registered_app.enabled:
+ return _RegisteredAppCredentials(app_id=None, app_secret=None)
+ return _RegisteredAppCredentials(app_id=registered_app.app_id, app_secret=registered_app.app_secret)
+
@SourceRegistry.register
-class BillomatSource(SimpleSource[BillomatSourceConfig]):
+class BillomatSource(ResumableSource[BillomatSourceConfig, BillomatResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://www.billomat.com/en/api/"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BILLOMAT
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The API key/app secret is sent to https://{billomat_id}.billomat.net, so retargeting
+ # billomat_id must re-require the secrets (prevents credential exfiltration to another host).
+ return ["billomat_id"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Billomat authentication failed. Check your Billomat ID and API key.",
+ "403 Client Error": "Billomat authentication failed. Check your Billomat ID and API key.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.billomat.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: BillomatSourceConfig,
+ 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: BillomatSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if not _BILLOMAT_ID_RE.match(config.billomat_id):
+ return (
+ False,
+ "That doesn't look like a Billomat ID. Enter just the subdomain (the 'acme' in "
+ "'acme.billomat.net'), not the full URL.",
+ )
+
+ registered_app_credentials = _registered_app_credentials(config)
+ if validate_billomat_credentials(
+ config.api_key, config.billomat_id, registered_app_credentials.app_id, registered_app_credentials.app_secret
+ ):
+ return True, None
+
+ return False, "Invalid credentials"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BillomatResumeConfig]:
+ return ResumableSourceManager[BillomatResumeConfig](inputs, BillomatResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BillomatSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BillomatResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ registered_app_credentials = _registered_app_credentials(config)
+ resource = billomat_source(
+ api_key=config.api_key,
+ billomat_id=config.billomat_id,
+ app_id=registered_app_credentials.app_id,
+ app_secret=registered_app_credentials.app_secret,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ 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,
+ )
+ return SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=["id"],
+ column_hints=resource.column_hints,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.BILLOMAT,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
- label="Billomat GmbH (Billomat)",
+ label="Billomat",
+ caption="Sync clients, suppliers, invoices, estimates, credit notes and incoming supplier bills from Billomat.",
+ docsUrl="https://posthog.com/docs/cdp/sources/billomat",
iconPath="/static/services/billomat.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["invoicing", "accounting", "invoices"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="billomat_id",
+ label="Billomat ID (subdomain)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="acme",
+ secret=False,
+ caption="The subdomain in your Billomat URL, the `acme` in `https://acme.billomat.net`.",
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ caption="Generate a personal API key under Settings > Administration > Users in Billomat.",
+ ),
+ SourceFieldSwitchGroupConfig(
+ name="registered_app",
+ label="Use a registered app to raise the rate limit?",
+ caption="Optional. Register a free app under Settings > Administration > Apps in Billomat to raise the default limit of 300 requests every 15 minutes.",
+ default=False,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="app_id",
+ label="App ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="app_secret",
+ label="App secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/billomat/tests/test_billomat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/billomat/tests/test_billomat.py
new file mode 100644
index 000000000000..b2c924ce936d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/billomat/tests/test_billomat.py
@@ -0,0 +1,575 @@
+import json
+from collections.abc import Iterable
+from datetime import date, datetime
+from typing import Any, cast
+
+import pytest
+from unittest import mock
+from unittest.mock import MagicMock, patch
+
+from requests import Response
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldSwitchGroupConfig,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.billomat.billomat import (
+ BillomatPaginator,
+ BillomatResumeConfig,
+ _extract_total_count,
+ _format_date,
+ billomat_source,
+ get_resource,
+ validate_credentials as validate_billomat_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.billomat.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.billomat.source import BillomatSource
+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 SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.billomat import (
+ BillomatRegisteredAppConfig,
+ BillomatSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+INCREMENTAL_ENDPOINTS = sorted(INCREMENTAL_FIELDS.keys())
+FULL_REFRESH_ENDPOINTS = sorted(set(ENDPOINTS) - set(INCREMENTAL_FIELDS.keys()))
+
+# (endpoint, JSON list wrapper key, JSON item key)
+_ENDPOINT_JSON_KEYS = {
+ "Clients": ("clients", "client"),
+ "Suppliers": ("suppliers", "supplier"),
+ "Invoices": ("invoices", "invoice"),
+ "Estimates": ("offers", "offer"),
+ "CreditNotes": ("credit-notes", "credit-note"),
+ "Incomings": ("incomings", "incoming"),
+}
+
+
+def _make_inputs(**overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": "Clients",
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 123,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": mock.MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestFormatDate:
+ def test_none_stays_none(self) -> None:
+ assert _format_date(None) is None
+
+ def test_date_formats_as_iso(self) -> None:
+ assert _format_date(date(2024, 3, 7)) == "2024-03-07"
+
+ def test_datetime_drops_time_component(self) -> None:
+ assert _format_date(datetime(2024, 3, 7, 13, 45, 0)) == "2024-03-07"
+
+ def test_string_passthrough(self) -> None:
+ assert _format_date("2024-03-07") == "2024-03-07"
+
+
+class TestGetResource:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_resource_shape(self, endpoint: str) -> None:
+ list_key, item_key = _ENDPOINT_JSON_KEYS[endpoint]
+ resource = get_resource(endpoint, should_use_incremental_field=False)
+
+ assert resource["name"] == endpoint
+ assert resource["table_format"] == "delta"
+ endpoint_config = cast(dict[str, Any], resource["endpoint"])
+ assert endpoint_config["data_selector"] == f'"{list_key}"."{item_key}"'
+ assert endpoint_config["params"]["per_page"] == 1000
+
+ @pytest.mark.parametrize("endpoint", FULL_REFRESH_ENDPOINTS)
+ def test_full_refresh_endpoints_always_replace(self, endpoint: str) -> None:
+ for should_use_incremental_field in (False, True):
+ resource = get_resource(endpoint, should_use_incremental_field=should_use_incremental_field)
+ assert resource["write_disposition"] == "replace"
+ endpoint_config = cast(dict[str, Any], resource["endpoint"])
+ assert "from" not in endpoint_config["params"]
+
+ @pytest.mark.parametrize("endpoint", INCREMENTAL_ENDPOINTS)
+ def test_incremental_endpoint_disabled_is_full_refresh(self, endpoint: str) -> None:
+ resource = get_resource(endpoint, should_use_incremental_field=False)
+ assert resource["write_disposition"] == "replace"
+ endpoint_config = cast(dict[str, Any], resource["endpoint"])
+ # The key is present (as a static None, filtered out before the request) but not an
+ # active incremental param, so no unbounded `from` filter leaks into a full sync.
+ assert endpoint_config["params"]["from"] is None
+
+ @pytest.mark.parametrize("endpoint", INCREMENTAL_ENDPOINTS)
+ def test_incremental_endpoint_enabled_uses_merge(self, endpoint: str) -> None:
+ resource = get_resource(endpoint, should_use_incremental_field=True)
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+ endpoint_config = cast(dict[str, Any], resource["endpoint"])
+ assert endpoint_config["params"]["from"]["type"] == "incremental"
+ assert endpoint_config["params"]["from"]["convert"] is _format_date
+
+
+def _make_http_response(body: Any, status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+class TestExtractTotalCount:
+ def test_reads_total_from_single_wrapper_key(self) -> None:
+ response = _make_http_response({"clients": {"client": [{"id": 1}], "total": "12"}})
+ assert _extract_total_count(response) == 12
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ {},
+ {"clients": {"client": []}},
+ {"clients": {"client": [], "total": "not-a-number"}},
+ {"clients": {}, "suppliers": {}},
+ [],
+ ],
+ )
+ def test_returns_none_for_missing_or_malformed_total(self, body: Any) -> None:
+ assert _extract_total_count(_make_http_response(body)) is None
+
+
+class TestBillomatPaginator:
+ def test_stops_once_page_times_per_page_covers_total(self) -> None:
+ paginator = BillomatPaginator(per_page=100, base_page=1, page=1)
+ paginator.update_state(_make_http_response({"clients": {"client": [{"id": 1}], "total": "100"}}))
+ assert paginator.has_next_page is False
+
+ def test_continues_while_total_exceeds_pages_fetched(self) -> None:
+ paginator = BillomatPaginator(per_page=100, base_page=1, page=1)
+ paginator.update_state(
+ _make_http_response({"clients": {"client": [{"id": 1}], "total": "250"}}), data=[{"id": 1}]
+ )
+ assert paginator.has_next_page is True
+ assert paginator.page == 2
+
+ def test_falls_back_to_empty_page_stop_when_total_missing(self) -> None:
+ paginator = BillomatPaginator(per_page=100, base_page=1, page=1)
+ paginator.update_state(_make_http_response({"clients": {"client": []}}), data=[])
+ assert paginator.has_next_page is False
+
+ def test_does_not_stop_early_when_total_missing_and_page_has_data(self) -> None:
+ paginator = BillomatPaginator(per_page=100, base_page=1, page=1)
+ paginator.update_state(_make_http_response({"clients": {"client": [{"id": 1}]}}), data=[{"id": 1}])
+ assert paginator.has_next_page is True
+
+
+class TestBillomatSourceResumeBehavior:
+ """End-to-end pagination/resume behaviour of ``billomat_source`` via ``rest_api_resource``."""
+
+ def _drive(
+ self,
+ endpoint: str,
+ manager: MagicMock,
+ responses: list[Response],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ ) -> tuple[MagicMock, list[dict[str, Any]]]:
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.billomat.billomat.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ resource = billomat_source(
+ api_key="test-key",
+ billomat_id="acme",
+ app_id=None,
+ app_secret=None,
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field,
+ )
+ list(cast(Iterable[Any], resource))
+ return mock_session, sent_params
+
+ def test_fresh_run_saves_page_after_each_non_terminal_page(self) -> None:
+ # `total` (2500) needs 3 pages at the real per_page (1000): pages 1 and 2 leave more
+ # records than fetched so far, page 3 covers the rest and stops without a 4th request.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response({"clients": {"client": [{"id": 1}], "total": "2500"}}),
+ _make_http_response({"clients": {"client": [{"id": 2}], "total": "2500"}}),
+ _make_http_response({"clients": {"client": [{"id": 3}], "total": "2500"}}),
+ ]
+ _, sent_params = self._drive("Clients", manager, responses)
+
+ assert [p.get("page") for p in sent_params] == [1, 2, 3]
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [
+ BillomatResumeConfig(next_page=2),
+ BillomatResumeConfig(next_page=3),
+ ]
+
+ def test_single_item_result_is_not_dropped(self) -> None:
+ # Billomat's XML-to-JSON conversion collapses a one-item list to a bare object instead
+ # of a one-element array — the extraction must still yield exactly one row.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = iter([_make_http_response({"clients": {"client": {"id": 42}, "total": "1"}})])
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.billomat.billomat.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = lambda *args, **kwargs: next(responses)
+
+ resource = billomat_source(
+ api_key="test-key",
+ billomat_id="acme",
+ app_id=None,
+ app_secret=None,
+ endpoint="Clients",
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=None,
+ should_use_incremental_field=False,
+ )
+ batches = list(cast(Iterable[Any], resource))
+
+ # One page yielded as one batch; the item that came back as a bare object (not a
+ # one-element array) must still land as a single row, not be dropped or double-wrapped.
+ assert batches == [[{"id": 42}]]
+
+ def test_terminal_page_does_not_save_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"clients": {"client": [{"id": "only"}], "total": "1"}})]
+ self._drive("Clients", manager, responses)
+
+ manager.save_state.assert_not_called()
+
+ def test_resume_seeds_paginator_with_saved_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = BillomatResumeConfig(next_page=5)
+
+ responses = [_make_http_response({"clients": {"client": [{"id": "50"}], "total": "50"}})]
+ _, sent_params = self._drive("Clients", manager, responses)
+
+ assert [p.get("page") for p in sent_params] == [5]
+ manager.load_state.assert_called_once()
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"clients": {"client": [{"id": "1"}], "total": "1"}})]
+ self._drive("Clients", manager, responses)
+
+ manager.load_state.assert_not_called()
+
+ def test_incremental_run_sends_formatted_from_param(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"invoices": {"invoice": [{"id": "1"}], "total": "1"}})]
+ _, sent_params = self._drive(
+ "Invoices",
+ manager,
+ responses,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2024, 5, 1),
+ )
+
+ assert sent_params[0]["from"] == "2024-05-01"
+
+ def test_full_refresh_run_omits_from_param(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"invoices": {"invoice": [{"id": "1"}], "total": "1"}})]
+ _, sent_params = self._drive("Invoices", manager, responses, should_use_incremental_field=False)
+
+ assert "from" not in sent_params[0]
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "expected"),
+ [(200, True), (401, False), (403, False), (500, False)],
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.billomat.billomat.make_tracked_session")
+ def test_status_maps_to_validity(self, mock_session_factory: MagicMock, status_code: int, expected: bool) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ mock_session_factory.return_value.get.return_value = response
+
+ assert validate_billomat_credentials("api-key", "acme", None, None) is expected
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.billomat.billomat.make_tracked_session")
+ def test_probes_clients_endpoint(self, mock_session_factory: MagicMock) -> None:
+ mock_session_factory.return_value.get.return_value = MagicMock(status_code=200)
+
+ validate_billomat_credentials("api-key", "acme", None, None)
+
+ mock_session_factory.return_value.get.assert_called_once_with(
+ "https://acme.billomat.net/api/clients?per_page=1"
+ )
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.billomat.billomat.make_tracked_session")
+ def test_registered_app_headers_included_when_both_present(self, mock_session_factory: MagicMock) -> None:
+ mock_session_factory.return_value.get.return_value = MagicMock(status_code=200)
+
+ validate_billomat_credentials("api-key", "acme", "app-1", "app-secret-1")
+
+ headers = mock_session_factory.call_args.kwargs["headers"]
+ assert headers["X-AppId"] == "app-1"
+ assert headers["X-AppSecret"] == "app-secret-1"
+
+ @pytest.mark.parametrize(("app_id", "app_secret"), [(None, "app-secret-1"), ("app-1", None), (None, None)])
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.billomat.billomat.make_tracked_session")
+ def test_registered_app_headers_omitted_unless_both_present(
+ self, mock_session_factory: MagicMock, app_id: str | None, app_secret: str | None
+ ) -> None:
+ mock_session_factory.return_value.get.return_value = MagicMock(status_code=200)
+
+ validate_billomat_credentials("api-key", "acme", app_id, app_secret)
+
+ headers = mock_session_factory.call_args.kwargs["headers"]
+ assert "X-AppId" not in headers
+ assert "X-AppSecret" not in headers
+
+
+class TestBillomatSource:
+ def setup_method(self) -> None:
+ self.source = BillomatSource()
+ self.team_id = 123
+ self.config = BillomatSourceConfig(billomat_id="acme", api_key="test-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.BILLOMAT
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_billomat_id_is_a_connection_host_field(self) -> None:
+ # billomat_id determines the request host (https://{billomat_id}.billomat.net), so
+ # changing it must force re-entry of the stored api_key/app_secret.
+ assert self.source.connection_host_fields == ["billomat_id"]
+
+ def test_api_docs_url(self) -> None:
+ assert self.source.api_docs_url is not None and self.source.api_docs_url.startswith("https://")
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Billomat"
+ assert config.category == DataWarehouseSourceCategory.FINANCE___ACCOUNTING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/billomat"
+ assert config.iconPath == "/static/services/billomat.png"
+ assert not config.unreleasedSource
+
+ billomat_id_field, api_key_field, registered_app_field = config.fields
+ assert isinstance(billomat_id_field, SourceFieldInputConfig)
+ assert billomat_id_field.name == "billomat_id"
+ assert billomat_id_field.required is True
+ assert billomat_id_field.secret is False
+
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ assert isinstance(registered_app_field, SourceFieldSwitchGroupConfig)
+ assert registered_app_field.default is False
+ assert {f.name for f in registered_app_field.fields} == {"app_id", "app_secret"}
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key: str) -> None:
+ assert any(expected_key in key for key in self.source.get_non_retryable_errors())
+
+ def test_get_schemas_returns_every_endpoint(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize("endpoint", INCREMENTAL_ENDPOINTS)
+ def test_get_schemas_incremental_endpoints(self, endpoint: str) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ schema = schemas[endpoint]
+ assert schema.supports_incremental is True
+ assert [f["field"] for f in schema.incremental_fields] == ["date"]
+
+ @pytest.mark.parametrize("endpoint", FULL_REFRESH_ENDPOINTS)
+ def test_get_schemas_full_refresh_endpoints(self, endpoint: str) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ schema = schemas[endpoint]
+ assert schema.supports_incremental is False
+ assert schema.incremental_fields == []
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ assert set(self.source.get_canonical_descriptions().keys()) == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ ("billomat_id", "valid"),
+ [
+ ("acme", True),
+ ("acme2024", True),
+ ("acme-test", True),
+ ("acme.billomat.net", False),
+ ("https://acme.billomat.net", False),
+ ("-acme", False),
+ ("", False),
+ ],
+ )
+ def test_validate_credentials_rejects_non_subdomain_without_calling_the_api(
+ self, billomat_id: str, valid: bool
+ ) -> None:
+ config = BillomatSourceConfig(billomat_id=billomat_id, api_key="key")
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.billomat.source.validate_billomat_credentials"
+ ) as mock_validate:
+ mock_validate.return_value = True
+ is_valid, message = self.source.validate_credentials(config, self.team_id)
+
+ assert is_valid is valid
+ if not valid:
+ mock_validate.assert_not_called()
+ assert message is not None
+
+ @pytest.mark.parametrize(
+ ("creds_valid", "expected_valid", "expected_message"),
+ [
+ (True, True, None),
+ (False, False, "Invalid credentials"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.billomat.source.validate_billomat_credentials"
+ )
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ creds_valid: bool,
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ mock_validate.return_value = creds_valid
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with("test-key", "acme", None, None)
+
+ def test_validate_credentials_passes_registered_app(self) -> None:
+ config = BillomatSourceConfig(
+ billomat_id="acme",
+ api_key="test-key",
+ registered_app=BillomatRegisteredAppConfig(app_id="app-1", app_secret="secret-1", enabled=True),
+ )
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.billomat.source.validate_billomat_credentials"
+ ) as mock_validate:
+ mock_validate.return_value = True
+ self.source.validate_credentials(config, self.team_id)
+
+ mock_validate.assert_called_once_with("test-key", "acme", "app-1", "secret-1")
+
+ def test_validate_credentials_ignores_disabled_registered_app(self) -> None:
+ config = BillomatSourceConfig(
+ billomat_id="acme",
+ api_key="test-key",
+ registered_app=BillomatRegisteredAppConfig(app_id="app-1", app_secret="secret-1", enabled=False),
+ )
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.billomat.source.validate_billomat_credentials"
+ ) as mock_validate:
+ mock_validate.return_value = True
+ self.source.validate_credentials(config, self.team_id)
+
+ mock_validate.assert_called_once_with("test-key", "acme", None, None)
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is BillomatResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.billomat.source.billomat_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(schema_name="Invoices", team_id=99, job_id="job-xyz")
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ response = self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once_with(
+ api_key="test-key",
+ billomat_id="acme",
+ app_id=None,
+ app_secret=None,
+ endpoint="Invoices",
+ team_id=99,
+ job_id="job-xyz",
+ resumable_source_manager=manager,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ assert response.primary_keys == ["id"]
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.billomat.source.billomat_source")
+ def test_source_for_pipeline_only_passes_last_value_when_incremental(self, mock_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(
+ schema_name="Invoices",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2024, 1, 1),
+ )
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] == date(2024, 1, 1)
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.billomat.source.billomat_source")
+ def test_source_for_pipeline_passes_registered_app_credentials(self, mock_source: mock.MagicMock) -> None:
+ config = BillomatSourceConfig(
+ billomat_id="acme",
+ api_key="test-key",
+ registered_app=BillomatRegisteredAppConfig(app_id="app-1", app_secret="secret-1", enabled=True),
+ )
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(config, manager, _make_inputs())
+
+ assert mock_source.call_args.kwargs["app_id"] == "app-1"
+ assert mock_source.call_args.kwargs["app_secret"] == "secret-1"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/billomat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/billomat.py
index fe1268943a2d..943453d062a1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/billomat.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/billomat.py
@@ -4,6 +4,15 @@
from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
+class BillomatRegisteredAppConfig(config.Config):
+ app_id: str
+ app_secret: str
+ enabled: bool = config.value(converter=config.str_to_bool, default=False)
+
+
@config.config
class BillomatSourceConfig(config.Config):
- pass
+ billomat_id: str
+ api_key: str
+ registered_app: BillomatRegisteredAppConfig | None = None
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index cb4e96126112..ea9345d5cf28 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -6069,6 +6069,78 @@ class TestExternalDataSource(APIBaseTest):
assert source.job_inputs["password"] == "new_password"
mock_validate_credentials.assert_called_once()
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.billomat.source.BillomatSource.validate_credentials",
+ return_value=(True, None),
+ )
+ def test_update_with_host_change_preserves_secret_nested_in_switch_group_is_rejected(
+ self, mock_validate_credentials
+ ):
+ """Billomat's `app_secret` lives nested inside the `registered_app` switch-group container,
+ not at the top level. Changing `billomat_id` (a `connection_host_fields` entry) must still be
+ rejected when that nested secret would be carried over unchanged — otherwise the preserved
+ `app_secret` gets sent to whatever host the new `billomat_id` resolves to."""
+ source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ destination_id=str(uuid.uuid4()),
+ source_type="Billomat",
+ created_by=self.user,
+ prefix="test_billomat_nested_secret",
+ job_inputs={
+ "source_type": "Billomat",
+ "billomat_id": "acme",
+ "api_key": "original_api_key",
+ "registered_app": {
+ "enabled": True,
+ "app_id": "original_app_id",
+ "app_secret": "original_app_secret",
+ },
+ },
+ )
+
+ # Re-supplying the top-level secret (api_key) but not the nested one (app_secret) must still
+ # be rejected: the preserved app_secret would otherwise follow billomat_id to the new host.
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
+ data={
+ "job_inputs": {
+ "billomat_id": "attacker-controlled",
+ "api_key": "original_api_key",
+ },
+ },
+ )
+
+ assert response.status_code == 400
+ assert "re-entering your credentials" in str(response.json())
+ source.refresh_from_db()
+ assert source.job_inputs["billomat_id"] == "acme"
+ assert source.job_inputs["registered_app"]["app_secret"] == "original_app_secret"
+ mock_validate_credentials.assert_not_called()
+
+ # Re-supplying both the top-level and nested secrets succeeds and adopts the new host.
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
+ data={
+ "job_inputs": {
+ "billomat_id": "new-tenant",
+ "api_key": "new_api_key",
+ "registered_app": {
+ "enabled": True,
+ "app_id": "original_app_id",
+ "app_secret": "new_app_secret",
+ },
+ },
+ },
+ )
+
+ assert response.status_code == 200, response.json()
+ source.refresh_from_db()
+ assert source.job_inputs["billomat_id"] == "new-tenant"
+ assert source.job_inputs["registered_app"]["app_secret"] == "new_app_secret"
+ mock_validate_credentials.assert_called_once()
+
@parameterized.expand([("with_password", {"password": "new_password"}, 200), ("without_password", {}, 400)])
@patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.validate_credentials",