: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 uppromote import source (#72651)
Tom Owersdb64a9b7613c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 658a53c399f6..4d2cbccfb09a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -566,6 +566,7 @@ the row lists both.| unleash | HTTP | requests | ✅ || unstructured | HTTP | requests | ✅ || upstash | HTTP | requests | ✅ |+| uppromote | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || uptimerobot | HTTP | requests | ✅ || us_census | HTTP | requests | ✅ || usersnap | HTTP | requests + PyJWT | ✅ |@@ -980,6 +981,7 @@ doesn't conflict with concurrent PRs.- twenty- twitter_ads+- tyntec_sms- uppromote- uptick- uservoicediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/uppromote.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/uppromote.pyindex 1eeb00ff3fe7..1862984e689f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/uppromote.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/uppromote.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass UpPromoteSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/canonical_descriptions.pynew file mode 100644index 000000000000..ffc41fc69a18--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/canonical_descriptions.py@@ -0,0 +1,143 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "programs": {+ "description": "An affiliate program with its commission structure, exclusions, and payment settings.",+ "docs_url": "https://aff-api.uppromote.com/docs/v2/get-programs-28435009e0",+ "columns": {+ "id": "Unique identifier for the program.",+ "name": "Name of the program.",+ "is_default": "Whether this is the store's default program.",+ "status": "Program status (active or inactive).",+ "rule": "Commission rule type applied by the program.",+ "description": "Description of the program.",+ "commission_type": "How commissions are calculated (e.g. percent of sale, flat rate).",+ "commission_amount": "Commission amount or rate applied by the program.",+ "commission_advanced": "Tiered commission levels with their conditions and rates.",+ "new_customer_commission": "Extra commission settings for referrals from new customers.",+ "lifetime_commission": "Lifetime commission settings for connected customers.",+ "special_coupon_commission": "Commission settings applied to special coupons.",+ "exclude_product_tax": "Whether product tax is excluded from commission calculation.",+ "exclude_shipping": "Whether shipping is excluded from commission calculation.",+ "exclude_shipping_tax": "Whether shipping tax is excluded from commission calculation.",+ "exclude_tip": "Whether tips are excluded from commission calculation.",+ "exclude_self_referral": "Whether self-referrals are excluded from commission.",+ "payment_methods": "Payment methods available to affiliates in this program.",+ "payment_default": "Default payment method for affiliates in this program.",+ "created_at": "When the program was created.",+ },+ },+ "affiliates": {+ "description": "An affiliate account with profile details, program membership, and commission totals.",+ "docs_url": "https://aff-api.uppromote.com/docs/v2/get-affiliates-21170049e0",+ "columns": {+ "id": "Unique identifier for the affiliate.",+ "email": "Email of the affiliate.",+ "first_name": "First name of the affiliate.",+ "last_name": "Last name of the affiliate.",+ "status": "Affiliate account status (active, inactive, or pending).",+ "email_verified": "Email verification status (verified or unverified).",+ "company": "Company name of the affiliate.",+ "address": "Address of the affiliate.",+ "city": "City of the affiliate.",+ "state": "State of the affiliate.",+ "zipcode": "Zip code of the affiliate.",+ "country": "Country of the affiliate.",+ "phone": "Phone number of the affiliate.",+ "facebook": "Facebook profile of the affiliate.",+ "twitter": "X (formerly Twitter) profile of the affiliate.",+ "youtube": "YouTube channel of the affiliate.",+ "instagram": "Instagram profile of the affiliate.",+ "website": "Website of the affiliate.",+ "tiktok": "TikTok profile of the affiliate.",+ "w9_form": "W9 form uploaded by the affiliate.",+ "internal_note": "Internal note about the affiliate.",+ "personal_detail": "Personal detail text from the affiliate's profile.",+ "created_at": "Affiliate account registration date and time.",+ "default_affiliate_link": "Default affiliate tracking link.",+ "custom_affiliate_link": "Custom affiliate tracking link.",+ "program_id": "ID of the program the affiliate belongs to.",+ "program_name": "Name of the program the affiliate belongs to.",+ "custom_fields": "Custom registration fields (label and value).",+ "coupons": "Coupons assigned to the affiliate.",+ "vat_number": "VAT number of the affiliate.",+ "tax_value": "Tax percentage of the affiliate.",+ "up_line_affiliate_id": "ID of the upline affiliate in a multi-level network.",+ "up_line_affiliate_email": "Email of the upline affiliate.",+ "payment_method": "Payment method of the affiliate (e.g. paypal, bank, store_credit).",+ "payment_info": "Payment details of the affiliate.",+ "paid_amount": "Total commission already paid to the affiliate.",+ "approved_amount": "Total approved commission awaiting payment.",+ "pending_amount": "Total pending commission of the affiliate.",+ "denied_amount": "Total denied commission of the affiliate.",+ },+ },+ "coupons": {+ "description": "A discount coupon assigned to an affiliate for coupon-based referral tracking.",+ "docs_url": "https://aff-api.uppromote.com/docs/v2/get-coupons-21170056e0",+ "columns": {+ "id": "Unique identifier for the coupon assignment.",+ "affiliate_id": "ID of the affiliate the coupon is assigned to.",+ "affiliate_email": "Email of the affiliate the coupon is assigned to.",+ "coupon": "The coupon code.",+ "description": "Description of the coupon (discount details).",+ "created_at": "When the coupon was assigned.",+ },+ },+ "referrals": {+ "description": "A referral (converted order) attributed to an affiliate, with its commission and status.",+ "docs_url": "https://aff-api.uppromote.com/docs/v2/get-list-referrals-21170075e0",+ "columns": {+ "id": "Unique identifier for the referral.",+ "order_id": "ID of the Shopify order the referral belongs to.",+ "order_number": "Order number of the referred order.",+ "customer_id": "ID of the customer who placed the order.",+ "quantity": "Number of items in the referred order.",+ "total_sales": "Total sales amount of the referred order.",+ "commission_rule": "Commission rule applied (program, rate, and type).",+ "commission_adjustment": "Manual adjustment applied to the commission.",+ "status": "Referral status (e.g. pending, approved, denied, paid).",+ "commission": "Commission amount earned by the affiliate.",+ "refund_id": "ID of the refund if the order was refunded.",+ "tracking_type": "How the referral was tracked (e.g. affiliate link, coupon).",+ "affiliate": "The affiliate credited with the referral (id, email, name).",+ "coupon_applied": "Coupon code applied to the order, if any.",+ "customer_email": "Email of the referred customer.",+ "created_at": "When the referral was recorded.",+ },+ },+ "payments_paid": {+ "description": "A completed affiliate payout, with the processed amount and payment method.",+ "docs_url": "https://aff-api.uppromote.com/docs/v2/get-paid-payments-history-21170059e0",+ "columns": {+ "payment_id": "Unique identifier for the payment.",+ "affiliate_id": "ID of the affiliate who was paid.",+ "affiliate_email": "Email of the affiliate who was paid.",+ "status": "Payment status.",+ "total_referrals": "Number of referrals covered by the payment.",+ "total_processed": "Amount processed in the payment.",+ "payment_method": "Payment method used (e.g. paypal, bank, store_credit).",+ "processed_at": "When the payment was processed.",+ "referral_ids": "IDs of the referrals covered by the payment.",+ },+ },+ "payments_unpaid": {+ "description": (+ "A snapshot of outstanding (approved but unpaid) commission per affiliate. "+ "Aggregated totals, refreshed in full on every sync."+ ),+ "docs_url": "https://aff-api.uppromote.com/docs/v2/get-unpaid-payments-21170058e0",+ "columns": {+ "affiliate_id": "ID of the affiliate with outstanding commission.",+ "affiliate_email": "Email of the affiliate with outstanding commission.",+ "total_referrals": "Number of referrals awaiting payment.",+ "payment_method": "Payment method configured by the affiliate.",+ "total_commission": "Total outstanding commission amount.",+ "total_sales": "Total sales amount behind the outstanding commission.",+ "total_products": "Number of products behind the outstanding commission.",+ "referral_ids": "IDs of the referrals awaiting payment.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/settings.pynew file mode 100644index 000000000000..65fbaf65e96c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/settings.py@@ -0,0 +1,114 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++UPPROMOTE_BASE_URL = "https://aff-api.uppromote.com/api/v2"++# The docs don't state a per_page cap; the API is a Laravel-style paginator whose examples use+# small values. 100 keeps request counts low without being an outlandish page size.+UPPROMOTE_PAGE_SIZE = 100++# Maps PostHog webhook-backed schema name -> the logical UpPromote object type used to route+# incoming webhook payloads into the right warehouse table (payloads carry no event name, so the+# hog function derives the type from the payload shape).+RESOURCE_TO_UPPROMOTE_OBJECT_TYPE: dict[str, str] = {+ "affiliates": "affiliate",+ "referrals": "referral",+ "payments_paid": "payment",+}++# The `*.status-changed` events are intentionally not subscribed: their payload is a+# {previous_status, current_status} diff, not the full object, so it can't be merged into the+# table on the primary key. Status changes reconcile on the next pull sync instead.+UPPROMOTE_OBJECT_TYPE_TO_EVENTS: dict[str, tuple[str, ...]] = {+ "affiliate": ("affiliate.new", "affiliate.approved", "affiliate.inactive"),+ "referral": ("referral.new", "referral.approved", "referral.denied"),+ "payment": ("payment.paid",),+}+++@dataclass+class UpPromoteEndpointConfig:+ name: str+ path: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Whether the endpoint accepts the `from_date`/`to_date` creation-time window params+ # (ISO 8601 UTC). UpPromote has no updated-at cursor, so this is the only server-side+ # incremental filter available.+ supports_date_window: bool = False+ # Referrals reject `from_date` without `to_date` ("required with to_date"), so both are sent.+ requires_to_date: bool = False+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable creation-time field used for datetime partitioning; never a mutable timestamp.+ partition_key: Optional[str] = None+++_CREATED_AT_FIELD: IncrementalField = {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+}++_PROCESSED_AT_FIELD: IncrementalField = {+ "label": "processed_at",+ "type": IncrementalFieldType.DateTime,+ "field": "processed_at",+ "field_type": IncrementalFieldType.DateTime,+}++UPPROMOTE_ENDPOINTS: dict[str, UpPromoteEndpointConfig] = {+ "programs": UpPromoteEndpointConfig(+ # No date filter on /programs and the table is small — full refresh only.+ name="programs",+ path="/programs",+ partition_key=None,+ ),+ "affiliates": UpPromoteEndpointConfig(+ name="affiliates",+ path="/affiliates",+ supports_date_window=True,+ incremental_fields=[_CREATED_AT_FIELD],+ partition_key="created_at",+ ),+ "coupons": UpPromoteEndpointConfig(+ name="coupons",+ path="/coupons",+ supports_date_window=True,+ incremental_fields=[_CREATED_AT_FIELD],+ partition_key="created_at",+ ),+ "referrals": UpPromoteEndpointConfig(+ name="referrals",+ path="/referrals",+ supports_date_window=True,+ requires_to_date=True,+ incremental_fields=[_CREATED_AT_FIELD],+ partition_key="created_at",+ ),+ "payments_paid": UpPromoteEndpointConfig(+ name="payments_paid",+ path="/payments/paid",+ primary_keys=["payment_id"],+ supports_date_window=True,+ # Paid-payment rows are created when the payout is processed, so the creation-time+ # window effectively filters on `processed_at` — the only timestamp on the row.+ incremental_fields=[_PROCESSED_AT_FIELD],+ partition_key="processed_at",+ ),+ "payments_unpaid": UpPromoteEndpointConfig(+ # Aggregated outstanding-commission snapshot per affiliate; no id or timestamp fields,+ # so it's a full-refresh-only table keyed on the affiliate.+ name="payments_unpaid",+ path="/payments/unpaid",+ primary_keys=["affiliate_id"],+ partition_key=None,+ ),+}++ENDPOINTS = tuple(UPPROMOTE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in UPPROMOTE_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/source.pyindex 6431b73c97c8..dcd849e7bd3c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/source.py@@ -1,21 +1,71 @@-from typing import cast+from typing import TYPE_CHECKING, 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 (+ ExternalWebhookInfo,+ FieldType,+ ResumableSource,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSource,+ WebhookSyncResult,+)+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.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.uppromote import (UpPromoteSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.uppromote.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ RESOURCE_TO_UPPROMOTE_OBJECT_TYPE,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.uppromote.uppromote import (+ UpPromoteResumeConfig,+ all_desired_webhook_events,+ create_webhook as create_uppromote_webhook,+ delete_webhook as delete_uppromote_webhook,+ get_external_webhook_info as get_uppromote_webhook_info,+ sync_webhook_events as sync_uppromote_webhook_events,+ uppromote_source,+ validate_credentials as validate_uppromote_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+if TYPE_CHECKING:+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC+@SourceRegistry.register-class UpPromoteSource(SimpleSource[UpPromoteSourceConfig]):+class UpPromoteSource(+ ResumableSource[UpPromoteSourceConfig, UpPromoteResumeConfig],+ WebhookSource[UpPromoteSourceConfig],+):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://aff-api.uppromote.com/docs/v2/api-overview-1615961m0"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.UPPROMOTE@@ -26,7 +76,166 @@ class UpPromoteSource(SimpleSource[UpPromoteSourceConfig]):name=SchemaExternalDataSourceType.UP_PROMOTE,category=DataWarehouseSourceCategory.ADVERTISING,label="UpPromote",+ releaseStatus=ReleaseStatus.ALPHA,+ caption=(+ "Enter your UpPromote API key to pull your affiliate programs, affiliates, "+ "referrals, coupons, and payments into the PostHog Data warehouse.\n\n"+ "You can create an API key in the UpPromote app under **Settings** > "+ "**Integrations** > **API Key** (available on the Professional plan and above)."+ ),iconPath="/static/services/uppromote.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/uppromote",+ keywords=["affiliate", "referral", "shopify"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="UpPromote API key",+ secret=True,+ ),+ ],+ ),+ webhookSetupCaption=(+ "PostHog subscribes to UpPromote's referral, affiliate, and payment webhook "+ "events for you using your API key, including the signing secret — no manual "+ "steps needed.\n\n"+ "**Manual setup** (only needed if auto-registration failed, e.g. an event is "+ "already subscribed to another URL — UpPromote allows one subscription per "+ "event):\n\n"+ "1. Subscribe the webhook URL shown below to the events you want via "+ "UpPromote's `POST /webhook-subscriptions` API endpoint\n"+ "2. In UpPromote, go to **Settings** > **Integrations** > **Get Secret Key**\n"+ "3. Copy the secret key into the field below"+ ),+ webhookFields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="signing_secret",+ label="Signing secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="UpPromote webhook secret key",+ secret=True,+ ),+ ],+ ),+ )++ @property+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:+ from products.warehouse_sources.backend.temporal.data_imports.sources.uppromote.webhook_template import template++ return template++ @property+ def webhook_resource_map(self) -> dict[str, str]:+ return RESOURCE_TO_UPPROMOTE_OBJECT_TYPE++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.uppromote.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://aff-api.uppromote.com": (+ "Your UpPromote API key is invalid or has been revoked. Create a new API key in "+ "the UpPromote app under Settings > Integrations > API Key, then reconnect."+ ),+ "403 Client Error: Forbidden for url: https://aff-api.uppromote.com": (+ "UpPromote rejected your API key. The API requires the Professional plan or "+ "above — check your plan and API key, then reconnect."+ ),+ }++ def get_schemas(+ self,+ config: UpPromoteSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ # Rows on every windowed endpoint are mutable (referral/affiliate statuses and+ # amounts change), so merge is the only safe incremental disposition.+ merge_only=ENDPOINTS,+ supports_webhooks=tuple(RESOURCE_TO_UPPROMOTE_OBJECT_TYPE.keys()),+ descriptions={+ "payments_unpaid": (+ "Outstanding (approved but unpaid) commission per affiliate. An aggregated "+ "snapshot, refreshed in full on every sync"+ ),+ },+ )++ def validate_credentials(+ self, config: UpPromoteSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ valid, error = validate_uppromote_credentials(config.api_key)+ if valid:+ return True, None+ return False, error or "Invalid UpPromote API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[UpPromoteResumeConfig]:+ return ResumableSourceManager[UpPromoteResumeConfig](inputs, UpPromoteResumeConfig)++ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:+ return WebhookSourceManager(inputs, inputs.logger)++ def create_webhook(self, config: UpPromoteSourceConfig, webhook_url: str, team_id: int) -> WebhookCreationResult:+ return create_uppromote_webhook(config.api_key, webhook_url)++ def get_desired_webhook_events(+ self, config: UpPromoteSourceConfig, eligible_schema_names: list[str]+ ) -> list[str] | None:+ # Every mappable event, not just the selected tables — auto-heals subscriptions created+ # before a table was enabled; unmapped payloads are dropped by the hog function.+ return all_desired_webhook_events()++ def sync_webhook_events(+ self,+ config: UpPromoteSourceConfig,+ webhook_url: str,+ team_id: int,+ eligible_schema_names: list[str],+ ) -> WebhookSyncResult:+ desired_events = self.get_desired_webhook_events(config, eligible_schema_names) or []+ return sync_uppromote_webhook_events(config.api_key, webhook_url, desired_events)++ def get_external_webhook_info(+ self, config: UpPromoteSourceConfig, webhook_url: str, team_id: int+ ) -> ExternalWebhookInfo | None:+ return get_uppromote_webhook_info(config.api_key, webhook_url)++ def delete_webhook(self, config: UpPromoteSourceConfig, webhook_url: str, team_id: int) -> WebhookDeletionResult:+ return delete_uppromote_webhook(config.api_key, webhook_url)++ def source_for_pipeline(+ self,+ config: UpPromoteSourceConfig,+ resumable_source_manager: ResumableSourceManager[UpPromoteResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return uppromote_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ webhook_source_manager=self.get_webhook_source_manager(inputs),+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/tests/test_uppromote.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/tests/test_uppromote.pynew file mode 100644index 000000000000..7ffb2ca4ab4b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/tests/test_uppromote.py@@ -0,0 +1,539 @@+import json+from collections.abc import Iterable+from datetime import UTC, date, datetime+from typing import Any, cast++from unittest.mock import AsyncMock, MagicMock, patch++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import table_from_py_list+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.uppromote.settings import (+ UPPROMOTE_ENDPOINTS,+ UPPROMOTE_PAGE_SIZE,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.uppromote.uppromote import (+ UpPromoteResumeConfig,+ _build_resource,+ _format_datetime,+ _make_webhook_table_transformer,+ _window_start,+ all_desired_webhook_events,+ create_webhook,+ delete_webhook,+ get_external_webhook_info,+ sync_webhook_events,+ uppromote_source,+ validate_credentials,+)++TRANSPORT_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.uppromote.uppromote"++WEBHOOK_URL = "https://hooks.posthog.com/uppromote"+++def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ resp.url = "https://aff-api.uppromote.com/api/v2/test"+ return resp+++def _page(rows: list[dict[str, Any]]) -> Response:+ return _make_http_response({"status": 200, "message": "success", "data": rows})+++def _endpoint(resource: Any) -> dict[str, Any]:+ return cast(dict[str, Any], resource["endpoint"])+++def _make_webhook_manager(enabled: bool = False) -> MagicMock:+ manager = MagicMock()+ manager.webhook_enabled = AsyncMock(return_value=enabled)+ return manager+++class TestDatetimeHelpers:+ @parameterized.expand(+ [+ ("datetime_naive", datetime(2026, 1, 2, 3, 4, 5), "2026-01-02T03:04:05Z"),+ ("datetime_aware", datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), "2026-01-02T03:04:05Z"),+ ("date", date(2026, 1, 2), "2026-01-02T00:00:00Z"),+ ]+ )+ def test_format_datetime(self, _label: str, value: Any, expected: str) -> None:+ assert _format_datetime(value) == expected++ @parameterized.expand(+ [+ # The window start re-reads one second before the watermark so an exclusive+ # `from_date` can't skip boundary rows.+ ("iso_string", "2026-01-01T00:00:10Z", "2026-01-01T00:00:09Z"),+ ("datetime", datetime(2026, 1, 1, 0, 0, 0, tzinfo=UTC), "2025-12-31T23:59:59Z"),+ ("unparseable", "not-a-date", None),+ ("unsupported_type", 12345, None),+ ]+ )+ def test_window_start(self, _label: str, value: Any, expected: str | None) -> None:+ assert _window_start(value) == expected+++class TestBuildResource:+ def test_incremental_run_sends_creation_window(self) -> None:+ resource = _build_resource(+ UPPROMOTE_ENDPOINTS["affiliates"],+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:10Z",+ window_end="2026-02-01T00:00:00Z",+ )+ params = _endpoint(resource)["params"]+ assert params["from_date"] == "2026-01-01T00:00:09Z"+ # Only referrals require the paired to_date; other endpoints filter with from_date alone.+ assert "to_date" not in params+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}++ def test_referrals_send_from_and_to_date_together(self) -> None:+ resource = _build_resource(+ UPPROMOTE_ENDPOINTS["referrals"],+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:10Z",+ window_end="2026-02-01T00:00:00Z",+ )+ params = _endpoint(resource)["params"]+ assert params["from_date"] == "2026-01-01T00:00:09Z"+ assert params["to_date"] == "2026-02-01T00:00:00Z"++ def test_first_incremental_run_sends_no_window(self) -> None:+ resource = _build_resource(+ UPPROMOTE_ENDPOINTS["referrals"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ window_end="2026-02-01T00:00:00Z",+ )+ params = _endpoint(resource)["params"]+ assert "from_date" not in params+ assert "to_date" not in params++ def test_full_refresh_replaces_and_sends_no_window(self) -> None:+ resource = _build_resource(+ UPPROMOTE_ENDPOINTS["affiliates"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ window_end="2026-02-01T00:00:00Z",+ )+ params = _endpoint(resource)["params"]+ assert params == {"per_page": UPPROMOTE_PAGE_SIZE}+ assert resource["write_disposition"] == "replace"++ @parameterized.expand([(name,) for name in UPPROMOTE_ENDPOINTS])+ def test_every_endpoint_builds_a_resource_with_data_selector(self, endpoint: str) -> None:+ resource = _build_resource(+ UPPROMOTE_ENDPOINTS[endpoint],+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ window_end="2026-02-01T00:00:00Z",+ )+ assert resource["name"] == endpoint+ assert _endpoint(resource)["data_selector"] == "data"+ assert resource["table_format"] == "delta"+++class TestUpPromoteSourcePagination:+ def _drive(+ self,+ endpoint: str,+ manager: MagicMock,+ responses: list[Response],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[dict[str, Any]], list[list[dict[str, Any]]]]:+ """Drive ``uppromote_source`` with a mocked HTTP session.++ Returns ``(sent_params, yielded_pages)``. Params are captured at send-time because the+ paginator mutates the Request in place between pages.+ """+ sent_params: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ return next(response_iter)++ # The pull path builds its own capture-disabled session and hands it to RESTClient+ # via config, so patch the factory where the source imports it.+ with patch(f"{TRANSPORT_MODULE}.make_tracked_session") as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ source = uppromote_source(+ api_key="test-key",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ webhook_source_manager=_make_webhook_manager(enabled=False),+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ pages = list(cast(Iterable[list[dict[str, Any]]], source.items()))+ return sent_params, pages++ def test_paginates_until_empty_page_and_saves_resume_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _page([{"id": 1}]),+ _page([{"id": 2}]),+ _page([]),+ ]+ sent_params, pages = self._drive("affiliates", manager, responses)++ assert [p.get("page") for p in sent_params] == [1, 2, 3]+ assert all(p.get("per_page") == UPPROMOTE_PAGE_SIZE for p in sent_params)+ # The terminal empty page only stops pagination; it is not yielded as a batch.+ assert pages == [[{"id": 1}], [{"id": 2}]]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert [state.page for state in saved] == [2, 3]++ def test_resume_seeds_paginator_with_saved_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = UpPromoteResumeConfig(page=5)++ sent_params, _ = self._drive("affiliates", manager, [_page([])])++ assert [p.get("page") for p in sent_params] == [5]+ manager.load_state.assert_called_once()++ def test_resume_reuses_frozen_referral_window_end(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = UpPromoteResumeConfig(page=3, to_date="2026-02-01T00:00:00Z")++ sent_params, _ = self._drive(+ "referrals",+ manager,+ [_page([{"id": 1}]), _page([])],+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:10Z",+ )++ assert [p.get("page") for p in sent_params] == [3, 4]+ assert all(p.get("to_date") == "2026-02-01T00:00:00Z" for p in sent_params)+ assert all(p.get("from_date") == "2026-01-01T00:00:09Z" for p in sent_params)++ # The frozen window end is carried into subsequent checkpoints too.+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert all(state.to_date == "2026-02-01T00:00:00Z" for state in saved)++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ self._drive("affiliates", manager, [_page([])])++ manager.save_state.assert_not_called()++ def test_pull_session_disables_http_sample_capture(self) -> None:+ # Affiliate/referral sync bodies carry PII, so the pull path must never let RESTClient+ # capture raw responses into the shared samples prefix.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ with patch(f"{TRANSPORT_MODULE}.make_tracked_session") as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = lambda *_a, **_k: _page([])++ source = uppromote_source(+ api_key="test-key",+ endpoint="affiliates",+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ webhook_source_manager=_make_webhook_manager(enabled=False),+ )+ list(cast(Iterable[list[dict[str, Any]]], source.items()))++ assert all(call.kwargs.get("capture") is False for call in MockSession.call_args_list)+ assert MockSession.call_args_list, "expected the pull path to build a tracked session"++ @parameterized.expand(+ [+ ("programs", ["id"]),+ ("affiliates", ["id"]),+ ("coupons", ["id"]),+ ("referrals", ["id"]),+ ("payments_paid", ["payment_id"]),+ ("payments_unpaid", ["affiliate_id"]),+ ]+ )+ def test_source_response_primary_keys(self, endpoint: str, expected_keys: list[str]) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ source = uppromote_source(+ api_key="test-key",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ webhook_source_manager=_make_webhook_manager(enabled=False),+ )++ assert source.name == endpoint+ assert source.primary_keys == expected_keys+ # Ordering is undocumented, so the watermark must only commit on completed syncs.+ assert source.sort_mode == "desc"++ def test_webhook_enabled_run_reads_webhook_items_instead_of_pulling(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ webhook_manager = _make_webhook_manager(enabled=True)++ source = uppromote_source(+ api_key="test-key",+ endpoint="referrals",+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ webhook_source_manager=webhook_manager,+ )+ source.items()++ webhook_manager.get_items.assert_called_once()+ assert "table_transformer" in webhook_manager.get_items.call_args.kwargs+++class TestWebhookTableTransformer:+ def test_keeps_latest_row_per_key_and_drops_keyless_rows(self) -> None:+ transform = _make_webhook_table_transformer("id")+ table = table_from_py_list(+ [+ {"id": 1, "status": "pending"},+ {"id": 2, "status": "pending"},+ # Arrival order is oldest-first, so the later row is the newer version.+ {"id": 1, "status": "approved"},+ {"id": None, "status": "ignored"},+ ]+ )++ result = transform(table)+ rows = {row["id"]: row for row in result.to_pylist()}++ assert set(rows.keys()) == {1, 2}+ assert rows[1]["status"] == "approved"++ def test_payment_rows_dedupe_on_payment_id(self) -> None:+ transform = _make_webhook_table_transformer("payment_id")+ table = table_from_py_list(+ [+ {"payment_id": 7, "status": "PENDING"},+ {"payment_id": 7, "status": "SUCCESS"},+ ]+ )++ result = transform(table)++ assert result.to_pylist() == [{"payment_id": 7, "status": "SUCCESS"}]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid", 200, {"status": 200, "message": "success", "data": []}, True),+ ("unauthorized", 401, {"message": "Unauthorized"}, False),+ ("server_error", 500, {"message": "Error"}, False),+ ]+ )+ def test_status_mapping(self, _label: str, status_code: int, body: dict[str, Any], expected_valid: bool) -> None:+ session = MagicMock()+ session.get.return_value = _make_http_response(body, status_code=status_code)++ with patch(f"{TRANSPORT_MODULE}._make_session", return_value=session):+ valid, error = validate_credentials("test-key")++ assert valid is expected_valid+ if expected_valid:+ assert error is None+ else:+ assert error++ def test_network_failure_is_reported_not_raised(self) -> None:+ session = MagicMock()+ session.get.side_effect = ConnectionError("boom")++ with patch(f"{TRANSPORT_MODULE}._make_session", return_value=session):+ valid, error = validate_credentials("test-key")++ assert valid is False+ assert error is not None and "Could not reach UpPromote" in error+++def _subscription(event: str, target_url: str = WEBHOOK_URL, secret: str | None = "sec-1") -> dict[str, Any]:+ return {+ "event": event,+ "target_url": target_url,+ "status": "active",+ "secret_key": secret,+ "created_at": "2026-01-01T00:00:00Z",+ }+++class TestWebhookManagement:+ def test_create_webhook_subscribes_every_desired_event(self) -> None:+ session = MagicMock()+ session.get.return_value = _make_http_response({"data": []})+ session.post.return_value = _make_http_response({"data": {"secret_key": "sec-9"}})++ with patch(f"{TRANSPORT_MODULE}._make_session", return_value=session):+ result = create_webhook("test-key", WEBHOOK_URL)++ assert result.success is True+ assert result.extra_inputs == {"signing_secret": "sec-9"}+ assert result.pending_inputs == []++ posted_events = {call.kwargs["json"]["event"] for call in session.post.call_args_list}+ assert posted_events == set(all_desired_webhook_events())++ def test_create_webhook_reuses_existing_own_subscriptions(self) -> None:+ session = MagicMock()+ session.get.return_value = _make_http_response(+ {"data": [_subscription(event) for event in all_desired_webhook_events()]}+ )++ with patch(f"{TRANSPORT_MODULE}._make_session", return_value=session):+ result = create_webhook("test-key", WEBHOOK_URL)++ assert result.success is True+ assert result.extra_inputs == {"signing_secret": "sec-1"}+ session.post.assert_not_called()++ def test_create_webhook_fails_when_every_event_is_taken(self) -> None:+ session = MagicMock()+ session.get.return_value = _make_http_response(+ {+ "data": [+ _subscription(event, target_url="https://elsewhere.example")+ for event in all_desired_webhook_events()+ ]+ }+ )++ with patch(f"{TRANSPORT_MODULE}._make_session", return_value=session):+ result = create_webhook("test-key", WEBHOOK_URL)++ assert result.success is False+ assert result.error is not None and "one subscription per event" in result.error+ session.post.assert_not_called()++ def test_create_webhook_without_secret_reports_pending_input(self) -> None:+ session = MagicMock()+ session.get.return_value = _make_http_response({"data": []})+ session.post.return_value = _make_http_response({"data": {}})++ with patch(f"{TRANSPORT_MODULE}._make_session", return_value=session):+ result = create_webhook("test-key", WEBHOOK_URL)++ assert result.success is True+ assert result.pending_inputs == ["signing_secret"]++ def test_create_webhook_surfaces_api_errors(self) -> None:+ session = MagicMock()+ session.get.return_value = _make_http_response({"message": "Unauthorized"}, status_code=401)++ with patch(f"{TRANSPORT_MODULE}._make_session", return_value=session):+ result = create_webhook("test-key", WEBHOOK_URL)++ assert result.success is False+ assert result.error == "Unauthorized"++ def test_sync_webhook_events_resubscribes_missing_events(self) -> None:+ session = MagicMock()+ session.get.return_value = _make_http_response({"data": [_subscription("referral.new")]})+ session.post.return_value = _make_http_response({"data": {"secret_key": "sec-1"}})++ with patch(f"{TRANSPORT_MODULE}._make_session", return_value=session):+ result = sync_webhook_events("test-key", WEBHOOK_URL, ["referral.new", "referral.approved"])++ assert result.success is True+ posted_events = {call.kwargs["json"]["event"] for call in session.post.call_args_list}+ assert posted_events == {"referral.approved"}++ def test_sync_webhook_events_reports_events_taken_by_other_urls(self) -> None:+ session = MagicMock()+ session.get.return_value = _make_http_response(+ {"data": [_subscription("referral.new", target_url="https://elsewhere.example")]}+ )++ with patch(f"{TRANSPORT_MODULE}._make_session", return_value=session):+ result = sync_webhook_events("test-key", WEBHOOK_URL, ["referral.new"])++ assert result.success is False+ assert result.error is not None and "referral.new" in result.error++ def test_get_external_webhook_info_reports_our_subscriptions(self) -> None:+ session = MagicMock()+ session.get.return_value = _make_http_response(+ {+ "data": [+ _subscription("referral.new"),+ _subscription("affiliate.new"),+ _subscription("payment.paid", target_url="https://elsewhere.example"),+ ]+ }+ )++ with patch(f"{TRANSPORT_MODULE}._make_session", return_value=session):+ info = get_external_webhook_info("test-key", WEBHOOK_URL)++ assert info.exists is True+ assert info.enabled_events == ["affiliate.new", "referral.new"]+ assert info.status == "active"++ def test_get_external_webhook_info_when_nothing_points_at_us(self) -> None:+ session = MagicMock()+ session.get.return_value = _make_http_response({"data": []})++ with patch(f"{TRANSPORT_MODULE}._make_session", return_value=session):+ info = get_external_webhook_info("test-key", WEBHOOK_URL)++ assert info.exists is False++ def test_delete_webhook_removes_only_our_subscriptions(self) -> None:+ session = MagicMock()+ session.get.return_value = _make_http_response(+ {+ "data": [+ _subscription("referral.new"),+ _subscription("payment.paid", target_url="https://elsewhere.example"),+ ]+ }+ )+ session.delete.return_value = _make_http_response({"status": 200, "message": "success"})++ with patch(f"{TRANSPORT_MODULE}._make_session", return_value=session):+ result = delete_webhook("test-key", WEBHOOK_URL)++ assert result.success is True+ deleted_events = [call.kwargs["json"]["event"] for call in session.delete.call_args_list]+ assert deleted_events == ["referral.new"]++ def test_delete_webhook_with_no_matching_subscription_fails(self) -> None:+ session = MagicMock()+ session.get.return_value = _make_http_response({"data": []})++ with patch(f"{TRANSPORT_MODULE}._make_session", return_value=session):+ result = delete_webhook("test-key", WEBHOOK_URL)++ assert result.success is False+ session.delete.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/tests/test_uppromote_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/tests/test_uppromote_source.pynew file mode 100644index 000000000000..2c525a2e91bc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/tests/test_uppromote_source.py@@ -0,0 +1,200 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,+ SourceFieldInputConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.uppromote.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.uppromote.source import UpPromoteSource+from products.warehouse_sources.backend.temporal.data_imports.sources.uppromote.uppromote import UpPromoteResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.uppromote.source"+++def _make_inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "affiliates",+ "schema_id": "schema-id",+ "source_id": "source-id",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-id",+ "logger": MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestUpPromoteSource:+ def setup_method(self) -> None:+ self.source = UpPromoteSource()++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.UPPROMOTE++ def test_source_config_is_released_with_api_key_field(self) -> None:+ config = self.source.get_source_config+ assert config.name == SchemaExternalDataSourceType.UP_PROMOTE+ # unreleasedSource hides the connector from every user; a finished source must not carry it.+ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/uppromote"++ fields = {f.name: f for f in config.fields}+ assert set(fields.keys()) == {"api_key"}+ api_key_field = fields["api_key"]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.type == "password"+ assert api_key_field.required is True++ webhook_fields = {f.name: f for f in config.webhookFields or []}+ assert set(webhook_fields.keys()) == {"signing_secret"}++ def test_get_schemas_covers_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(MagicMock(), team_id=1)+ assert [s.name for s in schemas] == list(ENDPOINTS)++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(MagicMock(), team_id=1, names=["affiliates", "referrals"])+ assert [s.name for s in schemas] == ["affiliates", "referrals"]++ @parameterized.expand(+ [+ # Windowed endpoints sync incrementally on the creation-time filter; programs has+ # no date filter and payments_unpaid is an aggregated snapshot — full refresh only.+ ("programs", False, False),+ ("affiliates", True, True),+ ("coupons", True, False),+ ("referrals", True, True),+ ("payments_paid", True, True),+ ("payments_unpaid", False, False),+ ]+ )+ def test_schema_sync_capabilities(self, endpoint: str, supports_incremental: bool, supports_webhooks: bool) -> None:+ schema = next(s for s in self.source.get_schemas(MagicMock(), team_id=1) if s.name == endpoint)+ assert schema.supports_incremental is supports_incremental+ assert schema.supports_webhooks is supports_webhooks+ # Every row is mutable (statuses, amounts), so append mode is never offered.+ assert schema.supports_append is False++ @parameterized.expand(+ [+ (True, None),+ (False, "UpPromote rejected the API key"),+ ]+ )+ def test_validate_credentials_delegates_to_transport(self, valid: bool, error: str | None) -> None:+ with patch(f"{SOURCE_MODULE}.validate_uppromote_credentials", return_value=(valid, error)) as mock_validate:+ result, message = self.source.validate_credentials(MagicMock(api_key="key-1"), team_id=1)++ mock_validate.assert_called_once_with("key-1")+ assert result is valid+ assert message == error++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is UpPromoteResumeConfig++ def test_source_for_pipeline_plumbs_incremental_arguments(self) -> None:+ inputs = _make_inputs(+ schema_name="referrals",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ incremental_field="created_at",+ )+ with patch(f"{SOURCE_MODULE}.uppromote_source") as mock_source:+ self.source.source_for_pipeline(MagicMock(api_key="key-1"), MagicMock(), inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "key-1"+ assert kwargs["endpoint"] == "referrals"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ def test_source_for_pipeline_drops_watermark_on_full_refresh(self) -> None:+ inputs = _make_inputs(+ should_use_incremental_field=False,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ )+ with patch(f"{SOURCE_MODULE}.uppromote_source") as mock_source:+ self.source.source_for_pipeline(MagicMock(api_key="key-1"), MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_webhook_resource_map_routes_object_types(self) -> None:+ assert self.source.webhook_resource_map == {+ "affiliates": "affiliate",+ "referrals": "referral",+ "payments_paid": "payment",+ }++ def test_webhook_template_routes_and_verifies_signature(self) -> None:+ template = self.source.webhook_template+ assert template is not None+ assert template.id == "template-warehouse-source-uppromote"+ assert template.type == "warehouse_source_webhook"+ input_keys = {i["key"] for i in template.inputs_schema}+ assert {"signing_secret", "bypass_signature_check", "schema_mapping", "source_id"} <= input_keys+ assert "x-uppromote-signature" in template.code+ assert "produceToWarehouseWebhooks" in template.code++ def test_desired_webhook_events_exclude_unmergeable_status_changed(self) -> None:+ events = self.source.get_desired_webhook_events(MagicMock(), ["affiliates"])+ assert events is not None+ assert set(events) == {+ "affiliate.new",+ "affiliate.approved",+ "affiliate.inactive",+ "referral.new",+ "referral.approved",+ "referral.denied",+ "payment.paid",+ }+ # Status-changed payloads are {previous_status, current_status} diffs and can't be+ # merged into a table row.+ assert not any(event.endswith("status-changed") for event in events)++ @parameterized.expand(+ [+ ("create_webhook", "create_uppromote_webhook"),+ ("delete_webhook", "delete_uppromote_webhook"),+ ("get_external_webhook_info", "get_uppromote_webhook_info"),+ ]+ )+ def test_webhook_management_delegates_to_transport(self, method: str, transport_fn: str) -> None:+ with patch(f"{SOURCE_MODULE}.{transport_fn}") as mock_fn:+ getattr(self.source, method)(MagicMock(api_key="key-1"), "https://hooks.posthog.com/x", team_id=1)++ mock_fn.assert_called_once_with("key-1", "https://hooks.posthog.com/x")++ def test_sync_webhook_events_passes_all_desired_events(self) -> None:+ with patch(f"{SOURCE_MODULE}.sync_uppromote_webhook_events") as mock_fn:+ self.source.sync_webhook_events(+ MagicMock(api_key="key-1"), "https://hooks.posthog.com/x", team_id=1, eligible_schema_names=[]+ )++ api_key, webhook_url, events = mock_fn.call_args.args+ assert api_key == "key-1"+ assert webhook_url == "https://hooks.posthog.com/x"+ assert len(events) == 7++ def test_non_retryable_errors_cover_auth_failures(self) -> None:+ errors = self.source.get_non_retryable_errors()+ assert any("401" in key for key in errors)+ assert any("403" in key for key in errors)+ assert all("aff-api.uppromote.com" in key for key in errors)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/uppromote.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/uppromote.pynew file mode 100644index 000000000000..baf80b8d2c1e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/uppromote.py@@ -0,0 +1,444 @@+import dataclasses+from collections.abc import Callable+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional++import pyarrow as pa+import requests+from asgiref.sync import async_to_sync+from dateutil import parser++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import table_from_py_list+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSyncResult,+)+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 EndpointResource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.uppromote.settings import (+ UPPROMOTE_BASE_URL,+ UPPROMOTE_ENDPOINTS,+ UPPROMOTE_OBJECT_TYPE_TO_EVENTS,+ UPPROMOTE_PAGE_SIZE,+ UpPromoteEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 30+++class UpPromoteResumeConfig:+ # The next page to fetch (page-number pagination; the API has no pagination metadata).+ page: int+ # Referrals require `from_date` and `to_date` together. The window end is frozen at the+ # first request and carried through resume so a resumed run pages through the same window+ # instead of one that shifted while the job was down.+ to_date: str | None = None+++def _format_datetime(value: datetime | date) -> str:+ """Format as ISO 8601 UTC with a Z suffix — the format UpPromote's date filters require."""+ if isinstance(value, datetime):+ utc_value = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ else:+ utc_value = datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ return utc_value.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _coerce_datetime(value: Any) -> datetime | None:+ if isinstance(value, datetime):+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ if isinstance(value, str):+ try:+ parsed = parser.parse(value)+ except (ValueError, OverflowError):+ return None+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)+ return None+++def _window_start(last_value: Any) -> str | None:+ """`from_date` for an incremental run: the watermark minus a one-second overlap.++ The docs don't state whether `from_date` is inclusive; re-reading one extra second makes+ either semantic safe — the boundary rows are re-fetched and deduped by the merge.+ """+ coerced = _coerce_datetime(last_value)+ if coerced is None:+ return None+ return _format_datetime(coerced - timedelta(seconds=1))+++def _get_headers(api_key: str) -> dict[str, str]:+ # The API key rides raw in the Authorization header — no Bearer prefix (verified in the+ # vendor docs and their own curl examples).+ return {+ "Authorization": api_key,+ "Accept": "application/json",+ "Content-Type": "application/json",+ }+++def _make_session(api_key: str) -> requests.Session:+ """Tracked session for webhook-management and credential-probe calls.++ ``capture=False``: affiliate rows carry PII (emails, addresses) and the webhook+ subscription responses carry the signing ``secret_key``; ``redact_values`` masks the API+ key anywhere it appears in logged URLs or headers.+ """+ return make_tracked_session(redact_values=(api_key,), capture=False)+++def _extract_message(response: requests.Response) -> str | None:+ try:+ message = response.json().get("message")+ except Exception:+ return None+ return message if isinstance(message, str) else None+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ """One cheap probe to confirm the API key is genuine.++ UpPromote returns 401 with {"message": "Unauthorized"} (or "Token not provided") for+ missing/invalid keys, verified against the live API.+ """+ url = f"{UPPROMOTE_BASE_URL}/affiliates"+ try:+ response = _make_session(api_key).get(+ url,+ headers=_get_headers(api_key),+ params={"page": 1, "per_page": 1},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ except Exception as e:+ return False, f"Could not reach UpPromote: {e}"++ if response.ok:+ return True, None++ if response.status_code == 401:+ return False, (+ "UpPromote rejected the API key. Create a key in the UpPromote app under "+ "Settings > Integrations > API Key (requires the Professional plan) and reconnect."+ )+ return False, _extract_message(response) or f"UpPromote returned status {response.status_code}"+++def _build_resource(+ config: UpPromoteEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+ window_end: str | None,+) -> EndpointResource:+ params: dict[str, Any] = {"per_page": UPPROMOTE_PAGE_SIZE}++ # The creation-time window is the only server-side filter UpPromote offers, so the values+ # are known up front and passed as plain params instead of the framework's incremental+ # param indirection. A first incremental run (no watermark) sends no window and pulls+ # everything.+ if should_use_incremental_field and config.supports_date_window and db_incremental_field_last_value is not None:+ from_date = _window_start(db_incremental_field_last_value)+ if from_date is not None:+ params["from_date"] = from_date+ if config.requires_to_date:+ params["to_date"] = window_end++ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ "endpoint": {+ "data_selector": "data",+ "path": config.path,+ "params": params,+ },+ "table_format": "delta",+ }+++def _make_webhook_table_transformer(primary_key: str) -> Callable[[pa.Table], pa.Table]:+ """Collapse a webhook batch to the latest version of each object.++ Several events for the same object (e.g. referral.new then referral.approved) can land in+ one batch, and delta merge doesn't dedupe within a batch. Payloads carry no event+ timestamp, but the S3 files are read oldest-first in arrival order, so the last row per+ key is the newest. Rows without the primary key (unexpected shapes) are dropped.+ """++ def transform(table: pa.Table) -> pa.Table:+ latest: dict[Any, dict[str, Any]] = {}+ for row in table.to_pylist():+ key = row.get(primary_key)+ if key is None:+ continue+ latest[key] = row+ return table_from_py_list(list(latest.values()))++ return transform+++def uppromote_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[UpPromoteResumeConfig],+ webhook_source_manager: WebhookSourceManager,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = UPPROMOTE_ENDPOINTS[endpoint]+ webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)()++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ window_end = (+ resume_config.to_date if resume_config and resume_config.to_date else _format_datetime(datetime.now(UTC))+ )++ def items():+ if webhook_enabled:+ return webhook_source_manager.get_items(+ table_transformer=_make_webhook_table_transformer(config.primary_keys[0])+ )++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": UPPROMOTE_BASE_URL,+ "auth": {+ "type": "api_key",+ "name": "Authorization",+ "location": "header",+ "api_key": api_key,+ },+ # Sync responses carry affiliate/referral PII (emails, addresses, payment+ # details), so reuse the capture-disabled, key-redacting tracked session+ # rather than letting RESTClient build its default capturing one.+ "session": _make_session(api_key),+ # No pagination metadata in responses — iterate pages until an empty one.+ "paginator": PageNumberPaginator(base_page=1, page_param="page", stop_after_empty_page=True),+ },+ "resource_defaults": {},+ "resources": [+ _build_resource(config, should_use_incremental_field, db_incremental_field_last_value, window_end)+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resume_config is not None:+ initial_paginator_state = {"page": resume_config.page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; the Redis TTL handles+ # cleanup on completion.+ if state and state.get("page"):+ resumable_source_manager.save_state(UpPromoteResumeConfig(page=int(state["page"]), to_date=window_end))++ return rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=config.primary_keys,+ # The API exposes no sort param and its ordering is undocumented (most likely+ # newest-first). "desc" defers the incremental watermark commit until a sync+ # completes, which is correct for either true ordering; mid-run progress is+ # protected by the resumable page state instead.+ sort_mode="desc",+ partition_count=1 if config.partition_key else None,+ partition_size=1 if config.partition_key else None,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++# --- Webhook management -------------------------------------------------------------------+++def all_desired_webhook_events() -> list[str]:+ return [event for events in UPPROMOTE_OBJECT_TYPE_TO_EVENTS.values() for event in events]+++def _format_http_error(error: requests.HTTPError) -> str:+ response: requests.Response | None = error.response+ if response is None:+ return str(error)+ return _extract_message(response) or f"UpPromote returned status {response.status_code}"+++def _list_subscriptions(session: requests.Session, api_key: str) -> list[dict[str, Any]]:+ response = session.get(+ f"{UPPROMOTE_BASE_URL}/webhook-subscriptions",+ headers=_get_headers(api_key),+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ data = response.json().get("data")+ return data if isinstance(data, list) else []+++def _subscribe_missing_events(+ session: requests.Session,+ api_key: str,+ webhook_url: str,+ desired_events: list[str],+) -> tuple[list[str], list[str], str | None]:+ """Ensure each desired event has a subscription pointing at our webhook URL.++ UpPromote allows a single subscription per event (update/delete are keyed by event alone),+ so an event already subscribed to a different URL is left untouched — hijacking it would+ silently break the customer's other integration. Returns (subscribed, taken_by_other_url,+ secret_key).+ """+ subscriptions = _list_subscriptions(session, api_key)+ by_event = {sub.get("event"): sub for sub in subscriptions if sub.get("event")}++ subscribed: list[str] = []+ taken: list[str] = []+ secret: str | None = None++ for event in desired_events:+ existing = by_event.get(event)+ if existing is not None:+ if existing.get("target_url") == webhook_url:+ subscribed.append(event)+ secret = secret or existing.get("secret_key")+ else:+ taken.append(event)+ continue++ response = session.post(+ f"{UPPROMOTE_BASE_URL}/webhook-subscriptions",+ headers=_get_headers(api_key),+ json={"target_url": webhook_url, "event": event},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ data = response.json().get("data") or {}+ secret = secret or data.get("secret_key")+ subscribed.append(event)++ return subscribed, taken, secret+++def create_webhook(api_key: str, webhook_url: str) -> WebhookCreationResult:+ session = _make_session(api_key)+ try:+ subscribed, taken, secret = _subscribe_missing_events(+ session, api_key, webhook_url, all_desired_webhook_events()+ )+ except requests.HTTPError as e:+ return WebhookCreationResult(success=False, error=_format_http_error(e))+ except Exception as e:+ return WebhookCreationResult(success=False, error=str(e))++ if not subscribed:+ return WebhookCreationResult(+ success=False,+ error=(+ "Every UpPromote webhook event is already subscribed to a different URL: "+ f"{', '.join(taken)}. UpPromote allows one subscription per event — free up the "+ "events you want PostHog to receive, or set the webhook up manually."+ ),+ )++ extra_inputs: dict[str, Any] = {"signing_secret": secret} if secret else {}+ return WebhookCreationResult(+ success=True,+ extra_inputs=extra_inputs,+ pending_inputs=[] if secret else ["signing_secret"],+ )+++def sync_webhook_events(api_key: str, webhook_url: str, desired_events: list[str]) -> WebhookSyncResult:+ session = _make_session(api_key)+ try:+ _, taken, _ = _subscribe_missing_events(session, api_key, webhook_url, desired_events)+ except requests.HTTPError as e:+ return WebhookSyncResult(success=False, error=_format_http_error(e))+ except Exception as e:+ return WebhookSyncResult(success=False, error=str(e))++ if taken:+ return WebhookSyncResult(+ success=False,+ error=(+ "Some UpPromote webhook events are subscribed to a different URL and were left "+ f"untouched: {', '.join(taken)}. UpPromote allows one subscription per event."+ ),+ )+ return WebhookSyncResult(success=True)+++def get_external_webhook_info(api_key: str, webhook_url: str) -> ExternalWebhookInfo:+ session = _make_session(api_key)+ try:+ subscriptions = _list_subscriptions(session, api_key)+ except requests.HTTPError as e:+ return ExternalWebhookInfo(exists=False, error=_format_http_error(e))+ except Exception as e:+ return ExternalWebhookInfo(exists=False, error=str(e))++ ours = [sub for sub in subscriptions if sub.get("target_url") == webhook_url]+ if not ours:+ return ExternalWebhookInfo(exists=False)++ statuses = {sub.get("status") for sub in ours}+ created_dates = [str(sub["created_at"]) for sub in ours if sub.get("created_at")]+ return ExternalWebhookInfo(+ exists=True,+ url=webhook_url,+ enabled_events=sorted(str(sub.get("event")) for sub in ours),+ status="active" if statuses == {"active"} else "inactive",+ created_at=min(created_dates) if created_dates else None,+ )+++def delete_webhook(api_key: str, webhook_url: str) -> WebhookDeletionResult:+ session = _make_session(api_key)+ try:+ subscriptions = _list_subscriptions(session, api_key)+ ours = [sub for sub in subscriptions if sub.get("target_url") == webhook_url]+ for sub in ours:+ response = session.delete(+ f"{UPPROMOTE_BASE_URL}/webhook-subscriptions",+ headers=_get_headers(api_key),+ json={"event": sub.get("event")},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ except requests.HTTPError as e:+ return WebhookDeletionResult(success=False, error=_format_http_error(e))+ except Exception as e:+ return WebhookDeletionResult(success=False, error=str(e))++ if not ours:+ return WebhookDeletionResult(success=False, error="No UpPromote webhook subscriptions point at this URL.")+ return WebhookDeletionResult(success=True)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/webhook_template.pynew file mode 100644index 000000000000..7490f27088c9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uppromote/webhook_template.py@@ -0,0 +1,135 @@+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC++# UpPromote signs webhooks with HMAC-SHA256 over the raw request body using the subscription's+# secret key, sent as X-UpPromote-Signature (hex digest, no timestamp). The payload is the bare+# object with no event-name envelope, so routing derives the object type from the payload shape:+# paid payments carry `payment_id`, referrals carry `tracking_type`/`commission_rule`, and+# affiliates carry a top-level `email`. The `*.status-changed` diff payloads+# ({previous_status, current_status}) match none of these and are skipped.+template: HogFunctionTemplateDC = HogFunctionTemplateDC(+ status="alpha",+ free=False,+ type="warehouse_source_webhook",+ id="template-warehouse-source-uppromote",+ name="UpPromote warehouse source webhook",+ description="Receive UpPromote webhook events for data warehouse ingestion",+ icon_url="/static/services/uppromote.png",+ category=["Data warehouse"],+ code_language="hog",+ code="""\+if (request.method != 'POST') {+ return {+ 'httpResponse': {+ 'status': 405,+ 'body': 'Method not allowed'+ }+ }+}++if (not inputs.bypass_signature_check) {+ if (empty(inputs.signing_secret)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Signing secret not configured',+ }+ }+ }++ let body := request.stringBody+ let signatureHeader := request.headers['x-uppromote-signature']++ if (empty(signatureHeader)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Missing signature',+ }+ }+ }++ let computedSignature := sha256HmacChainHex([inputs.signing_secret, body])++ if (computedSignature != signatureHeader) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Bad signature',+ }+ }+ }+}++let payload := request.body+let objectType := ''++if (not empty(payload.payment_id)) {+ objectType := 'payment'+}+if (objectType == '' and (not empty(payload.tracking_type) or not empty(payload.commission_rule))) {+ objectType := 'referral'+}+if (objectType == '' and not empty(payload.email)) {+ objectType := 'affiliate'+}++if (empty(objectType)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'Unrecognized payload shape, skipping'+ }+ }+}++let schemaId := inputs.schema_mapping?.[objectType]++if (empty(schemaId)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': f'No schema mapping for object type: {objectType}, skipping'+ }+ }+}++produceToWarehouseWebhooks(request.body, schemaId)""",+ inputs_schema=[+ {+ "type": "string",+ "key": "signing_secret",+ "label": "Signing secret",+ "required": False,+ "secret": True,+ "hidden": False,+ "description": "Used to validate the webhook came from UpPromote",+ },+ {+ "type": "boolean",+ "key": "bypass_signature_check",+ "label": "Bypass signature check",+ "description": "If set, the X-UpPromote-Signature header will not be checked. This is not recommended.",+ "default": False,+ "required": False,+ "secret": False,+ },+ {+ "type": "json",+ "key": "schema_mapping",+ "label": "Schema mapping",+ "description": "Maps UpPromote object types to ExternalDataSchema IDs",+ "required": True,+ "secret": False,+ "hidden": True,+ },+ {+ "type": "string",+ "key": "source_id",+ "label": "Source ID",+ "description": "The ExternalDataSource ID this webhook is associated with",+ "required": True,+ "secret": False,+ "hidden": True,+ },+ ],+)