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 Housecall Pro import source (#84372)

Tom Owersb79e0f858dbc
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/housecallpro.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/housecallpro.py
index 6a1683592e95..a7cd10d43a52 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/housecallpro.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/housecallpro.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class HousecallProSourceConfig(config.Config):
- pass
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/canonical_descriptions.py
new file mode 100644
index 000000000000..bbc856cb7bb9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/canonical_descriptions.py
@@ -0,0 +1,110 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from Housecall Pro's public API docs (https://docs.housecallpro.com/docs/housecall-public-api).
+# Keyed by the endpoint name from ENDPOINTS / get_schemas. Partial coverage is fine — anything not
+# listed here falls back to LLM enrichment using the docs_url and column data types.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "customers": {
+ "description": "Customer records in the Housecall Pro account, including contact details and service addresses.",
+ "docs_url": "https://docs.housecallpro.com/docs/housecall-public-api/042bd3bf861ae-get-customers",
+ "columns": {
+ "id": "Unique identifier for the customer.",
+ "first_name": "Customer's first name.",
+ "last_name": "Customer's last name.",
+ "email": "Customer's email address.",
+ "company": "Company name, for commercial customers.",
+ "mobile_number": "Customer's mobile phone number.",
+ "home_number": "Customer's home phone number.",
+ "work_number": "Customer's work phone number.",
+ "notifications_enabled": "Whether the customer receives automated notifications.",
+ "tags": "Tags applied to the customer for segmentation.",
+ "lead_source": "Marketing source attributed to the customer.",
+ "notes": "Free-text notes on the customer.",
+ "addresses": "Service addresses associated with the customer.",
+ "created_at": "When the customer was created.",
+ "updated_at": "When the customer was last updated.",
+ },
+ },
+ "jobs": {
+ "description": "Scheduled and completed jobs (appointments) performed for customers.",
+ "docs_url": "https://docs.housecallpro.com/docs/housecall-public-api/6c97704da8bf3-get-jobs",
+ "columns": {
+ "id": "Unique identifier for the job.",
+ "customer_id": "Identifier of the customer the job is for.",
+ "address_id": "Identifier of the service address for the job.",
+ "notes": "Free-text notes on the job.",
+ "lead_source": "Marketing source attributed to the job.",
+ "invoice_number": "Invoice number associated with the job.",
+ "work_status": "Current status of the job (e.g. scheduled, completed, canceled).",
+ "schedule": "Scheduling window for the job, including start and end time.",
+ "assigned_employee_ids": "Employees assigned to perform the job.",
+ "line_items": "Products and services billed on the job.",
+ "tags": "Tags applied to the job.",
+ "created_at": "When the job was created.",
+ "updated_at": "When the job was last updated.",
+ },
+ },
+ "estimates": {
+ "description": "Estimates (quotes) sent to customers before a job is booked.",
+ "docs_url": "https://docs.housecallpro.com/docs/housecall-public-api/e430ba3d520a0",
+ "columns": {
+ "id": "Unique identifier for the estimate.",
+ "customer_id": "Identifier of the customer the estimate is for.",
+ "address_id": "Identifier of the service address for the estimate.",
+ "work_status": "Current status of the estimate (e.g. scheduled, completed, canceled).",
+ "options": "Pricing options presented to the customer, each with its own line items.",
+ "schedule": "Scheduling window for the estimate visit.",
+ "assigned_employee_ids": "Employees assigned to the estimate.",
+ "lead_source": "Marketing source attributed to the estimate.",
+ "estimate_number": "Estimate number, unique across the company.",
+ "created_at": "When the estimate was created.",
+ "updated_at": "When the estimate was last updated.",
+ },
+ },
+ "invoices": {
+ "description": "Invoices issued to customers for completed work, including payment status.",
+ "docs_url": "https://docs.housecallpro.com/docs/housecall-public-api/65ce9f430d605",
+ "columns": {
+ "id": "Unique identifier for the invoice.",
+ "customer_id": "Identifier of the customer the invoice was issued to.",
+ "status": "Current status of the invoice (e.g. open, paid, voided).",
+ "amount_due": "Amount still owed on the invoice.",
+ "payment_method": "Method used to pay the invoice, once paid.",
+ "due_at": "When the invoice is due.",
+ "paid_at": "When the invoice was paid, if applicable.",
+ "created_at": "When the invoice was created. Stable, used for incremental sync.",
+ },
+ },
+ "employees": {
+ "description": "Employee (team member) accounts in the Housecall Pro account.",
+ "docs_url": "https://docs.housecallpro.com/docs/housecall-public-api/303ee235f23fa-get-employees",
+ "columns": {
+ "id": "Unique identifier for the employee.",
+ "first_name": "Employee's first name.",
+ "last_name": "Employee's last name.",
+ "email": "Employee's email address.",
+ "mobile_number": "Employee's mobile phone number.",
+ "role": "Role assigned to the employee in the account.",
+ "tags": "Tags applied to the employee.",
+ },
+ },
+ "leads": {
+ "description": "Inbound leads not yet converted into a job or estimate.",
+ "docs_url": "https://docs.housecallpro.com/docs/housecall-public-api/278974bc87e32-get-leads",
+ "columns": {
+ "id": "Unique identifier for the lead.",
+ "customer_id": "Identifier of the customer the lead is associated with.",
+ "address_id": "Identifier of the service address for the lead.",
+ "assigned_employee_id": "Employee assigned to follow up on the lead.",
+ "status": "Current status of the lead (e.g. open, won, lost).",
+ "lead_source": "Marketing source attributed to the lead.",
+ "note": "Free-text note on the lead.",
+ "tags": "Tags applied to the lead.",
+ "line_items": "Products and services proposed on the lead.",
+ "created_at": "When the lead was created.",
+ "updated_at": "When the lead was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/housecall_pro.py b/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/housecall_pro.py
new file mode 100644
index 000000000000..2f812dc12a2a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/housecall_pro.py
@@ -0,0 +1,158 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional, cast
+
+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 (
+ Endpoint,
+ 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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.housecall_pro.settings import (
+ HOUSECALL_PRO_ENDPOINTS,
+)
+
+HOUSECALL_PRO_BASE_URL = "https://api.housecallpro.com"
+
+# The vendor's own default is 10; raising it cuts round trips against an undisclosed rate limit.
+# Pagination termination reads `total_pages` from the body, so a smaller honored page size still
+# walks every page correctly.
+PAGE_SIZE = 100
+
+# Hard cap so a paginator that never sees `total_pages` drop below the current page can't loop forever.
+MAX_PAGES = 100_000
+
+
[email protected](frozen=False) # resume state is rebuilt wholesale each save, not mutated in place
+class HousecallProResumeConfig:
+ # Next 1-indexed page to fetch.
+ page: int
+
+
+def _format_created_at_min(value: Any) -> str | None:
+ """Format an incremental cursor as the ISO 8601 UTC timestamp `created_at_min` expects."""
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, str) and value:
+ return value
+ return None
+
+
+def validate_credentials(api_key: str) -> bool:
+ """Confirm the API key is genuine by fetching the account's company profile."""
+ ok, _status = validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_key,)),
+ f"{HOUSECALL_PRO_BASE_URL}/company",
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ )
+ return ok
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[HousecallProResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = HOUSECALL_PRO_ENDPOINTS[endpoint]
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ initial_paginator_state: Optional[dict[str, Any]] = {"page": resume.page} if resume is not None else None
+
+ params: dict[str, Any] = {"page_size": PAGE_SIZE}
+ if config.sort_field:
+ # Ascending on the cursor field so the pipeline watermark advances safely and full-refresh
+ # pages don't skip/duplicate rows inserted mid-sync.
+ params["sort_by"] = config.sort_field
+ params["sort_direction"] = "asc"
+
+ endpoint_config: Endpoint = {
+ "path": config.path,
+ "params": params,
+ # A 200 body without the response key reads as an empty page and ends pagination.
+ "data_selector": config.response_key,
+ # `total_pages` in the body is the number of PAGES, so pagination stops after the last page
+ # without paying an extra empty-page request.
+ "paginator": PageNumberPaginator(
+ base_page=1,
+ page_param="page",
+ total_path="total_pages",
+ maximum_page=MAX_PAGES,
+ ),
+ }
+ if config.supports_incremental and config.incremental_param and should_use_incremental_field:
+ endpoint_config["incremental"] = {
+ "start_param": config.incremental_param,
+ "cursor_path": cast("str", config.sort_field),
+ "convert": _format_created_at_min,
+ }
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": HOUSECALL_PRO_BASE_URL,
+ "headers": {"Accept": "application/json"},
+ "auth": {"type": "bearer", "token": api_key},
+ },
+ "resources": [{"name": endpoint, "endpoint": endpoint_config}],
+ }
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only when a next page remains; the framework calls this AFTER a page is yielded
+ # so a crash re-pulls from the next page rather than losing the page we just handed off —
+ # the merge dedupes any overlap on the primary key.
+ if state and state.get("page") is not None:
+ resumable_source_manager.save_state(HousecallProResumeConfig(page=int(state["page"])))
+
+ yield from rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+
+def housecall_pro_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[HousecallProResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = HOUSECALL_PRO_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ team_id=team_id,
+ job_id=job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/settings.py
new file mode 100644
index 000000000000..173a3b5427ca
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/settings.py
@@ -0,0 +1,96 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass(frozen=False) # static endpoint catalog, never mutated after construction
+class HousecallProEndpointConfig:
+ name: str
+ path: str
+ # Key the list lives under in the JSON envelope, e.g. {"customers": [...], "total_pages": N}.
+ response_key: str
+ incremental_fields: list[IncrementalField]
+ # Stable datetime field used for datetime partitioning. Left unset for resources we have no
+ # confirmed created_at field for (employees).
+ partition_key: Optional[str] = None
+ # Field passed to the API's `sort_by` param (ascending) and, for the incremental endpoint, the
+ # field the `created_at_min` server-side filter narrows on. Only set where the vendor docs
+ # confirm the field exists on the resource — left unset elsewhere rather than guessed, since an
+ # unsupported `sort_by` value could 400 every page of the sync.
+ sort_field: Optional[str] = None
+ # Query param name for a genuine server-side timestamp filter, if the endpoint documents one.
+ incremental_param: Optional[str] = None
+ supports_incremental: bool = False
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ should_sync_default: bool = True
+
+
+# Housecall Pro REST API (https://api.housecallpro.com). Every list endpoint supports page-number
+# pagination (`page`, `page_size`) and reports `total_pages` in the body.
+#
+# Only Invoices documents a genuine server-side timestamp filter (`created_at_min`), so it's the
+# only endpoint marked incremental. The others (Customers, Jobs, Estimates, Leads) accept
+# `sort_by`/`sort_direction` generically per the vendor docs, but don't expose a filter that
+# narrows the result set to "changed since X" — enabling incremental sync on those would still walk
+# every page each run, which isn't a real incremental sync. Employees has neither a confirmed
+# timestamp field nor a documented filter, so it ships full refresh with no explicit sort.
+HOUSECALL_PRO_ENDPOINTS: dict[str, HousecallProEndpointConfig] = {
+ "customers": HousecallProEndpointConfig(
+ name="customers",
+ path="/customers",
+ response_key="customers",
+ partition_key="created_at",
+ incremental_fields=[],
+ ),
+ "jobs": HousecallProEndpointConfig(
+ name="jobs",
+ path="/jobs",
+ response_key="jobs",
+ partition_key="created_at",
+ incremental_fields=[],
+ ),
+ "estimates": HousecallProEndpointConfig(
+ name="estimates",
+ path="/estimates",
+ response_key="estimates",
+ partition_key="created_at",
+ incremental_fields=[],
+ ),
+ "invoices": HousecallProEndpointConfig(
+ name="invoices",
+ path="/invoices",
+ response_key="invoices",
+ partition_key="created_at",
+ sort_field="created_at",
+ incremental_param="created_at_min",
+ supports_incremental=True,
+ incremental_fields=[
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "employees": HousecallProEndpointConfig(
+ name="employees",
+ path="/employees",
+ response_key="employees",
+ incremental_fields=[],
+ ),
+ "leads": HousecallProEndpointConfig(
+ name="leads",
+ path="/leads",
+ response_key="leads",
+ partition_key="created_at",
+ incremental_fields=[],
+ ),
+}
+
+ENDPOINTS = tuple(HOUSECALL_PRO_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in HOUSECALL_PRO_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/source.py
index 23de542f148d..bcfbde267643 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/source.py
@@ -1,21 +1,47 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.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.housecallpro import (
HousecallProSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.housecall_pro.housecall_pro import (
+ HousecallProResumeConfig,
+ housecall_pro_source,
+ validate_credentials as validate_housecall_pro_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.housecall_pro.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class HousecallProSource(SimpleSource[HousecallProSourceConfig]):
+class HousecallProSource(ResumableSource[HousecallProSourceConfig, HousecallProResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ # No URL path segment, version header, or dated query param — the vendor's API has no
+ # meaningful version scheme to pin.
+ api_docs_url = "https://docs.housecallpro.com/docs/housecall-public-api"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.HOUSECALLPRO
@@ -26,7 +52,81 @@ class HousecallProSource(SimpleSource[HousecallProSourceConfig]):
name=SchemaExternalDataSourceType.HOUSECALL_PRO,
category=DataWarehouseSourceCategory.CRM,
label="Housecall Pro",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Housecall Pro API key to pull your jobs, customers, and invoices into the PostHog Data warehouse.
+
+API access needs a MAX plan. An account admin can generate a key under **My Apps → All Apps → API Key Management** — choose read-only access for a sync-only key.""",
iconPath="/static/services/housecall_pro.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/housecall-pro",
+ keywords=["field service", "fsm"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.housecall_pro.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.housecallpro.com": "Your Housecall Pro API key is invalid or has been revoked. Generate a new key under My Apps → API Key Management, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.housecallpro.com": "Housecall Pro rejected this request. API access needs a MAX plan and a key with the right access level — check both, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: HousecallProSourceConfig,
+ 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: HousecallProSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if validate_housecall_pro_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Housecall Pro API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HousecallProResumeConfig]:
+ return ResumableSourceManager[HousecallProResumeConfig](inputs, HousecallProResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: HousecallProSourceConfig,
+ resumable_source_manager: ResumableSourceManager[HousecallProResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return housecall_pro_source(
+ api_key=config.api_key,
+ 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,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/tests/test_housecall_pro.py b/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/tests/test_housecall_pro.py
new file mode 100644
index 000000000000..16938aef3568
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/tests/test_housecall_pro.py
@@ -0,0 +1,262 @@
+import json
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.housecall_pro.housecall_pro import (
+ HousecallProResumeConfig,
+ _format_created_at_min,
+ get_rows,
+ housecall_pro_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.housecall_pro.settings import (
+ ENDPOINTS,
+ HOUSECALL_PRO_ENDPOINTS,
+)
+
+# RESTClient builds its session via make_tracked_session in the rest_client module.
+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+# validate_credentials builds its own tracked session in the housecall_pro module.
+HOUSECALL_PRO_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.housecall_pro.housecall_pro.make_tracked_session"
+)
+
+
+def _response(body: dict[str, Any]) -> Response:
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
+def _page(response_key: str, items: list[dict[str, Any]], total_pages: int) -> Response:
+ return _response({response_key: items, "page": 1, "page_size": 100, "total_pages": total_pages})
+
+
+def _make_manager(resume_state: HousecallProResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ """Wire a mock session and return snapshots of each request AT PREPARE TIME.
+
+ ``request.params`` is a single dict mutated in place across pages, so inspecting it after the
+ run shows only the final state — snapshot a copy when each request is prepared instead.
+ """
+ session.headers = {}
+ snapshots: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ snapshots.append({"url": request.url, "params": dict(request.params or {}), "auth": request.auth})
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return snapshots
+
+
+def _collect(
+ endpoint: str,
+ responses: list[Response],
+ MockSession: mock.MagicMock,
+ manager: mock.MagicMock | None = None,
+ **kwargs: Any,
+) -> tuple[list[list[dict[str, Any]]], list[dict[str, Any]], mock.MagicMock]:
+ session = MockSession.return_value
+ snapshots = _wire(session, responses)
+ manager = manager if manager is not None else _make_manager()
+ batches = list(get_rows("key", endpoint, team_id=1, job_id="j", resumable_source_manager=manager, **kwargs))
+ return batches, snapshots, manager
+
+
+class TestFormatCreatedAtMin:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (None, None),
+ (datetime(2026, 3, 4, 22, 13, 20, tzinfo=UTC), "2026-03-04T22:13:20Z"),
+ (date(2026, 3, 4), "2026-03-04T00:00:00Z"),
+ ("2026-03-04T22:13:20Z", "2026-03-04T22:13:20Z"),
+ ("", None),
+ ],
+ )
+ def test_format_created_at_min(self, value: Any, expected: str | None) -> None:
+ assert _format_created_at_min(value) == expected
+
+ def test_naive_datetime_is_treated_as_utc(self) -> None:
+ assert _format_created_at_min(datetime(2026, 3, 4, 12, 0, 0)) == "2026-03-04T12:00:00Z"
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @mock.patch(HOUSECALL_PRO_SESSION_PATCH)
+ def test_validate_credentials_status_mapping(
+ self, mock_session: mock.MagicMock, status_code: int, expected: bool
+ ) -> None:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert validate_credentials("key") is expected
+
+ @mock.patch(HOUSECALL_PRO_SESSION_PATCH)
+ def test_validate_credentials_swallows_exceptions(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("key") is False
+
+
+class TestGetRows:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_paginates_by_page_number(self, MockSession: mock.MagicMock) -> None:
+ batches, snapshots, manager = _collect(
+ "customers",
+ [
+ _page("customers", [{"id": "1"}, {"id": "2"}], total_pages=2),
+ _page("customers", [{"id": "3"}], total_pages=2),
+ ],
+ MockSession,
+ )
+
+ assert [item["id"] for batch in batches for item in batch] == ["1", "2", "3"]
+ assert snapshots[0]["params"]["page"] == 1
+ assert snapshots[0]["params"]["page_size"] == 100
+ assert snapshots[1]["params"]["page"] == 2
+ # State saved once (after page 1, pointing at page 2); page 2 is the last so no save after it.
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0] == HousecallProResumeConfig(page=2)
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_auth_header_is_bearer_token(self, MockSession: mock.MagicMock) -> None:
+ _, snapshots, _ = _collect("customers", [_page("customers", [{"id": "1"}], total_pages=1)], MockSession)
+ assert snapshots[0]["auth"].token == "key"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_saved_page(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _, snapshots, _ = _collect(
+ "customers",
+ [_page("customers", [{"id": "9"}], total_pages=5)],
+ MockSession,
+ manager=_make_manager(HousecallProResumeConfig(page=5)),
+ )
+
+ assert session.send.call_count == 1
+ assert snapshots[0]["params"]["page"] == 5
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_empty_page_stops_without_saving(self, MockSession: mock.MagicMock) -> None:
+ batches, _, manager = _collect("customers", [_page("customers", [], total_pages=0)], MockSession)
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_missing_response_key_stops_without_rows(self, MockSession: mock.MagicMock) -> None:
+ # A 200 body without the list key reads as an empty page — end of data, not an error.
+ batches, _, manager = _collect("customers", [_response({"total_pages": 3})], MockSession)
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_request_carries_created_at_min_and_sort(self, MockSession: mock.MagicMock) -> None:
+ _, snapshots, _ = _collect(
+ "invoices",
+ [_page("invoices", [{"id": "1"}], total_pages=1)],
+ MockSession,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+
+ assert snapshots[0]["params"]["created_at_min"] == "2026-01-01T00:00:00Z"
+ assert snapshots[0]["params"]["sort_by"] == "created_at"
+ assert snapshots[0]["params"]["sort_direction"] == "asc"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_created_at_min_omitted_when_not_using_incremental(self, MockSession: mock.MagicMock) -> None:
+ _, snapshots, _ = _collect(
+ "invoices",
+ [_page("invoices", [{"id": "1"}], total_pages=1)],
+ MockSession,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+
+ assert "created_at_min" not in snapshots[0]["params"]
+ # Sort is still ascending on the cursor field so full-refresh pages don't skip/duplicate.
+ assert snapshots[0]["params"]["sort_by"] == "created_at"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_created_at_min_omitted_when_last_value_missing(self, MockSession: mock.MagicMock) -> None:
+ _, snapshots, _ = _collect(
+ "invoices",
+ [_page("invoices", [{"id": "1"}], total_pages=1)],
+ MockSession,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ )
+
+ assert "created_at_min" not in snapshots[0]["params"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_refresh_endpoint_has_no_sort_or_created_at_min(self, MockSession: mock.MagicMock) -> None:
+ _, snapshots, _ = _collect(
+ "customers",
+ [_page("customers", [{"id": "1"}], total_pages=1)],
+ MockSession,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+
+ assert "sort_by" not in snapshots[0]["params"]
+ assert "sort_direction" not in snapshots[0]["params"]
+ assert "created_at_min" not in snapshots[0]["params"]
+
+
+class TestHousecallProSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint: str) -> None:
+ config = HOUSECALL_PRO_ENDPOINTS[endpoint]
+ response = housecall_pro_source(
+ "key", endpoint, team_id=1, job_id="j", resumable_source_manager=_make_manager()
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == "asc"
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ @pytest.mark.parametrize("config", list(HOUSECALL_PRO_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_creation_fields(self, config: Any) -> None:
+ # Never partition on a mutable field; only stable creation timestamps are allowed.
+ if config.partition_key:
+ assert config.partition_key == "created_at"
+
+ @pytest.mark.parametrize("config", list(HOUSECALL_PRO_ENDPOINTS.values()))
+ def test_incremental_endpoints_have_a_sort_field(self, config: Any) -> None:
+ # An incremental endpoint must sort ascending on its cursor so the watermark advances.
+ if config.supports_incremental:
+ assert config.sort_field is not None
+ assert config.incremental_param is not None
+ assert config.incremental_fields
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/tests/test_housecall_pro_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/tests/test_housecall_pro_source.py
new file mode 100644
index 000000000000..95c73cd32d3f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/housecall_pro/tests/test_housecall_pro_source.py
@@ -0,0 +1,167 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.housecallpro import (
+ HousecallProSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.housecall_pro.housecall_pro import (
+ HousecallProResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.housecall_pro.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.housecall_pro.source import HousecallProSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestHousecallProSource:
+ def setup_method(self) -> None:
+ self.source = HousecallProSource()
+ self.team_id = 123
+ self.config = HousecallProSourceConfig(api_key="key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.HOUSECALLPRO
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "HousecallPro"
+ assert config.label == "Housecall Pro"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/housecall-pro"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert key_field.secret is True
+ assert key_field.required is True
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+ assert len(self.source.get_documented_tables()) == len(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.housecallpro.com/customers?page=1",
+ "403 Client Error: Forbidden for url: https://api.housecallpro.com/jobs",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.housecallpro.com/customers",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_covers_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_only_invoices_is_incremental(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ incremental = {name for name, s in schemas.items() if s.supports_incremental}
+ # Only Invoices documents a genuine server-side timestamp filter (created_at_min).
+ assert incremental == {"invoices"}
+
+ def test_incremental_schema_advertises_its_fields(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["invoices"].incremental_fields == INCREMENTAL_FIELDS["invoices"]
+ assert schemas["customers"].incremental_fields == []
+ assert schemas["customers"].supports_append is False
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["customers"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "customers"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_get_canonical_descriptions_keys_match_endpoints(self) -> None:
+ canonical = self.source.get_canonical_descriptions()
+ assert set(canonical).issubset(set(ENDPOINTS))
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Housecall Pro API key"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.housecall_pro.source.validate_housecall_pro_credentials"
+ )
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ mock_return: bool,
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ mock_validate.return_value = mock_return
+
+ 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(self.config.api_key)
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is HousecallProResumeConfig
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.housecall_pro.source.housecall_pro_source"
+ )
+ def test_source_for_pipeline_plumbs_arguments(self, mock_housecall_pro_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "invoices"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1700000000
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_housecall_pro_source.call_args.kwargs
+ assert kwargs["api_key"] == "key"
+ assert kwargs["endpoint"] == "invoices"
+ assert kwargs["team_id"] is inputs.team_id
+ assert kwargs["job_id"] is inputs.job_id
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1700000000
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.housecall_pro.source.housecall_pro_source"
+ )
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(
+ self, mock_housecall_pro_source: mock.MagicMock
+ ) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "customers"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1700000000
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_housecall_pro_source.call_args.kwargs["db_incremental_field_last_value"] is None