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 Asaas import source (#84289)

Tom Owers6f00a62d5d58
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/asaas.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/asaas.py
new file mode 100644
index 000000000000..c89d8ee40960
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/asaas.py
@@ -0,0 +1,143 @@
+from datetime import date, datetime
+from typing import Any, Optional
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.asaas.settings import (
+ INCREMENTAL_DATE_PARAM,
+ INCREMENTAL_FIELDS,
+ TABLE_NAMES,
+)
+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 (
+ OffsetPaginator,
+)
+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
+
+SANDBOX_BASE_URL = "https://api-sandbox.asaas.com"
+PRODUCTION_BASE_URL = "https://api.asaas.com"
+API_PATH = "/v3"
+
+# Asaas caps list endpoints at 100 rows/page (offset/limit + hasMore/totalCount envelope).
+PAGE_SIZE = 100
+
+
+@frozen
+class AsaasResumeConfig:
+ offset: int
+
+
+def base_url(environment: str) -> str:
+ return PRODUCTION_BASE_URL if environment == "production" else SANDBOX_BASE_URL
+
+
+def format_date_param(value: Any) -> str:
+ """Format an incremental watermark for Asaas's `dateCreated[ge]` filter (`YYYY-MM-DD`)."""
+ if isinstance(value, datetime):
+ return value.date().isoformat()
+ if isinstance(value, date):
+ return value.isoformat()
+ return str(value)[:10]
+
+
+def get_resource(endpoint: str, should_use_incremental_field: bool) -> EndpointResource:
+ table_name = TABLE_NAMES[endpoint]
+ is_incremental_endpoint = should_use_incremental_field and endpoint in INCREMENTAL_FIELDS
+
+ params: dict[str, Any] = {}
+ if is_incremental_endpoint:
+ params[INCREMENTAL_DATE_PARAM] = {
+ "type": "incremental",
+ "cursor_path": "dateCreated",
+ # Well before Asaas existed, so an unset watermark still fetches full history.
+ "initial_value": "2000-01-01",
+ "convert": format_date_param,
+ }
+
+ return {
+ "name": endpoint,
+ "table_name": table_name,
+ "write_disposition": {
+ "disposition": "merge",
+ "strategy": "upsert",
+ }
+ if is_incremental_endpoint
+ else "replace",
+ "endpoint": {
+ "data_selector": "data[*]",
+ "path": f"{API_PATH}/{table_name}",
+ "params": params,
+ },
+ "table_format": "delta",
+ }
+
+
+def asaas_source(
+ api_key: str,
+ environment: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[AsaasResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+ should_use_incremental_field: bool = False,
+):
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": base_url(environment),
+ "auth": {
+ "type": "api_key",
+ "name": "access_token",
+ "api_key": api_key,
+ "location": "header",
+ },
+ "paginator": OffsetPaginator(limit=PAGE_SIZE, total_path="totalCount"),
+ # Reject redirects: the `access_token` header must never be replayed onto
+ # a host other than the one it was issued for.
+ "allow_redirects": False,
+ },
+ "resource_defaults": {
+ "write_disposition": {
+ "disposition": "merge",
+ "strategy": "upsert",
+ }
+ if should_use_incremental_field
+ else "replace",
+ },
+ "resources": [get_resource(endpoint, should_use_incremental_field)],
+ }
+
+ 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 = {"offset": resume_config.offset}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup on completion.
+ if state and state.get("offset") is not None:
+ resumable_source_manager.save_state(AsaasResumeConfig(offset=int(state["offset"])))
+
+ 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, environment: str) -> bool:
+ # allow_redirects=False: a redirect would forward the access_token header off
+ # the validated Asaas host.
+ res = make_tracked_session(redact_values=(api_key,), allow_redirects=False).get(
+ f"{base_url(environment)}{API_PATH}/customers?limit=1",
+ headers={"access_token": api_key},
+ )
+ return res.status_code == 200
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/canonical_descriptions.py
new file mode 100644
index 000000000000..495eb9a6a409
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/canonical_descriptions.py
@@ -0,0 +1,123 @@
+"""Canonical, documentation-sourced descriptions for Asaas endpoints and columns.
+
+Sourced from the official Asaas API v3 reference (https://docs.asaas.com). Keyed by the
+resource names in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name` of a
+synced Asaas 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 = {
+ "Customers": {
+ "description": "A customer (payer) registered in the Asaas account, who owns charges and subscriptions.",
+ "docs_url": "https://docs.asaas.com/reference/listar-clientes",
+ "columns": {
+ "id": "Unique identifier of the customer.",
+ "name": "Customer's full name.",
+ "email": "Customer's email address.",
+ "phone": "Customer's landline phone number.",
+ "mobilePhone": "Customer's mobile phone number.",
+ "cpfCnpj": "Customer's CPF (individual) or CNPJ (company) document number.",
+ "personType": "Whether the customer is an individual (FISICA) or a company (JURIDICA).",
+ "dateCreated": "Date the customer was created (YYYY-MM-DD).",
+ "address": "Customer's street address.",
+ "addressNumber": "Street number of the customer's address.",
+ "complement": "Additional address details (apartment, suite, etc.).",
+ "province": "Neighborhood of the customer's address.",
+ "city": "City code of the customer's address.",
+ "cityName": "City name of the customer's address.",
+ "state": "State (UF) of the customer's address.",
+ "postalCode": "Postal code (CEP) of the customer's address.",
+ "externalReference": "Identifier for this customer in the caller's own system.",
+ "observations": "Free-text notes about the customer.",
+ "deleted": "Whether the customer has been deleted.",
+ "foreignCustomer": "Whether the customer is a foreign resident without a CPF/CNPJ.",
+ },
+ },
+ "Payments": {
+ "description": "A charge (cobrança) — a single boleto, Pix, or credit card payment request.",
+ "docs_url": "https://docs.asaas.com/reference/listar-cobrancas",
+ "columns": {
+ "id": "Unique identifier of the charge.",
+ "customer": "Identifier of the customer being charged.",
+ "subscription": "Identifier of the subscription this charge belongs to, if any.",
+ "installment": "Identifier of the installment plan this charge belongs to, if any.",
+ "value": "Charge amount, in BRL.",
+ "netValue": "Amount received after Asaas fees, in BRL.",
+ "billingType": "Payment method: BOLETO, CREDIT_CARD, DEBIT_CARD, PIX, TRANSFER, DEPOSIT, or UNDEFINED.",
+ "status": "Current status of the charge (PENDING, RECEIVED, CONFIRMED, OVERDUE, REFUNDED, etc.).",
+ "dueDate": "Date the charge is due (YYYY-MM-DD).",
+ "originalDueDate": "Original due date before any renegotiation (YYYY-MM-DD).",
+ "paymentDate": "Date the charge was actually paid (YYYY-MM-DD), if paid.",
+ "clientPaymentDate": "Date the payment was confirmed to the customer (YYYY-MM-DD).",
+ "dateCreated": "Date the charge was created (YYYY-MM-DD).",
+ "description": "Free-text description of the charge shown to the customer.",
+ "invoiceNumber": "Sequential invoice number assigned by Asaas.",
+ "invoiceUrl": "URL of the hosted invoice/payment page for this charge.",
+ "externalReference": "Identifier for this charge in the caller's own system.",
+ "discount": "Discount configuration applied to the charge, if any.",
+ "fine": "Late-payment fine configuration applied to the charge, if any.",
+ "interest": "Late-payment interest configuration applied to the charge, if any.",
+ "deleted": "Whether the charge has been deleted.",
+ },
+ },
+ "Subscriptions": {
+ "description": "A recurring billing plan (assinatura) that generates charges on a fixed cycle.",
+ "docs_url": "https://docs.asaas.com/reference/listar-assinaturas",
+ "columns": {
+ "id": "Unique identifier of the subscription.",
+ "customer": "Identifier of the customer subscribed.",
+ "billingType": "Payment method used for generated charges.",
+ "cycle": "Billing cycle (WEEKLY, MONTHLY, YEARLY, etc.).",
+ "value": "Amount charged on each cycle, in BRL.",
+ "nextDueDate": "Due date of the next charge to be generated (YYYY-MM-DD).",
+ "endDate": "Date the subscription ends and stops generating charges (YYYY-MM-DD), if set.",
+ "description": "Free-text description shown on generated charges.",
+ "status": "Subscription status: ACTIVE, EXPIRED, or INACTIVE.",
+ "dateCreated": "Date the subscription was created (YYYY-MM-DD).",
+ "maxPayments": "Maximum number of charges this subscription will generate, if capped.",
+ "externalReference": "Identifier for this subscription in the caller's own system.",
+ "deleted": "Whether the subscription has been deleted.",
+ },
+ },
+ "Transfers": {
+ "description": "A transfer of funds from the Asaas account balance to a bank account or Pix key.",
+ "docs_url": "https://docs.asaas.com/reference/listar-transferencias",
+ "columns": {
+ "id": "Unique identifier of the transfer.",
+ "type": "Transfer rail used: PIX, TED, or INTERNAL.",
+ "value": "Transfer amount, in BRL.",
+ "netValue": "Amount received after any transfer fee, in BRL.",
+ "transferFee": "Fee charged by Asaas for the transfer, in BRL.",
+ "status": "Current status of the transfer.",
+ "dateCreated": "Date the transfer was requested (YYYY-MM-DD).",
+ "effectiveDate": "Date the transfer was completed (YYYY-MM-DD), if completed.",
+ "scheduleDate": "Date the transfer is scheduled to run (YYYY-MM-DD), if scheduled.",
+ "endToEndIdentifier": "End-to-end identifier of the underlying Pix transaction, if applicable.",
+ "authorized": "Whether the transfer has been authorized.",
+ "failReason": "Reason the transfer failed, if it did.",
+ "externalReference": "Identifier for this transfer in the caller's own system.",
+ "operationType": "Direction/kind of the balance operation the transfer represents.",
+ },
+ },
+ "Installments": {
+ "description": "An installment plan (parcelamento) grouping the charges of a single sale paid over time.",
+ "docs_url": "https://docs.asaas.com/reference/listar-parcelamentos",
+ "columns": {
+ "id": "Unique identifier of the installment plan.",
+ "customer": "Identifier of the customer being charged.",
+ "value": "Total value of the installment plan, in BRL.",
+ "netValue": "Total amount received after Asaas fees, in BRL.",
+ "paymentValue": "Value of each individual installment charge, in BRL.",
+ "installmentCount": "Number of charges the plan is split into.",
+ "billingType": "Payment method used for the installment charges.",
+ "paymentDate": "Date the first installment charge is due (YYYY-MM-DD).",
+ "description": "Free-text description shown on the installment charges.",
+ "dateCreated": "Date the installment plan was created (YYYY-MM-DD).",
+ "expirationDay": "Day of the month each installment charge is due.",
+ "deleted": "Whether the installment plan has been deleted.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/settings.py
new file mode 100644
index 000000000000..6b150af27a11
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/settings.py
@@ -0,0 +1,52 @@
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Maps our schema/endpoint name to the API resource path segment and merge primary key.
+# All ids are account-wide unique (no fan-out), so every endpoint uses a plain "id" key.
+ENDPOINTS = (
+ "Customers",
+ "Payments",
+ "Subscriptions",
+ "Transfers",
+ "Installments",
+)
+
+TABLE_NAMES: dict[str, str] = {
+ "Customers": "customers",
+ "Payments": "payments",
+ "Subscriptions": "subscriptions",
+ "Transfers": "transfers",
+ "Installments": "installments",
+}
+
+# A stable, never-mutated per-row field to partition on for every endpoint.
+PARTITION_KEYS: dict[str, str] = {
+ "Customers": "dateCreated",
+ "Payments": "dateCreated",
+ "Subscriptions": "dateCreated",
+ "Transfers": "dateCreated",
+ "Installments": "dateCreated",
+}
+
+# Only endpoints that document a server-side `dateCreated[ge]` range filter are incremental.
+# Customers, Subscriptions, and Installments only accept `offset`/`limit` plus non-date
+# filters, so a client-side "since" cursor there would still re-fetch every page every run.
+INCREMENTAL_DATE_PARAM = "dateCreated[ge]"
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "Payments": [
+ {
+ "label": "dateCreated",
+ "type": IncrementalFieldType.Date,
+ "field": "dateCreated",
+ "field_type": IncrementalFieldType.Date,
+ },
+ ],
+ "Transfers": [
+ {
+ "label": "dateCreated",
+ "type": IncrementalFieldType.Date,
+ "field": "dateCreated",
+ "field_type": IncrementalFieldType.Date,
+ },
+ ],
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/source.py
index a49efbd103a0..945fa12b7491 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/source.py
@@ -1,30 +1,152 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.asaas.asaas import (
+ AsaasResumeConfig,
+ asaas_source,
+ validate_credentials as validate_asaas_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.asaas.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.asaas import AsaasSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AsaasSource(SimpleSource[AsaasSourceConfig]):
+class AsaasSource(ResumableSource[AsaasSourceConfig, AsaasResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ supported_versions = ("v3",)
+ default_version = "v3"
+ api_docs_url = "https://docs.asaas.com/reference/comece-por-aqui"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ASAAS
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your Asaas API key is invalid or expired. Please generate a new key and reconnect.",
+ "403 Client Error": "Your Asaas API key doesn't have permission for this request. Check the key's account and try again.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.asaas.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AsaasSourceConfig,
+ 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: AsaasSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if validate_asaas_credentials(config.api_key, config.environment):
+ return True, None
+
+ return False, "Invalid credentials"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AsaasResumeConfig]:
+ return ResumableSourceManager[AsaasResumeConfig](inputs, AsaasResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AsaasSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AsaasResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ resource = asaas_source(
+ api_key=config.api_key,
+ 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,
+ )
+ return SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=["id"],
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=["dateCreated"],
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.ASAAS,
category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
label="Asaas",
+ caption=(
+ "Connect your Asaas account using an API key to sync customers, payments, "
+ "subscriptions, transfers, and installments. Find your key in Asaas under "
+ "**Integrações** > **API**."
+ ),
+ keywords=["billing", "payments", "brazil"],
iconPath="/static/services/asaas.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,
+ ),
+ SourceFieldSelectConfig(
+ name="environment",
+ label="Environment",
+ required=True,
+ defaultValue="production",
+ options=[
+ SourceFieldSelectConfigOption(label="Production (api.asaas.com)", value="production"),
+ SourceFieldSelectConfigOption(label="Sandbox (api-sandbox.asaas.com)", value="sandbox"),
+ ],
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/tests/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/tests/test_asaas.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/tests/test_asaas.py
new file mode 100644
index 000000000000..93e9eadeb79a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/tests/test_asaas.py
@@ -0,0 +1,349 @@
+from datetime import UTC, date, datetime
+from typing import cast
+
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.asaas.asaas import (
+ PRODUCTION_BASE_URL,
+ SANDBOX_BASE_URL,
+ AsaasResumeConfig,
+ asaas_source,
+ base_url,
+ format_date_param,
+ get_resource,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.asaas.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.asaas.source import AsaasSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpoint
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.asaas import AsaasSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_INCREMENTAL_ENDPOINTS = {"Payments", "Transfers"}
+_FULL_REFRESH_ENDPOINTS = {"Customers", "Subscriptions", "Installments"}
+
+VALIDATE_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.asaas.source.validate_asaas_credentials"
+)
+ASAAS_SOURCE_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.asaas.source.asaas_source"
+REST_API_RESOURCE_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.asaas.asaas.rest_api_resource"
+)
+SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.asaas.asaas.make_tracked_session"
+
+
+class TestBaseUrl:
+ @parameterized.expand(
+ [
+ ("production", PRODUCTION_BASE_URL),
+ ("sandbox", SANDBOX_BASE_URL),
+ ("unknown_defaults_to_sandbox", SANDBOX_BASE_URL),
+ ]
+ )
+ def test_resolves_environment(self, environment: str, expected: str) -> None:
+ assert base_url(environment) == expected
+
+
+class TestFormatDateParam:
+ @parameterized.expand(
+ [
+ ("datetime_utc", datetime(2026, 1, 15, 10, 30, tzinfo=UTC), "2026-01-15"),
+ ("naive_datetime", datetime(2026, 1, 15, 10, 30), "2026-01-15"),
+ ("date_object", date(2026, 1, 15), "2026-01-15"),
+ ("date_string_passthrough", "2026-01-15", "2026-01-15"),
+ ("datetime_string_truncated", "2026-01-15T10:30:00Z", "2026-01-15"),
+ ]
+ )
+ def test_formats_to_date_only_string(self, _name: str, value, expected: str) -> None:
+ assert format_date_param(value) == expected
+
+
+class TestGetResource:
+ @parameterized.expand(sorted(_INCREMENTAL_ENDPOINTS))
+ def test_incremental_endpoint_adds_date_filter_when_requested(self, endpoint: str) -> None:
+ resource = get_resource(endpoint, should_use_incremental_field=True)
+
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+ endpoint_config = cast(Endpoint, resource["endpoint"])
+ params = endpoint_config["params"]
+ assert params is not None
+ assert "dateCreated[ge]" in params
+ assert params["dateCreated[ge]"]["type"] == "incremental"
+
+ @parameterized.expand(sorted(_INCREMENTAL_ENDPOINTS))
+ def test_incremental_endpoint_omits_filter_when_not_requested(self, endpoint: str) -> None:
+ resource = get_resource(endpoint, should_use_incremental_field=False)
+
+ assert resource["write_disposition"] == "replace"
+ endpoint_config = cast(Endpoint, resource["endpoint"])
+ assert endpoint_config["params"] == {}
+
+ @parameterized.expand(sorted(_FULL_REFRESH_ENDPOINTS))
+ def test_full_refresh_endpoint_never_adds_date_filter(self, endpoint: str) -> None:
+ # These endpoints don't document a server-side date filter; requesting incremental
+ # must not fabricate one that the API would silently ignore or reject.
+ resource = get_resource(endpoint, should_use_incremental_field=True)
+
+ assert resource["write_disposition"] == "replace"
+ endpoint_config = cast(Endpoint, resource["endpoint"])
+ assert endpoint_config["params"] == {}
+
+ def test_path_and_selector_match_every_endpoint(self) -> None:
+ for endpoint in ENDPOINTS:
+ resource = get_resource(endpoint, should_use_incremental_field=False)
+ endpoint_config = cast(Endpoint, resource["endpoint"])
+ assert endpoint_config["data_selector"] == "data[*]"
+ path = endpoint_config["path"]
+ assert path is not None
+ assert path.startswith("/v3/")
+ assert resource["table_format"] == "delta"
+
+
+class TestAsaasSourceResumeBehavior:
+ """`asaas_source` plumbing: resume seeding and checkpoint persistence."""
+
+ def _run(self, manager: mock.MagicMock, *, should_use_incremental_field: bool = False):
+ with mock.patch(REST_API_RESOURCE_PATCH) as mock_rest_api_resource:
+ mock_rest_api_resource.return_value = mock.MagicMock(name="Payments")
+ asaas_source(
+ api_key="test-key",
+ environment="production",
+ endpoint="Payments",
+ team_id=123,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=None,
+ should_use_incremental_field=should_use_incremental_field,
+ )
+ return mock_rest_api_resource
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ mock_rest_api_resource = self._run(manager)
+
+ manager.load_state.assert_not_called()
+ assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] is None
+
+ def test_seeds_initial_offset_from_saved_state(self) -> None:
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = AsaasResumeConfig(offset=200)
+
+ mock_rest_api_resource = self._run(manager)
+
+ assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] == {"offset": 200}
+
+ def test_resume_hook_saves_offset_when_present(self) -> None:
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ mock_rest_api_resource = self._run(manager)
+ resume_hook = mock_rest_api_resource.call_args.kwargs["resume_hook"]
+
+ resume_hook({"offset": 300})
+
+ manager.save_state.assert_called_once_with(AsaasResumeConfig(offset=300))
+
+ def test_resume_hook_skips_save_on_terminal_page(self) -> None:
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ mock_rest_api_resource = self._run(manager)
+ resume_hook = mock_rest_api_resource.call_args.kwargs["resume_hook"]
+
+ resume_hook(None)
+
+ manager.save_state.assert_not_called()
+
+ @parameterized.expand([("production", PRODUCTION_BASE_URL), ("sandbox", SANDBOX_BASE_URL)])
+ def test_client_config_targets_the_selected_environment(self, environment: str, expected_base_url: str) -> None:
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ with mock.patch(REST_API_RESOURCE_PATCH) as mock_rest_api_resource:
+ mock_rest_api_resource.return_value = mock.MagicMock()
+ asaas_source(
+ api_key="test-key",
+ environment=environment,
+ endpoint="Payments",
+ team_id=123,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=None,
+ )
+ config = mock_rest_api_resource.call_args.args[0]
+ assert config["client"]["base_url"] == expected_base_url
+ assert config["client"]["auth"] == {
+ "type": "api_key",
+ "name": "access_token",
+ "api_key": "test-key",
+ "location": "header",
+ }
+
+
+class TestValidateCredentials:
+ @parameterized.expand([(200, True), (401, False), (403, False)])
+ def test_status_code_maps_to_validity(self, status_code: int, expected: bool) -> None:
+ with mock.patch(SESSION_PATCH) as mock_make_session:
+ mock_response = mock.MagicMock()
+ mock_response.status_code = status_code
+ mock_make_session.return_value.get.return_value = mock_response
+
+ assert validate_credentials("test-key", "production") is expected
+
+ def test_requests_the_selected_environment_host(self) -> None:
+ with mock.patch(SESSION_PATCH) as mock_make_session:
+ mock_response = mock.MagicMock()
+ mock_response.status_code = 200
+ mock_make_session.return_value.get.return_value = mock_response
+
+ validate_credentials("test-key", "sandbox")
+
+ called_url = mock_make_session.return_value.get.call_args.args[0]
+ assert called_url.startswith(SANDBOX_BASE_URL)
+ headers = mock_make_session.return_value.get.call_args.kwargs["headers"]
+ assert headers == {"access_token": "test-key"}
+
+
+class TestAsaasSource:
+ def setup_method(self) -> None:
+ self.source = AsaasSource()
+ self.team_id = 123
+ self.config = AsaasSourceConfig(api_key="test-key", environment="production")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.ASAAS
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Asaas"
+ assert config.label == "Asaas"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/asaas.png"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["api_key", "environment"]
+
+ def test_api_key_field_is_secret_password(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.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+
+ def test_environment_field_defaults_to_production(self) -> None:
+ config = self.source.get_source_config
+ environment_field = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig))
+ assert environment_field.defaultValue == "production"
+ assert {option.value for option in environment_field.options} == {"production", "sandbox"}
+
+ def test_api_version_metadata(self) -> None:
+ assert self.source.supported_versions == ("v3",)
+ assert self.source.default_version == "v3"
+ assert self.source.api_docs_url is not None and self.source.api_docs_url.startswith("https://")
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.asaas.com/v3/customers?limit=1",
+ "403 Client Error: Forbidden for url: https://api.asaas.com/v3/payments?limit=100",
+ ],
+ )
+ 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",
+ [
+ "429 Client Error: Too Many Requests for url: https://api.asaas.com/v3/payments",
+ "500 Server Error: Internal Server Error for url: https://api.asaas.com/v3/payments",
+ ],
+ )
+ def test_non_retryable_errors_do_not_match_transient(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_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] == ["dateCreated"]
+ 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=["Payments"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "Payments"
+
+ 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_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)
+ for endpoint in ENDPOINTS:
+ assert canonical[endpoint]["columns"].get("id")
+
+ @parameterized.expand([(True, True, None), (False, False, "Invalid credentials")])
+ def test_validate_credentials(self, mock_return: bool, expected_valid: bool, expected_message) -> None:
+ with mock.patch(VALIDATE_PATCH, return_value=mock_return) as mock_validate:
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert (is_valid, error_message) == (expected_valid, expected_message)
+ mock_validate.assert_called_once_with("test-key", "production")
+
+ 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 AsaasResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Payments"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01"
+ manager = mock.MagicMock()
+
+ with mock.patch(ASAAS_SOURCE_PATCH) as mock_asaas_source:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_asaas_source.assert_called_once()
+ kwargs = mock_asaas_source.call_args.kwargs
+ assert kwargs["api_key"] == "test-key"
+ assert kwargs["environment"] == "production"
+ assert kwargs["endpoint"] == "Payments"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01"
+
+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Customers"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01"
+
+ with mock.patch(ASAAS_SOURCE_PATCH) as mock_asaas_source:
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_asaas_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/asaas.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/asaas.py
index 4274ae43be32..d3a5d96c9dc7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/asaas.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/asaas.py
@@ -1,9 +1,12 @@
# This file is automatically generated from `SourceRegistry.get_all_sources()`
# Do not edit manually - run `pnpm generate:source-configs` to regenerate.
+from typing import Literal
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
@config.config
class AsaasSourceConfig(config.Config):
- pass
+ api_key: str
+ environment: Literal["production", "sandbox"] = config.value(default="production")