: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): add FirstPromoter source (#77099)
Tom Owers01ef5939e590
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 35c88f6cd127..6bd3d553ff3a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -257,6 +257,7 @@ the row lists both.| fireworks_ai | HTTP | requests | ✅ || fleetio | HTTP | requests | ✅ || firehydrant | HTTP | requests | ✅ |+| first_promoter | HTTP | requests + `rest_source.RESTClient` | ✅ || flagsmith | HTTP | requests | ✅ || flexmail | HTTP | requests | ✅ || float_app | HTTP | requests | ✅ |@@ -939,7 +940,6 @@ doesn't conflict with concurrent PRs.- fintoc- firebase- firebolt-- first_promoter- five9- flagsmith- flexera_cloud_costdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/canonical_descriptions.pynew file mode 100644index 000000000000..5d7ab4917cdc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/canonical_descriptions.py@@ -0,0 +1,147 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "commissions": {+ "description": "Commissions earned by promoters for the sales and events they referred.",+ "docs_url": "https://docs.firstpromoter.com/api-reference-v2/api-admin/commissions/get-all-commissions",+ "columns": {+ "id": "Unique identifier for the commission.",+ "status": "Approval state of the commission: pending, approved or denied.",+ "status_updated_at": "When the commission's status last changed.",+ "commission_type": "What earned the commission, for example a sale or a signup.",+ "amount": "Commission paid to the promoter, in the smallest unit of the account currency.",+ "unit": "Unit the amount is expressed in, for example a currency code, credits or points.",+ "sale_amount": "Value of the referred sale the commission was calculated from.",+ "original_sale_amount": "Sale value in the currency the sale was originally made in.",+ "original_sale_currency": "Currency the referred sale was originally made in.",+ "is_paid": "Whether the commission has been paid out to the promoter.",+ "is_split": "Whether the commission is shared between several promoters.",+ "split_details": "Per-promoter share of a split commission.",+ "is_self_referral": "Whether the promoter referred themselves.",+ "event_id": "Identifier of the tracked event that generated the commission.",+ "plan_id": "Identifier of the plan the referred sale was made on.",+ "tier": "Referral tier the commission was earned at, for multi-level programs.",+ "fraud_check": "Result of the fraud check, for example no_suspicion or same_ip_suspicion.",+ "metadata": "Custom metadata sent with the tracked event.",+ "internal_note": "Note visible only to the program admins.",+ "external_note": "Note visible to the promoter.",+ "created_by_user_email": "Email of the admin who created the commission manually, if any.",+ "created_by_user_at": "When an admin created the commission manually, if applicable.",+ "created_at": "When the commission was created.",+ "promoter_campaign": "The promoter and campaign the commission belongs to.",+ "referral": "The referred lead or customer the commission came from.",+ "reward": "The reward rule the commission was calculated with.",+ },+ },+ "payouts": {+ "description": "Payouts owed to or already paid to promoters for a given payout period.",+ "docs_url": "https://docs.firstpromoter.com/api-reference-v2/api-admin/payouts/get-all-payouts",+ "columns": {+ "id": "Unique identifier for the payout.",+ "status": "Payout state: pending, processing, completed, failed or cancelled.",+ "amount": "Payout amount, excluding tax.",+ "total_incl_tax": "Payout amount including tax.",+ "tax_rate": "Tax rate applied to the payout.",+ "unit": "Unit the amount is expressed in, for example a currency code.",+ "period_start": "Start of the period the payout covers.",+ "period_end": "End of the period the payout covers.",+ "paid_at": "When the payout was paid.",+ "processing_started_at": "When the payout started processing.",+ "failed_at": "When the payout failed, if it did.",+ "error": "Reason the payout failed, if it did.",+ "payments_batch_id": "Identifier of the batch the payout was processed in.",+ "payout_method": "Payout method used, for example PayPal, bank, Wise or crypto.",+ "promoter": "The promoter being paid.",+ "campaign": "The campaign the payout belongs to.",+ "created_at": "When the payout was created.",+ },+ },+ "promo_codes": {+ "description": "Promo and coupon codes attached to promoter campaigns.",+ "docs_url": "https://docs.firstpromoter.com/api-reference-v2/api-admin/promo-codes/get-promo-codes",+ "columns": {+ "id": "Unique identifier for the promo code entry.",+ "code": "The promo code itself.",+ "ext_id": "Identifier of the matching coupon in the connected billing provider.",+ "description": "Description of the promo code.",+ "company_id": "Identifier of the company the promo code belongs to.",+ "promoter_campaign_id": "Identifier of the promoter campaign the code is attached to.",+ "reward": "The reward the promo code grants.",+ "metadata": "Custom metadata stored on the promo code.",+ "details": "Additional promo code details, such as its discount configuration.",+ "archived_at": "When the promo code was archived, if it was.",+ },+ },+ "promoter_campaigns": {+ "description": "A promoter's participation in one campaign, with their referral link, coupon and stats.",+ "docs_url": "https://docs.firstpromoter.com/api-reference-v2/api-admin/promoter-campaigns/get-available-promoter-campaigns",+ "columns": {+ "id": "Unique identifier for the promoter campaign.",+ "campaign_id": "Identifier of the campaign.",+ "promoter_id": "Identifier of the promoter.",+ "state": "Promoter's state in this campaign: pending, accepted, rejected, blocked or inactive.",+ "coupon": "Coupon code assigned to the promoter for this campaign.",+ "display_coupon": "Coupon code as shown to the promoter.",+ "ref_token": "Referral token used to attribute traffic to the promoter.",+ "ref_link": "Referral link the promoter shares.",+ "direct_url": "Destination the referral link points at.",+ "is_customized": "Whether the promoter's rewards differ from the campaign defaults.",+ "stats": "Clicks, referrals, sales, customers and revenue for this promoter campaign.",+ "rewards_for_promoters": "Rewards the promoter earns in this campaign.",+ "rewards_for_referrals": "Rewards the promoter's referrals receive in this campaign.",+ "promo_codes": "Promo codes attached to this promoter campaign.",+ "promoter": "The promoter this record belongs to.",+ "campaign": "The campaign this record belongs to.",+ "created_at": "When the promoter joined the campaign.",+ },+ },+ "promoters": {+ "description": "Affiliates and referral partners in your program, with their profile, stats and balances.",+ "docs_url": "https://docs.firstpromoter.com/api-reference-v2/api-admin/promoters/get-available-promoters",+ "columns": {+ "id": "Unique identifier for the promoter.",+ "email": "Promoter's email address.",+ "name": "Promoter's display name.",+ "cust_id": "Your own identifier for the promoter, if you set one.",+ "note": "Internal note about the promoter.",+ "stats": "Clicks, referrals, sales, customers and revenue attributed to the promoter.",+ "balances": "Promoter's cash, credits, points, free months and discount balances.",+ "profile": "Promoter's profile details, including name, company, country and social links.",+ "promoter_campaigns": "Campaigns the promoter takes part in, with their links and coupons.",+ "is_customized": "Whether the promoter's rewards differ from the campaign defaults.",+ "is_confirmed": "Whether the promoter has confirmed their email address.",+ "fraud_suspicions": "Fraud suspicions raised against the promoter.",+ "invoice_details_status": "State of the promoter's invoice details: approved, pending, rejected or not_submitted.",+ "custom_fields": "Custom fields collected on the promoter's signup form.",+ "auth_provider": "How the promoter signs in, for example email or Google.",+ "selected_payout_method": "Payout method the promoter chose to be paid with.",+ "track_ad_traffic": "Whether the promoter is allowed to send paid ad traffic.",+ "password_setup_url": "One-time link for the promoter to set their password, when available.",+ "joined_at": "When the promoter joined the program.",+ "first_event_at": "When the promoter's first tracked event happened.",+ "last_login_at": "When the promoter last logged in to their dashboard.",+ "archived_at": "When the promoter was archived, if they were.",+ },+ },+ "referrals": {+ "description": "Leads and customers referred by your promoters, with their state and attribution.",+ "docs_url": "https://docs.firstpromoter.com/api-reference-v2/api-admin/referrals/get-referrals",+ "columns": {+ "id": "Unique identifier for the referral.",+ "email": "Referred person's email address.",+ "uid": "Your own identifier for the referred customer.",+ "username": "Referred person's username, if you send one.",+ "state": "Referral state, for example signup, active, cancelled or refunded.",+ "entry_source": "How the referral was attributed: api, coupon, cookie, manual_admin or manual_affiliate.",+ "fraud_check": "Result of the fraud check, for example no_suspicion or same_ip_suspicion.",+ "split_details": "Promoters the referral is split between, and each one's percentage.",+ "promoter_campaign": "The promoter campaign the referral is attributed to.",+ "is_expired": "Whether the referral has passed the program's attribution window.",+ "customer_since": "When the referral became a paying customer.",+ "cancelled_at": "When the referral cancelled, if they did.",+ "created_at": "When the referral was first tracked.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/first_promoter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/first_promoter.pynew file mode 100644index 000000000000..4423baa3156c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/first_promoter.py@@ -0,0 +1,276 @@+import logging+import dataclasses+from collections.abc import Callable, Iterable+from functools import partial+from typing import Any, Optional++from requests import Request, Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (+ coerce_datetime_to_utc,+)+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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+ IncrementalConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.settings import (+ DEFAULT_PAGE_SIZE,+ FIRST_PROMOTER_ENDPOINTS,+ FirstPromoterEndpointConfig,+ base_url,+)++logger = logging.getLogger(__name__)+++class FirstPromoterResumeConfig:+ page: int+++def _format_filter_date(value: Any) -> str:+ """Format the incremental watermark for a `filters[<field>][from]` bound.++ The Admin API documents these bounds as `YYYY-MM-DD` dates, so the watermark is truncated to+ its day. That rounds the lower bound *down*, re-fetching at most one day of rows (which the+ merge dedupes on `id`) rather than skipping any.+ """+ normalized_value = coerce_datetime_to_utc(value)+ if normalized_value is None:+ return str(value)+ return normalized_value.strftime("%Y-%m-%d")+++def _incremental_window(start_param: str, cursor_path: str) -> IncrementalConfig:+ return {+ "cursor_path": cursor_path,+ "start_param": start_param,+ "initial_value": "1970-01-01",+ "convert": _format_filter_date,+ }+++def _page_signature(data: Optional[list[Any]]) -> Optional[tuple[Any, ...]]:+ """Identity of a page's rows, or None when the rows carry no usable id."""+ if not data:+ return None+ ids = []+ for row in data:+ if not isinstance(row, dict) or row.get("id") is None:+ return None+ ids.append(row["id"])+ return tuple(ids)+++class FirstPromoterPaginator(PageNumberPaginator):+ """`page`/`per_page` paginator with the two stop conditions the plain page paginator lacks.++ FirstPromoter documents `page`/`per_page` once, globally, rather than per endpoint, and its+ list responses carry no page-count metadata. So this stops on the vendor's documented+ end-of-data signal (a page shorter than `per_page`) and, as a backstop, on a page whose rows+ repeat the previous page's - which is what an endpoint that quietly ignores `page` would+ return forever.+ """++ def __init__(self, per_page: int = DEFAULT_PAGE_SIZE) -> None:+ super().__init__(base_page=1, page_param="page")+ self.per_page = per_page+ self._previous_signature: Optional[tuple[Any, ...]] = None++ def _apply_page_size(self, request: Request) -> None:+ if request.params is None:+ request.params = {}+ request.params["per_page"] = self.per_page++ def init_request(self, request: Request) -> None:+ super().init_request(request)+ self._apply_page_size(request)++ def update_request(self, request: Request) -> None:+ super().update_request(request)+ self._apply_page_size(request)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ signature = _page_signature(data)+ repeats_previous_page = signature is not None and signature == self._previous_signature+ self._previous_signature = signature++ # Handles the empty-page case and advances self.page.+ super().update_state(response, data)+ if not self._has_next_page:+ return++ if data is not None and len(data) < self.per_page:+ self._has_next_page = False+ return++ if repeats_previous_page:+ logger.warning(+ "FirstPromoter returned an identical page twice; stopping pagination "+ "(the endpoint may not support the `page` parameter)"+ )+ self._has_next_page = False+++def _drop_fields(row: dict[str, Any], fields: tuple[str, ...]) -> dict[str, Any]:+ """Strip `fields` from a row before storage. Mutates and returns `row` so it can be used+ directly as a `data_map`."""+ for field in fields:+ row.pop(field, None)+ return row+++def rest_api_client_config(api_key: str, account_id: str, api_version: str) -> ClientConfig:+ return {+ "base_url": base_url(api_version),+ "auth": {"type": "bearer", "token": api_key},+ # The account id header is mandatory on every Admin API call - without it the API key+ # alone fails auth.+ "headers": {"ACCOUNT-ID": account_id, "Accept": "application/json"},+ # Pin every request to the FirstPromoter host and refuse to follow a 3xx, so a+ # server-side redirect can never replay the bearer token off-host.+ "allowed_hosts": [],+ "allow_redirects": False,+ # Promoter rows carry the `password_setup_url` credential plus PII (emails, names, tax-form+ # URLs) that the name-based sample scrubbers don't recognise. Sample capture observes the+ # raw body before `data_map` strips the credential, so keep these bodies out of shared HTTP+ # sample storage entirely. Requests stay metered and logged with the API key redacted.+ "session": make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False),+ }+++def get_resource(+ endpoint: str,+ should_use_incremental_field: bool,+ incremental_field_name: str | None = None,+) -> EndpointResource:+ config = FIRST_PROMOTER_ENDPOINTS[endpoint]++ endpoint_config: Endpoint = {+ "path": config.path,+ "params": dict(config.extra_params),+ "paginator": FirstPromoterPaginator(),+ # Fail loud if the response shape changes, rather than silently syncing 0 rows.+ "data_selector_required": True,+ }+ if config.data_selector:+ endpoint_config["data_selector"] = config.data_selector++ use_incremental = (+ should_use_incremental_field and bool(config.incremental_fields) and config.incremental_start_param is not None+ )+ if use_incremental and config.incremental_start_param is not None:+ endpoint_config["incremental"] = _incremental_window(+ config.incremental_start_param,+ incremental_field_name or config.default_incremental_field or "created_at",+ )++ resource: EndpointResource = {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+ if config.redact_fields:+ # Strip credential fields (e.g. `password_setup_url`) from each row before it's persisted.+ resource["data_map"] = partial(_drop_fields, fields=config.redact_fields)+ return resource+++def _make_source_response(+ endpoint_config: FirstPromoterEndpointConfig,+ items_fn: Callable[[], Iterable[Any]],+) -> SourceResponse:+ return SourceResponse(+ name=endpoint_config.name,+ items=items_fn,+ primary_keys=endpoint_config.primary_key,+ # Every incremental endpoint is requested with an explicit ascending sort on its cursor.+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )+++def first_promoter_source(+ api_key: str,+ account_id: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ api_version: str,+ resumable_source_manager: Optional[ResumableSourceManager[FirstPromoterResumeConfig]] = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = FIRST_PROMOTER_ENDPOINTS[endpoint]++ config: RESTAPIConfig = {+ "client": rest_api_client_config(api_key, account_id, api_version),+ "resource_defaults": {},+ "resources": [get_resource(endpoint, should_use_incremental_field, incremental_field)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None+ if resumable_source_manager is not None:+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"page": resume_config.page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only while there is another page to resume to; the Redis TTL cleans up on+ # completion.+ if resumable_source_manager is None or not state or state.get("page") is None:+ return+ resumable_source_manager.save_state(FirstPromoterResumeConfig(page=int(state["page"])))++ resume_hook = save_checkpoint++ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=resume_hook,+ initial_paginator_state=initial_paginator_state,+ )+ return _make_source_response(endpoint_config, lambda: resource)+++def validate_credentials(api_key: str, account_id: str, api_version: str) -> tuple[bool, str | None]:+ # capture=False: the probe hits `/promoters`, whose rows carry the `password_setup_url`+ # credential and promoter PII; keep the response body out of shared HTTP sample storage.+ response = make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False).get(+ f"{base_url(api_version)}/promoters",+ headers={"Authorization": f"Bearer {api_key}", "ACCOUNT-ID": account_id, "Accept": "application/json"},+ params={"per_page": 1},+ timeout=10,+ )+ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return (+ False,+ "FirstPromoter rejected these credentials. Check the API key and account ID under "+ "Settings > Integrations > Manage API keys.",+ )+ return False, f"FirstPromoter API returned an unexpected status code: {response.status_code}"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/settings.pynew file mode 100644index 000000000000..370fcdbee6e9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/settings.py@@ -0,0 +1,121 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++FIRST_PROMOTER_HOST = "https://api.firstpromoter.com"++# The Admin API's maximum `per_page`. Requesting less just costs more round trips against the+# 400 requests/minute per-account budget.+DEFAULT_PAGE_SIZE = 100++# A commission's `status` (pending -> approved/denied), `is_paid` and payout linkage all change+# after the row is created, but the only server-side time filter is on `created_at`. Re-read a+# trailing month on every incremental run so those transitions land; the merge dedupes on `id`.+# Users whose approval window is longer can raise it in the schema's sync settings.+COMMISSIONS_INCREMENTAL_LOOKBACK_SECONDS = 30 * 24 * 60 * 60+++def base_url(api_version: str) -> str:+ return f"{FIRST_PROMOTER_HOST}/api/{api_version}/company"+++@dataclass+class FirstPromoterEndpointConfig:+ name: str+ path: str+ primary_key: list[str]+ # Only /promoters wraps its rows in `{"data": [...], "meta": {...}}`; every other Admin API+ # list endpoint returns a bare JSON array.+ data_selector: str | None = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+ # Bracket-nested server-side filter that carries the incremental watermark, e.g.+ # `filters[created_at][from]`.+ incremental_start_param: str | None = None+ partition_key: str | None = None+ # Merged into every request. Used for the documented `sorting[<field>]` params, which keep+ # page boundaries stable while rows are inserted mid-sync.+ extra_params: dict[str, str] = field(default_factory=dict)+ # Response fields stripped from every row before storage because they are credentials, not+ # data - a warehouse table is the wrong place for them and any project member with query+ # access could read one.+ redact_fields: tuple[str, ...] = ()+ description: str | None = None+++FIRST_PROMOTER_ENDPOINTS: dict[str, FirstPromoterEndpointConfig] = {+ "commissions": FirstPromoterEndpointConfig(+ name="commissions",+ path="/commissions",+ primary_key=["id"],+ incremental_fields=[incremental_field("created_at")],+ default_incremental_field="created_at",+ incremental_start_param="filters[created_at][from]",+ partition_key="created_at",+ extra_params={"sorting[created_at]": "asc"},+ description="Commissions earned by promoters, including sale amount, payout status and fraud checks.",+ ),+ "payouts": FirstPromoterEndpointConfig(+ name="payouts",+ path="/payouts",+ primary_key=["id"],+ partition_key="created_at",+ extra_params={"sorting[period_start]": "asc"},+ # Full refresh: the only date filters are on the payout period, not on creation, and a+ # payout's status walks pending -> processing -> completed/failed long after it exists.+ description="Payouts owed to or already paid to promoters, grouped by payout period.",+ ),+ "promo_codes": FirstPromoterEndpointConfig(+ name="promo_codes",+ path="/promo_codes",+ primary_key=["id"],+ description="Promo/coupon codes attached to promoter campaigns.",+ ),+ "promoter_campaigns": FirstPromoterEndpointConfig(+ name="promoter_campaigns",+ path="/promoter_campaigns",+ primary_key=["id"],+ partition_key="created_at",+ description="A promoter's participation in one campaign, with its referral link, coupon and stats.",+ ),+ "promoters": FirstPromoterEndpointConfig(+ name="promoters",+ path="/promoters",+ primary_key=["id"],+ data_selector="data",+ partition_key="joined_at",+ extra_params={"sorting[joined_at]": "asc"},+ # A promoter row carries `password_setup_url`, a link that sets that promoter's dashboard+ # password. It's a live credential, not analytics data, so it never reaches a table.+ redact_fields=("password_setup_url",),+ # Full refresh: `filters[joined_at][from]` exists, but every interesting field on a+ # promoter (stats, balances, state, last_login_at) keeps moving after they join, so a+ # joined_at cursor would freeze them at their first-imported values.+ description="Affiliates and referral partners, with their profile, campaign stats and balances.",+ ),+ "referrals": FirstPromoterEndpointConfig(+ name="referrals",+ path="/referrals",+ primary_key=["id"],+ partition_key="created_at",+ # Full refresh: `filters[created_at][from]` exists, but this endpoint documents no+ # `sorting` param, so row order can't be pinned, and a referral's `state` changes for as+ # long as the customer is around.+ description="Leads and customers referred by promoters, with their state and attribution.",+ ),+}++ENDPOINTS = tuple(FIRST_PROMOTER_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in FIRST_PROMOTER_ENDPOINTS.items()+}++DESCRIPTIONS: dict[str, str] = {+ name: config.description for name, config in FIRST_PROMOTER_ENDPOINTS.items() if config.description+}++INCREMENTAL_LOOKBACK_SECONDS: dict[str, int] = {+ "commissions": COMMISSIONS_INCREMENTAL_LOOKBACK_SECONDS,+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/source.pyindex 7f2ee7d23472..5c6e10a981e3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/source.py@@ -1,13 +1,36 @@-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.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 (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.first_promoter import (+ FirstPromoterResumeConfig,+ first_promoter_source,+ validate_credentials as validate_first_promoter_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.settings import (+ DESCRIPTIONS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ INCREMENTAL_LOOKBACK_SECONDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.firstpromoter import (FirstPromoterSourceConfig,)@@ -15,19 +38,115 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class FirstPromoterSource(SimpleSource[FirstPromoterSourceConfig]):+class FirstPromoterSource(ResumableSource[FirstPromoterSourceConfig, FirstPromoterResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # `/api/v2/` is a real version segment: the legacy v1 Admin API still answers on the same+ # host and is not what this source calls.+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://docs.firstpromoter.com/api-reference-v2/api-admin/introduction"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FIRSTPROMOTER+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "FirstPromoter rejected these credentials. Check the API key and account ID under Settings > Integrations > Manage API keys.",+ "403 Client Error: Forbidden for url": "This FirstPromoter API key is not allowed to read this data. Check the key under Settings > Integrations > Manage API keys.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: FirstPromoterSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ schemas = build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, descriptions=DESCRIPTIONS)+ for schema in schemas:+ schema.default_incremental_lookback_seconds = INCREMENTAL_LOOKBACK_SECONDS.get(schema.name)+ return schemas++ def validate_credentials(+ self,+ config: FirstPromoterSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_first_promoter_credentials(+ config.api_key, config.account_id, self.resolve_api_version(api_version)+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FirstPromoterResumeConfig]:+ return ResumableSourceManager[FirstPromoterResumeConfig](inputs, FirstPromoterResumeConfig)++ def source_for_pipeline(+ self,+ config: FirstPromoterSourceConfig,+ resumable_source_manager: ResumableSourceManager[FirstPromoterResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return first_promoter_source(+ api_key=config.api_key,+ account_id=config.account_id,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ api_version=self.resolve_api_version(inputs.api_version),+ 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,+ incremental_field=inputs.incremental_field,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.FIRST_PROMOTER,category=DataWarehouseSourceCategory.MARKETING___EMAIL,- keywords=["first promoter"],label="FirstPromoter",+ caption=(+ "Import promoters, referrals, commissions, payouts and promo codes from your "+ "FirstPromoter affiliate program.\n\n"+ "Find your API key and account ID in FirstPromoter under "+ "**Settings > Integrations > Manage API keys**."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/first-promoter",iconPath="/static/services/first_promoter.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ keywords=["first promoter", "affiliate", "referral"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="account_id",+ label="Account ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/tests/test_first_promoter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/tests/test_first_promoter.pynew file mode 100644index 000000000000..55732e40fe85--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/tests/test_first_promoter.py@@ -0,0 +1,297 @@+from datetime import UTC, date, datetime+from typing import Any, cast++from unittest.mock import MagicMock, Mock, patch++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.first_promoter import (+ FirstPromoterPaginator,+ FirstPromoterResumeConfig,+ _format_filter_date,+ first_promoter_source,+ get_resource,+ rest_api_client_config,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.settings import DEFAULT_PAGE_SIZE+++def _rows(count: int, start_id: int = 1) -> list[dict[str, Any]]:+ return [{"id": start_id + i} for i in range(count)]+++def _request() -> Mock:+ request = Mock()+ request.params = None+ return request+++class TestFirstPromoterTransport:+ @parameterized.expand(+ [+ ("full_page_keeps_paging", _rows(DEFAULT_PAGE_SIZE), True),+ # The vendor's documented end-of-data signal: fewer records than per_page.+ ("short_page_is_terminal", _rows(DEFAULT_PAGE_SIZE - 1), False),+ ("empty_page_is_terminal", [], False),+ ]+ )+ def test_paginator_termination(self, _name: str, data: list[dict[str, Any]], expected_has_next: bool) -> None:+ paginator = FirstPromoterPaginator()+ paginator.update_state(Mock(), data=data)+ assert paginator.has_next_page is expected_has_next++ def test_paginator_stops_when_a_page_repeats(self) -> None:+ # An endpoint that ignores `page` would otherwise return the same full page forever and+ # spin until the Temporal activity times out.+ paginator = FirstPromoterPaginator()+ page = _rows(DEFAULT_PAGE_SIZE)++ paginator.update_state(Mock(), data=page)+ assert paginator.has_next_page is True++ paginator.update_state(Mock(), data=list(page))+ assert paginator.has_next_page is False++ def test_paginator_keeps_paging_through_distinct_full_pages(self) -> None:+ paginator = FirstPromoterPaginator()+ paginator.update_state(Mock(), data=_rows(DEFAULT_PAGE_SIZE, start_id=1))+ paginator.update_state(Mock(), data=_rows(DEFAULT_PAGE_SIZE, start_id=1 + DEFAULT_PAGE_SIZE))+ assert paginator.has_next_page is True++ def test_paginator_sends_page_and_page_size(self) -> None:+ paginator = FirstPromoterPaginator()+ request = _request()++ paginator.init_request(request)+ assert request.params == {"page": 1, "per_page": DEFAULT_PAGE_SIZE}++ paginator.update_state(Mock(), data=_rows(DEFAULT_PAGE_SIZE))+ paginator.update_request(request)+ assert request.params == {"page": 2, "per_page": DEFAULT_PAGE_SIZE}++ def test_paginator_resume_state_round_trip(self) -> None:+ paginator = FirstPromoterPaginator()+ paginator.update_state(Mock(), data=_rows(DEFAULT_PAGE_SIZE))+ state = paginator.get_resume_state()+ assert state == {"page": 2}++ resumed = FirstPromoterPaginator()+ resumed.set_resume_state(cast(dict[str, Any], state))+ request = _request()+ resumed.init_request(request)+ assert request.params["page"] == 2++ @parameterized.expand(+ [+ ("naive_datetime", datetime(2026, 3, 1, 12, 30, 45, 999999), "2026-03-01"),+ ("aware_datetime", datetime(2026, 3, 1, 23, 59, 59, tzinfo=UTC), "2026-03-01"),+ ("date", date(2026, 3, 1), "2026-03-01"),+ ("passthrough_string", "1970-01-01", "1970-01-01"),+ ]+ )+ def test_format_filter_date(self, _name: str, value: Any, expected: str) -> None:+ assert _format_filter_date(value) == expected++ def test_commissions_resource_is_incremental(self) -> None:+ resource = cast(dict[str, Any], get_resource("commissions", should_use_incremental_field=True))+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}+ incremental = resource["endpoint"]["incremental"]+ # A flat `created_at` param is silently ignored by the API — the filter is bracket-nested.+ assert incremental["start_param"] == "filters[created_at][from]"+ assert incremental["cursor_path"] == "created_at"+ # sort_mode="asc" checkpoints the watermark mid-sync, so the request must pin that order.+ assert resource["endpoint"]["params"]["sorting[created_at]"] == "asc"++ def test_commissions_resource_full_refresh(self) -> None:+ resource = cast(dict[str, Any], get_resource("commissions", should_use_incremental_field=False))+ assert resource["write_disposition"] == "replace"+ assert "incremental" not in resource["endpoint"]++ def test_commissions_resource_honors_user_selected_cursor(self) -> None:+ resource = cast(+ dict[str, Any],+ get_resource("commissions", should_use_incremental_field=True, incremental_field_name="created_at"),+ )+ assert resource["endpoint"]["incremental"]["cursor_path"] == "created_at"++ @parameterized.expand(+ [+ ("payouts",),+ ("promo_codes",),+ ("promoter_campaigns",),+ ("promoters",),+ ("referrals",),+ ]+ )+ def test_full_refresh_endpoints_never_send_an_incremental_filter(self, endpoint: str) -> None:+ # These have no usable incremental filter, so asking for incremental must not quietly+ # produce a merge write with no window on it.+ resource = cast(dict[str, Any], get_resource(endpoint, should_use_incremental_field=True))+ assert resource["write_disposition"] == "replace"+ assert "incremental" not in resource["endpoint"]++ @parameterized.expand(+ [+ # Only /promoters wraps its rows in an envelope; the rest return a bare array.+ ("promoters", "data"),+ ("commissions", None),+ ("referrals", None),+ ("payouts", None),+ ("promo_codes", None),+ ("promoter_campaigns", None),+ ]+ )+ def test_response_envelope_per_endpoint(self, endpoint: str, expected_selector: str | None) -> None:+ resource = cast(dict[str, Any], get_resource(endpoint, should_use_incremental_field=False))+ assert resource["endpoint"].get("data_selector") == expected_selector+ # Fail loud on a changed response shape instead of silently syncing 0 rows.+ assert resource["endpoint"]["data_selector_required"] is True++ def test_promoters_resource_strips_the_password_setup_credential(self) -> None:+ # `password_setup_url` is a live link that sets the promoter's password; stripping it in the+ # data_map is what keeps it out of the warehouse table. Losing this wiring is a silent+ # account-takeover leak, so pin the behaviour end to end.+ resource = cast(dict[str, Any], get_resource("promoters", should_use_incremental_field=False))+ redacted = resource["data_map"]({"id": 1, "email": "[email protected]", "password_setup_url": "https://fp/setup"})+ assert redacted == {"id": 1, "email": "[email protected]"}++ @parameterized.expand([("commissions",), ("payouts",), ("promo_codes",), ("promoter_campaigns",), ("referrals",)])+ def test_non_promoter_resources_keep_every_field(self, endpoint: str) -> None:+ # Only /promoters carries a credential; the redaction must not silently drop columns anywhere+ # else, so these endpoints get no data_map at all.+ resource = cast(dict[str, Any], get_resource(endpoint, should_use_incremental_field=False))+ assert "data_map" not in resource++ def test_client_config_sends_both_credentials_and_pins_the_host(self) -> None:+ config = rest_api_client_config("fp-key", "98765", "v2")+ assert config["base_url"] == "https://api.firstpromoter.com/api/v2/company"+ assert config["auth"] == {"type": "bearer", "token": "fp-key"}+ # Omitting the account id header fails auth even with a valid bearer token.+ assert cast(dict[str, str], config["headers"])["ACCOUNT-ID"] == "98765"+ # A redirect off the FirstPromoter host would otherwise replay the bearer token.+ assert config["allowed_hosts"] == []+ assert config["allow_redirects"] is False++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.first_promoter.make_tracked_session"+ )+ def test_client_config_keeps_response_bodies_out_of_sample_capture(self, mock_session: MagicMock) -> None:+ # Sample capture sees the raw body before the data_map runs, so the promoter credential (and+ # PII) would leak into shared sample storage unless capture is off on the sync session.+ config = rest_api_client_config("fp-key", "98765", "v2")+ assert config["session"] is mock_session.return_value+ assert mock_session.call_args.kwargs["capture"] is False+ assert mock_session.call_args.kwargs["redact_values"] == ("fp-key",)++ @parameterized.expand(+ [+ (200, True, None),+ (401, False, "rejected these credentials"),+ (403, False, "rejected these credentials"),+ (500, False, "unexpected status code"),+ ]+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.first_promoter.make_tracked_session"+ )+ def test_validate_credentials_status_mapping(+ self, status: int, expected_valid: bool, message_fragment: str | None, mock_session: MagicMock+ ) -> None:+ mock_session.return_value.get.return_value = Mock(status_code=status)++ is_valid, message = validate_credentials("fp-key", "98765", "v2")++ assert is_valid is expected_valid+ if message_fragment is None:+ assert message is None+ else:+ assert message is not None and message_fragment in message++ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://api.firstpromoter.com/api/v2/company/promoters"+ assert call.kwargs["headers"]["Authorization"] == "Bearer fp-key"+ assert call.kwargs["headers"]["ACCOUNT-ID"] == "98765"+ assert mock_session.call_args.kwargs["allow_redirects"] is False+ # The probe reads /promoters, whose bodies carry the password_setup_url credential and PII.+ assert mock_session.call_args.kwargs["capture"] is False++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.first_promoter.rest_api_resource"+ )+ def test_saved_state_resumes_at_the_next_page(self, mock_rest_api_resource: MagicMock) -> None:+ manager = MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = FirstPromoterResumeConfig(page=7)++ first_promoter_source(+ api_key="fp-key",+ account_id="98765",+ endpoint="commissions",+ team_id=1,+ job_id="job-1",+ api_version="v2",+ resumable_source_manager=manager,+ )++ assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] == {"page": 7}++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.first_promoter.rest_api_resource"+ )+ def test_resume_hook_saves_state_only_when_there_is_a_next_page(self, mock_rest_api_resource: MagicMock) -> None:+ manager = MagicMock()+ manager.can_resume.return_value = False++ first_promoter_source(+ api_key="fp-key",+ account_id="98765",+ endpoint="commissions",+ team_id=1,+ job_id="job-1",+ api_version="v2",+ resumable_source_manager=manager,+ )++ resume_hook = mock_rest_api_resource.call_args.kwargs["resume_hook"]++ resume_hook({"page": 3})+ assert manager.save_state.call_args.args[0] == FirstPromoterResumeConfig(page=3)++ manager.save_state.reset_mock()+ resume_hook(None)+ resume_hook({})+ manager.save_state.assert_not_called()++ @parameterized.expand(+ [+ ("commissions", ["id"], ["created_at"]),+ ("promoters", ["id"], ["joined_at"]),+ ("promo_codes", ["id"], None),+ ]+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.first_promoter.rest_api_resource"+ )+ def test_source_response_keys_and_partitioning(+ self,+ endpoint: str,+ expected_primary_keys: list[str],+ expected_partition_keys: list[str] | None,+ _mock_rest_api_resource: MagicMock,+ ) -> None:+ response = first_promoter_source(+ api_key="fp-key",+ account_id="98765",+ endpoint=endpoint,+ team_id=1,+ job_id="job-1",+ api_version="v2",+ )++ assert response.name == endpoint+ assert response.primary_keys == expected_primary_keys+ assert response.sort_mode == "asc"+ assert response.partition_keys == expected_partition_keys+ # Partitioning on a field that never changes once set; never on a mutating one.+ assert response.partition_mode == ("datetime" if expected_partition_keys else None)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/tests/test_first_promoter_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/tests/test_first_promoter_source.pynew file mode 100644index 000000000000..f9b61cdf41f8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/tests/test_first_promoter_source.py@@ -0,0 +1,156 @@+from unittest import mock++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.first_promoter import (+ FirstPromoterResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.settings import (+ COMMISSIONS_INCREMENTAL_LOOKBACK_SECONDS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.source import FirstPromoterSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.firstpromoter import (+ FirstPromoterSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++FULL_REFRESH_ENDPOINTS = ("payouts", "promo_codes", "promoter_campaigns", "promoters", "referrals")+++class TestFirstPromoterSource:+ def setup_method(self) -> None:+ self.source = FirstPromoterSource()+ self.team_id = 123+ self.config = FirstPromoterSourceConfig(api_key="fp-key", account_id="98765")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.FIRSTPROMOTER++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "FirstPromoter"+ assert config.label == "FirstPromoter"+ assert config.category == DataWarehouseSourceCategory.MARKETING___EMAIL+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/first_promoter.png"+ # The source ships visible — a truthy unreleasedSource hides it from every user.+ assert not config.unreleasedSource++ def test_credential_fields(self) -> None:+ config = self.source.get_source_config+ # Both are mandatory: the Admin API rejects a request carrying only the bearer token.+ assert [f.name for f in config.fields] == ["api_key", "account_id"]+ api_key, account_id = config.fields+ assert isinstance(api_key, SourceFieldInputConfig)+ assert isinstance(account_id, SourceFieldInputConfig)+ assert api_key.type == SourceFieldInputConfigType.PASSWORD+ assert api_key.secret is True+ assert api_key.required is True+ assert account_id.required is True++ def test_get_schemas_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_commissions_is_the_only_incremental_table(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["commissions"].supports_incremental is True+ assert [f["field"] for f in schemas["commissions"].incremental_fields] == ["created_at"]+ # Commission status and payout linkage mutate after creation, so an incremental run has to+ # re-read a trailing window rather than only rows newer than the watermark.+ assert schemas["commissions"].default_incremental_lookback_seconds == COMMISSIONS_INCREMENTAL_LOOKBACK_SECONDS++ @parameterized.expand([(name,) for name in FULL_REFRESH_ENDPOINTS])+ def test_mutable_tables_stay_full_refresh(self, name: str) -> None:+ # These endpoints either have no usable server-side time filter or no way to pin row+ # order; offering incremental would freeze their mutating fields at first-import values.+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas[name].supports_incremental is False+ assert schemas[name].incremental_fields == []+ assert schemas[name].default_incremental_lookback_seconds is None++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["commissions"])+ assert [s.name for s in schemas] == ["commissions"]++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://api.firstpromoter.com/api/v2/company/promoters", True),+ ("403 Client Error: Forbidden for url: https://api.firstpromoter.com/api/v2/company/commissions", True),+ (+ "429 Client Error: Too Many Requests for url: https://api.firstpromoter.com/api/v2/company/payouts",+ False,+ ),+ (+ "500 Server Error: Internal Server Error for url: https://api.firstpromoter.com/api/v2/company/payouts",+ False,+ ),+ ]+ )+ def test_non_retryable_errors_match_auth_failures_only(self, observed_error: str, expect_match: bool) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable) is expect_match++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.source.validate_first_promoter_credentials"+ )+ def test_validate_credentials_plumbs_both_credentials_and_version(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)+ assert mock_validate.call_args.args == ("fp-key", "98765", "v2")++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert manager._data_class is FirstPromoterResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.source.first_promoter_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "commissions"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ inputs.api_version = None+ inputs.should_use_incremental_field = True+ inputs.incremental_field = "created_at"+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "fp-key"+ assert kwargs["account_id"] == "98765"+ assert kwargs["endpoint"] == "commissions"+ assert kwargs["api_version"] == "v2"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["incremental_field"] == "created_at"+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.source.first_promoter_source"+ )+ def test_source_for_pipeline_omits_watermark_when_not_incremental(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "commissions"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_canonical_descriptions_cover_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/firstpromoter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/firstpromoter.pyindex cbf44a139dbb..9623312afefb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/firstpromoter.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/firstpromoter.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass FirstPromoterSourceConfig(config.Config):- pass+ api_key: str+ account_id: str