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.

5.7 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.brex._config import BrexSourceConfig
from products.warehouse_sources.sources.brex.brex import (
    BREX_API_VERSION_V1,
    BREX_API_VERSION_V2,
    BrexResumeConfig,
    brex_source,
    validate_credentials as validate_brex_credentials,
)
from products.warehouse_sources.sources.brex.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    VersionDeprecation,
    build_endpoint_schemas,
    detect,
)


@SourceRegistry.register
class BrexSource(ResumableSource[BrexSourceConfig, BrexResumeConfig]):
    codebase_detection = detect(env=("^BREX_",))

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs
    api_docs_url = "https://developer.brex.com/changelog"

    supported_versions = (BREX_API_VERSION_V1, BREX_API_VERSION_V2)
    default_version = BREX_API_VERSION_V2
    # Brex deprecated its Spend Limits v1 endpoints in favor of the v2 Budgets API; the vendor
    # announced no sunset date. v1 stays supported so existing pins keep working, but carries the
    # deprecation flag so the generic in-product warning fires.
    deprecated_versions = (VersionDeprecation(version=BREX_API_VERSION_V1, sunset_at=None),)

    @property
    def source_type(self) -> ExternalDataSourceType:
        return ExternalDataSourceType.BREX

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.sources.brex.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.brex.com": "Brex authentication failed. Your API user token is invalid or has expired — Brex tokens expire after 90 days without API activity. Please generate a new token in your Brex dashboard and reconnect.",
            "403 Client Error: Forbidden for url: https://api.brex.com": "Brex denied access. Please check that your API user token has the required scopes for the tables you are syncing, and that the token's user is still active.",
        }

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.BREX,
            category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
            label="Brex",
            caption="""Enter your Brex API user token to pull your Brex data into the PostHog Data warehouse.

You can create a token in your [Brex dashboard](https://dashboard.brex.com/settings/developer) under Settings → Developer. Grant read access to the data you want to sync: Transactions and Accounts (card and cash transactions, card and cash accounts), Expenses, Team (users, departments, locations, titles, cost centers, cards), Payments (vendors, transfers), Budgets (budgets, budget programs, spend limits), and Fields (custom fields and their values).

Note: Brex tokens expire after 90 days without API activity, so a token that hasn't been used recently may need to be regenerated.""",
            iconPath="/static/services/brex.png",
            docsUrl="https://posthog.com/docs/cdp/sources/brex",
            releaseStatus=ReleaseStatus.BETA,
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API user token",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="bxt_...",
                        secret=True,
                    ),
                ],
            ),
        )

    def get_schemas(
        self,
        config: BrexSourceConfig,
        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: BrexSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
    ) -> tuple[bool, str | None]:
        if validate_brex_credentials(config.api_key):
            return True, None

        return False, "Invalid Brex API user token. Note that Brex tokens expire after 90 days without API activity."

    def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BrexResumeConfig]:
        return ResumableSourceManager[BrexResumeConfig](inputs, BrexResumeConfig)

    def source_for_pipeline(
        self,
        config: BrexSourceConfig,
        resumable_source_manager: ResumableSourceManager[BrexResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return brex_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,
            api_version=self.resolve_api_version(inputs.api_version),
            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,
        )