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.2 KB
Raw Blame
import datetime
from typing import Optional, cast

from products.warehouse_sources.sources.payfit._config import PayFitSourceConfig
from products.warehouse_sources.sources.payfit.payfit import (
    PayFitResumeConfig,
    check_schema_access,
    payfit_source,
    validate_credentials,
)
from products.warehouse_sources.sources.payfit.settings import (
    ENDPOINTS,
    INCREMENTAL_FIELDS,
    MONTHLY_HISTORY_LOOKBACK,
    PAYFIT_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 PayFitSource(ResumableSource[PayFitSourceConfig, PayFitResumeConfig]):
    codebase_detection = detect(env=("^(PAY_FIT|PAYFIT)_",))

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs
    api_docs_url = "https://developers.payfit.io/reference/"

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

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.PAYFIT,
            category=DataWarehouseSourceCategory.HR___RECRUITING,
            label="PayFit",
            releaseStatus=ReleaseStatus.BETA,
            caption="""Enter your PayFit API key to pull your HR and payroll data into the PostHog Data warehouse.

You can create an API key from the **API access** tab on the [integrations page](https://app.payfit.com/integrations/hub/api) of your PayFit admin account. Grant it the `collaborators:read`, `contracts:read`, `time:read`, `contracts:payslips:read`, and `accounting:read` scopes so every table can sync. The `accounting_entries` and `contracts_worked_time` tables are only available for companies based in France.
""",
            iconPath="/static/services/payfit.png",
            docsUrl="https://posthog.com/docs/cdp/sources/payfit",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        secret=True,
                    ),
                ],
            ),
        )

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

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error: Unauthorized for url: https://partner-api.payfit.com": "Your PayFit API key is invalid or has been revoked. Create a new key under Integrations → API access in PayFit, then reconnect.",
            "403 Client Error: Forbidden for url: https://partner-api.payfit.com": "Your PayFit API key is missing a scope this table needs. Create a key with the collaborators:read, contracts:read, time:read, contracts:payslips:read, and accounting:read scopes, then reconnect.",
            "PayFit API key is inactive or invalid": "Your PayFit API key is invalid or has been revoked. Create a new key under Integrations → API access in PayFit, then reconnect.",
        }

    def get_schemas(
        self,
        config: PayFitSourceConfig,
        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=endpoint in INCREMENTAL_FIELDS,
                supports_append=False,
                incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
            )
            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: PayFitSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        # PayFit API keys carry per-endpoint scopes, so probe the specific endpoint when asked for
        # one schema; at source-create only the token itself is validated (via introspection).
        if schema_name is not None and schema_name in PAYFIT_ENDPOINTS:
            return check_schema_access(config.api_key, schema_name)
        return validate_credentials(config.api_key)

    def history_lookback_for_schema(
        self, schema_name: str, config: PayFitSourceConfig | None = None
    ) -> datetime.timedelta | None:
        endpoint_config = PAYFIT_ENDPOINTS.get(schema_name)
        if endpoint_config is not None and endpoint_config.monthly:
            return MONTHLY_HISTORY_LOOKBACK
        return None

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

    def source_for_pipeline(
        self,
        config: PayFitSourceConfig,
        resumable_source_manager: ResumableSourceManager[PayFitResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        if inputs.schema_name not in PAYFIT_ENDPOINTS:
            raise ValueError(f"Unknown PayFit schema '{inputs.schema_name}'")

        return payfit_source(
            api_key=config.api_key,
            endpoint=inputs.schema_name,
            logger=inputs.logger,
            resumable_source_manager=resumable_source_manager,
            history_start=inputs.history_start,
            db_incremental_field_last_value=(
                inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None
            ),
        )