: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): expose stripe coupon and discount data (#56742)
Daniel RC4532d8111855
diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex ac81fe9eebda..c1d714887f13 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5956,6 +5956,9 @@ export interface ExternalDataSourceSyncSchema {cdc_available?: booleancdc_table_mode?: 'consolidated' | 'cdc_only' | 'both'supports_webhooks: boolean+ /** True when the resource has no API list endpoint and can only be populated via webhooks+ * (e.g. Stripe Discount). The picker should hide non-webhook sync methods. */+ webhook_only?: booleandescription?: string | nullshould_sync_default: booleanprimary_key_columns: string[] | nulldiff --git a/posthog/temporal/data_imports/sources/common/schema.py b/posthog/temporal/data_imports/sources/common/schema.pyindex bea9a70c4d70..310ea7b955bc 100644--- a/posthog/temporal/data_imports/sources/common/schema.py+++ b/posthog/temporal/data_imports/sources/common/schema.py@@ -11,6 +11,9 @@ class SourceSchema:incremental_fields: list[IncrementalField] = field(default_factory=list)row_count: int | None = Nonesupports_webhooks: bool = False+ # True for resources with no API list endpoint that can only be populated via webhooks+ # (e.g. Stripe `Discount`). The UI should hide non-webhook sync methods for these.+ webhook_only: bool = Falsesupports_cdc: bool = Falsecolumns: list[tuple[str, str, bool]] = field(default_factory=list)foreign_keys: list[tuple[str, str, str]] = field(default_factory=list)diff --git a/posthog/temporal/data_imports/sources/stripe/constants.py b/posthog/temporal/data_imports/sources/stripe/constants.pyindex e9ae806c1675..3abf7090222e 100644--- a/posthog/temporal/data_imports/sources/stripe/constants.py+++ b/posthog/temporal/data_imports/sources/stripe/constants.py@@ -13,6 +13,8 @@ SUBSCRIPTION_RESOURCE_NAME = "Subscription"CREDIT_NOTE_RESOURCE_NAME = "CreditNote"CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME = "CustomerBalanceTransaction"CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME = "CustomerPaymentMethod"+COUPON_RESOURCE_NAME = "Coupon"+DISCOUNT_RESOURCE_NAME = "Discount"# Maps PostHog resource name -> Stripe API object type (as it appears in webhook data.object.object)RESOURCE_TO_STRIPE_OBJECT_TYPE: dict[str, str] = {@@ -31,6 +33,8 @@ RESOURCE_TO_STRIPE_OBJECT_TYPE: dict[str, str] = {CREDIT_NOTE_RESOURCE_NAME: "credit_note",CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME: "customer_balance_transaction",CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME: "payment_method",+ COUPON_RESOURCE_NAME: "coupon",+ DISCOUNT_RESOURCE_NAME: "discount",}RESOURCE_TO_STRIPE_WEBHOOK_EVENT: dict[str, str] = {@@ -49,4 +53,6 @@ RESOURCE_TO_STRIPE_WEBHOOK_EVENT: dict[str, str] = {CREDIT_NOTE_RESOURCE_NAME: "credit_note",CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME: "billing",CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME: "payment_method",+ COUPON_RESOURCE_NAME: "coupon",+ DISCOUNT_RESOURCE_NAME: "customer.discount",}diff --git a/posthog/temporal/data_imports/sources/stripe/settings.py b/posthog/temporal/data_imports/sources/stripe/settings.pyindex 4883714f9dab..56e2b398087a 100644--- a/posthog/temporal/data_imports/sources/stripe/settings.py+++ b/posthog/temporal/data_imports/sources/stripe/settings.py@@ -8,10 +8,12 @@ from posthog.temporal.data_imports.sources.stripe.constants import (ACCOUNT_RESOURCE_NAME,BALANCE_TRANSACTION_RESOURCE_NAME,CHARGE_RESOURCE_NAME,+ COUPON_RESOURCE_NAME,CREDIT_NOTE_RESOURCE_NAME,CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,CUSTOMER_RESOURCE_NAME,+ DISCOUNT_RESOURCE_NAME,DISPUTE_RESOURCE_NAME,INVOICE_ITEM_RESOURCE_NAME,INVOICE_RESOURCE_NAME,@@ -39,6 +41,8 @@ ENDPOINTS = (CREDIT_NOTE_RESOURCE_NAME,CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,+ COUPON_RESOURCE_NAME,+ DISCOUNT_RESOURCE_NAME,)@@ -56,8 +60,12 @@ INCREMENTAL_ENDPOINTS = (REFUND_RESOURCE_NAME,SUBSCRIPTION_RESOURCE_NAME,CREDIT_NOTE_RESOURCE_NAME,+ COUPON_RESOURCE_NAME,)+# Endpoints that have no API list path — populated only via webhooks.+WEBHOOK_ONLY_ENDPOINTS = (DISCOUNT_RESOURCE_NAME,)+APPEND_ONLY_INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {ACCOUNT_RESOURCE_NAME: [{@@ -163,4 +171,12 @@ APPEND_ONLY_INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {"field_type": IncrementalFieldType.Integer,}],+ COUPON_RESOURCE_NAME: [+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created",+ "field_type": IncrementalFieldType.Integer,+ }+ ],}diff --git a/posthog/temporal/data_imports/sources/stripe/source.py b/posthog/temporal/data_imports/sources/stripe/source.pyindex 6d87122d0dfa..7ed941dad3e4 100644--- a/posthog/temporal/data_imports/sources/stripe/source.py+++ b/posthog/temporal/data_imports/sources/stripe/source.py@@ -43,6 +43,7 @@ from posthog.temporal.data_imports.sources.stripe.constants import (from posthog.temporal.data_imports.sources.stripe.settings import (APPEND_ONLY_INCREMENTAL_FIELDS as STRIPE_APPEND_ONLY_INCREMENTAL_FIELDS,ENDPOINTS as STRIPE_ENDPOINTS,+ WEBHOOK_ONLY_ENDPOINTS as STRIPE_WEBHOOK_ONLY_ENDPOINTS,)from posthog.temporal.data_imports.sources.stripe.stripe import (StripeAuthenticationError,@@ -272,7 +273,14 @@ If automatic creation failed due to a permissions error and you're using a restrSourceSchema(name=endpoint,supports_incremental=False,- supports_webhooks=STRIPE_APPEND_ONLY_INCREMENTAL_FIELDS.get(endpoint, None) is not None,+ # Webhook-only endpoints (e.g. Discount) have no list API and therefore no+ # incremental fields, but they must still expose webhook support so the+ # warehouse pipeline can route events into the correct table.+ supports_webhooks=(+ STRIPE_APPEND_ONLY_INCREMENTAL_FIELDS.get(endpoint, None) is not None+ or endpoint in STRIPE_WEBHOOK_ONLY_ENDPOINTS+ ),+ webhook_only=endpoint in STRIPE_WEBHOOK_ONLY_ENDPOINTS,# nested resources are only full refresh and are not in STRIPE_APPEND_ONLY_INCREMENTAL_FIELDSsupports_append=STRIPE_APPEND_ONLY_INCREMENTAL_FIELDS.get(endpoint, None) is not None,incremental_fields=STRIPE_APPEND_ONLY_INCREMENTAL_FIELDS.get(endpoint, []),diff --git a/posthog/temporal/data_imports/sources/stripe/stripe.py b/posthog/temporal/data_imports/sources/stripe/stripe.pyindex 2ff0f047dda9..60caee5c2f20 100644--- a/posthog/temporal/data_imports/sources/stripe/stripe.py+++ b/posthog/temporal/data_imports/sources/stripe/stripe.py@@ -29,6 +29,7 @@ from posthog.temporal.data_imports.sources.stripe.constants import (ACCOUNT_RESOURCE_NAME,BALANCE_TRANSACTION_RESOURCE_NAME,CHARGE_RESOURCE_NAME,+ COUPON_RESOURCE_NAME,CREDIT_NOTE_RESOURCE_NAME,CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,@@ -44,7 +45,7 @@ from posthog.temporal.data_imports.sources.stripe.constants import (SUBSCRIPTION_RESOURCE_NAME,)from posthog.temporal.data_imports.sources.stripe.custom import InvoiceListWithAllLines-from posthog.temporal.data_imports.sources.stripe.settings import APPEND_ONLY_INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.stripe.settings import APPEND_ONLY_INCREMENTAL_FIELDS, WEBHOOK_ONLY_ENDPOINTSfrom products.warehouse_sources.backend.models.external_table_definitions import get_dlt_mapping_for_external_table@@ -139,8 +140,17 @@ def _build_resources(PRICE_RESOURCE_NAME: StripeResource(method=client.prices.list, params={"expand[]": "data.tiers"}),PRODUCT_RESOURCE_NAME: StripeResource(method=client.products.list),REFUND_RESOURCE_NAME: StripeResource(method=client.refunds.list),- SUBSCRIPTION_RESOURCE_NAME: StripeResource(method=client.subscriptions.list, params={"status": "all"}),+ SUBSCRIPTION_RESOURCE_NAME: StripeResource(+ method=client.subscriptions.list,+ params={+ "status": "all",+ # Expand discount objects so coupon details (amount_off, percent_off, duration) are inline.+ # Without expansion Stripe returns only discount IDs, which prevents revenue projection.+ "expand[]": ["data.discounts", "data.items.data.discounts"],+ },+ ),CREDIT_NOTE_RESOURCE_NAME: StripeResource(method=client.credit_notes.list),+ COUPON_RESOURCE_NAME: StripeResource(method=client.coupons.list),CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME: StripeNestedResource(method=client.customers.balance_transactions.list,nested_parent_param="customer",@@ -181,6 +191,15 @@ def get_rows(batcher = Batcher(logger=logger)+ if endpoint in WEBHOOK_ONLY_ENDPOINTS:+ # Webhook-only resources (e.g. Discount) have no Stripe list endpoint — Discount+ # can only be retrieved in the context of a customer/subscription/invoice. These+ # tables are populated exclusively by their corresponding webhook events. Yield+ # nothing so the initial "sync" completes immediately, allowing the webhook source+ # manager to take over (it requires schema.initial_sync_complete=True before activating).+ logger.debug(f"Stripe: {endpoint} endpoint is webhook-only, skipping API list")+ return+resource = resources.get(endpoint, None)if not resource:raise Exception(f"Stripe endpoint does not exist: {endpoint}")@@ -462,6 +481,9 @@ def validate_credentials(# "not available for OAuth" reason instead since it feeds the UI.if auth_method == "oauth" and name == ACCOUNT_RESOURCE_NAME:continue+ # Webhook-only resources (e.g. Discount) have no list API to probe.+ if name in WEBHOOK_ONLY_ENDPOINTS:+ continueif name not in all_resources:raise StripePermissionError({name: f"{name} does not exist"})resources_to_check.append(_resolve_to_flat(name, all_resources))@@ -499,6 +521,10 @@ def check_endpoint_permissions(if auth_method == "oauth" and name == ACCOUNT_RESOURCE_NAME:results[name] = "Account is not available for OAuth-connected Stripe sources"continue+ # Webhook-only resources (e.g. Discount) have no list API — treat as reachable.+ if name in WEBHOOK_ONLY_ENDPOINTS:+ results[name] = None+ continueif name not in all_resources:results[name] = f"{name} is not a known Stripe resource"continuediff --git a/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py b/posthog/temporal/tests/data_imports/stripe/test_stripe_source.pyindex 8f3c81e6571b..c422aae4b2fe 100644--- a/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py+++ b/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py@@ -13,7 +13,9 @@ from posthog.temporal.data_imports.sources.stripe.constants import (ACCOUNT_RESOURCE_NAME,CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,+ SUBSCRIPTION_RESOURCE_NAME,)+from posthog.temporal.data_imports.sources.stripe.settings import WEBHOOK_ONLY_ENDPOINTSfrom posthog.temporal.data_imports.sources.stripe.source import StripeSourcefrom posthog.temporal.data_imports.sources.stripe.stripe import (StripeAuthenticationError,@@ -25,6 +27,7 @@ from posthog.temporal.data_imports.sources.stripe.stripe import (_build_resources,_clean_stripe_error_message,check_endpoint_permissions,+ get_rows,validate_credentials,)from posthog.temporal.tests.data_imports.conftest import run_external_data_job_workflow@@ -239,6 +242,7 @@ def _mock_all_stripe_endpoints(mock_client):mock_client.subscriptions.list = mock.MagicMock()mock_client.refunds.list = mock.MagicMock()mock_client.credit_notes.list = mock.MagicMock()+ mock_client.coupons.list = mock.MagicMock()def test_validate_credentials_basic_only_probes_one_endpoint():@@ -268,6 +272,88 @@ def test_validate_credentials_basic_only_probes_one_endpoint():mock_client.subscriptions.list.assert_not_called()mock_client.refunds.list.assert_not_called()mock_client.credit_notes.list.assert_not_called()+ mock_client.coupons.list.assert_not_called()+++def test_subscription_list_uses_expand_for_discounts():+ """Subscription list call must expand discounts so coupon details ride inline.++ Without `expand=data.discounts` Stripe returns an array of discount IDs, which is+ insufficient for revenue projection — customers need amount_off / percent_off /+ duration. Item-level discounts (`items.data.discounts`) need the same treatment.+ """+ mock_client = mock.MagicMock()++ # Empty page response — we only care about how the list method was invoked.+ empty_page = mock.MagicMock()+ empty_page.auto_paging_iter.return_value = iter([])+ mock_client.subscriptions.list.return_value = empty_page++ resumable_manager = mock.MagicMock()+ resumable_manager.can_resume.return_value = False++ with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):+ # Drain the generator so the list call actually happens.+ list(+ get_rows(+ api_key="api_key",+ endpoint=SUBSCRIPTION_RESOURCE_NAME,+ account_id=None,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ logger=mock.MagicMock(),+ resumable_source_manager=resumable_manager,+ should_use_incremental_field=False,+ )+ )++ mock_client.subscriptions.list.assert_called_once()+ call_params = mock_client.subscriptions.list.call_args.kwargs["params"]+ assert call_params["status"] == "all"+ assert call_params["expand[]"] == ["data.discounts", "data.items.data.discounts"]++[email protected]("endpoint", WEBHOOK_ONLY_ENDPOINTS)+def test_webhook_only_endpoint_yields_no_rows(endpoint):+ """Webhook-only resources have no API list endpoint; get_rows must short-circuit+ cleanly so the initial sync completes and the webhook source manager can take over."""+ mock_client = mock.MagicMock()+ resumable_manager = mock.MagicMock()+ resumable_manager.can_resume.return_value = False++ with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):+ rows = list(+ get_rows(+ api_key="api_key",+ endpoint=endpoint,+ account_id=None,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ logger=mock.MagicMock(),+ resumable_source_manager=resumable_manager,+ should_use_incremental_field=False,+ )+ )++ assert rows == []+ # No Stripe list endpoint should be hit for a webhook-only resource.+ mock_client.subscriptions.list.assert_not_called()+ mock_client.coupons.list.assert_not_called()++[email protected]("endpoint", WEBHOOK_ONLY_ENDPOINTS)+def test_validate_credentials_skips_webhook_only_resource(endpoint):+ """Webhook-only resources have no list endpoint, so validation should short-circuit+ and not hit Stripe."""+ mock_client = mock.MagicMock()++ with mock.patch("posthog.temporal.data_imports.sources.stripe.stripe.StripeClient", return_value=mock_client):+ result = validate_credentials("api_key", [endpoint])++ assert result is True+ # No list method should be called when validating a webhook-only resource.+ mock_client.coupons.list.assert_not_called()+ mock_client.subscriptions.list.assert_not_called()def test_validate_credentials_basic_treats_403_as_success():@@ -525,6 +611,7 @@ def test_validate_credentials_with_missing_table_name():mock_client.subscriptions.list.assert_not_called()mock_client.refunds.list.assert_not_called()mock_client.credit_notes.list.assert_not_called()+ mock_client.coupons.list.assert_not_called()assert "bad_table" in str(e)diff --git a/products/data_warehouse/backend/api/external_data_schema.py b/products/data_warehouse/backend/api/external_data_schema.pyindex 9cb8a883d303..ecd13d3fa187 100644--- a/products/data_warehouse/backend/api/external_data_schema.py+++ b/products/data_warehouse/backend/api/external_data_schema.py@@ -358,6 +358,14 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):if not is_cdc_enabled_for_team(team):raise ValidationError("CDC is not enabled for this team")+ # Reject non-webhook sync types for webhook-only schemas (e.g. Stripe Discount —+ # no API list endpoint, so anything other than webhook produces an empty sync).+ if "sync_type" in data and sync_type != ExternalDataSchema.SyncType.WEBHOOK:+ if self._is_webhook_only_schema(instance):+ raise ValidationError(+ f"{instance.name} can only be synced via webhooks — pick the Webhook sync method."+ )+# Only update sync_type if it was explicitly provided in the requestif "sync_type" in data:validated_data["sync_type"] = sync_type@@ -610,6 +618,22 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):return updated_instance+ def _is_webhook_only_schema(self, schema: ExternalDataSchema) -> bool:+ source = schema.source+ if not source.job_inputs:+ return False+ try:+ source_type = ExternalDataSourceType(source.source_type)+ source_impl = SourceRegistry.get_source(source_type)+ except Exception:+ return False+ try:+ config = source_impl.parse_config(source.job_inputs)+ source_schemas = source_impl.get_schemas(config, schema.team_id, names=[schema.name])+ except Exception:+ return False+ return any(s.name == schema.name and s.webhook_only for s in source_schemas)+def _maybe_create_webhook(self, schema: ExternalDataSchema) -> None:source = schema.sourceif not source.job_inputs:@@ -901,8 +925,9 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"incremental_available": schema.supports_incremental,"append_available": schema.supports_append,"cdc_available": cdc_available,- "full_refresh_available": True,+ "full_refresh_available": not schema.webhook_only,"supports_webhooks": schema.supports_webhooks,+ "webhook_only": schema.webhook_only,"available_columns": [{"field": col_name, "label": col_name, "type": col_type, "nullable": nullable}for col_name, col_type, nullable in schema.columnsdiff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex b3b547af5e25..361718198a37 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -1836,6 +1836,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi"sync_type": None,"rows": schema.row_count,"supports_webhooks": schema.supports_webhooks,+ "webhook_only": schema.webhook_only,"description": schema.description,"should_sync_default": schema.should_sync_default,"available_columns": [diff --git a/products/data_warehouse/backend/api/test/test_external_data_schema.py b/products/data_warehouse/backend/api/test/test_external_data_schema.pyindex a798d7ce3fe5..162a165dc56b 100644--- a/products/data_warehouse/backend/api/test/test_external_data_schema.py+++ b/products/data_warehouse/backend/api/test/test_external_data_schema.py@@ -106,6 +106,7 @@ class TestExternalDataSchema(APIBaseTest):"cdc_available": None,"full_refresh_available": True,"supports_webhooks": True,+ "webhook_only": False,"available_columns": [],"detected_primary_keys": None,}@@ -214,6 +215,7 @@ class TestExternalDataSchema(APIBaseTest):"cdc_available": None,"full_refresh_available": True,"supports_webhooks": False,+ "webhook_only": False,"available_columns": [{"field": "id", "label": "id", "type": "integer", "nullable": True},],diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.pyindex 026adbe75f3a..6591862dce28 100644--- a/products/data_warehouse/backend/api/test/test_external_data_source.py+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py@@ -36,10 +36,12 @@ from posthog.temporal.data_imports.sources.postgres.source import PostgresSourcefrom posthog.temporal.data_imports.sources.stripe.constants import (BALANCE_TRANSACTION_RESOURCE_NAME as STRIPE_BALANCE_TRANSACTION_RESOURCE_NAME,CHARGE_RESOURCE_NAME as STRIPE_CHARGE_RESOURCE_NAME,+ COUPON_RESOURCE_NAME as STRIPE_COUPON_RESOURCE_NAME,CREDIT_NOTE_RESOURCE_NAME as STRIPE_CREDIT_NOTE_RESOURCE_NAME,CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME as STRIPE_CUSTOMER_BALANCE_TRANSACTION_RESOURCE_NAME,CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME as STRIPE_CUSTOMER_PAYMENT_METHOD_RESOURCE_NAME,CUSTOMER_RESOURCE_NAME as STRIPE_CUSTOMER_RESOURCE_NAME,+ DISCOUNT_RESOURCE_NAME as STRIPE_DISCOUNT_RESOURCE_NAME,DISPUTE_RESOURCE_NAME as STRIPE_DISPUTE_RESOURCE_NAME,INVOICE_ITEM_RESOURCE_NAME as STRIPE_INVOICE_ITEM_RESOURCE_NAME,INVOICE_RESOURCE_NAME as STRIPE_INVOICE_RESOURCE_NAME,@@ -129,6 +131,8 @@ class TestExternalDataSource(APIBaseTest):"should_sync": True,"sync_type": "full_refresh",},+ {"name": STRIPE_COUPON_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},+ {"name": STRIPE_DISCOUNT_RESOURCE_NAME, "should_sync": True, "sync_type": "full_refresh"},],},},@@ -3298,6 +3302,7 @@ class TestExternalDataSource(APIBaseTest):"incremental_field": "id","sync_type": None,"supports_webhooks": False,+ "webhook_only": False,"available_columns": [{"field": "id", "label": "id", "type": "integer", "nullable": True},],@@ -3366,6 +3371,7 @@ class TestExternalDataSource(APIBaseTest):"incremental_field": "id","sync_type": None,"supports_webhooks": False,+ "webhook_only": False,"available_columns": [{"field": "id", "label": "id", "type": "integer", "nullable": True},],diff --git a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsxindex 22e4e75dc1aa..26160601a607 100644--- a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx+++ b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx@@ -118,6 +118,10 @@ const getInitialRadioState = (if (schema.sync_type) {return schema.sync_type}+ // Webhook-only schemas can only ever use the webhook sync method.+ if (schema.webhook_only) {+ return 'webhook'+ }if (schema.supports_webhooks) {return 'webhook'}@@ -208,7 +212,11 @@ export const SyncMethodForm = forwardRef<SyncMethodFormHandle, SyncMethodFormPro})}- if (schema.cdc_available) {+ // Webhook-only schemas (e.g. Stripe Discount) have no API list endpoint, so the+ // incremental / append / cdc / full_refresh options would all produce empty syncs.+ const hideNonWebhookOptions = !!schema.webhook_only++ if (!hideNonWebhookOptions && schema.cdc_available) {radioOptions.push({value: 'cdc',disabledReason: (cdcSyncSupported.disabled && cdcSyncSupported.disabledReason) || undefined,@@ -277,196 +285,205 @@ export const SyncMethodForm = forwardRef<SyncMethodFormHandle, SyncMethodFormPro})}- radioOptions.push(- {- value: 'incremental',- disabledReason: (incrementalSyncSupported.disabled && incrementalSyncSupported.disabledReason) || undefined,- label: (- <div className="mb-4 font-normal">- <div className="items-center flex leading-[normal] overflow-hidden mb-1">- <h4 className="mb-0 mr-2 text-base font-semibold">Incremental replication</h4>- {!incrementalSyncSupported.disabled && !schema.supports_webhooks && !schema.cdc_available && (- <LemonTag type="success">Recommended</LemonTag>- )}- </div>- <p className="mb-2">- When using incremental replication, we'll store the max value of the below field on each sync- and only sync rows with greater or equal value on the next run.- </p>- <p className="mb-2">- You should pick a field that increments or updates each time the row is updated, such as a{' '}- <code>updated_at</code> timestamp.- </p>- {!incrementalSyncSupported.disabled && (- <>- <LemonSelect- value={incrementalFieldValue}- onChange={(newValue) => {- setIncrementalFieldValue(newValue)- setRadioValue('incremental')- }}- options={- schema.incremental_fields.map((n) => ({- value: n.field,- label: (- <>- <span className="leading-5">{n.label}</span>- <LemonTag className="ml-2" type="success">- {n.type}- </LemonTag>- </>- ),- })) ?? []- }- />- {radioValue === 'incremental' &&- incrementalFieldValue &&- schema.incremental_fields.find((n) => n.field === incrementalFieldValue)?.nullable && (- <LemonBanner type="warning" className="mt-2">- This field is nullable. Any rows where <code>{incrementalFieldValue}</code> is- null will not be synced.- </LemonBanner>- )}- {radioValue === 'incremental' &&- incrementalFieldValue &&- schema.incremental_fields.find((n) => n.field === incrementalFieldValue)?.is_indexed ===- false && (- <LemonBanner type="warning" className="mt-2">- No index detected on <code>{incrementalFieldValue}</code>. Incremental syncs- query this column on every run; without an index the source database may scan- the full table on each sync. Consider adding an index, or pick a different- incremental field.- </LemonBanner>- )}- {radioValue === 'incremental' && columns.length > 0 && (- <>- <p className="mt-4 mb-2">- Optionally, select one or more columns to use as the primary key for- deduplication. If not set, PostHog will attempt to auto-detect the primary key- from the source.- </p>- <LemonInputSelect- mode="multiple"- value={primaryKeyColumns}- onChange={(newValue) => !primaryKeyLocked && setPrimaryKeyColumns(newValue)}- disabled={primaryKeyLocked}- options={columns.map((col) => ({- key: col.field,- label: `${col.label} (${col.type})`,- }))}- placeholder={- resolvedDetectedPks- ? `Auto-detected: ${resolvedDetectedPks.join(', ')}`- : 'No primary key detected'- }- />- {primaryKeyLocked && (- <LemonBanner type="info" className="mt-2">- Primary key cannot be changed after data has been synced. Delete the synced- data first to change it.+ if (!hideNonWebhookOptions) {+ radioOptions.push(+ {+ value: 'incremental',+ disabledReason:+ (incrementalSyncSupported.disabled && incrementalSyncSupported.disabledReason) || undefined,+ label: (+ <div className="mb-4 font-normal">+ <div className="items-center flex leading-[normal] overflow-hidden mb-1">+ <h4 className="mb-0 mr-2 text-base font-semibold">Incremental replication</h4>+ {!incrementalSyncSupported.disabled &&+ !schema.supports_webhooks &&+ !schema.cdc_available && <LemonTag type="success">Recommended</LemonTag>}+ </div>+ <p className="mb-2">+ When using incremental replication, we'll store the max value of the below field on each+ sync and only sync rows with greater or equal value on the next run.+ </p>+ <p className="mb-2">+ You should pick a field that increments or updates each time the row is updated, such as a{' '}+ <code>updated_at</code> timestamp.+ </p>+ {!incrementalSyncSupported.disabled && (+ <>+ <LemonSelect+ value={incrementalFieldValue}+ onChange={(newValue) => {+ setIncrementalFieldValue(newValue)+ setRadioValue('incremental')+ }}+ options={+ schema.incremental_fields.map((n) => ({+ value: n.field,+ label: (+ <>+ <span className="leading-5">{n.label}</span>+ <LemonTag className="ml-2" type="success">+ {n.type}+ </LemonTag>+ </>+ ),+ })) ?? []+ }+ />+ {radioValue === 'incremental' &&+ incrementalFieldValue &&+ schema.incremental_fields.find((n) => n.field === incrementalFieldValue)+ ?.nullable && (+ <LemonBanner type="warning" className="mt-2">+ This field is nullable. Any rows where <code>{incrementalFieldValue}</code>{' '}+ is null will not be synced.</LemonBanner>)}- {primaryKeyColumns.length === 0 && !resolvedDetectedPks && !primaryKeyLocked && (- <LemonBanner type="info" className="mt-2">- No primary key could be auto-detected from the source. Select one manually- to enable incremental sync, or use full table replication instead.+ {radioValue === 'incremental' &&+ incrementalFieldValue &&+ schema.incremental_fields.find((n) => n.field === incrementalFieldValue)+ ?.is_indexed === false && (+ <LemonBanner type="warning" className="mt-2">+ No index detected on <code>{incrementalFieldValue}</code>. Incremental syncs+ query this column on every run; without an index the source database may+ scan the full table on each sync. Consider adding an index, or pick a+ different incremental field.</LemonBanner>)}- {primaryKeyColumns.length > 0 &&- primaryKeyColumns.some(- (pk) => columns.find((col) => col.field === pk)?.nullable- ) && (- <LemonBanner type="warning" className="mt-2">- One or more selected primary key columns are nullable. Rows with null- values may cause issues with deduplication.+ {radioValue === 'incremental' && columns.length > 0 && (+ <>+ <p className="mt-4 mb-2">+ Optionally, select one or more columns to use as the primary key for+ deduplication. If not set, PostHog will attempt to auto-detect the primary+ key from the source.+ </p>+ <LemonInputSelect+ mode="multiple"+ value={primaryKeyColumns}+ onChange={(newValue) => !primaryKeyLocked && setPrimaryKeyColumns(newValue)}+ disabled={primaryKeyLocked}+ options={columns.map((col) => ({+ key: col.field,+ label: `${col.label} (${col.type})`,+ }))}+ placeholder={+ resolvedDetectedPks+ ? `Auto-detected: ${resolvedDetectedPks.join(', ')}`+ : 'No primary key detected'+ }+ />+ {primaryKeyLocked && (+ <LemonBanner type="info" className="mt-2">+ Primary key cannot be changed after data has been synced. Delete the+ synced data first to change it.</LemonBanner>)}- </>- )}- </>- )}- </div>- ),- },- {- value: 'append',- disabledReason: (appendSyncSupported.disabled && appendSyncSupported.disabledReason) || undefined,- label: (- <div className="mb-4 font-normal">- <div className="items-center flex leading-[normal] overflow-hidden mb-1">- <h4 className="mb-0 mr-2 text-base font-semibold">Append only replication</h4>- </div>- <p className="mb-2">- When using append only replication, similar to incremental above, we'll store the max value of- the below field on each sync and only sync rows with greater or equal value on the next run. But- unlike incremental replication, we'll append the rows as opposed to merge them into the existing- table, meaning you can have duplicate data if the value for the below field changes on a row.- You should only use append only replication for sources that don't support incremental.- </p>- <p className="mb-2">- You should pick a field that doesn't change each time the row is updated, such as a{' '}- <code>created_at</code> timestamp.- </p>- {!appendSyncSupported.disabled && (- <>- <LemonSelect- value={appendFieldValue}- onChange={(newValue) => {- setAppendFieldValue(newValue)- setRadioValue('append')- }}- options={- schema.incremental_fields.map((n) => ({- value: n.field,- label: (- <>- <span className="leading-5">{n.label}</span>- <LemonTag className="ml-2" type="success">- {n.type}- </LemonTag>- </>- ),- })) ?? []- }- />- {radioValue === 'append' &&- appendFieldValue &&- schema.incremental_fields.find((n) => n.field === appendFieldValue)?.nullable && (- <LemonBanner type="warning" className="mt-2">- This field is nullable. Any rows where <code>{appendFieldValue}</code> is null- will not be synced.- </LemonBanner>+ {primaryKeyColumns.length === 0 &&+ !resolvedDetectedPks &&+ !primaryKeyLocked && (+ <LemonBanner type="info" className="mt-2">+ No primary key could be auto-detected from the source. Select one+ manually to enable incremental sync, or use full table replication+ instead.+ </LemonBanner>+ )}+ {primaryKeyColumns.length > 0 &&+ primaryKeyColumns.some(+ (pk) => columns.find((col) => col.field === pk)?.nullable+ ) && (+ <LemonBanner type="warning" className="mt-2">+ One or more selected primary key columns are nullable. Rows with+ null values may cause issues with deduplication.+ </LemonBanner>+ )}+ </>)}- {radioValue === 'append' &&- appendFieldValue &&- schema.incremental_fields.find((n) => n.field === appendFieldValue)?.is_indexed ===- false && (- <LemonBanner type="warning" className="mt-2">- No index detected on <code>{appendFieldValue}</code>. Append only syncs query- this column on every run; without an index the source database may scan the full- table on each sync. Consider adding an index, or pick a different field.- </LemonBanner>- )}- </>- )}- </div>- ),- },- {- value: 'full_refresh',- label: (- <div className="mb-6 font-normal">- <div className="items-center flex leading-[normal] overflow-hidden mb-1">- <h4 className="mb-0 mr-2 text-base font-semibold">Full table replication</h4>+ </>+ )}</div>- <p className="m-0">- We'll replicate the whole table on every sync. This can take longer to sync and increase your- monthly billing.- </p>- </div>- ),- }- )+ ),+ },+ {+ value: 'append',+ disabledReason: (appendSyncSupported.disabled && appendSyncSupported.disabledReason) || undefined,+ label: (+ <div className="mb-4 font-normal">+ <div className="items-center flex leading-[normal] overflow-hidden mb-1">+ <h4 className="mb-0 mr-2 text-base font-semibold">Append only replication</h4>+ </div>+ <p className="mb-2">+ When using append only replication, similar to incremental above, we'll store the max value+ of the below field on each sync and only sync rows with greater or equal value on the next+ run. But unlike incremental replication, we'll append the rows as opposed to merge them into+ the existing table, meaning you can have duplicate data if the value for the below field+ changes on a row. You should only use append only replication for sources that don't support+ incremental.+ </p>+ <p className="mb-2">+ You should pick a field that doesn't change each time the row is updated, such as a{' '}+ <code>created_at</code> timestamp.+ </p>+ {!appendSyncSupported.disabled && (+ <>+ <LemonSelect+ value={appendFieldValue}+ onChange={(newValue) => {+ setAppendFieldValue(newValue)+ setRadioValue('append')+ }}+ options={+ schema.incremental_fields.map((n) => ({+ value: n.field,+ label: (+ <>+ <span className="leading-5">{n.label}</span>+ <LemonTag className="ml-2" type="success">+ {n.type}+ </LemonTag>+ </>+ ),+ })) ?? []+ }+ />+ {radioValue === 'append' &&+ appendFieldValue &&+ schema.incremental_fields.find((n) => n.field === appendFieldValue)?.nullable && (+ <LemonBanner type="warning" className="mt-2">+ This field is nullable. Any rows where <code>{appendFieldValue}</code> is+ null will not be synced.+ </LemonBanner>+ )}+ {radioValue === 'append' &&+ appendFieldValue &&+ schema.incremental_fields.find((n) => n.field === appendFieldValue)?.is_indexed ===+ false && (+ <LemonBanner type="warning" className="mt-2">+ No index detected on <code>{appendFieldValue}</code>. Append only syncs+ query this column on every run; without an index the source database may+ scan the full table on each sync. Consider adding an index, or pick a+ different field.+ </LemonBanner>+ )}+ </>+ )}+ </div>+ ),+ },+ {+ value: 'full_refresh',+ label: (+ <div className="mb-6 font-normal">+ <div className="items-center flex leading-[normal] overflow-hidden mb-1">+ <h4 className="mb-0 mr-2 text-base font-semibold">Full table replication</h4>+ </div>+ <p className="m-0">+ We'll replicate the whole table on every sync. This can take longer to sync and increase+ your monthly billing.+ </p>+ </div>+ ),+ }+ )+ }// The form is "dirty" if the user has deviated from the server-persisted sync config. For a// schema that has never been set up (`schema.sync_type` is null), any selection counts asdiff --git a/products/warehouse_sources/backend/models/external_table_definitions.py b/products/warehouse_sources/backend/models/external_table_definitions.pyindex 636c06123b1a..0cf2ea61ec2b 100644--- a/products/warehouse_sources/backend/models/external_table_definitions.py+++ b/products/warehouse_sources/backend/models/external_table_definitions.py@@ -519,6 +519,10 @@ external_tables: dict[str, dict[str, DatabaseField]] = {"cancel_at": StringDatabaseField(name="cancel_at"),"cancel_at_period_end": BooleanDatabaseField(name="cancel_at_period_end"),"cancellation_details": StringJSONDatabaseField(name="cancellation_details"),+ # Expanded via API sync (`expand=data.discounts`); contains full Discount objects+ # with embedded Coupon. Under webhook-only mode this is an array of `di_*` IDs —+ # join to `stripe_discount.id` for full details.+ "discounts": StringJSONDatabaseField(name="discounts"),"__trial_end": IntegerDatabaseField(name="trial_end", hidden=True),"trial_end": ast.ExpressionField(isolate_scope=True,@@ -797,6 +801,73 @@ external_tables: dict[str, dict[str, DatabaseField]] = {"metadata": StringJSONDatabaseField(name="metadata"),"type": StringDatabaseField(name="type"),},+ "stripe_coupon": {+ "id": StringDatabaseField(name="id"),+ "object": StringDatabaseField(name="object"),+ "__created": IntegerDatabaseField(name="created", hidden=True),+ "created_at": ast.ExpressionField(+ isolate_scope=True,+ expr=ast.Call(+ name="toDateTime",+ args=[ast.Call(name="toString", args=[ast.Field(chain=["__created"])])],+ ),+ name="created_at",+ ),+ "amount_off": IntegerDatabaseField(name="amount_off"),+ "percent_off": FloatDatabaseField(name="percent_off"),+ "currency": StringDatabaseField(name="currency"),+ "duration": StringDatabaseField(name="duration"),+ "duration_in_months": IntegerDatabaseField(name="duration_in_months"),+ "max_redemptions": IntegerDatabaseField(name="max_redemptions"),+ "__redeem_by": IntegerDatabaseField(name="redeem_by", hidden=True),+ "redeem_by": ast.ExpressionField(+ isolate_scope=True,+ expr=ast.Call(+ name="toDateTime",+ args=[ast.Call(name="toString", args=[ast.Field(chain=["__redeem_by"])])],+ ),+ name="redeem_by",+ ),+ "times_redeemed": IntegerDatabaseField(name="times_redeemed"),+ "valid": BooleanDatabaseField(name="valid"),+ "name": StringDatabaseField(name="name"),+ "livemode": BooleanDatabaseField(name="livemode"),+ "metadata": StringJSONDatabaseField(name="metadata"),+ "applies_to": StringJSONDatabaseField(name="applies_to"),+ },+ # Webhook-only — populated by `customer.discount.created|updated|deleted` events.+ # Discount has no API list endpoint, so this table backfills only forward.+ "stripe_discount": {+ "id": StringDatabaseField(name="id"),+ "object": StringDatabaseField(name="object"),+ "customer": StringDatabaseField(name="customer"),+ "subscription": StringDatabaseField(name="subscription"),+ "subscription_item": StringDatabaseField(name="subscription_item"),+ "invoice": StringDatabaseField(name="invoice"),+ "invoice_item": StringDatabaseField(name="invoice_item"),+ "promotion_code": StringDatabaseField(name="promotion_code"),+ "checkout_session": StringDatabaseField(name="checkout_session"),+ # Coupon is always embedded inline in a Discount object — full coupon details live here.+ "coupon": StringJSONDatabaseField(name="coupon"),+ "__start": IntegerDatabaseField(name="start", hidden=True),+ "start": ast.ExpressionField(+ isolate_scope=True,+ expr=ast.Call(+ name="toDateTime",+ args=[ast.Call(name="toString", args=[ast.Field(chain=["__start"])])],+ ),+ name="start",+ ),+ "__end": IntegerDatabaseField(name="end", hidden=True),+ "end": ast.ExpressionField(+ isolate_scope=True,+ expr=ast.Call(+ name="toDateTime",+ args=[ast.Call(name="toString", args=[ast.Field(chain=["__end"])])],+ ),+ name="end",+ ),+ },"zendesk_brands": {"id": IntegerDatabaseField(name="id"),"url": StringDatabaseField(name="url"),