:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Pipedrive webhook ingestion (#77472)
Tom Owers6e15f137fb08
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.mdindex ea732ac3c6dd..5f93f7ca04c1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md@@ -764,7 +764,7 @@ gaps, so that earlier "looks proportionate" read was wrong. See the appendix forThe two worth pulling forward, because both are higher-adoption than most appendix entries:- **ActiveCampaign** — no `emailActivities` (per-contact opens and clicks), no e-commerce objects at all (`ecomOrders`, `ecomOrderProducts`, `ecomCustomers`), and no membership tables joining the contacts we sync to the lists and automations we also sync.-- **Pipedrive** — no deal line items (`deals/{id}/products`), so deal revenue is only readable as a single number; `/deals` excludes archived deals, so closed pipeline history is silently missing; and no `deals/{id}/flow` changelog, so stage-transition and velocity analysis is impossible.+- **Pipedrive** — no deal line items (`deals/{id}/products`), so deal revenue is only readable as a single number; `/deals` excludes archived deals, so closed pipeline history is silently missing; and no `deals/{id}/flow` changelog, so stage-transition and velocity analysis is impossible. Webhook ingest now supplements the poll for the seven API v2 entity tables (activities, deals, organizations, persons, pipelines, products, stages); the remaining v1-shaped tables stay poll-only.## Full sweep resultsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex ded53f12bd4c..18b172fa77f1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -484,7 +484,7 @@ the row lists both.| picqer | HTTP | requests | ✅ || pingdom | HTTP | requests | ✅ || pinterest_ads | HTTP | requests | ✅ |-| pipedrive | HTTP | requests | ✅ |+| pipedrive | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || pipeliner | HTTP | requests | ✅ || plain | HTTP | requests | ✅ || planhat | HTTP | requests | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/pipedrive.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/pipedrive.pyindex 7c18ba18e07f..af54b3ec6038 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/pipedrive.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/pipedrive.py@@ -1,8 +1,24 @@import re+import secrets+import datetimeimport dataclassesfrom typing import Any, Optionalfrom urllib.parse import urlencode+import orjson+import pyarrow as pa+import structlog+from asgiref.sync import async_to_sync+from dateutil import parser as dateutil_parser+from requests import Session+from requests.exceptions import HTTPError, RequestException++from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ WebhookCreationResult,+ WebhookDeletionResult,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,@@ -16,14 +32,28 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.pipedrive.settings import (PipedriveEndpointConfig,endpoints_for_version,)+LOGGER = structlog.get_logger(__name__)+# Pipedrive caps list pages at 500 items (default 100).PAGE_SIZE = 500+# Webhook management lives on v1; there is no v2 equivalent.+WEBHOOKS_PATH = "/api/v1/webhooks"+# The payload format we register. v2 deliveries carry the entity under `data` in the same shape+# the API v2 collections return, which is what lets pushed rows merge into the polled tables.+WEBHOOK_PAYLOAD_VERSION = "2.0"+WEBHOOK_NAME = "PostHog data warehouse"+# Pipedrive echoes the basic auth credentials set on the subscription back on every delivery.+# The username is fixed and the password is the generated secret.+WEBHOOK_AUTH_USER = "posthog"+WEBHOOK_REQUEST_TIMEOUT_SECONDS = 30+_SUBDOMAIN_RE = re.compile(r"^[a-z0-9-]+$")# Never reflects the raw input back: it can be a full URL or website domain the user pasted by@@ -110,6 +140,215 @@ def validate_credentials(company_domain: str, api_token: str) -> Optional[int]:return status+def _coerce_payload(value: Any) -> Optional[dict[str, Any]]:+ """Webhook payload blocks arrive as dicts, or as JSON strings once buffered through parquet."""+ if isinstance(value, str | bytes):+ try:+ value = orjson.loads(value)+ except orjson.JSONDecodeError:+ return None+ return value if isinstance(value, dict) else None+++def _parse_timestamp(value: Any) -> Optional[datetime.datetime]:+ if not isinstance(value, str):+ return None+ try:+ return dateutil_parser.parse(value)+ except (ValueError, OverflowError):+ return None+++def _webhook_table_transformer(table: pa.Table) -> pa.Table:+ """Reshape raw webhook deliveries into rows matching the pull-API table shape.++ A delivery lands as the whole v2 envelope (`{"meta": {...}, "data": {...}, "previous": {...}}`),+ so the entity has to be lifted out of `data`. Only the newest delivery per id survives: delta+ merge dedupes across syncs but not within one batch, so a `create` followed by a `change` for+ the same deal must collapse here or the batch would merge the same key twice.+ """+ if "data" not in table.column_names:+ return table_from_py_list([])++ meta_column = table.column("meta").to_pylist() if "meta" in table.column_names else [None] * table.num_rows++ latest_by_id: dict[Any, tuple[Optional[datetime.datetime], dict[str, Any]]] = {}+ for data, meta in zip(table.column("data").to_pylist(), meta_column):+ row = _coerce_payload(data)+ if row is None:+ continue++ row_id = row.get("id")+ if row_id is None:+ continue++ meta_row = _coerce_payload(meta) or {}+ # The Hog template already drops deletions; this keeps a hand-configured webhook that+ # subscribed to them from blanking a polled row with a tombstone payload.+ if meta_row.get("action") == "delete":+ continue++ timestamp = _parse_timestamp(meta_row.get("timestamp"))+ existing = latest_by_id.get(row_id)+ # Later rows win ties so batch arrival order breaks equal or unparseable timestamps.+ if existing is None or existing[0] is None or (timestamp is not None and timestamp >= existing[0]):+ latest_by_id[row_id] = (timestamp, row)++ return table_from_py_list([row for _, row in latest_by_id.values()])+++def _webhook_error_result(action: str, error: Exception, status_code: Optional[int]) -> str:+ LOGGER.warning(f"Failed to {action} Pipedrive webhook", error=str(error), status_code=status_code)+ if status_code in (401, 403):+ return (+ "Pipedrive rejected the API token while managing the webhook. The token's user needs "+ "permission to manage webhooks."+ )+ if status_code is not None:+ return f"Pipedrive API error ({status_code})."+ return f"Could not reach Pipedrive: {error}"+++def _webhooks_url(company_domain: str, webhook_id: Optional[int] = None) -> str:+ path = WEBHOOKS_PATH if webhook_id is None else f"{WEBHOOKS_PATH}/{webhook_id}"+ return _build_url(company_domain, path, {})+++def _list_webhooks(company_domain: str, api_token: str) -> list[dict[str, Any]]:+ session = make_tracked_session(redact_values=(api_token,))+ response = session.get(+ _webhooks_url(company_domain),+ headers=_get_headers(api_token),+ timeout=WEBHOOK_REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ data = response.json().get("data")+ return [hook for hook in data if isinstance(hook, dict)] if isinstance(data, list) else []+++def create_webhook(company_domain: str, api_token: str, webhook_url: str) -> WebhookCreationResult:+ """Register one wildcard webhook (`event_action="*"`, `event_object="*"`) on the account.++ Pipedrive scopes a subscription to a single action/object pair, so a per-entity subscription+ would burn one of the account's 40 webhook slots per table. The Hog template drops every+ entity that isn't mapped to a selected schema before anything is persisted, and the wildcard+ can't drift out of sync when the user enables another table later.+ """+ password = secrets.token_urlsafe(32)+ session = make_tracked_session(redact_values=(api_token, password))++ try:+ response = session.post(+ _webhooks_url(company_domain),+ json={+ "name": WEBHOOK_NAME,+ "subscription_url": webhook_url,+ "event_action": "*",+ "event_object": "*",+ "version": WEBHOOK_PAYLOAD_VERSION,+ "http_auth_user": WEBHOOK_AUTH_USER,+ "http_auth_password": password,+ },+ headers=_get_headers(api_token),+ timeout=WEBHOOK_REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ except ValueError as e:+ return WebhookCreationResult(success=False, error=str(e))+ except HTTPError as e:+ status_code = e.response.status_code if e.response is not None else None+ return WebhookCreationResult(success=False, error=_webhook_error_result("create", e, status_code))+ except RequestException as e:+ return WebhookCreationResult(success=False, error=_webhook_error_result("create", e, None))++ created_id = (response.json().get("data") or {}).get("id")+ _remove_superseded_webhooks(session, company_domain, api_token, webhook_url, created_id)++ return WebhookCreationResult(+ success=True,+ extra_inputs={"http_auth_user": WEBHOOK_AUTH_USER, "http_auth_password": password},+ )+++def _remove_superseded_webhooks(+ session: Session, company_domain: str, api_token: str, webhook_url: str, created_id: Any+) -> None:+ """Drop earlier subscriptions on the same URL, best effort, after the replacement is live.++ Re-running setup mints a fresh password, so an older subscription would keep delivering with+ credentials the Hog function no longer accepts. Cleaning up after the create (rather than+ before) means the account is never left without a working webhook if the create fails.+ """+ try:+ for hook in _list_webhooks(company_domain, api_token):+ if hook.get("subscription_url") != webhook_url or hook.get("id") == created_id:+ continue+ session.delete(+ _webhooks_url(company_domain, hook.get("id")),+ headers=_get_headers(api_token),+ timeout=WEBHOOK_REQUEST_TIMEOUT_SECONDS,+ ).raise_for_status()+ except RequestException as e:+ LOGGER.warning("Could not remove superseded Pipedrive webhooks", error=str(e))+++def get_external_webhook_info(company_domain: str, api_token: str, webhook_url: str) -> ExternalWebhookInfo:+ try:+ hooks = _list_webhooks(company_domain, api_token)+ except ValueError as e:+ return ExternalWebhookInfo(exists=False, error=str(e))+ except HTTPError as e:+ status_code = e.response.status_code if e.response is not None else None+ return ExternalWebhookInfo(exists=False, error=_webhook_error_result("look up", e, status_code))+ except RequestException as e:+ return ExternalWebhookInfo(exists=False, error=_webhook_error_result("look up", e, None))++ matches = [hook for hook in hooks if hook.get("subscription_url") == webhook_url]+ if not matches:+ return ExternalWebhookInfo(exists=False, url=webhook_url)++ return ExternalWebhookInfo(+ exists=True,+ url=webhook_url,+ enabled_events=[f"{hook.get('event_action')}.{hook.get('event_object')}" for hook in matches],+ status="active" if any(hook.get("is_active") for hook in matches) else "inactive",+ created_at=matches[0].get("add_time"),+ description=matches[0].get("name"),+ )+++def delete_webhook(company_domain: str, api_token: str, webhook_url: str) -> WebhookDeletionResult:+ try:+ hooks = _list_webhooks(company_domain, api_token)+ except ValueError as e:+ return WebhookDeletionResult(success=False, error=str(e))+ except HTTPError as e:+ status_code = e.response.status_code if e.response is not None else None+ return WebhookDeletionResult(success=False, error=_webhook_error_result("delete", e, status_code))+ except RequestException as e:+ return WebhookDeletionResult(success=False, error=_webhook_error_result("delete", e, None))++ session = make_tracked_session(redact_values=(api_token,))+ for hook in hooks:+ if hook.get("subscription_url") != webhook_url:+ continue+ try:+ response = session.delete(+ _webhooks_url(company_domain, hook.get("id")),+ headers=_get_headers(api_token),+ timeout=WEBHOOK_REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ except HTTPError as e:+ status_code = e.response.status_code if e.response is not None else None+ return WebhookDeletionResult(success=False, error=_webhook_error_result("delete", e, status_code))+ except RequestException as e:+ return WebhookDeletionResult(success=False, error=_webhook_error_result("delete", e, None))++ # Nothing matching left on the account, whether we deleted it now or it was already gone.+ return WebhookDeletionResult(success=True)++def pipedrive_source(company_domain: str,api_token: str,@@ -117,6 +356,7 @@ def pipedrive_source(team_id: int,job_id: str,resumable_source_manager: ResumableSourceManager[PipedriveResumeConfig],+ webhook_source_manager: WebhookSourceManager,db_incremental_field_last_value: Optional[Any] = None,api_version: str = "v2",) -> SourceResponse:@@ -176,9 +416,18 @@ def pipedrive_source(initial_paginator_state=initial_paginator_state,)+ webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)()++ def items() -> Any:+ # Once the backfill has landed and the schema is on webhook sync, pushed rows replace the+ # poll for this run; the poll stays the only path until then.+ if webhook_enabled:+ return webhook_source_manager.get_items(table_transformer=_webhook_table_transformer)+ return resource+return SourceResponse(name=endpoint,- items=lambda: resource,+ items=items,primary_keys=[config.primary_key],partition_count=1,partition_size=1,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/settings.pyindex 3f30978ec9ff..97404e6f45fc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/settings.py@@ -61,3 +61,30 @@ def endpoints_for_version(api_version: str) -> dict[str, PipedriveEndpointConfig# Endpoint names are version-independent (`activities` exists under both), so schema discovery# can enumerate them without a resolved version.ENDPOINTS = (*_SHARED_ENDPOINTS.keys(), "activities")+++# Our schema name -> the Pipedrive webhook entity, which is both the `event_object` we subscribe+# to and the `meta.entity` a delivery carries. Only endpoints polled from the API v2 collections+# appear: a webhooks v2 delivery carries the v2 entity shape, so routing one into a table+# backfilled from a v1 collection (notes, leads, users, the *_fields catalogs) would merge rows+# whose field names don't match the ones already in the table.+WEBHOOK_ENTITY_BY_SCHEMA: dict[str, str] = {+ "activities": "activity",+ "deals": "deal",+ "organizations": "organization",+ "persons": "person",+ "pipelines": "pipeline",+ "products": "product",+ "stages": "stage",+}+++def webhook_schema_names(api_version: str) -> frozenset[str]:+ """Schemas a webhook can feed for a resolved source version.++ We always register version 2.0 webhooks, so a schema only qualifies while its polled+ endpoint is the matching v2 collection. That excludes `activities` under a deliberate `v1`+ pin, where the backfill still comes from the deprecated v1 offset endpoint.+ """+ endpoints = endpoints_for_version(api_version)+ return frozenset(name for name in WEBHOOK_ENTITY_BY_SCHEMA if endpoints[name].path.startswith("/api/v2/"))diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/source.pyindex c123fc726aa6..336fd1e80d54 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/source.py@@ -1,5 +1,5 @@import datetime-from typing import Optional, cast+from typing import TYPE_CHECKING, Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,@@ -11,9 +11,13 @@ from posthog.schema import ()from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,FieldType,ResumableSource,VersionDeprecation,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,@@ -22,21 +26,35 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.regfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.pipedrive import (PipedriveSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.pipedrive.pipedrive import (PipedriveResumeConfig,+ create_webhook as create_pipedrive_webhook,+ delete_webhook as delete_pipedrive_webhook,+ get_external_webhook_info as get_pipedrive_webhook_info,normalize_company_domain,pipedrive_source,validate_credentials as validate_pipedrive_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.pipedrive.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.pipedrive.settings import (+ ENDPOINTS,+ WEBHOOK_ENTITY_BY_SCHEMA,+ webhook_schema_names,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+if TYPE_CHECKING:+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC+@SourceRegistry.register-class PipedriveSource(ResumableSource[PipedriveSourceConfig, PipedriveResumeConfig]):+class PipedriveSource(+ ResumableSource[PipedriveSourceConfig, PipedriveResumeConfig],+ WebhookSource[PipedriveSourceConfig],+):supported_versions = ("v1", "v2")default_version = "v2"# v1 only differs from v2 in the `activities` endpoint; the vendor deprecated the v1@@ -50,6 +68,16 @@ class PipedriveSource(ResumableSource[PipedriveSourceConfig, PipedriveResumeConfdef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PIPEDRIVE+ @property+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:+ from products.warehouse_sources.backend.temporal.data_imports.sources.pipedrive.webhook_template import template++ return template++ @property+ def webhook_resource_map(self) -> dict[str, str]:+ return WEBHOOK_ENTITY_BY_SCHEMA+@propertydef connection_host_fields(self) -> list[str]:# The stored API token is sent to `{company_domain}.pipedrive.com`; retargeting the@@ -89,6 +117,40 @@ You can find your personal API token in Pipedrive under **Settings > Personal pr),],),+ webhookSetupCaption="""PostHog registers one webhook on your Pipedrive account using your API token. Pipedrive does not sign deliveries, so PostHog generates HTTP auth credentials, sets them on the webhook, and rejects any delivery that does not send them back.++**Manual setup** (only needed if automatic registration failed):++1. Go to **Tools and apps > Webhooks** in Pipedrive and click **Create new webhook**+2. Paste the webhook URL shown below into the **Endpoint URL** field+3. Set both **Event action** and **Event object** to **All**, and leave the payload version on **v2**+4. Fill in **HTTP Auth username** and **HTTP Auth password**, then enter the same two values below so PostHog can verify deliveries+5. Click **Save**++Deletions in Pipedrive are not applied to tables synced by webhook. Switch a table back to a full sync to drop deleted rows.""",+ webhookFields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="http_auth_user",+ label="HTTP auth username",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="posthog",+ caption="The HTTP auth username set on the Pipedrive webhook.",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="http_auth_password",+ label="HTTP auth password",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ caption="The HTTP auth password set on the Pipedrive webhook. PostHog checks both values on every delivery.",+ secret=True,+ ),+ ],+ ),)def get_non_retryable_errors(self) -> dict[str, str | None]:@@ -115,8 +177,15 @@ You can find your personal API token in Pipedrive under **Settings > Personal pr) -> list[SourceSchema]:# Full refresh only: Pipedrive's v1 collections have no server-side updated_after# filter, and the v2 `updated_since` filter is unverified (no credentials to curl with).+ webhook_capable = webhook_schema_names(self.resolve_api_version(api_version))schemas = [- SourceSchema(name=endpoint, supports_incremental=False, supports_append=False, incremental_fields=[])+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ supports_webhooks=endpoint in webhook_capable,+ )for endpoint in list(ENDPOINTS)]if names is not None:@@ -149,6 +218,24 @@ You can find your personal API token in Pipedrive under **Settings > Personal prdef get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PipedriveResumeConfig]:return ResumableSourceManager[PipedriveResumeConfig](inputs, PipedriveResumeConfig)+ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:+ return WebhookSourceManager(inputs, inputs.logger)++ def create_webhook(+ self, config: PipedriveSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookCreationResult:+ return create_pipedrive_webhook(config.company_domain, config.api_token, webhook_url)++ def get_external_webhook_info(+ self, config: PipedriveSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> ExternalWebhookInfo:+ return get_pipedrive_webhook_info(config.company_domain, config.api_token, webhook_url)++ def delete_webhook(+ self, config: PipedriveSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookDeletionResult:+ return delete_pipedrive_webhook(config.company_domain, config.api_token, webhook_url)+def source_for_pipeline(self,config: PipedriveSourceConfig,@@ -163,5 +250,6 @@ You can find your personal API token in Pipedrive under **Settings > Personal prjob_id=inputs.job_id,api_version=self.resolve_api_version(inputs.api_version),resumable_source_manager=resumable_source_manager,+ webhook_source_manager=self.get_webhook_source_manager(inputs),db_incremental_field_last_value=None, # every Pipedrive endpoint is full refresh)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/tests/test_pipedrive.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/tests/test_pipedrive.pyindex ce130d5dedbd..e94fcd0f75d9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/tests/test_pipedrive.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/tests/test_pipedrive.py@@ -5,11 +5,18 @@ import pytestfrom unittest import mockfrom requests import Response+from requests.exceptions import RequestException+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_listfrom products.warehouse_sources.backend.temporal.data_imports.sources.pipedrive.pipedrive import (PAGE_SIZE,+ WEBHOOK_AUTH_USER,PipedriveResumeConfig,+ _webhook_table_transformer,base_url,+ create_webhook,+ delete_webhook,+ get_external_webhook_info,normalize_company_domain,pipedrive_source,validate_credentials,@@ -78,8 +85,22 @@ def _rows(source_response) -> list[dict[str, Any]]:return [row for page in source_response.items() for row in page]-def _source(endpoint: str, manager: mock.MagicMock):- return pipedrive_source("acme", "token", endpoint, team_id=1, job_id="j", resumable_source_manager=manager)+def _webhook_manager(enabled: bool = False) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.webhook_enabled = mock.AsyncMock(return_value=enabled)+ return manager+++def _source(endpoint: str, manager: mock.MagicMock, webhook_manager: mock.MagicMock | None = None):+ return pipedrive_source(+ "acme",+ "token",+ endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ webhook_source_manager=webhook_manager or _webhook_manager(),+ )class TestNormalizeCompanyDomain:@@ -343,3 +364,256 @@ class TestEndpointsForVersion:v1 = {name: cfg for name, cfg in endpoints_for_version("v1").items() if name != "activities"}v2 = {name: cfg for name, cfg in endpoints_for_version("v2").items() if name != "activities"}assert v1 == v2+++def _json_response(body: dict[str, Any], status: int = 200) -> Response:+ resp = Response()+ resp.status_code = status+ resp.reason = "OK" if status < 400 else "Error"+ resp.url = "https://acme.pipedrive.com/api/v1/webhooks"+ resp._content = json.dumps(body).encode()+ return resp+++WEBHOOK_URL = "https://webhooks.us.posthog.com/public/webhooks/dwh/hf_1"+++class TestWebhookManagement:+ @mock.patch(PIPEDRIVE_SESSION_PATCH)+ def test_create_registers_a_wildcard_v2_subscription_with_generated_credentials(+ self, MockSession: mock.MagicMock+ ) -> None:+ session = MockSession.return_value+ session.post.return_value = _json_response({"success": True, "data": {"id": 9}}, status=201)++ result = create_webhook("acme", "token", WEBHOOK_URL)++ assert result.success is True+ body = session.post.call_args.kwargs["json"]+ assert body["subscription_url"] == WEBHOOK_URL+ assert (body["event_action"], body["event_object"]) == ("*", "*")+ assert body["version"] == "2.0"+ # Pipedrive signs nothing, so the generated basic auth credentials are the only thing+ # separating our ingest endpoint from an unauthenticated one. They have to reach both+ # Pipedrive and the hog function or every delivery is unverifiable.+ assert body["http_auth_user"] == result.extra_inputs["http_auth_user"] == WEBHOOK_AUTH_USER+ assert body["http_auth_password"] == result.extra_inputs["http_auth_password"]+ assert len(body["http_auth_password"]) >= 32++ @mock.patch(PIPEDRIVE_SESSION_PATCH)+ def test_create_generates_a_fresh_password_each_time(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ session.post.return_value = _json_response({"success": True, "data": {"id": 9}}, status=201)+ session.get.return_value = _json_response({"data": []})++ first = create_webhook("acme", "token", WEBHOOK_URL)+ second = create_webhook("acme", "token", WEBHOOK_URL)++ assert first.extra_inputs["http_auth_password"] != second.extra_inputs["http_auth_password"]++ @mock.patch(PIPEDRIVE_SESSION_PATCH)+ def test_create_removes_the_subscription_it_replaces(self, MockSession: mock.MagicMock) -> None:+ # Each create mints a new password, so an older subscription on the same URL would keep+ # delivering with credentials the hog function no longer accepts.+ session = MockSession.return_value+ session.post.return_value = _json_response({"success": True, "data": {"id": 9}}, status=201)+ session.get.return_value = _json_response(+ {+ "data": [+ {"id": 4, "subscription_url": WEBHOOK_URL},+ {"id": 9, "subscription_url": WEBHOOK_URL},+ {"id": 5, "subscription_url": "https://someone-else.example.com/hook"},+ ]+ }+ )+ session.delete.return_value = _json_response({"success": True})++ result = create_webhook("acme", "token", WEBHOOK_URL)++ assert result.success is True+ assert [call.args[0] for call in session.delete.call_args_list] == [+ "https://acme.pipedrive.com/api/v1/webhooks/4"+ ]++ @mock.patch(PIPEDRIVE_SESSION_PATCH)+ def test_create_succeeds_even_if_cleanup_fails(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ session.post.return_value = _json_response({"success": True, "data": {"id": 9}}, status=201)+ session.get.side_effect = RequestException("boom")++ result = create_webhook("acme", "token", WEBHOOK_URL)++ assert result.success is True+ assert result.extra_inputs["http_auth_password"]++ @pytest.mark.parametrize(+ "status, expected_fragment",+ [+ (401, "rejected the API token"),+ (403, "rejected the API token"),+ (500, "Pipedrive API error (500)"),+ ],+ )+ @mock.patch(PIPEDRIVE_SESSION_PATCH)+ def test_create_maps_api_failures_to_an_actionable_error(+ self, MockSession: mock.MagicMock, status: int, expected_fragment: str+ ) -> None:+ session = MockSession.return_value+ session.post.return_value = _json_response({"success": False}, status=status)++ result = create_webhook("acme", "token", WEBHOOK_URL)++ assert result.success is False+ assert result.error is not None and expected_fragment in result.error++ @mock.patch(PIPEDRIVE_SESSION_PATCH)+ def test_create_rejects_an_invalid_company_domain(self, MockSession: mock.MagicMock) -> None:+ result = create_webhook("evil.example.com", "token", WEBHOOK_URL)++ assert result.success is False+ assert result.error is not None and "Invalid Pipedrive company domain" in result.error+ MockSession.return_value.post.assert_not_called()++ @mock.patch(PIPEDRIVE_SESSION_PATCH)+ def test_delete_removes_only_our_subscriptions(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ session.get.return_value = _json_response(+ {+ "data": [+ {"id": 1, "subscription_url": WEBHOOK_URL},+ {"id": 2, "subscription_url": "https://someone-else.example.com/hook"},+ {"id": 3, "subscription_url": WEBHOOK_URL},+ ]+ }+ )+ session.delete.return_value = _json_response({"success": True})++ result = delete_webhook("acme", "token", WEBHOOK_URL)++ assert result.success is True+ deleted_urls = [call.args[0] for call in session.delete.call_args_list]+ assert deleted_urls == [+ "https://acme.pipedrive.com/api/v1/webhooks/1",+ "https://acme.pipedrive.com/api/v1/webhooks/3",+ ]++ @mock.patch(PIPEDRIVE_SESSION_PATCH)+ def test_delete_succeeds_when_the_webhook_is_already_gone(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ session.get.return_value = _json_response({"data": None})++ result = delete_webhook("acme", "token", WEBHOOK_URL)++ assert result.success is True+ session.delete.assert_not_called()++ @mock.patch(PIPEDRIVE_SESSION_PATCH)+ def test_external_info_reports_the_registered_subscription(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ session.get.return_value = _json_response(+ {+ "data": [+ {+ "id": 1,+ "subscription_url": WEBHOOK_URL,+ "event_action": "*",+ "event_object": "*",+ "is_active": 1,+ "add_time": "2026-05-01 10:00:00",+ "name": "PostHog data warehouse",+ }+ ]+ }+ )++ info = get_external_webhook_info("acme", "token", WEBHOOK_URL)++ assert info.exists is True+ assert info.enabled_events == ["*.*"]+ assert info.status == "active"+ assert info.created_at == "2026-05-01 10:00:00"++ @mock.patch(PIPEDRIVE_SESSION_PATCH)+ def test_external_info_reports_a_missing_subscription(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ session.get.return_value = _json_response({"data": [{"id": 1, "subscription_url": "https://other/hook"}]})++ info = get_external_webhook_info("acme", "token", WEBHOOK_URL)++ assert info.exists is False+ assert info.error is None++ @mock.patch(PIPEDRIVE_SESSION_PATCH)+ def test_external_info_surfaces_an_api_failure(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ session.get.return_value = _json_response({}, status=403)++ info = get_external_webhook_info("acme", "token", WEBHOOK_URL)++ assert info.exists is False+ assert info.error is not None and "rejected the API token" in info.error+++def _delivery(entity_id: int, action: str, timestamp: str, **fields: Any) -> dict[str, Any]:+ return {+ "meta": {"action": action, "entity": "deal", "version": "2.0", "timestamp": timestamp},+ "data": {"id": entity_id, **fields},+ "previous": {},+ }+++class TestWebhookTableTransformer:+ def test_keeps_only_the_latest_delivery_per_id(self) -> None:+ # Delta merge dedupes across syncs but not within one batch, so a create followed by a+ # change for the same deal would otherwise merge the same primary key twice.+ table = table_from_py_list(+ [+ _delivery(1, "create", "2026-05-01T10:00:00.000Z", title="Draft"),+ _delivery(1, "change", "2026-05-01T10:05:00.000Z", title="Renewal"),+ _delivery(2, "create", "2026-05-01T10:01:00.000Z", title="Other"),+ ]+ )++ rows = sorted(_webhook_table_transformer(table).to_pylist(), key=lambda row: row["id"])++ assert rows == [{"id": 1, "title": "Renewal"}, {"id": 2, "title": "Other"}]++ def test_drops_deletions_and_rows_without_an_id(self) -> None:+ table = table_from_py_list(+ [+ _delivery(1, "delete", "2026-05-01T10:00:00.000Z", title="Gone"),+ {"meta": {"action": "create", "entity": "deal"}, "data": {"title": "No id"}, "previous": {}},+ _delivery(2, "create", "2026-05-01T10:01:00.000Z", title="Kept"),+ ]+ )++ assert _webhook_table_transformer(table).to_pylist() == [{"id": 2, "title": "Kept"}]++ def test_empty_batch_yields_no_rows(self) -> None:+ assert _webhook_table_transformer(table_from_py_list([])).num_rows == 0+++class TestWebhookSourceWiring:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_webhook_sync_reads_pushed_rows_instead_of_polling(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ _wire(session, [_response([{"id": 1}], {"next_cursor": None})])+ webhook_manager = _webhook_manager(enabled=True)++ response = _source("deals", _make_manager(), webhook_manager)+ items = response.items()++ assert items is webhook_manager.get_items.return_value+ assert webhook_manager.get_items.call_args.kwargs["table_transformer"] is _webhook_table_transformer+ session.send.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_poll_still_runs_when_webhook_sync_is_off(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ _wire(session, [_response([{"id": 1}], {"next_cursor": None})])+ webhook_manager = _webhook_manager(enabled=False)++ rows = _rows(_source("deals", _make_manager(), webhook_manager))++ assert rows == [{"id": 1}]+ webhook_manager.get_items.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/tests/test_pipedrive_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/tests/test_pipedrive_source.pyindex 486375f75a79..aaa414048e89 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/tests/test_pipedrive_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/tests/test_pipedrive_source.py@@ -6,6 +6,7 @@ from unittest import mockfrom posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigTypefrom 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 WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.pipedrive import (PipedriveSourceConfig,)@@ -184,3 +185,75 @@ class TestPipedriveSource:)assert mock_pipedrive_source.call_args.kwargs["company_domain"] == "acme"++ @pytest.mark.parametrize(+ "api_version, expected",+ [+ # Only the schemas backfilled from the API v2 collections can take a v2 delivery.+ ("v2", {"activities", "deals", "organizations", "persons", "pipelines", "products", "stages"}),+ # A v1 pin still polls `activities` from the v1 collection, whose rows are shaped+ # differently to the v2 payload we would push into the same table.+ ("v1", {"deals", "organizations", "persons", "pipelines", "products", "stages"}),+ ],+ )+ def test_only_v2_shaped_schemas_support_webhooks(self, api_version: str, expected: set[str]) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, api_version=api_version)++ assert {schema.name for schema in schemas if schema.supports_webhooks} == expected++ def test_webhook_mapping_keys_are_the_pipedrive_entity_names(self) -> None:+ # Deliveries are routed by `meta.entity`, so a schema whose key isn't the singular entity+ # name would have every one of its events dropped as unmapped.+ webhook_schemas = [s.name for s in self.source.get_schemas(self.config, self.team_id) if s.supports_webhooks]++ assert {name: self.source.webhook_mapping_key(name) for name in webhook_schemas} == {+ "activities": "activity",+ "deals": "deal",+ "organizations": "organization",+ "persons": "person",+ "pipelines": "pipeline",+ "products": "product",+ "stages": "stage",+ }++ def test_webhook_template_verifies_basic_auth_credentials(self) -> None:+ template = self.source.webhook_template++ assert template is not None+ assert template.type == "warehouse_source_webhook"+ input_keys = {item["key"] for item in template.inputs_schema}+ assert {"http_auth_user", "http_auth_password"} <= input_keys++ def test_webhook_fields_match_the_template_inputs(self) -> None:+ # The values a user pastes after a manual setup land on the hog function under these+ # keys, so a mismatch leaves the template with no credentials to check against.+ webhook_fields = self.source.get_source_config.webhookFields or []+ assert [f.name for f in webhook_fields if isinstance(f, SourceFieldInputConfig)] == [+ "http_auth_user",+ "http_auth_password",+ ]++ @pytest.mark.parametrize(+ "method_name, patched",+ [+ ("create_webhook", "create_pipedrive_webhook"),+ ("delete_webhook", "delete_pipedrive_webhook"),+ ("get_external_webhook_info", "get_pipedrive_webhook_info"),+ ],+ )+ def test_webhook_management_passes_domain_then_token(self, method_name: str, patched: str) -> None:+ with mock.patch(+ f"products.warehouse_sources.backend.temporal.data_imports.sources.pipedrive.source.{patched}"+ ) as mocked:+ getattr(self.source, method_name)(self.config, "https://webhooks.example/hook", self.team_id)++ mocked.assert_called_once_with("acme", "token", "https://webhooks.example/hook")++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.pipedrive.source.pipedrive_source")+ def test_source_for_pipeline_passes_a_webhook_manager(self, mock_pipedrive_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "deals"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert isinstance(mock_pipedrive_source.call_args.kwargs["webhook_source_manager"], WebhookSourceManager)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/tests/test_pipedrive_webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/tests/test_pipedrive_webhook_template.pynew file mode 100644index 000000000000..9fe9cb759b09--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/tests/test_pipedrive_webhook_template.py@@ -0,0 +1,140 @@+import json+import base64+from typing import Any++from parameterized import parameterized++from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest++from products.warehouse_sources.backend.temporal.data_imports.sources.pipedrive.webhook_template import template++SOURCE_ID = "source_test_123"+AUTH_USER = "posthog"+AUTH_PASSWORD = "s3cr3t-token-value"+SCHEMA_MAPPING = {"deal": "schema_deals", "person": "schema_persons", "activity": "schema_activities"}+++def _basic(user: str, password: str) -> str:+ return "Basic " + base64.b64encode(f"{user}:{password}".encode()).decode()+++class TestPipedriveWarehouseWebhookTemplate(BaseHogFunctionTemplateTest):+ template = template++ def createHogGlobals(self, globals=None) -> dict:+ data: dict = {+ "request": {+ "method": "POST",+ "headers": {},+ "body": {},+ "query": {},+ "stringBody": "",+ "ip": "127.0.0.1",+ },+ }+ if globals and globals.get("request"):+ data["request"].update(globals["request"])+ return data++ def _payload(self, entity: str = "deal", action: str = "create", version: str = "2.0") -> dict[str, Any]:+ return {+ "meta": {+ "action": action,+ "entity": entity,+ "version": version,+ "entity_id": "42",+ "timestamp": "2026-05-01T10:00:00.000Z",+ "company_id": "1",+ "user_id": "2",+ },+ "data": {"id": 42, "title": "Renewal"},+ "previous": {},+ }++ def _request(self, body: dict, *, headers: dict[str, str] | None = None, method: str = "POST") -> dict:+ payload = json.dumps(body)+ return {+ "request": {+ "method": method,+ "headers": {"authorization": _basic(AUTH_USER, AUTH_PASSWORD)} if headers is None else headers,+ "body": json.loads(payload),+ "stringBody": payload,+ "query": {},+ }+ }++ def _inputs(self, **overrides) -> dict:+ return {+ "http_auth_user": AUTH_USER,+ "http_auth_password": AUTH_PASSWORD,+ "bypass_auth_check": False,+ "schema_mapping": SCHEMA_MAPPING,+ "source_id": SOURCE_ID,+ **overrides,+ }++ @parameterized.expand(+ [+ ("deal", "schema_deals"),+ ("person", "schema_persons"),+ ("activity", "schema_activities"),+ ]+ )+ def test_routes_each_entity_to_its_table(self, entity: str, expected_schema_id: str) -> None:+ globals = self._request(self._payload(entity=entity))++ self.run_function(self._inputs(), globals=globals)++ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(globals["request"]["body"], expected_schema_id)++ @parameterized.expand(+ [+ ("wrong_password", {"authorization": _basic(AUTH_USER, "not-the-password")}, {}, 401),+ ("wrong_user", {"authorization": _basic("someone-else", AUTH_PASSWORD)}, {}, 401),+ ("missing_header", {}, {}, 401),+ ("no_credentials_configured", {"authorization": "Basic x"}, {"http_auth_password": ""}, 400),+ ]+ )+ def test_unverified_delivery_is_rejected(+ self, _name: str, headers: dict[str, str], input_overrides: dict[str, Any], expected_status: int+ ) -> None:+ globals = self._request(self._payload(), headers=headers)++ res = self.run_function(self._inputs(**input_overrides), globals=globals)++ assert res.result["httpResponse"]["status"] == expected_status+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_delete_event_is_acknowledged_and_dropped(self) -> None:+ globals = self._request(self._payload(action="delete"))++ res = self.run_function(self._inputs(), globals=globals)++ assert res.result["httpResponse"]["status"] == 200+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_v1_payload_is_rejected(self) -> None:+ globals = self._request(self._payload(version="1.0"))++ res = self.run_function(self._inputs(), globals=globals)++ assert res.result["httpResponse"]["status"] == 400+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_entity_without_a_selected_table_is_acknowledged_and_dropped(self) -> None:+ # The subscription is a wildcard, so entities the user never selected arrive on every+ # account. A non-2xx here would put the webhook into Pipedrive's retry and ban path.+ globals = self._request(self._payload(entity="note"))++ res = self.run_function(self._inputs(), globals=globals)++ assert res.result["httpResponse"]["status"] == 200+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_non_post_request_returns_405(self) -> None:+ globals = self._request(self._payload(), method="GET")++ res = self.run_function(self._inputs(), globals=globals)++ assert res.result == {"httpResponse": {"status": 405, "body": "Method not allowed"}}+ self.mock_produce_to_warehouse_webhooks.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/webhook_template.pynew file mode 100644index 000000000000..d6b6fc50ac8b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pipedrive/webhook_template.py@@ -0,0 +1,167 @@+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC++template: HogFunctionTemplateDC = HogFunctionTemplateDC(+ status="alpha",+ free=False,+ type="warehouse_source_webhook",+ id="template-warehouse-source-pipedrive",+ name="Pipedrive warehouse source webhook",+ description="Receive Pipedrive webhook events for data warehouse ingestion",+ icon_url="/static/services/pipedrive.png",+ category=["Data warehouse"],+ code_language="hog",+ code="""\+if (request.method != 'POST') {+ return {+ 'httpResponse': {+ 'status': 405,+ 'body': 'Method not allowed'+ }+ }+}++if (not inputs.bypass_auth_check) {+ if (empty(inputs.http_auth_user) or empty(inputs.http_auth_password)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'HTTP auth credentials not configured',+ }+ }+ }++ let providedHeader := request.headers['authorization']++ if (empty(providedHeader)) {+ return {+ 'httpResponse': {+ 'status': 401,+ 'body': 'Missing authorization header',+ }+ }+ }++ // Pipedrive signs nothing; it sends back the HTTP basic credentials set on the subscription.+ let expectedHeader := concat('Basic ', base64Encode(concat(inputs.http_auth_user, ':', inputs.http_auth_password)))++ if (providedHeader != expectedHeader) {+ return {+ 'httpResponse': {+ 'status': 401,+ 'body': 'Bad authorization header',+ }+ }+ }+}++let meta := request.body.meta++if (empty(meta)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'No meta block found, skipping'+ }+ }+}++// Only v2 deliveries carry the entity under `data` in the shape the polled tables use. A v1.0+// webhook would put a differently named payload in `current`, so reject it loudly instead of+// merging mismatched rows.+if (meta.version != '2.0') {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Only Pipedrive webhooks v2 deliveries are supported',+ }+ }+}++// Deletions carry no object to merge, and the warehouse table keeps the last known version of a+// row rather than tracking removals.+if (meta.action = 'delete') {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'Delete event, skipping'+ }+ }+}++let entity := meta.entity++if (empty(entity)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'No entity found, skipping'+ }+ }+}++let schemaId := inputs.schema_mapping?.[entity]++if (empty(schemaId)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': f'No schema mapping for entity: {entity}, skipping'+ }+ }+}++produceToWarehouseWebhooks(request.body, schemaId)""",+ inputs_schema=[+ {+ "type": "string",+ "key": "http_auth_user",+ "label": "HTTP auth username",+ "required": False,+ "secret": False,+ "hidden": False,+ "description": (+ "The HTTP auth username set on the Pipedrive webhook. Pipedrive sends it back on "+ "every delivery as HTTP basic auth, which is how PostHog verifies the delivery."+ ),+ },+ {+ "type": "string",+ "key": "http_auth_password",+ "label": "HTTP auth password",+ "required": False,+ "secret": True,+ "hidden": False,+ "description": (+ "The HTTP auth password set on the Pipedrive webhook. PostHog rejects deliveries "+ "whose basic auth credentials do not match."+ ),+ },+ {+ "type": "boolean",+ "key": "bypass_auth_check",+ "label": "Bypass HTTP auth check",+ "description": "If set, the Authorization 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 Pipedrive entity names 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,+ },+ ],+)