: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add HitPay import source (#84393)
Tom Owersfe4a50f653f9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hitpay.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hitpay.pyindex ef76b3d3542a..a7a75979c620 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hitpay.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hitpay.py@@ -1,9 +1,13 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass HitpaySourceConfig(config.Config):- pass+ api_key: str+ platform_api_key: str | None = None+ environment: Literal["production", "sandbox"] = config.value(default="production")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/canonical_descriptions.pynew file mode 100644index 000000000000..080d9ce436bb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/canonical_descriptions.py@@ -0,0 +1,120 @@+"""Canonical, documentation-sourced descriptions for HitPay endpoints and columns.++Sourced from the official HitPay API reference (https://docs.hitpayapp.com/reference). Keyed by+the resource names in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name` of a+synced HitPay 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 = {+ "PaymentRequests": {+ "description": "A payment link a merchant creates to collect a specific amount via card, PayNow, FPX, GrabPay, or another supported method.",+ "docs_url": "https://docs.hitpayapp.com/reference/get_payment-requests",+ "columns": {+ "id": "Unique identifier for the payment request.",+ "name": "Name of the customer the request was created for.",+ "email": "Email address the payment request was sent to.",+ "phone": "Phone number the payment request was sent to.",+ "amount": "Amount requested, as a decimal string in the request's currency.",+ "currency": "Three-letter currency code for the amount (e.g. sgd, myr).",+ "status": "Payment status: pending, completed, failed, expired, canceled, or inactive.",+ "purpose": "Free-text description of what the payment is for.",+ "reference_number": "Merchant-supplied reference number for the request.",+ "payment_methods": "Payment methods enabled for this request (e.g. card, paynow).",+ "url": "Hosted checkout URL the customer pays at.",+ "redirect_url": "URL the customer is redirected to after paying.",+ "webhook": "URL HitPay calls with payment status updates for this request.",+ "allow_repeated_payments": "Whether the same link can be paid more than once.",+ "expiry_date": "Date and time after which the request can no longer be paid.",+ "created_at": "Time the payment request was created.",+ "updated_at": "Time the payment request was last updated.",+ },+ },+ "Charges": {+ "description": "A completed attempt to collect payment, created from a payment request or another checkout flow.",+ "docs_url": "https://docs.hitpayapp.com/reference/get_charges",+ "columns": {+ "id": "Unique identifier for the charge.",+ "currency": "Three-letter currency code the charge was collected in.",+ "home_currency": "Three-letter currency code of the merchant's settlement currency.",+ "exchange_rate": "Exchange rate applied between the charge and home currency, if they differ.",+ "amount": "Amount collected, as a decimal in the charge's currency.",+ "fixed_fee": "Fixed processing fee charged by HitPay for this transaction.",+ "discount_fee": "Percentage-based processing fee charged by HitPay for this transaction.",+ "discount_fee_rate": "Percentage rate used to calculate discount_fee.",+ "remark": "Free-text note attached to the charge.",+ "status": "Charge status (e.g. succeeded, failed, refunded, partially_refunded, void).",+ "payment_method": "Payment method used, including card brand and last 4 digits where applicable.",+ "customer_id": "Identifier of the customer this charge belongs to, if any.",+ "payment_request_id": "Identifier of the payment request this charge fulfilled, if any.",+ "order_reference_number": "Merchant-supplied order reference associated with the charge.",+ "channel": "Origin of the charge (e.g. api, point of sale, checkout link).",+ "closed_at": "Time the charge was finalized (e.g. captured or settled).",+ "created_at": "Time the charge was created.",+ "updated_at": "Time the charge was last updated.",+ },+ },+ "SubscriptionPlans": {+ "description": "A recurring billing plan template merchants can subscribe customers to.",+ "docs_url": "https://docs.hitpayapp.com/reference/get_subscription-plan",+ "columns": {+ "id": "Unique identifier for the subscription plan.",+ "name": "Name of the plan.",+ "description": "Description of the plan.",+ "cycle": "Billing cycle type (e.g. daily, weekly, monthly, custom).",+ "cycle_repeat": "Number of cycle units between charges, for custom cycles.",+ "cycle_frequency": "Unit of the custom cycle (e.g. day, week, month).",+ "currency": "Three-letter currency code for the plan's price.",+ "price": "List price of the plan.",+ "amount": "Amount charged per billing cycle.",+ "reference": "Merchant-supplied reference for the plan.",+ "created_at": "Time the plan was created.",+ "updated_at": "Time the plan was last updated.",+ },+ },+ "Customers": {+ "description": "A saved customer record used to associate charges, payment requests, and recurring billing.",+ "docs_url": "https://docs.hitpayapp.com/reference/get_customers",+ "columns": {+ "id": "Unique identifier for the customer.",+ "name": "Customer's full name.",+ "email": "Customer's email address.",+ "phone_number": "Customer's phone number.",+ "phone_number_country_code": "Country code for the customer's phone number.",+ "birth_date": "Customer's date of birth.",+ "gender": "Customer's gender, if provided.",+ "address": "Customer's billing address (city, state, street, postal code, country).",+ "remark": "Free-text note attached to the customer.",+ "created_at": "Time the customer record was created.",+ "updated_at": "Time the customer record was last updated.",+ },+ },+ "RecurringBilling": {+ "description": "A recurring billing agreement charging a customer on a schedule, either from a subscription plan or a saved card.",+ "docs_url": "https://docs.hitpayapp.com/reference/get_recurring-billing",+ "columns": {+ "id": "Unique identifier for the recurring billing agreement.",+ "business_recurring_plans_id": "Identifier of the subscription plan this billing is based on, if any.",+ "customer_name": "Name of the customer being billed.",+ "customer_email": "Email address of the customer being billed.",+ "name": "Name of the recurring billing agreement.",+ "description": "Description of the recurring billing agreement.",+ "reference": "Merchant-supplied reference for the agreement.",+ "cycle": "Billing cycle type (e.g. daily, weekly, monthly, custom, save_card).",+ "cycle_repeat": "Number of cycle units between charges, for custom cycles.",+ "cycle_frequency": "Unit of the custom cycle (e.g. day, week, month).",+ "currency": "Three-letter currency code for the billed amount.",+ "price": "List price per billing cycle.",+ "amount": "Amount charged per billing cycle.",+ "times_to_be_charged": "Total number of charges planned for this agreement, if limited.",+ "times_charged": "Number of charges collected so far.",+ "status": "Agreement status: active, scheduled, retrying, inactive, or canceled.",+ "payment_methods": "Payment methods enabled for this agreement.",+ "created_at": "Time the agreement was created.",+ "updated_at": "Time the agreement was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/hitpay.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/hitpay.pynew file mode 100644index 000000000000..2846526521db--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/hitpay.py@@ -0,0 +1,242 @@+from collections.abc import Iterable+from typing import Any, Optional++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (+ coerce_datetime_to_utc,+)+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.auth import APIKeyAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ JSONResponseCursorPaginator,+ PageNumberPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ EndpointResource,+)+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.hitpay.settings import (+ HITPAY_ENDPOINTS,+ RECURRING_BILLING_STATUSES,+ HitpayEndpointConfig,+)++HITPAY_PRODUCTION_BASE_URL = "https://api.hit-pay.com"+HITPAY_SANDBOX_BASE_URL = "https://api.sandbox.hit-pay.com"+++@frozen+class HitpayResumeConfig:+ """Paginator checkpoint. Only one of the two is ever set, matching the endpoint's pagination+ kind (page-number for most endpoints, cursor for Charges)."""++ next_page: Optional[int] = None+ next_cursor: Optional[str] = None+++def base_url_for_environment(environment: Optional[str]) -> str:+ return HITPAY_SANDBOX_BASE_URL if environment == "sandbox" else HITPAY_PRODUCTION_BASE_URL+++def _extra_headers(platform_api_key: Optional[str]) -> dict[str, str]:+ headers = {"Accept": "application/json"}+ if platform_api_key:+ headers["X-PLATFORM-KEY"] = platform_api_key+ return headers+++def _redact_values(api_key: str, platform_api_key: Optional[str]) -> tuple[str, ...]:+ return tuple(value for value in (api_key, platform_api_key) if value)+++def _format_charge_date(value: Any) -> str:+ """Format the incremental watermark for Charges' `date_from` filter (YYYY-MM-DD, day granularity).++ Truncating to the day rounds the lower bound down, so a resumed sync re-reads the watermark+ day rather than skipping charges created later on it. The merge upsert dedupes the overlap.+ """+ normalized = coerce_datetime_to_utc(value)+ if normalized is None:+ return str(value)+ return normalized.strftime("%Y-%m-%d")+++def _incremental_param(cursor_path: str) -> dict[str, Any]:+ return {+ "type": "incremental",+ "cursor_path": cursor_path,+ "initial_value": "1970-01-01",+ "convert": _format_charge_date,+ }+++def _paginator_for(config: HitpayEndpointConfig) -> BasePaginator:+ if config.pagination == "cursor":+ return JSONResponseCursorPaginator(cursor_path="meta.next_cursor", cursor_param="cursor")+ if config.pagination == "page":+ return PageNumberPaginator(base_page=1, page_param=config.page_param, total_path="meta.last_page")+ return SinglePagePaginator()+++def get_resource(endpoint: str, should_use_incremental_field: bool) -> EndpointResource:+ config = HITPAY_ENDPOINTS[endpoint]+ is_incremental = bool(config.incremental_fields) and should_use_incremental_field++ params: dict[str, Any] = {}+ if is_incremental:+ params["date_from"] = _incremental_param("created_at")++ return {+ "name": endpoint,+ "table_name": config.table_name,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if is_incremental else "replace",+ "endpoint": {+ "data_selector": "data",+ "path": config.path,+ "params": params,+ "paginator": _paginator_for(config),+ },+ "table_format": "delta",+ }+++def _client_config(api_key: str, platform_api_key: Optional[str], environment: Optional[str]) -> ClientConfig:+ return {+ "base_url": base_url_for_environment(environment),+ "headers": _extra_headers(platform_api_key),+ "auth": APIKeyAuth(api_key=api_key, name="X-BUSINESS-API-KEY", location="header"),+ # Built explicitly (rather than left to RESTClient's default) so the optional+ # X-PLATFORM-KEY header value is also redacted from logged/sampled requests — the+ # framework auth object only knows about the business API key.+ "session": make_tracked_session(redact_values=_redact_values(api_key, platform_api_key)),+ # X-BUSINESS-API-KEY/X-PLATFORM-KEY are custom headers; `requests` doesn't strip them on+ # a cross-origin redirect, so refuse to follow one rather than replay the keys elsewhere.+ "allow_redirects": False,+ }+++def _recurring_billing_source(+ api_key: str,+ platform_api_key: Optional[str],+ environment: Optional[str],+) -> SourceResponse:+ config = HITPAY_ENDPOINTS["RecurringBilling"]+ client = RESTClient(+ base_url=base_url_for_environment(environment),+ headers=_extra_headers(platform_api_key),+ auth=APIKeyAuth(api_key=api_key, name="X-BUSINESS-API-KEY", location="header"),+ session=make_tracked_session(redact_values=_redact_values(api_key, platform_api_key)),+ allow_redirects=False,+ )++ def iterate_all_statuses() -> Iterable[list[dict[str, Any]]]:+ for status in RECURRING_BILLING_STATUSES:+ for page in client.paginate(+ path=config.path,+ params={"status": status},+ paginator=SinglePagePaginator(),+ data_selector="data",+ ):+ if page:+ yield page++ return SourceResponse(+ name="RecurringBilling",+ items=iterate_all_statuses,+ 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,+ )+++def hitpay_source(+ api_key: str,+ platform_api_key: Optional[str],+ environment: Optional[str],+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[HitpayResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+) -> SourceResponse:+ if endpoint == "RecurringBilling":+ return _recurring_billing_source(api_key, platform_api_key, environment)++ config = HITPAY_ENDPOINTS[endpoint]+ rest_config: RESTAPIConfig = {+ "client": _client_config(api_key, platform_api_key, environment),+ "resource_defaults": {},+ "resources": [get_resource(endpoint, should_use_incremental_field)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ if resume.next_page is not None:+ initial_paginator_state = {"page": resume.next_page}+ elif resume.next_cursor is not None:+ initial_paginator_state = {"cursor": resume.next_cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if not state:+ return+ if state.get("page") is not None:+ resumable_source_manager.save_state(HitpayResumeConfig(next_page=int(state["page"])))+ elif state.get("cursor") is not None:+ resumable_source_manager.save_state(HitpayResumeConfig(next_cursor=str(state["cursor"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ 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,+ column_hints=resource.column_hints,+ )+++def validate_credentials(+ api_key: str, platform_api_key: Optional[str], environment: Optional[str]+) -> tuple[bool, str | None]:+ headers = {"X-BUSINESS-API-KEY": api_key, **_extra_headers(platform_api_key)}+ is_valid, status_code = validate_via_probe(+ lambda: make_tracked_session(redact_values=_redact_values(api_key, platform_api_key)),+ f"{base_url_for_environment(environment)}/v1/account-status",+ headers=headers,+ # X-BUSINESS-API-KEY is a custom header; `requests` doesn't strip non-Authorization+ # headers on a cross-origin redirect, so refuse to follow one.+ allow_redirects=False,+ )+ if is_valid:+ return True, None+ if status_code == 401:+ return False, "Invalid HitPay API key. Check the key in your HitPay dashboard and try again."+ return False, "Could not connect to HitPay with the provided API key."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/settings.pynew file mode 100644index 000000000000..44e2af31b246--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/settings.py@@ -0,0 +1,86 @@+from dataclasses import field+from typing import Literal++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++PaginationKind = Literal["cursor", "page", "single"]+++def _created_at_incremental_fields() -> list[IncrementalField]:+ return [+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ]+++@frozen+class HitpayEndpointConfig:+ name: str+ table_name: str+ path: str+ pagination: PaginationKind = "page"+ # Query param carrying the page number. HitPay is not consistent across endpoints:+ # /v1/payment-requests uses `current_page`, everything else uses `page`.+ page_param: str = "page"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ partition_key: str | None = "created_at"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++HITPAY_ENDPOINTS: dict[str, HitpayEndpointConfig] = {+ "PaymentRequests": HitpayEndpointConfig(+ name="PaymentRequests",+ table_name="payment_requests",+ path="/v1/payment-requests",+ pagination="page",+ page_param="current_page",+ # No documented date/status-since filter for this endpoint, so it's full refresh only.+ ),+ "Charges": HitpayEndpointConfig(+ name="Charges",+ table_name="charges",+ path="/v1/charges",+ pagination="cursor",+ incremental_fields=_created_at_incremental_fields(),+ ),+ "SubscriptionPlans": HitpayEndpointConfig(+ name="SubscriptionPlans",+ table_name="subscription_plans",+ path="/v1/subscription-plan",+ pagination="page",+ page_param="page",+ ),+ "Customers": HitpayEndpointConfig(+ name="Customers",+ table_name="customers",+ path="/v1/customers",+ pagination="page",+ page_param="page",+ ),+ "RecurringBilling": HitpayEndpointConfig(+ name="RecurringBilling",+ table_name="recurring_billing",+ path="/v1/recurring-billing",+ # HitPay's OpenAPI spec documents no pagination params at all for this endpoint (unlike+ # every sibling list endpoint), so it's fetched as a single page per status filter below.+ pagination="single",+ ),+}++ENDPOINTS = tuple(HITPAY_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in HITPAY_ENDPOINTS.items()+}++# GET /v1/recurring-billing filters on `status` and defaults to "active" when the param is+# omitted, so a single unfiltered request would silently hide every canceled/inactive/scheduled/+# retrying subscription. The values are mutually exclusive, so requesting each one in turn covers+# the full table with no duplicate rows across requests.+RECURRING_BILLING_STATUSES = ("active", "scheduled", "retrying", "inactive", "canceled")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/source.pyindex d5a3fa659327..e49544e500e4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/source.py@@ -1,30 +1,152 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.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, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.hitpay import HitpaySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.hitpay.hitpay import (+ HitpayResumeConfig,+ hitpay_source,+ validate_credentials as validate_hitpay_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.hitpay.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class HitpaySource(SimpleSource[HitpaySourceConfig]):+class HitpaySource(ResumableSource[HitpaySourceConfig, HitpayResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # HitPay's API is served unversioned at /v1, with no other version ever documented or+ # offered — not a real version choice to pin.+ api_docs_url = "https://docs.hitpayapp.com/reference"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.HITPAY+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized": "Your HitPay API key is invalid or has been revoked. Please generate a new key and reconnect.",+ "403 Client Error: Forbidden": "Your HitPay API key does not have permission to access this data.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.hitpay.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: HitpaySourceConfig,+ 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: HitpaySourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_hitpay_credentials(config.api_key, config.platform_api_key, config.environment)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HitpayResumeConfig]:+ return ResumableSourceManager[HitpayResumeConfig](inputs, HitpayResumeConfig)++ def source_for_pipeline(+ self,+ config: HitpaySourceConfig,+ resumable_source_manager: ResumableSourceManager[HitpayResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return hitpay_source(+ api_key=config.api_key,+ platform_api_key=config.platform_api_key or None,+ environment=config.environment,+ 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,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.HITPAY,category=DataWarehouseSourceCategory.PAYMENTS___BILLING,- label="HitPay Payment Solutions Pte. Ltd.",+ label="HitPay",+ caption=(+ "Connect your HitPay account using an API key to sync payment requests, charges, "+ "subscription plans, customers, and recurring billing. Find your key in the HitPay "+ "dashboard under **Settings** > **Payment Gateway**."+ ),+ keywords=["payments", "paynow", "duitnow", "billing"],+ docsUrl="https://posthog.com/docs/cdp/sources/hitpay",iconPath="/static/services/hitpay.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="platform_api_key",+ label="Platform API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ caption="Only needed for HitPay platform accounts. Leave blank otherwise.",+ ),+ SourceFieldSelectConfig(+ name="environment",+ label="Environment",+ required=True,+ defaultValue="production",+ options=[+ SourceFieldSelectConfigOption(label="Production (api.hit-pay.com)", value="production"),+ SourceFieldSelectConfigOption(label="Sandbox (api.sandbox.hit-pay.com)", value="sandbox"),+ ],+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/tests/test_hitpay.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/tests/test_hitpay.pynew file mode 100644index 000000000000..8a5ef3243db6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/tests/test_hitpay.py@@ -0,0 +1,414 @@+import json+from datetime import UTC, date, datetime+from typing import Any, cast++from unittest import mock++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+ PageNumberPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.hitpay.hitpay import (+ HitpayResumeConfig,+ _format_charge_date,+ _paginator_for,+ base_url_for_environment,+ get_resource,+ hitpay_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.hitpay.settings import (+ HITPAY_ENDPOINTS,+ RECURRING_BILLING_STATUSES,+)++# RESTClient (and the hand-rolled RecurringBilling client) build their session via+# make_tracked_session, imported directly into the hitpay module.+SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.hitpay.hitpay.make_tracked_session"+VALIDATE_SESSION_PATCH = SESSION_PATCH+++class TestBaseUrlForEnvironment:+ @parameterized.expand(+ [+ ("production", "production", "https://api.hit-pay.com"),+ ("sandbox", "sandbox", "https://api.sandbox.hit-pay.com"),+ ("none_defaults_to_production", None, "https://api.hit-pay.com"),+ ("unknown_defaults_to_production", "staging", "https://api.hit-pay.com"),+ ]+ )+ def test_base_url(self, _name: str, environment: str | None, expected: str) -> None:+ assert base_url_for_environment(environment) == expected+++class TestFormatChargeDate:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04"),+ ("date_value", date(2026, 3, 4), "2026-03-04"),+ ("string_passthrough", "1970-01-01", "1970-01-01"),+ ]+ )+ def test_format(self, _name: str, value: Any, expected: str) -> None:+ assert _format_charge_date(value) == expected+++class TestPaginatorFor:+ def test_cursor_endpoint_gets_cursor_paginator(self) -> None:+ paginator = _paginator_for(HITPAY_ENDPOINTS["Charges"])+ assert isinstance(paginator, JSONResponseCursorPaginator)+ assert paginator.cursor_path == "meta.next_cursor"+ assert paginator.cursor_param == "cursor"++ def test_page_endpoint_gets_page_number_paginator_with_configured_param(self) -> None:+ paginator = _paginator_for(HITPAY_ENDPOINTS["PaymentRequests"])+ assert isinstance(paginator, PageNumberPaginator)+ assert paginator.page_param == "current_page"+ assert paginator.base_page == 1++ def test_single_endpoint_gets_single_page_paginator(self) -> None:+ assert isinstance(_paginator_for(HITPAY_ENDPOINTS["RecurringBilling"]), SinglePagePaginator)+++class TestGetResource:+ def test_full_refresh_endpoint_has_no_incremental_param(self) -> None:+ resource = cast(dict[str, Any], get_resource("Customers", should_use_incremental_field=True))+ assert resource["endpoint"]["params"] == {}+ assert resource["write_disposition"] == "replace"+ assert resource["endpoint"]["data_selector"] == "data"+ assert resource["endpoint"]["path"] == "/v1/customers"++ def test_incremental_endpoint_adds_date_from_when_enabled(self) -> None:+ resource = cast(dict[str, Any], get_resource("Charges", should_use_incremental_field=True))+ assert "date_from" in resource["endpoint"]["params"]+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}++ def test_incremental_endpoint_omits_date_from_when_disabled(self) -> None:+ resource = cast(dict[str, Any], get_resource("Charges", should_use_incremental_field=False))+ assert resource["endpoint"]["params"] == {}+ assert resource["write_disposition"] == "replace"++ def test_table_name_matches_settings(self) -> None:+ resource = cast(dict[str, Any], get_resource("SubscriptionPlans", should_use_incremental_field=False))+ assert resource["table_name"] == "subscription_plans"+++def _response(items: list[dict[str, Any]], *, extra: dict[str, Any] | None = None) -> Response:+ body: dict[str, Any] = {"data": items}+ if extra:+ body.update(extra)+ resp = Response()+ resp.status_code = 200+ resp._content = json.dumps(body).encode()+ return resp+++def _make_manager(resume_state: HitpayResumeConfig | 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]]:+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"url": request.url, "params": dict(request.params or {})})+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _rows(source_response: Any) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++class TestHitpaySourcePageNumberEndpoint:+ @mock.patch(SESSION_PATCH)+ def test_paginates_until_last_page(self, mock_make_session: mock.MagicMock) -> None:+ session = mock_make_session.return_value+ _wire(+ session,+ [+ _response([{"id": "1"}, {"id": "2"}], extra={"meta": {"last_page": 2}}),+ _response([{"id": "3"}], extra={"meta": {"last_page": 2}}),+ ],+ )++ rows = _rows(+ hitpay_source(+ api_key="key",+ platform_api_key=None,+ environment="production",+ endpoint="SubscriptionPlans",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ )++ assert [r["id"] for r in rows] == ["1", "2", "3"]+ assert session.send.call_count == 2++ @mock.patch(SESSION_PATCH)+ def test_saves_resume_state_only_while_pages_remain(self, mock_make_session: mock.MagicMock) -> None:+ session = mock_make_session.return_value+ _wire(+ session,+ [+ _response([{"id": "1"}], extra={"meta": {"last_page": 2}}),+ _response([{"id": "2"}], extra={"meta": {"last_page": 2}}),+ ],+ )+ manager = _make_manager()++ _rows(+ hitpay_source(+ api_key="key",+ platform_api_key=None,+ environment="production",+ endpoint="SubscriptionPlans",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ )++ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == HitpayResumeConfig(next_page=2)++ @mock.patch(SESSION_PATCH)+ def test_resumes_from_saved_page(self, mock_make_session: mock.MagicMock) -> None:+ session = mock_make_session.return_value+ snapshots = _wire(session, [_response([{"id": "2"}], extra={"meta": {"last_page": 2}})])++ rows = _rows(+ hitpay_source(+ api_key="key",+ platform_api_key=None,+ environment="production",+ endpoint="SubscriptionPlans",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(HitpayResumeConfig(next_page=2)),+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ )++ assert [r["id"] for r in rows] == ["2"]+ assert session.send.call_count == 1+ assert snapshots[0]["params"]["page"] == 2++ @mock.patch(SESSION_PATCH)+ def test_current_page_param_used_for_payment_requests(self, mock_make_session: mock.MagicMock) -> None:+ session = mock_make_session.return_value+ snapshots = _wire(session, [_response([{"id": "1"}], extra={"meta": {"last_page": 1}})])++ _rows(+ hitpay_source(+ api_key="key",+ platform_api_key=None,+ environment="production",+ endpoint="PaymentRequests",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ )++ assert "current_page" in snapshots[0]["params"]+ assert "page" not in snapshots[0]["params"]+++class TestHitpaySourceCursorEndpoint:+ @mock.patch(SESSION_PATCH)+ def test_paginates_via_cursor(self, mock_make_session: mock.MagicMock) -> None:+ session = mock_make_session.return_value+ _wire(+ session,+ [+ _response([{"id": "1"}], extra={"meta": {"next_cursor": "abc"}}),+ _response([{"id": "2"}], extra={"meta": {"next_cursor": None}}),+ ],+ )++ rows = _rows(+ hitpay_source(+ api_key="key",+ platform_api_key=None,+ environment="production",+ endpoint="Charges",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ )++ assert [r["id"] for r in rows] == ["1", "2"]+ assert session.send.call_count == 2++ @mock.patch(SESSION_PATCH)+ def test_saves_cursor_resume_state(self, mock_make_session: mock.MagicMock) -> None:+ session = mock_make_session.return_value+ _wire(+ session,+ [+ _response([{"id": "1"}], extra={"meta": {"next_cursor": "abc"}}),+ _response([{"id": "2"}], extra={"meta": {"next_cursor": None}}),+ ],+ )+ manager = _make_manager()++ _rows(+ hitpay_source(+ api_key="key",+ platform_api_key=None,+ environment="production",+ endpoint="Charges",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ )++ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == HitpayResumeConfig(next_cursor="abc")++ @mock.patch(SESSION_PATCH)+ def test_incremental_date_from_sent_when_enabled(self, mock_make_session: mock.MagicMock) -> None:+ session = mock_make_session.return_value+ snapshots = _wire(session, [_response([{"id": "1"}], extra={"meta": {"next_cursor": None}})])++ _rows(+ hitpay_source(+ api_key="key",+ platform_api_key=None,+ environment="production",+ endpoint="Charges",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ )++ assert snapshots[0]["params"]["date_from"] == "2026-03-04"+++class TestRecurringBillingFanOut:+ @mock.patch(SESSION_PATCH)+ def test_requests_every_status_and_concatenates_rows(self, mock_make_session: mock.MagicMock) -> None:+ session = mock_make_session.return_value+ responses = [_response([{"id": status}]) for status in RECURRING_BILLING_STATUSES]+ snapshots = _wire(session, responses)++ rows = _rows(+ hitpay_source(+ api_key="key",+ platform_api_key="platform-key",+ environment="production",+ endpoint="RecurringBilling",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ )++ assert [r["id"] for r in rows] == list(RECURRING_BILLING_STATUSES)+ assert session.send.call_count == len(RECURRING_BILLING_STATUSES)+ assert [s["params"]["status"] for s in snapshots] == list(RECURRING_BILLING_STATUSES)++ @mock.patch(SESSION_PATCH)+ def test_empty_status_pages_are_skipped(self, mock_make_session: mock.MagicMock) -> None:+ session = mock_make_session.return_value+ responses = [_response([]) for _ in RECURRING_BILLING_STATUSES]+ responses[0] = _response([{"id": "only-active"}])+ _wire(session, responses)++ rows = _rows(+ hitpay_source(+ api_key="key",+ platform_api_key=None,+ environment="production",+ endpoint="RecurringBilling",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ )++ assert [r["id"] for r in rows] == ["only-active"]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid", 200, True, None),+ ("invalid_key", 401, False, "Invalid HitPay API key"),+ ("forbidden", 403, False, "Could not connect to HitPay"),+ ("unreachable", None, False, "Could not connect to HitPay"),+ ]+ )+ @mock.patch(VALIDATE_SESSION_PATCH)+ def test_validate_credentials(+ self,+ _name: str,+ status_code: int | None,+ expected_valid: bool,+ expected_message_snippet: str | None,+ mock_make_session: mock.MagicMock,+ ) -> None:+ session = mock_make_session.return_value+ if status_code is None:+ session.get.side_effect = ConnectionError("boom")+ else:+ resp = Response()+ resp.status_code = status_code+ session.get.return_value = resp++ is_valid, message = validate_credentials("key", None, "production")++ assert is_valid is expected_valid+ if expected_message_snippet is None:+ assert message is None+ else:+ assert expected_message_snippet in (message or "")++ @mock.patch(VALIDATE_SESSION_PATCH)+ def test_sends_platform_key_header_when_provided(self, mock_make_session: mock.MagicMock) -> None:+ session = mock_make_session.return_value+ resp = Response()+ resp.status_code = 200+ session.get.return_value = resp++ validate_credentials("key", "platform-key", "sandbox")++ _, kwargs = session.get.call_args+ assert kwargs["headers"]["X-BUSINESS-API-KEY"] == "key"+ assert kwargs["headers"]["X-PLATFORM-KEY"] == "platform-key"+ assert session.get.call_args.args[0] == "https://api.sandbox.hit-pay.com/v1/account-status"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/tests/test_hitpay_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/tests/test_hitpay_source.pynew file mode 100644index 000000000000..669dca734697--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hitpay/tests/test_hitpay_source.py@@ -0,0 +1,185 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.hitpay import HitpaySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.hitpay.hitpay import HitpayResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.hitpay.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.hitpay.source import HitpaySource+from products.warehouse_sources.backend.types import ExternalDataSourceType++_INCREMENTAL_ENDPOINTS = {"Charges"}+_FULL_REFRESH_ENDPOINTS = {"PaymentRequests", "SubscriptionPlans", "Customers", "RecurringBilling"}+++class TestHitpaySource:+ def setup_method(self) -> None:+ self.source = HitpaySource()+ self.team_id = 123+ self.config = HitpaySourceConfig(api_key="key", environment="production")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.HITPAY++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Hitpay"+ assert config.label == "HitPay"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/hitpay.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/hitpay"++ field_names = [f.name for f in config.fields]+ assert field_names == ["api_key", "platform_api_key", "environment"]++ def test_api_key_field_is_secret_password_and_required(self) -> None:+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.secret is True+ assert api_key_field.required is True++ def test_platform_api_key_field_is_secret_but_optional(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "platform_api_key")+ assert field.secret is True+ assert field.required is False++ def test_environment_field_defaults_to_production(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig) and f.name == "environment")+ assert field.defaultValue == "production"+ assert {o.value for o in field.options} == {"production", "sandbox"}++ def test_lists_tables_without_credentials_publishes_catalog(self) -> None:+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(ENDPOINTS)++ def test_get_schemas_match_endpoints_with_correct_sync_modes(self) -> None:+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for name in _INCREMENTAL_ENDPOINTS:+ assert schemas[name].supports_incremental is True+ assert schemas[name].supports_append is True+ assert [f["field"] for f in schemas[name].incremental_fields] == ["created_at"]+ for name in _FULL_REFRESH_ENDPOINTS:+ assert schemas[name].supports_incremental is False+ assert schemas[name].supports_append is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Charges"])+ assert len(schemas) == 1+ assert schemas[0].name == "Charges"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @parameterized.expand(+ [+ ("401", "401 Client Error: Unauthorized for url: https://api.hit-pay.com/v1/charges"),+ ("403", "403 Client Error: Forbidden for url: https://api.hit-pay.com/v1/charges"),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, 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)++ @parameterized.expand(+ [+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.hit-pay.com/v1/charges"),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.hit-pay.com/v1/charges"),+ ("timeout", "HTTPSConnectionPool(host='api.hit-pay.com', port=443): Read timed out."),+ ]+ )+ def test_non_retryable_errors_do_not_match_transient(self, _name: str, 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_resumable_source_manager_bound_to_resume_config(self) -> None:+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is HitpayResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.hitpay.source.hitpay_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_hitpay_source: mock.MagicMock) -> None:+ config = HitpaySourceConfig(api_key="key", platform_api_key="platform-key", environment="sandbox")+ inputs = mock.MagicMock()+ inputs.schema_name = "Charges"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(config, manager, inputs)++ mock_hitpay_source.assert_called_once()+ kwargs = mock_hitpay_source.call_args.kwargs+ assert kwargs["api_key"] == "key"+ assert kwargs["platform_api_key"] == "platform-key"+ assert kwargs["environment"] == "sandbox"+ assert kwargs["endpoint"] == "Charges"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.hitpay.source.hitpay_source")+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_hitpay_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "PaymentRequests"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_hitpay_source.call_args.kwargs["db_incremental_field_last_value"] is None++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.hitpay.source.hitpay_source")+ def test_source_for_pipeline_blank_platform_key_becomes_none(self, mock_hitpay_source: mock.MagicMock) -> None:+ config = HitpaySourceConfig(api_key="key", platform_api_key="", environment="production")+ inputs = mock.MagicMock()+ inputs.schema_name = "Customers"+ inputs.should_use_incremental_field = False++ self.source.source_for_pipeline(config, mock.MagicMock(), inputs)++ assert mock_hitpay_source.call_args.kwargs["platform_api_key"] is None++ @pytest.mark.parametrize(+ ("probe_result", "expected_valid", "expected_message"),+ [+ ((True, None), True, None),+ (+ (False, "Invalid HitPay API key. Check the key in your HitPay dashboard and try again."),+ False,+ "Invalid HitPay API key",+ ),+ ((False, "Could not connect to HitPay with the provided API key."), False, "Could not connect to HitPay"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.hitpay.source.validate_hitpay_credentials"+ )+ def test_validate_credentials_delegates_and_maps_result(+ self, mock_validate, probe_result, expected_valid, expected_message+ ) -> None:+ mock_validate.return_value = probe_result++ is_valid, message = self.source.validate_credentials(self.config, self.team_id)++ mock_validate.assert_called_once_with("key", None, "production")+ assert is_valid is expected_valid+ if expected_message is None:+ assert message is None+ else:+ assert expected_message in (message or "")