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.

6.3 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.invoiceninja._config import InvoiceninjaSourceConfig
from products.warehouse_sources.sources.invoiceninja.invoiceninja import (
    HOST_NOT_ALLOWED_ERROR,
    HTTP_NOT_ALLOWED_ERROR,
    InvoiceNinjaResumeConfig,
    invoiceninja_source,
    validate_credentials as validate_invoiceninja_credentials,
)
from products.warehouse_sources.sources.invoiceninja.settings import (
    ENDPOINTS,
    INCREMENTAL_FIELDS,
    INVOICENINJA_ENDPOINTS,
)
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    detect,
)


@SourceRegistry.register
class InvoiceninjaSource(ResumableSource[InvoiceninjaSourceConfig, InvoiceNinjaResumeConfig]):
    codebase_detection = detect(
        env=("^INVOICENINJA_",), composer=("invoiceninja/sdk-php", "invoiceninja/einvoice", "invoiceninja/ubl_invoice")
    )

    supported_versions = ("v1",)
    default_version = "v1"
    api_docs_url = "https://api-docs.invoicing.co"
    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs

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

    @property
    def connection_host_fields(self) -> list[str]:
        # `base_url` is where the stored API token is sent; retargeting it must re-require the token.
        return ["base_url"]

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error": "Invalid Invoice Ninja API token. Generate a new token in Settings > Account Management > Integrations > API tokens and reconnect.",
            "403 Client Error": "Your Invoice Ninja API token is invalid or lacks permission for this data. Check the token and try again.",
            HOST_NOT_ALLOWED_ERROR: "The Invoice Ninja API URL is not allowed. Please use a publicly reachable host.",
            HTTP_NOT_ALLOWED_ERROR: "The Invoice Ninja API URL must use HTTPS. Please update the API URL to use https://.",
        }

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.sources.invoiceninja.canonical_descriptions import (
            CANONICAL_DESCRIPTIONS,  # noqa: PLC0415
        )

        return CANONICAL_DESCRIPTIONS

    def get_schemas(
        self,
        config: InvoiceninjaSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        schemas = [
            SourceSchema(
                name=endpoint,
                supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),
                supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),
                incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
                should_sync_default=INVOICENINJA_ENDPOINTS[endpoint].should_sync_default,
            )
            for endpoint in ENDPOINTS
        ]
        if names is not None:
            names_set = set(names)
            schemas = [s for s in schemas if s.name in names_set]
        return schemas

    def validate_credentials(
        self,
        config: InvoiceninjaSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        return validate_invoiceninja_credentials(config.base_url, config.api_token, schema_name, team_id)

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

    def source_for_pipeline(
        self,
        config: InvoiceninjaSourceConfig,
        resumable_source_manager: ResumableSourceManager[InvoiceNinjaResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return invoiceninja_source(
            base_url=config.base_url,
            api_token=config.api_token,
            endpoint=inputs.schema_name,
            team_id=inputs.team_id,
            job_id=inputs.job_id,
            resumable_source_manager=resumable_source_manager,
            db_incremental_field_last_value=None,  # every Invoice Ninja endpoint is full refresh
        )

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.INVOICENINJA,
            category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
            label="Invoice Ninja",
            releaseStatus=ReleaseStatus.BETA,
            keywords=["invoice ninja", "invoicing", "billing"],
            caption="""Enter your Invoice Ninja API token to pull your invoicing data into the PostHog Data warehouse.

You can create an API token in Invoice Ninja under **Settings > Account Management > Integrations > API tokens**.

Self-hosted users should set the API URL to their own Invoice Ninja host (for example `https://invoices.example.com`). Leave it blank to use the hosted Invoice Ninja (`https://invoicing.co`).""",
            iconPath="/static/services/invoiceninja.png",
            docsUrl="https://posthog.com/docs/cdp/sources/invoiceninja",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_token",
                        label="API token",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        secret=True,
                    ),
                    SourceFieldInputConfig(
                        name="base_url",
                        label="API URL (self-hosted only)",
                        type=SourceFieldInputConfigType.TEXT,
                        required=False,
                        placeholder="https://invoicing.co",
                        secret=False,
                    ),
                ],
            ),
        )