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.

7.2 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.ramp._config import RampSourceConfig
from products.warehouse_sources.sources.ramp.ramp import (
    RampResumeConfig,
    check_endpoint_access,
    ramp_source,
    validate_credentials as validate_ramp_credentials,
)
from products.warehouse_sources.sources.ramp.settings import (
    DEFAULT_INCREMENTAL_LOOKBACK_SECONDS,
    ENDPOINTS,
    INCREMENTAL_FIELDS,
    SHOULD_SYNC_DEFAULT,
)
from products.warehouse_sources.sources.sdk import (
    OAUTH2_PERMANENT_ERROR_MARKER,
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceFieldSelectConfig,
    SourceFieldSelectConfigOption,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    build_endpoint_schemas,
    detect,
)


@SourceRegistry.register
class RampSource(ResumableSource[RampSourceConfig, RampResumeConfig]):
    codebase_detection = detect(env=("^RAMP_",))

    supported_versions = ("v1",)
    default_version = "v1"
    api_docs_url = "https://docs.ramp.com/developer-api/v1"

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs

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

    @property
    def connection_host_fields(self) -> list[str]:
        # ``environment`` picks api.ramp.com vs demo-api.ramp.com, so changing it retargets where the
        # stored client secret is sent — require re-entering secrets when it changes.
        return ["environment"]

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.sources.ramp.canonical_descriptions import CANONICAL_DESCRIPTIONS

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            # Permanent token-exchange failures (invalid_client, bad request, missing scopes, …)
            # all carry the framework's stable marker; transient 429/5xx token errors don't.
            OAUTH2_PERMANENT_ERROR_MARKER: "Ramp authentication failed. Please check your client ID and client secret (and that they match the selected environment and have the required read scopes).",
            "403 Client Error: Forbidden for url: https://api.ramp.com": "Ramp denied access. Please check that your developer app has the read scope for this dataset.",
            "403 Client Error: Forbidden for url: https://demo-api.ramp.com": "Ramp denied access. Please check that your developer app has the read scope for this dataset.",
        }

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.RAMP,
            category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
            label="Ramp",
            caption="""Connect your Ramp account to pull your spend data into the PostHog Data warehouse.

A Ramp admin can create a developer app under Settings > Developer API. Grant it the `transactions:read`, `reimbursements:read`, `users:read`, `cards:read`, and `departments:read` scopes (scopes are fixed at app creation) and enable client credentials, then enter the app's client ID and secret here.

To also sync billing statements, vendors, merchants, bills, general ledger accounts, locations, business entities, transfers, or statements, grant `billing_statements:read`, `vendors:read`, `merchants:read`, `bills:read`, `accounting:read`, `locations:read`, `entities:read`, `transfers:read`, or `statements:read` as well.""",
            iconPath="/static/services/ramp.png",
            docsUrl="https://posthog.com/docs/cdp/sources/ramp",
            releaseStatus=ReleaseStatus.GA,
            fields=cast(
                list[FieldType],
                [
                    SourceFieldSelectConfig(
                        name="environment",
                        label="Environment",
                        required=True,
                        defaultValue="production",
                        options=[
                            SourceFieldSelectConfigOption(label="Production", value="production"),
                            SourceFieldSelectConfigOption(label="Sandbox (demo)", value="sandbox"),
                        ],
                    ),
                    SourceFieldInputConfig(
                        name="client_id",
                        label="Client ID",
                        type=SourceFieldInputConfigType.TEXT,
                        required=True,
                        placeholder="ramp_id_...",
                        secret=False,
                    ),
                    SourceFieldInputConfig(
                        name="client_secret",
                        label="Client secret",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="ramp_sec_...",
                        secret=True,
                    ),
                ],
            ),
        )

    def get_schemas(
        self,
        config: RampSourceConfig,
        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,
            should_sync_default=SHOULD_SYNC_DEFAULT,
            default_incremental_lookback_seconds=DEFAULT_INCREMENTAL_LOOKBACK_SECONDS,
        )

    def validate_credentials(
        self, config: RampSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
    ) -> tuple[bool, str | None]:
        return validate_ramp_credentials(config.environment, config.client_id, config.client_secret, schema_name)

    def get_endpoint_permissions(
        self, config: RampSourceConfig, team_id: int, endpoints: list[str], api_version: str | None = None
    ) -> dict[str, str | None]:
        return {
            endpoint: check_endpoint_access(config.environment, config.client_id, config.client_secret, endpoint)
            for endpoint in endpoints
        }

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

    def source_for_pipeline(
        self,
        config: RampSourceConfig,
        resumable_source_manager: ResumableSourceManager[RampResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return ramp_source(
            environment=config.environment,
            client_id=config.client_id,
            client_secret=config.client_secret,
            endpoint=inputs.schema_name,
            team_id=inputs.team_id,
            job_id=inputs.job_id,
            resumable_source_manager=resumable_source_manager,
            should_use_incremental_field=inputs.should_use_incremental_field,
            db_incremental_field_last_value=inputs.db_incremental_field_last_value
            if inputs.should_use_incremental_field
            else None,
        )