: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement payfit import source (#69366)
Tom Owers6256b059cf6f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 55955c42ad15..acecd2cd90b2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -279,6 +279,7 @@ the row lists both.| papersign | HTTP | requests | ✅ || partnerize | HTTP | requests | ✅ || partnerstack | HTTP | requests | ✅ |+| payfit | HTTP | requests | ✅ || paystack | HTTP | requests + `rest_source.RESTClient` | ✅ || pendo | HTTP | requests | ✅ || persistiq | HTTP | requests | ✅ |@@ -684,7 +685,6 @@ doesn't conflict with concurrent PRs.- pabbly_subscriptions_billing- pagerduty- pardot-- payfit- paylocity- paypal- peec_aidiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 0d2271354185..9a9f86ecd770 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -2721,7 +2721,7 @@ class PartnerizeSourceConfig(config.Config):@config.configclass PayFitSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/canonical_descriptions.pynew file mode 100644index 000000000000..f720ea437827--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/canonical_descriptions.py@@ -0,0 +1,72 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the PayFit Partner API reference (https://developers.payfit.io/reference).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "collaborators": {+ "description": "An employee (collaborator) of your company in PayFit, including admins.",+ "docs_url": "https://developers.payfit.io/reference",+ "columns": {+ "id": "The unique ID of the collaborator.",+ "matricule": "Custom ID that can be set on a collaborator to ease synchronization with external software.",+ "firstName": "First name of the collaborator.",+ "lastName": "Last name of the collaborator.",+ "birthName": "Birth name of the collaborator.",+ "birthDate": "Birth date of the collaborator (YYYY-MM-DD).",+ "terminationDate": "End date of the collaborator's last active or current contract (YYYY-MM-DD).",+ "gender": "The gender of the collaborator.",+ "nationality": "Nationality of the collaborator (requires the collaborators:legal-identity:read scope).",+ "countryOfBirth": "Country of birth of the collaborator (requires the collaborators:legal-identity:read scope).",+ "emails": "List of emails of the collaborator.",+ "phoneNumbers": "List of phone numbers of the collaborator.",+ "addresses": "List of addresses of the collaborator.",+ "managerId": "The collaborator ID of this collaborator's manager, or null if they have no manager.",+ "teamName": "The team name of the collaborator, or null if they do not belong to a team.",+ "contracts": "The list of contracts of the collaborator (requires the collaborators:contracts:read scope).",+ },+ },+ "contracts": {+ "description": "An employment contract in your company in PayFit.",+ "docs_url": "https://developers.payfit.io/reference",+ "columns": {+ "contractId": "The unique ID of the contract.",+ "companyId": "The ID of the contract's company.",+ "collaboratorId": "The ID of the collaborator linked to the contract.",+ "startDate": "Contract start date.",+ "endDate": "Contract end date.",+ "probationEndDate": "Contract probation end date.",+ "jobName": "Job name of the employee.",+ "status": "Status of the contract.",+ "contactEmail": "The contact email of the contract (not validated by PayFit).",+ "standardWeeklyHours": "Weekly hours defined in the contract (requires the contracts:time-information:read scope).",+ "fullTimeEquivalent": "Percentage of weekly hours in the contract (requires the contracts:time-information:read scope).",+ "isFullTime": "Whether the contract is full time (fullTimeEquivalent at 1).",+ },+ },+ "absences": {+ "description": "An absence (leave) registered against a contract in PayFit. All statuses are synced, including pending, declined, and cancelled absences.",+ "docs_url": "https://developers.payfit.io/reference",+ "columns": {+ "id": "The unique ID of the absence.",+ "contractId": "Contract ID of the absence owner.",+ "startDate": "Date and moment of the day when the absence starts.",+ "endDate": "Date and moment of the day when the absence ends.",+ "type": "Type of the absence. 'Other' is used when the type is not yet defined.",+ "status": "Status of the absence (approved, pending_approval, declined, cancelled, or pending_cancellation).",+ },+ },+ "payslips": {+ "description": "A payslip issued to a collaborator for a given month in PayFit.",+ "docs_url": "https://developers.payfit.io/reference",+ "columns": {+ "collaboratorId": "The ID of the collaborator the payslip belongs to.",+ "payslipId": "The unique ID of the payslip.",+ "contractId": "The contract the payslip is associated with.",+ "year": "The year of the payslip.",+ "month": "The month of the payslip ('01' being January and '12' December).",+ "payslipUrl": "URL on the PayFit API to retrieve the payslip file.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/payfit.py b/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/payfit.pynew file mode 100644index 000000000000..c297689f076a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/payfit.py@@ -0,0 +1,320 @@+import dataclasses+from collections.abc import Iterator+from typing import Any++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.payfit.settings import (+ PAYFIT_ENDPOINTS,+ PayFitEndpointConfig,+)++PAYFIT_BASE_URL = "https://partner-api.payfit.com"+# The API key only grants access to the key's own company; introspection returns its company_id.+PAYFIT_INTROSPECT_URL = "https://oauth.payfit.com/introspect"+# List endpoints accept a `maxResults` of up to 50 (default 10); the largest page minimises round trips.+PAGE_SIZE = 50+REQUEST_TIMEOUT_SECONDS = 60+# Interactive credential validation runs on the API request thread, so it gets a tighter+# per-attempt budget than sync-time calls.+VALIDATION_TIMEOUT_SECONDS = 15++INVALID_TOKEN_MESSAGE = "PayFit API key is inactive or invalid"+++class PayFitRetryableError(Exception):+ pass+++class PayFitInvalidTokenError(Exception):+ pass+++class PayFitResumeConfig:+ # `nextPageToken` cursor for the next page. For `payslips` this is the cursor of the+ # *collaborators* page being fanned out over. `None` means start from the first page. A crashed+ # sync resumes from the page after the last one yielded; merge dedupes on the primary key.+ next_page_token: str | None = None+++def _headers(api_key: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}+++def _make_introspection_session(api_key: str) -> requests.Session:+ # capture=False: the introspection request body carries the raw API key under the generic+ # `token` field, which the name-based sample scrubbers don't recognise — keep the exchange out+ # of HTTP sample capture entirely (it stays metered and logged). allow_redirects=False pins the+ # credential-bearing request to the introspection host.+ return make_tracked_session(+ headers=_headers(api_key),+ redact_values=(api_key,),+ capture=False,+ allow_redirects=False,+ )+++@retry(+ retry=retry_if_exception_type((PayFitRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _introspect(session: requests.Session, api_key: str, timeout: float = REQUEST_TIMEOUT_SECONDS) -> dict[str, Any]:+ response = session.post(+ PAYFIT_INTROSPECT_URL,+ json={"token": api_key},+ timeout=timeout,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise PayFitRetryableError(f"PayFit introspection error (retryable): status={response.status_code}")++ # Introspection authenticates with the token itself, so a 401/403 means the key is bad — the+ # same signal as an {"active": false} body.+ if response.status_code in (401, 403):+ return {"active": False}++ if not response.ok:+ response.raise_for_status()++ data = response.json()+ if not isinstance(data, dict):+ raise PayFitRetryableError(f"PayFit introspection returned an unexpected payload: {type(data).__name__}")+ return data+++def get_company_id(api_key: str) -> str:+ claims = _introspect(_make_introspection_session(api_key), api_key)+ if not claims.get("active"):+ raise PayFitInvalidTokenError(INVALID_TOKEN_MESSAGE)++ company_id = claims.get("company_id")+ if not isinstance(company_id, str) or not company_id:+ raise PayFitInvalidTokenError(f"{INVALID_TOKEN_MESSAGE}: introspection returned no company_id")+ return company_id+++@retry(+ retry=retry_if_exception_type((PayFitRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ path: str,+ data_key: str,+ next_page_token: str | None,+ extra_params: dict[str, str],+ logger: FilteringBoundLogger,+) -> tuple[list[dict[str, Any]], str | None]:+ params: dict[str, Any] = {"maxResults": PAGE_SIZE, **extra_params}+ if next_page_token is not None:+ params["nextPageToken"] = next_page_token++ response = session.get(+ f"{PAYFIT_BASE_URL}{path}",+ params=params,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise PayFitRetryableError(f"PayFit API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"PayFit API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ # List endpoints wrap rows as {"<data_key>": [...], "meta": {"nextPageToken": str | null}}.+ if not isinstance(data, dict) or not isinstance(data.get(data_key), list):+ raise PayFitRetryableError(f"PayFit returned an unexpected payload for {path}: {type(data).__name__}")++ rows: list[dict[str, Any]] = data[data_key]+ meta = data.get("meta") or {}+ next_token = meta.get("nextPageToken") if isinstance(meta, dict) else None+ return rows, next_token or None+++@retry(+ retry=retry_if_exception_type((PayFitRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_payslips(+ session: requests.Session,+ company_id: str,+ collaborator_id: str,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ path = f"/companies/{company_id}/collaborators/{collaborator_id}/payslips"+ response = session.get(f"{PAYFIT_BASE_URL}{path}", timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise PayFitRetryableError(f"PayFit API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"PayFit API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ if not isinstance(data, dict) or not isinstance(data.get("payslips"), list):+ raise PayFitRetryableError(f"PayFit returned an unexpected payload for {path}: {type(data).__name__}")++ # The response only carries year/month/contractId/payslipId, so stamp the parent id onto each+ # row — it is part of the primary key.+ return [{**payslip, "collaboratorId": collaborator_id} for payslip in data["payslips"]]+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PayFitResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = PAYFIT_ENDPOINTS[endpoint]+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))+ company_id = get_company_id(api_key)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ next_page_token = resume.next_page_token if resume else None+ if resume and resume.next_page_token is not None:+ logger.debug(f"PayFit: resuming {endpoint} from page token {next_page_token}")++ if config.fan_out_over_collaborators:+ yield from _get_payslip_rows(session, company_id, next_page_token, logger, resumable_source_manager)+ return++ path = f"/companies/{company_id}{config.path}"+ while True:+ rows, next_token = _fetch_page(session, path, config.data_key, next_page_token, config.extra_params, logger)+ if rows:+ yield rows++ # A missing/null nextPageToken (or an empty page) means we've reached the end of the list.+ if not next_token or not rows:+ break++ next_page_token = next_token+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(PayFitResumeConfig(next_page_token=next_page_token))+++def _get_payslip_rows(+ session: requests.Session,+ company_id: str,+ next_page_token: str | None,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PayFitResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ # Payslips have no list-all endpoint, so paginate collaborators and fetch each collaborator's+ # payslips. Resume state tracks the collaborators page cursor: one page of collaborators is one+ # yielded batch.+ collaborators_path = f"/companies/{company_id}/collaborators"+ while True:+ collaborators, next_token = _fetch_page(+ session, collaborators_path, "collaborators", next_page_token, {}, logger+ )++ batch: list[dict[str, Any]] = []+ for collaborator in collaborators:+ batch.extend(_fetch_payslips(session, company_id, collaborator["id"], logger))+ if batch:+ yield batch++ if not next_token or not collaborators:+ break++ next_page_token = next_token+ resumable_source_manager.save_state(PayFitResumeConfig(next_page_token=next_page_token))+++def payfit_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PayFitResumeConfig],+) -> SourceResponse:+ config = PAYFIT_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ """Validate the API key via token introspection — one cheap probe that needs no endpoint scope+ and also proves we can resolve the company_id every sync depends on. Shares `_introspect` with+ the sync path so a transient 429/5xx blip is retried rather than failing source creation."""+ session = _make_introspection_session(api_key)+ try:+ claims = _introspect(session, api_key, timeout=VALIDATION_TIMEOUT_SECONDS)+ except Exception as e:+ return False, f"Could not validate PayFit API key: {e}"++ if not claims.get("active"):+ return False, "Invalid PayFit API key"++ if not claims.get("company_id"):+ return False, "PayFit token introspection returned no company ID"++ return True, None+++def check_schema_access(api_key: str, schema_name: str) -> tuple[bool, str | None]:+ """Probe a single endpoint to confirm the API key carries the scope that schema needs."""+ endpoint_config = PAYFIT_ENDPOINTS[schema_name]+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))++ try:+ company_id = get_company_id(api_key)+ except PayFitInvalidTokenError:+ return False, "Invalid PayFit API key"+ except Exception as e:+ return False, f"Could not validate PayFit API key: {e}"++ probe = _probe_endpoint(endpoint_config)+ probe_params: dict[str, Any] = {"maxResults": 1, **probe.extra_params}+ try:+ response = session.get(+ f"{PAYFIT_BASE_URL}/companies/{company_id}{probe.path}",+ params=probe_params,+ timeout=15,+ )+ except Exception as e:+ return False, f"Could not connect to PayFit: {e}"++ if response.status_code == 401:+ return False, "Invalid PayFit API key"+ if response.status_code == 403:+ return False, f"Your PayFit API key is missing the `{probe.scope}` scope required for `{schema_name}`"+ if not response.ok:+ return False, f"PayFit returned HTTP {response.status_code}"+ return True, None+++def _probe_endpoint(endpoint_config: PayFitEndpointConfig) -> PayFitEndpointConfig:+ # Payslips are enumerated per collaborator, so probe the collaborators dependency instead of a+ # per-collaborator path; a missing `contracts:payslips:read` scope still surfaces as a+ # non-retryable 403 at sync time.+ if endpoint_config.fan_out_over_collaborators:+ return PAYFIT_ENDPOINTS["collaborators"]+ return endpoint_configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/settings.pynew file mode 100644index 000000000000..c5ce4bd918a4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/settings.py@@ -0,0 +1,59 @@+from dataclasses import dataclass, field+++@dataclass+class PayFitEndpointConfig:+ name: str+ # Appended to /companies/{companyId} on the Partner API host.+ path: str+ # Key wrapping the rows in the JSON response, e.g. {"collaborators": [...], "meta": {...}}.+ data_key: str+ # OAuth scope the API key must carry to read this endpoint.+ scope: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Payslips have no list-all endpoint; they are fetched per collaborator.+ fan_out_over_collaborators: bool = False+ extra_params: dict[str, str] = field(default_factory=dict)+++# PayFit Partner API list endpoints. All are full-refresh only: PayFit exposes no server-side+# `updated_after`/`since` filter on any of them, so there is no incremental cursor to advance.+# Country-specific endpoints (meal vouchers, health insurance and provident funds, accounting CSV+# exports) are intentionally not synced.+PAYFIT_ENDPOINTS: dict[str, PayFitEndpointConfig] = {+ "collaborators": PayFitEndpointConfig(+ name="collaborators",+ path="/collaborators",+ data_key="collaborators",+ scope="collaborators:read",+ ),+ "contracts": PayFitEndpointConfig(+ name="contracts",+ path="/contracts",+ data_key="contracts",+ scope="contracts:read",+ primary_keys=["contractId"],+ ),+ "absences": PayFitEndpointConfig(+ name="absences",+ path="/absences",+ data_key="absences",+ scope="time:read",+ # The API defaults to approved absences only; sync every status so the warehouse keeps+ # pending/declined/cancelled rows with their `status` column.+ extra_params={"status": "all"},+ ),+ "payslips": PayFitEndpointConfig(+ name="payslips",+ path="/collaborators/{collaboratorId}/payslips",+ data_key="payslips",+ scope="contracts:payslips:read",+ # Rows are aggregated across every collaborator, so the parent id is part of the key.+ primary_keys=["collaboratorId", "payslipId"],+ fan_out_over_collaborators=True,+ ),+}++ENDPOINTS = tuple(PAYFIT_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/source.pyindex ba2381a2f606..2b4ce2a85341 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/source.py@@ -1,19 +1,40 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PayFitSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.payfit.payfit import (+ PayFitResumeConfig,+ check_schema_access,+ payfit_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.payfit.settings import ENDPOINTS, PAYFIT_ENDPOINTSfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class PayFitSource(SimpleSource[PayFitSourceConfig]):+class PayFitSource(ResumableSource[PayFitSourceConfig, PayFitResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PAYFIT@@ -24,7 +45,91 @@ class PayFitSource(SimpleSource[PayFitSourceConfig]):name=SchemaExternalDataSourceType.PAY_FIT,category=DataWarehouseSourceCategory.HR___RECRUITING,label="PayFit",+ releaseStatus=ReleaseStatus.ALPHA,+ 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`, and `contracts:payslips:read` scopes so every table can sync.+""",iconPath="/static/services/payfit.png",- fields=cast(list[FieldType], []),+ 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,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.payfit.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ 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, and contracts:payslips: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,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — PayFit exposes no server-side updated_after/since+ # filter on any list endpoint, so there is no incremental cursor to advance.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ 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+ ) -> 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 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,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/tests/test_payfit.py b/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/tests/test_payfit.pynew file mode 100644index 000000000000..4dcdc795d28f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/tests/test_payfit.py@@ -0,0 +1,391 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.payfit import payfit+from products.warehouse_sources.backend.temporal.data_imports.sources.payfit.payfit import (+ PAGE_SIZE,+ PAYFIT_BASE_URL,+ PayFitInvalidTokenError,+ PayFitResumeConfig,+ PayFitRetryableError,+ check_schema_access,+ get_company_id,+ get_rows,+ payfit_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.payfit.settings import ENDPOINTS, PAYFIT_ENDPOINTS++# Call the undecorated functions so the tenacity retry/backoff wrappers don't slow failure-path tests.+_fetch_page_unwrapped = payfit._fetch_page.__wrapped__ # type: ignore[attr-defined]+_fetch_payslips_unwrapped = payfit._fetch_payslips.__wrapped__ # type: ignore[attr-defined]+_introspect_unwrapped = payfit._introspect.__wrapped__ # type: ignore[attr-defined]++COMPANY_ID = "company-1"+++class _FakeResumableManager:+ def __init__(self, state: PayFitResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[PayFitResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> PayFitResumeConfig | None:+ return self._state++ def save_state(self, data: PayFitResumeConfig) -> None:+ self.saved.append(data)+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[str | None, tuple[list[dict], str | None]],+ endpoint: str = "collaborators",+ ) -> list[dict]:+ def fake_fetch(+ session: Any,+ path: str,+ data_key: str,+ next_page_token: str | None,+ extra_params: dict,+ logger: Any,+ ) -> tuple[list[dict], str | None]:+ return pages[next_page_token]++ monkeypatch.setattr(payfit, "_fetch_page", fake_fetch)+ monkeypatch.setattr(payfit, "get_company_id", lambda api_key: COMPANY_ID)+ monkeypatch.setattr(payfit, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="payfit-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_page_without_token_yields_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {None: ([{"id": "1"}, {"id": "2"}], None)})+ assert rows == [{"id": "1"}, {"id": "2"}]+ # No next page token, so we stop without persisting resume state.+ assert manager.saved == []++ def test_follows_page_token_until_exhausted(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: dict[str | None, tuple[list[dict], str | None]] = {+ None: ([{"id": "1"}], "tok-2"),+ "tok-2": ([{"id": "2"}], None),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": "1"}, {"id": "2"}]+ # State is saved after the first page is yielded, then we stop on the final page.+ assert [s.next_page_token for s in manager.saved] == ["tok-2"]++ def test_resumes_from_saved_page_token(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(PayFitResumeConfig(next_page_token="tok-99"))+ # The initial (token=None) page must never be fetched on resume.+ rows = self._collect(manager, monkeypatch, {"tok-99": ([{"id": "5"}], None)})+ assert rows == [{"id": "5"}]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {None: ([], None)})+ assert rows == []+ assert manager.saved == []+++class TestGetPayslipRows:+ def test_fans_out_over_collaborator_pages_and_stamps_parent_id(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ collaborator_pages: dict[str | None, tuple[list[dict], str | None]] = {+ None: ([{"id": "collab-1"}, {"id": "collab-2"}], "tok-2"),+ "tok-2": ([{"id": "collab-3"}], None),+ }+ payslips_by_collaborator = {+ "collab-1": [{"payslipId": "p1", "collaboratorId": "collab-1"}],+ "collab-2": [],+ "collab-3": [{"payslipId": "p2", "collaboratorId": "collab-3"}],+ }++ def fake_fetch(+ session: Any,+ path: str,+ data_key: str,+ next_page_token: str | None,+ extra_params: dict,+ logger: Any,+ ) -> tuple[list[dict], str | None]:+ assert path == f"/companies/{COMPANY_ID}/collaborators"+ return collaborator_pages[next_page_token]++ def fake_payslips(session: Any, company_id: str, collaborator_id: str, logger: Any) -> list[dict]:+ assert company_id == COMPANY_ID+ return payslips_by_collaborator[collaborator_id]++ monkeypatch.setattr(payfit, "_fetch_page", fake_fetch)+ monkeypatch.setattr(payfit, "_fetch_payslips", fake_payslips)+ monkeypatch.setattr(payfit, "get_company_id", lambda api_key: COMPANY_ID)+ monkeypatch.setattr(payfit, "make_tracked_session", lambda **kwargs: MagicMock())++ batches = list(+ get_rows(+ api_key="payfit-key",+ endpoint="payslips",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ )+ )++ # One batch per collaborators page; resume state tracks the collaborators cursor after each+ # yielded batch.+ assert batches == [+ [{"payslipId": "p1", "collaboratorId": "collab-1"}],+ [{"payslipId": "p2", "collaboratorId": "collab-3"}],+ ]+ assert [s.next_page_token for s in manager.saved] == ["tok-2"]+++class _ResponseSessionMixin:+ @staticmethod+ def _response(status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ return response++ @classmethod+ def _session_returning(cls, status_code: int, body: Any = None) -> MagicMock:+ session = MagicMock()+ session.get.return_value = cls._response(status_code, body)+ session.post.return_value = cls._response(status_code, body)+ return session+++class TestFetchPage(_ResponseSessionMixin):+ _EMPTY: dict[str, Any] = {"collaborators": [], "meta": {}}++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(PayFitRetryableError):+ _fetch_page_unwrapped(session, "/companies/c/collaborators", "collaborators", None, {}, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "/companies/c/collaborators", "collaborators", None, {}, MagicMock())++ @parameterized.expand(+ [+ ("next_token_present", {"collaborators": [{"id": "1"}], "meta": {"nextPageToken": "tok"}}, "tok"),+ ("next_token_null", {"collaborators": [{"id": "1"}], "meta": {"nextPageToken": None}}, None),+ ("meta_missing", {"collaborators": [{"id": "1"}]}, None),+ ]+ )+ def test_success_returns_rows_and_next_token(self, _name: str, body: dict, expected_token: str | None) -> None:+ session = self._session_returning(200, body)+ rows, next_token = _fetch_page_unwrapped(+ session, "/companies/c/collaborators", "collaborators", None, {}, MagicMock()+ )+ assert rows == [{"id": "1"}]+ assert next_token == expected_token++ @parameterized.expand([("non_dict", [{"id": "1"}]), ("missing_data_key", {"meta": {}})])+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:+ session = self._session_returning(200, body)+ with pytest.raises(PayFitRetryableError):+ _fetch_page_unwrapped(session, "/companies/c/collaborators", "collaborators", None, {}, MagicMock())++ def test_first_page_sends_max_results_and_extra_params_without_token(self) -> None:+ session = self._session_returning(200, {"absences": [], "meta": {}})+ _fetch_page_unwrapped(session, "/companies/c/absences", "absences", None, {"status": "all"}, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"maxResults": PAGE_SIZE, "status": "all"}++ def test_subsequent_page_sends_next_page_token(self) -> None:+ session = self._session_returning(200, self._EMPTY)+ _fetch_page_unwrapped(session, "/companies/c/collaborators", "collaborators", "tok-42", {}, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"maxResults": PAGE_SIZE, "nextPageToken": "tok-42"}+++class TestFetchPayslips(_ResponseSessionMixin):+ def test_stamps_collaborator_id_onto_rows(self) -> None:+ body = {"payslips": [{"payslipId": "p1", "year": "2026", "month": "01"}]}+ session = self._session_returning(200, body)+ rows = _fetch_payslips_unwrapped(session, "company-1", "collab-1", MagicMock())+ assert rows == [{"payslipId": "p1", "year": "2026", "month": "01", "collaboratorId": "collab-1"}]+ args, _ = session.get.call_args+ assert args[0] == f"{PAYFIT_BASE_URL}/companies/company-1/collaborators/collab-1/payslips"++ def test_unexpected_payload_is_retryable(self) -> None:+ session = self._session_returning(200, {"nope": []})+ with pytest.raises(PayFitRetryableError):+ _fetch_payslips_unwrapped(session, "company-1", "collab-1", MagicMock())+++class TestGetCompanyId(_ResponseSessionMixin):+ @patch(f"{payfit.__name__}.make_tracked_session")+ def test_returns_company_id_for_active_token(self, mock_session: MagicMock) -> None:+ session = self._session_returning(200, {"active": True, "company_id": "company-1"})+ mock_session.return_value = session+ assert get_company_id("payfit-key") == "company-1"+ args, kwargs = session.post.call_args+ assert args[0] == payfit.PAYFIT_INTROSPECT_URL+ assert kwargs["json"] == {"token": "payfit-key"}+ # The introspection body carries the raw API key, so the exchange must stay out of HTTP+ # sample capture and must not follow redirects with the credential.+ session_kwargs = mock_session.call_args.kwargs+ assert session_kwargs["capture"] is False+ assert session_kwargs["allow_redirects"] is False++ @parameterized.expand(+ [+ ("inactive_token", 200, {"active": False}),+ ("missing_company_id", 200, {"active": True}),+ ("unauthorized", 401, None),+ ("forbidden", 403, None),+ ]+ )+ @patch(f"{payfit.__name__}.make_tracked_session")+ def test_invalid_tokens_raise_non_retryable_error(+ self, _name: str, status: int, body: Any, mock_session: MagicMock+ ) -> None:+ mock_session.return_value = self._session_returning(status, body)+ with pytest.raises(PayFitInvalidTokenError):+ get_company_id("payfit-key")++ @parameterized.expand([("rate_limited", 429), ("server_error", 500)])+ def test_transient_statuses_are_retryable(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(PayFitRetryableError):+ _introspect_unwrapped(session, "payfit-key")+++class TestValidateCredentials(_ResponseSessionMixin):+ # Status-code handling (401/403, 429/5xx retries, malformed payloads) lives in `_introspect`+ # and is covered by TestGetCompanyId; validation shares that path, so here we only assert the+ # claims-to-verdict mapping and that introspection failures surface as a message, not a raise.+ @parameterized.expand(+ [+ ("active_with_company", {"active": True, "company_id": "company-1"}, True, None),+ ("inactive", {"active": False}, False, "Invalid PayFit API key"),+ ("no_company_id", {"active": True}, False, "PayFit token introspection returned no company ID"),+ ]+ )+ @patch(f"{payfit.__name__}._introspect")+ def test_claims_mapping(+ self,+ _name: str,+ claims: dict,+ expected_valid: bool,+ expected_message: str | None,+ mock_introspect: MagicMock,+ ) -> None:+ mock_introspect.return_value = claims+ assert validate_credentials("payfit-key") == (expected_valid, expected_message)++ @parameterized.expand(+ [+ ("exhausted_retries", PayFitRetryableError("PayFit introspection error (retryable): status=500"), "500"),+ ("connection_error", requests.ConnectionError("boom"), "boom"),+ ]+ )+ @patch(f"{payfit.__name__}._introspect")+ def test_introspection_failure_maps_to_message(+ self, _name: str, error: Exception, expected_fragment: str, mock_introspect: MagicMock+ ) -> None:+ mock_introspect.side_effect = error+ valid, message = validate_credentials("payfit-key")+ assert valid is False+ assert message is not None and expected_fragment in message+++class TestCheckSchemaAccess(_ResponseSessionMixin):+ @staticmethod+ def _session_with(introspect_body: dict, endpoint_status: int) -> MagicMock:+ session = MagicMock()+ session.post.return_value = _ResponseSessionMixin._response(200, introspect_body)+ session.get.return_value = _ResponseSessionMixin._response(endpoint_status, {})+ return session++ _ACTIVE = {"active": True, "company_id": "company-1"}++ @parameterized.expand(+ [+ ("reachable", 200, True),+ ("missing_scope", 403, False),+ ("bad_key", 401, False),+ ]+ )+ @patch(f"{payfit.__name__}.make_tracked_session")+ def test_endpoint_status_mapping(+ self, _name: str, endpoint_status: int, expected_valid: bool, mock_session: MagicMock+ ) -> None:+ mock_session.return_value = self._session_with(self._ACTIVE, endpoint_status)+ valid, _message = check_schema_access("payfit-key", "contracts")+ assert valid is expected_valid++ @patch(f"{payfit.__name__}.make_tracked_session")+ def test_missing_scope_message_names_the_scope(self, mock_session: MagicMock) -> None:+ mock_session.return_value = self._session_with(self._ACTIVE, 403)+ valid, message = check_schema_access("payfit-key", "absences")+ assert valid is False+ assert message is not None and "time:read" in message++ @patch(f"{payfit.__name__}.make_tracked_session")+ def test_payslips_probe_uses_collaborators_dependency(self, mock_session: MagicMock) -> None:+ session = self._session_with(self._ACTIVE, 200)+ mock_session.return_value = session+ valid, _message = check_schema_access("payfit-key", "payslips")+ assert valid is True+ args, _ = session.get.call_args+ # Payslip paths need a collaborator id, so the scope probe targets the collaborators list.+ assert args[0] == f"{PAYFIT_BASE_URL}/companies/company-1/collaborators"++ @patch(f"{payfit.__name__}.make_tracked_session")+ def test_inactive_token_fails_before_probing(self, mock_session: MagicMock) -> None:+ session = self._session_with({"active": False}, 200)+ mock_session.return_value = session+ valid, message = check_schema_access("payfit-key", "contracts")+ assert valid is False+ assert message == "Invalid PayFit API key"+ session.get.assert_not_called()+++class TestPayFitSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = payfit_source(+ api_key="payfit-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == PAYFIT_ENDPOINTS[endpoint].primary_keys+ # No stable creation timestamp exists across the endpoints, so we don't partition.+ assert response.partition_mode is None++ def test_payslips_primary_key_includes_parent_id(self) -> None:+ # Payslip rows are aggregated across every collaborator, so the key must carry the parent id.+ assert PAYFIT_ENDPOINTS["payslips"].primary_keys == ["collaboratorId", "payslipId"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/tests/test_payfit_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/tests/test_payfit_source.pynew file mode 100644index 000000000000..bcf3a31f6ed9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/payfit/tests/test_payfit_source.py@@ -0,0 +1,151 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PayFitSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.payfit.payfit import PayFitResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.payfit.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.payfit.source import PayFitSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestPayFitSource:+ def setup_method(self) -> None:+ self.source = PayFitSource()+ self.team_id = 123+ self.config = PayFitSourceConfig(api_key="payfit-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.PAYFIT++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "PayFit"+ assert config.label == "PayFit"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/payfit"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # The only field is the secret API key; both hosts are hardcoded, so there is no non-secret+ # field an editor could retarget to reuse a preserved key against another server.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["contracts"])+ assert len(schemas) == 1+ assert schemas[0].name == "contracts"++ 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_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://partner-api.payfit.com/companies/c/collaborators?maxResults=50",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://partner-api.payfit.com/companies/c/contracts?maxResults=50",+ ),+ ("inactive_token", "PayFit API key is inactive or invalid"),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://partner-api.payfit.com/companies/c/absences",+ ),+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://partner-api.payfit.com/companies/c/contracts",+ ),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.payfit.source.validate_credentials")+ def test_validate_credentials_probes_token_at_source_create(self, mock_validate: mock.MagicMock) -> None:+ # The status-to-message mapping lives in payfit.validate_credentials; here we only assert the+ # source probes with the configured key and returns the delegate's verdict unchanged.+ mock_validate.return_value = (False, "Invalid PayFit API key")+ result = self.source.validate_credentials(self.config, self.team_id)+ mock_validate.assert_called_once_with("payfit-key")+ assert result == (False, "Invalid PayFit API key")++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.payfit.source.check_schema_access")+ def test_validate_credentials_probes_endpoint_scope_for_schema(self, mock_check: mock.MagicMock) -> None:+ # PayFit keys carry per-endpoint scopes, so per-schema validation must probe that endpoint+ # rather than only introspecting the token.+ mock_check.return_value = (True, None)+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="absences")+ mock_check.assert_called_once_with("payfit-key", "absences")+ assert result == (True, None)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.payfit.source.validate_credentials")+ def test_validate_credentials_falls_back_for_unknown_schema(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="not_a_table")+ mock_validate.assert_called_once_with("payfit-key")+ assert result == (True, None)++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is PayFitResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.payfit.source.payfit_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "collaborators"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "payfit-key"+ assert kwargs["endpoint"] == "collaborators"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown PayFit schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)