: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 yousign import source (#72654)
Tom Owers776ebd552a83
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 04c540413563..bd0eefec3ec3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -594,6 +594,7 @@ the row lists both.| writesonic | HTTP | requests | ✅ || wufoo | HTTP | requests | ✅ || xmatters | HTTP | requests | ✅ |+| yousign | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || zapier_supported_storage | HTTP | requests | ✅ || zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ || zendesk_sell | HTTP | requests | ✅ |@@ -1003,7 +1004,6 @@ doesn't conflict with concurrent PRs.- ynab- yotpo- younium-- yousign- youtube_analytics- youtube_data- zapsigndiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/yousign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/yousign.pyindex bf56a8df2068..09f2b28eee5f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/yousign.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/yousign.py@@ -1,9 +1,12 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass YouSignSourceConfig(config.Config):- pass+ api_key: str+ environment: Literal["production", "sandbox"] = config.value(default="production")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/canonical_descriptions.pynew file mode 100644index 000000000000..93ca6756bca6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/canonical_descriptions.py@@ -0,0 +1,134 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "signature_requests": {+ "description": (+ "A signature request groups the documents to sign, the signers, and optional "+ "approvers, and tracks the signing process from draft to completion."+ ),+ "docs_url": "https://developers.yousign.com/reference/get-signature_requests-1",+ "columns": {+ "id": "Unique identifier of the signature request.",+ "status": (+ "Lifecycle status: draft, ongoing, done, deleted, expired, canceled, approval, "+ "rejected, declined, or paused."+ ),+ "name": "Name of the signature request.",+ "delivery_mode": "How signers are notified: email, or none for API-driven flows.",+ "created_at": "When the signature request was created.",+ "activated_at": "When the signature request was activated and sent to signers.",+ "completed_at": "When every signer completed their signature.",+ "approved_at": "When every approver approved the request.",+ "ordered_signers": "Whether signers must sign in a set order.",+ "timezone": "Timezone used for dates shown to recipients.",+ "expiration_date": "When the signature request expires.",+ "source": "Application that created the request (app, public_api, or a connector).",+ "signers": "Embedded signer references with their per-signer status.",+ "approvers": "Embedded approver references with their per-approver status.",+ "documents": "Embedded document references with their nature.",+ "labels": "Labels attached to the signature request.",+ "sender": "User who sent the signature request.",+ "external_id": "Caller-supplied identifier for correlating with external systems.",+ "workspace_id": "Workspace the signature request belongs to.",+ "audit_trail_locale": "Language of the generated audit trail.",+ },+ },+ "signers": {+ "description": (+ "A signer of a signature request, with their identity details, signature level, "+ "authentication mode, and signing status."+ ),+ "docs_url": "https://developers.yousign.com/reference/get-signature_requests-signaturerequestid-signers-1",+ "columns": {+ "id": "Unique identifier of the signer.",+ "signature_request_id": "Signature request this signer belongs to.",+ "info": "Signer identity: first name, last name, email, phone number, and locale.",+ "status": (+ "Signing status: initiated, declined, notified, verified, processing, "+ "consent_given, signed, aborted, or error."+ ),+ "signature_level": (+ "eIDAS signature level: electronic_signature, advanced_electronic_signature, "+ "or qualified_electronic_signature."+ ),+ "signature_authentication_mode": "How the signer is authenticated: otp_email, otp_sms, or no_otp.",+ # signature_link is intentionally not imported — it is a directly usable signing URL+ # (see yousign.SIGNER_CAPABILITY_FIELDS), so it is stripped before rows are persisted.+ "signature_link_expiration_date": "When the signer's (non-imported) signature link expires.",+ "delivery_mode": "How this signer is notified: email, or none.",+ "fields": "Fields placed on the documents for this signer.",+ "signed_at": "When the signer completed their signature.",+ "recipient_stage_index": "Notification stage; recipients sharing an index are notified together.",+ },+ },+ "documents": {+ "description": "A document attached to a signature request, either signable or a simple attachment.",+ "docs_url": "https://developers.yousign.com/reference/get-signature_requests-signaturerequestid-documents-1",+ "columns": {+ "id": "Unique identifier of the document.",+ "signature_request_id": "Signature request this document belongs to.",+ "filename": "Original file name of the document.",+ "nature": "Document nature: signable_document or attachment.",+ "content_type": "MIME type of the document, e.g. application/pdf.",+ "sha256": "SHA-256 checksum of the document content.",+ "is_signed": "Whether the document has been signed.",+ "is_protected": "Whether the document is password-protected.",+ "created_at": "When the document was uploaded.",+ "total_pages": "Number of pages of a signable document.",+ },+ },+ "contacts": {+ "description": "A contact saved in the organization's contact book, reusable as a recipient.",+ "docs_url": "https://developers.yousign.com/reference/get-contacts-1",+ "columns": {+ "id": "Unique identifier of the contact.",+ "first_name": "Contact's first name.",+ "last_name": "Contact's last name.",+ "email": "Contact's email address.",+ "phone_number": "Contact's phone number in E.164 format.",+ "locale": "Contact's preferred language.",+ "company_name": "Company the contact belongs to.",+ "job_title": "Contact's job title.",+ "workspace_id": "Workspace the contact belongs to, if workspace-scoped.",+ },+ },+ "users": {+ "description": "A member of the Yousign organization.",+ "docs_url": "https://developers.yousign.com/reference/get-users-1",+ "columns": {+ "id": "Unique identifier of the user.",+ "first_name": "User's first name.",+ "last_name": "User's last name.",+ "email": "User's email address.",+ "role": "Organization role: owner, admin, or member.",+ "status": "Account status: invited, signed_up, verified, or completed.",+ "is_active": "Whether the user account is active.",+ "created_at": "When the user was created.",+ "workspaces": "Workspaces the user belongs to.",+ },+ },+ "workspaces": {+ "description": "A workspace used to partition members, signature requests, and contacts.",+ "docs_url": "https://developers.yousign.com/reference/get-workspaces-1",+ "columns": {+ "id": "Unique identifier of the workspace.",+ "name": "Internal name of the workspace.",+ "external_name": "Name shown to recipients, when different from the internal name.",+ "default": "Whether this is the organization's default workspace.",+ "created_at": "When the workspace was created.",+ "updated_at": "When the workspace was last updated.",+ "users": "Members of the workspace.",+ },+ },+ "labels": {+ "description": "A label used to organize and filter signature requests.",+ "docs_url": "https://developers.yousign.com/reference/get-labels",+ "columns": {+ "id": "Unique identifier of the label.",+ "name": "Name of the label.",+ "created_at": "When the label was created.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/settings.pynew file mode 100644index 000000000000..91ab629056e8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/settings.py@@ -0,0 +1,174 @@+from dataclasses import dataclass, field+from typing import Any, Optional++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++PRODUCTION_BASE_URL = "https://api.yousign.app/v3"+SANDBOX_BASE_URL = "https://api-sandbox.yousign.app/v3"++# Cursor-paginated list endpoints cap `limit` at 100 (workspaces defaults to 10, so we always+# pass the cap explicitly).+DEFAULT_PAGE_SIZE = 100++# The signature requests list defaults to `source[eq]=public_api`, silently hiding requests+# created from the Yousign app or other integrations. Override with every documented source so+# the warehouse sees the whole account; a value Yousign adds later would be missed until this+# list is updated.+SIGNATURE_REQUEST_SOURCES = (+ "app,public_api,hubspot_integration,connector_salesforce_api,connector_google_api,connector_zapier_api"+)++# Server-side date filters on the signature requests list (`<field>[after]=yyyy-mm-dd`). These+# are the only timestamp filters the v3 API exposes; every other list endpoint is full refresh.+SIGNATURE_REQUEST_INCREMENTAL_FIELDS: list[IncrementalField] = [+ incremental_field("created_at"),+ incremental_field("activated_at"),+ incremental_field("completed_at"),+]+++@dataclass+class YousignEndpointConfig:+ name: str+ path: str+ # jsonpath into the response body: "data" for cursor-paginated wrappers, "$" for the bare+ # arrays the per-signature-request child endpoints return.+ data_selector: str+ primary_key: str | list[str]+ # Cursor pagination (`after` param, `meta.next_cursor` in the body). Child endpoints return+ # everything in one response.+ paginated: bool = True+ page_size: int = DEFAULT_PAGE_SIZE+ # Stable creation-time field for datetime partitioning; never an updated-style field.+ partition_key: Optional[str] = None+ params: dict[str, Any] = field(default_factory=dict)+ fanout: Optional[DependentEndpointConfig] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: Optional[str] = None+ supports_webhooks: bool = False+ description: Optional[str] = None+++YOUSIGN_ENDPOINTS: dict[str, YousignEndpointConfig] = {+ "signature_requests": YousignEndpointConfig(+ name="signature_requests",+ path="/signature_requests",+ data_selector="data",+ primary_key="id",+ partition_key="created_at",+ params={"source[in]": SIGNATURE_REQUEST_SOURCES},+ incremental_fields=SIGNATURE_REQUEST_INCREMENTAL_FIELDS,+ default_incremental_field="created_at",+ supports_webhooks=True,+ description=(+ "One row per signature request, with embedded signer, approver, and document ids and their statuses."+ ),+ ),+ "signers": YousignEndpointConfig(+ name="signers",+ path="/signature_requests/{signatureRequestId}/signers",+ data_selector="$",+ # Signer ids are UUIDs, but the docs don't state global uniqueness — the parent id keeps+ # the key unique across the aggregated table.+ primary_key=["signature_request_id", "id"],+ paginated=False,+ fanout=DependentEndpointConfig(+ parent_name="signature_requests",+ resolve_param="signatureRequestId",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "signature_request_id"},+ parent_params={"source[in]": SIGNATURE_REQUEST_SOURCES},+ ),+ description="Signer details for every signature request, one row per signer.",+ ),+ "documents": YousignEndpointConfig(+ name="documents",+ path="/signature_requests/{signatureRequestId}/documents",+ data_selector="$",+ primary_key=["signature_request_id", "id"],+ paginated=False,+ partition_key="created_at",+ fanout=DependentEndpointConfig(+ parent_name="signature_requests",+ resolve_param="signatureRequestId",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "signature_request_id"},+ parent_params={"source[in]": SIGNATURE_REQUEST_SOURCES},+ ),+ description="Document metadata for every signature request, one row per document.",+ ),+ "contacts": YousignEndpointConfig(+ name="contacts",+ path="/contacts",+ data_selector="data",+ primary_key="id",+ description="Contacts saved in the organization's contact book.",+ ),+ "users": YousignEndpointConfig(+ name="users",+ path="/users",+ data_selector="data",+ primary_key="id",+ partition_key="created_at",+ description="Members of the Yousign organization.",+ ),+ "workspaces": YousignEndpointConfig(+ name="workspaces",+ path="/workspaces",+ data_selector="data",+ primary_key="id",+ partition_key="created_at",+ description="Workspaces in the Yousign organization.",+ ),+ "labels": YousignEndpointConfig(+ name="labels",+ path="/labels",+ data_selector="data",+ primary_key="id",+ partition_key="created_at",+ description="Labels used to organize signature requests.",+ ),+}++ENDPOINTS = tuple(YOUSIGN_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in YOUSIGN_ENDPOINTS.items()+}++ENDPOINT_DESCRIPTIONS: dict[str, str] = {+ name: config.description for name, config in YOUSIGN_ENDPOINTS.items() if config.description+}++# Maps our schema name to the object type prefix of Yousign webhook event names+# (`signature_request.done` -> `signature_request`), used to route incoming webhooks to tables.+RESOURCE_TO_WEBHOOK_OBJECT_TYPE: dict[str, str] = {+ "signature_requests": "signature_request",+}++# Lifecycle events that change a signature request's state. Reminder events are excluded — they+# carry the same object without a state change and would only add delivery volume.+WEBHOOK_EVENTS: list[str] = [+ "signature_request.activated",+ "signature_request.approved",+ "signature_request.canceled",+ "signature_request.declined",+ "signature_request.deleted",+ "signature_request.done",+ "signature_request.expired",+ "signature_request.permanently_deleted",+ "signature_request.reactivated",+ "signature_request.rejected",+ "signature_request.paused",+ "signature_request.resumed",+]+++def all_webhook_events() -> list[str]:+ return list(WEBHOOK_EVENTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/source.pyindex 6bbfe9531902..f8496542948c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/source.py@@ -1,21 +1,81 @@-from typing import cast+from typing import TYPE_CHECKING, Optional, cast++import structlog++if TYPE_CHECKING:+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDCfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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.yousign import (YouSignSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.yousign.settings import (+ ENDPOINT_DESCRIPTIONS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ RESOURCE_TO_WEBHOOK_OBJECT_TYPE,+ YOUSIGN_ENDPOINTS,+ all_webhook_events,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign import (+ YousignResumeConfig,+ create_webhook as create_yousign_webhook,+ delete_webhook as delete_yousign_webhook,+ get_external_webhook_info as get_yousign_webhook_info,+ update_webhook_events as update_yousign_webhook_events,+ validate_credentials as validate_yousign_credentials,+ yousign_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+# Webhook management calls run in the API request path where no job logger exists.+logger = structlog.get_logger(__name__)+@SourceRegistry.register-class YouSignSource(SimpleSource[YouSignSourceConfig]):+class YouSignSource(+ ResumableSource[YouSignSourceConfig, YousignResumeConfig],+ WebhookSource[YouSignSourceConfig],+):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs++ supported_versions = ("v3",)+ default_version = "v3"+ api_docs_url = "https://developers.yousign.com/changelog"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.YOUSIGN@@ -25,8 +85,169 @@ class YouSignSource(SimpleSource[YouSignSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.YOU_SIGN,category=DataWarehouseSourceCategory.SALES,- label="YouSign",+ label="Yousign",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Sync signature requests, signers, documents, contacts, and more from Yousign into the PostHog Data warehouse.++Create an API key in the Yousign app under **Integrations → API keys**. Keys are environment-scoped, so pick the environment that matches your key — a sandbox key cannot access production data. A read-only, organization-scoped key is enough for syncing; managing webhooks automatically additionally requires a full-access key.""",iconPath="/static/services/yousign.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/yousign",+ keywords=["esignature", "e-signature", "electronic signature", "youtrust"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="environment",+ label="Environment",+ required=True,+ defaultValue="production",+ options=[+ SourceFieldSelectConfigOption(label="Production", value="production"),+ SourceFieldSelectConfigOption(label="Sandbox", value="sandbox"),+ ],+ ),+ ],+ ),+ webhookSetupCaption="""To set up the webhook manually:++1. In the Yousign app, go to **Integrations → Webhooks** and create a subscription+2. Paste the webhook URL shown below as the endpoint+3. Subscribe to the signature request lifecycle events (`signature_request.activated`, `signature_request.done`, `signature_request.expired`, and the other `signature_request.*` events)+4. Copy the subscription's **secret key** and paste it into the signing secret field below++If automatic creation failed, note that webhook management requires a full-access API key, and sandbox-scoped keys can only manage sandbox subscriptions.""",+ webhookFields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="signing_secret",+ label="Signing secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.yousign.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ @property+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:+ from products.warehouse_sources.backend.temporal.data_imports.sources.yousign.webhook_template import ( # noqa: PLC0415+ template,+ )++ return template++ @property+ def webhook_resource_map(self) -> dict[str, str]:+ return RESOURCE_TO_WEBHOOK_OBJECT_TYPE++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": (+ "Yousign rejected your API key. Check the key is correct, has not been revoked, and "+ "matches the selected environment (sandbox keys cannot access production), then reconnect."+ ),+ "403 Client Error": (+ "Your Yousign API key does not have permission to read this data. Check the key's "+ "scope and permissions in Yousign, then reconnect."+ ),+ }++ def get_schemas(+ self,+ config: YouSignSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Rows arrive newest-first with no sort control, so signature_requests is merge-only —+ # append mode needs a verified ordering guarantee the API doesn't give.+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ merge_only=("signature_requests",),+ supports_webhooks=("signature_requests",),+ descriptions=ENDPOINT_DESCRIPTIONS,+ )++ def validate_credentials(+ self, config: YouSignSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_yousign_credentials(config.api_key, config.environment, schema_name)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[YousignResumeConfig]:+ return ResumableSourceManager[YousignResumeConfig](inputs, YousignResumeConfig)++ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:+ return WebhookSourceManager(inputs, inputs.logger)++ def create_webhook(self, config: YouSignSourceConfig, webhook_url: str, team_id: int) -> WebhookCreationResult:+ return create_yousign_webhook(config.api_key, config.environment, webhook_url, logger)++ def get_desired_webhook_events(+ self, config: YouSignSourceConfig, eligible_schema_names: list[str]+ ) -> list[str] | None:+ # Every mappable event, not just the selected tables — auto-heals webhooks created before+ # WEBHOOK_EVENTS gained new entries.+ return all_webhook_events()++ def sync_webhook_events(+ self,+ config: YouSignSourceConfig,+ 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 update_yousign_webhook_events(config.api_key, config.environment, webhook_url, desired_events, logger)++ def get_external_webhook_info(+ self, config: YouSignSourceConfig, webhook_url: str, team_id: int+ ) -> ExternalWebhookInfo:+ return get_yousign_webhook_info(config.api_key, config.environment, webhook_url)++ def delete_webhook(self, config: YouSignSourceConfig, webhook_url: str, team_id: int) -> WebhookDeletionResult:+ return delete_yousign_webhook(config.api_key, config.environment, webhook_url, logger)++ def source_for_pipeline(+ self,+ config: YouSignSourceConfig,+ resumable_source_manager: ResumableSourceManager[YousignResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in YOUSIGN_ENDPOINTS:+ raise ValueError(f"Unknown Yousign schema '{inputs.schema_name}'")++ return yousign_source(+ api_key=config.api_key,+ environment=config.environment,+ 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,+ incremental_field=inputs.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/yousign/tests/test_yousign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/tests/test_yousign.pynew file mode 100644index 000000000000..174f3231cda0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/tests/test_yousign.py@@ -0,0 +1,449 @@+from collections.abc import Iterable+from datetime import UTC, date, datetime+from typing import Any, cast++import pytest+from unittest import mock++import orjson+from requests import Request++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.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.yousign.settings import (+ SIGNATURE_REQUEST_SOURCES,+ WEBHOOK_EVENTS,+ YOUSIGN_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign import (+ YousignResumeConfig,+ _cursor_paginator,+ _date_filter_value,+ create_webhook,+ delete_webhook,+ get_resource,+ make_webhook_table_transformer,+ update_webhook_events,+ validate_credentials,+ yousign_source,+)++TEAM_ID = 1+JOB_ID = "job-1"+++def _make_manager(resume_state: YousignResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _resp(payload: Any, status: int = 200) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.status_code = status+ resp.ok = status < 400+ resp.json.return_value = payload+ resp.content = b"x"+ return resp+++class TestDateFilterValue:+ @pytest.mark.parametrize(+ "value, expected",+ [+ # Backs off one day so the date-granular filter can't drop rows from the watermark day.+ (datetime(2025, 3, 2, 15, 30, tzinfo=UTC), "2025-03-01"),+ (date(2025, 3, 2), "2025-03-01"),+ ("2025-03-02T15:30:00Z", "2025-03-01"),+ (1740924000, "2025-03-01"), # 2025-03-02 UTC as epoch seconds+ (None, None),+ ("not-a-date", None),+ ],+ )+ def test_formats_watermark_as_previous_day(self, value: Any, expected: str | None) -> None:+ assert _date_filter_value(value) == expected+++def _endpoint_params(resource: Any) -> dict[str, Any]:+ return cast(dict[str, Any], resource["endpoint"]["params"])+++class TestGetResource:+ def test_signature_requests_override_the_source_filter(self) -> None:+ # Without the override Yousign only returns API-created requests (source[eq]=public_api),+ # silently dropping everything created from the app.+ resource = get_resource(YOUSIGN_ENDPOINTS["signature_requests"], False, None)+ params = _endpoint_params(resource)+ assert params["source[in]"] == SIGNATURE_REQUEST_SOURCES+ assert params["limit"] == 100+ assert resource["write_disposition"] == "replace"+ assert not any("[after]" in key for key in params)++ @pytest.mark.parametrize("field", ["created_at", "activated_at", "completed_at"])+ def test_incremental_adds_server_side_date_filter(self, field: str) -> None:+ resource = get_resource(YOUSIGN_ENDPOINTS["signature_requests"], True, field)+ incremental_param = _endpoint_params(resource)[f"{field}[after]"]+ assert incremental_param["type"] == "incremental"+ assert incremental_param["cursor_path"] == field+ assert incremental_param["convert"] is _date_filter_value+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}++ def test_incremental_defaults_to_created_at(self) -> None:+ resource = get_resource(YOUSIGN_ENDPOINTS["signature_requests"], True, None)+ assert "created_at[after]" in _endpoint_params(resource)++ @pytest.mark.parametrize("endpoint, field", [("signature_requests", "updated_at"), ("contacts", "created_at")])+ def test_incremental_rejects_unsupported_fields(self, endpoint: str, field: str) -> None:+ with pytest.raises(ValueError, match="does not support incremental field"):+ get_resource(YOUSIGN_ENDPOINTS[endpoint], True, field)+++class TestCursorPaginator:+ def test_follows_meta_next_cursor_until_null(self) -> None:+ paginator = _cursor_paginator()++ paginator.update_state(_resp({"data": [{"id": "a"}], "meta": {"next_cursor": "tok1"}}))+ assert paginator.has_next_page+ request = Request(method="GET", url="https://api.yousign.app/v3/signature_requests", params={})+ paginator.update_request(request)+ assert request.params["after"] == "tok1"++ paginator.update_state(_resp({"data": [{"id": "b"}], "meta": {"next_cursor": None}}))+ assert not paginator.has_next_page++ def test_resume_state_roundtrip(self) -> None:+ paginator = _cursor_paginator()+ paginator.update_state(_resp({"data": [], "meta": {"next_cursor": "tok2"}}))+ state = paginator.get_resume_state()+ assert state == {"cursor": "tok2"}++ resumed = _cursor_paginator()+ resumed.set_resume_state(state)+ request = Request(method="GET", url="https://api.yousign.app/v3/contacts", params={})+ resumed.init_request(request)+ assert request.params["after"] == "tok2"+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status, schema_name, expected_valid",+ [+ (200, None, True),+ (401, None, False),+ # A workspace-scoped key may legitimately lack some permissions — don't block+ # source-create on a 403, but do fail the per-schema probe.+ (403, None, True),+ (403, "users", False),+ (500, None, False),+ ],+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign.make_tracked_session")+ def test_status_mapping(+ self, mock_session: mock.MagicMock, status: int, schema_name: str | None, expected_valid: bool+ ) -> None:+ mock_session.return_value.get.return_value = _resp({}, status=status)+ valid, _ = validate_credentials("key", "production", schema_name)+ assert valid is expected_valid++ @pytest.mark.parametrize(+ "environment, expected_host",+ [("production", "https://api.yousign.app/v3"), ("sandbox", "https://api-sandbox.yousign.app/v3")],+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign.make_tracked_session")+ def test_probes_the_environment_host(+ self, mock_session: mock.MagicMock, environment: str, expected_host: str+ ) -> None:+ mock_session.return_value.get.return_value = _resp({}, status=200)+ validate_credentials("key", environment)+ assert mock_session.return_value.get.call_args.args[0] == f"{expected_host}/users"+++class TestYousignSourceResponse:+ @pytest.mark.parametrize("endpoint", list(YOUSIGN_ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint: str) -> None:+ response = yousign_source(+ api_key="key",+ environment="production",+ endpoint=endpoint,+ team_id=TEAM_ID,+ job_id=JOB_ID,+ resumable_source_manager=_make_manager(),+ )+ config = YOUSIGN_ENDPOINTS[endpoint]+ expected_keys = config.primary_key if isinstance(config.primary_key, list) else [config.primary_key]+ assert response.name == endpoint+ assert response.primary_keys == expected_keys+ # Yousign has no sort param and pages arrive newest-first; declaring "asc" would corrupt+ # the incremental watermark after the first batch.+ assert response.sort_mode == "desc"+ if config.partition_key:+ assert response.partition_keys == [config.partition_key]+ assert response.partition_mode == "datetime"++ @pytest.mark.parametrize("endpoint", ["signers", "documents"])+ def test_fanout_children_key_on_parent_id(self, endpoint: str) -> None:+ # Fan-out children aggregate rows across every signature request; without the parent id+ # in the key, duplicate ids would multi-match on every merge.+ response = yousign_source(+ api_key="key",+ environment="production",+ endpoint=endpoint,+ team_id=TEAM_ID,+ job_id=JOB_ID,+ resumable_source_manager=_make_manager(),+ )+ assert response.primary_keys == ["signature_request_id", "id"]++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign.rest_api_resource")+ def test_resumes_from_saved_cursor(self, mock_rest_api_resource: mock.MagicMock) -> None:+ manager = _make_manager(YousignResumeConfig(cursor="tok"))+ yousign_source(+ api_key="key",+ environment="production",+ endpoint="signature_requests",+ team_id=TEAM_ID,+ job_id=JOB_ID,+ resumable_source_manager=manager,+ )+ kwargs = mock_rest_api_resource.call_args.kwargs+ assert kwargs["initial_paginator_state"] == {"cursor": "tok"}++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign.rest_api_resource")+ def test_checkpoint_saves_only_when_a_next_page_exists(self, mock_rest_api_resource: mock.MagicMock) -> None:+ manager = _make_manager()+ yousign_source(+ api_key="key",+ environment="production",+ endpoint="signature_requests",+ team_id=TEAM_ID,+ job_id=JOB_ID,+ resumable_source_manager=manager,+ )+ save_checkpoint = mock_rest_api_resource.call_args.kwargs["resume_hook"]++ save_checkpoint({"cursor": "tok3"})+ manager.save_state.assert_called_once_with(YousignResumeConfig(cursor="tok3"))++ manager.save_state.reset_mock()+ save_checkpoint(None)+ save_checkpoint({"cursor": None})+ manager.save_state.assert_not_called()++ # Patch out the real async_to_sync: running its event loop closes the thread-local Django+ # connection, which poisons DB-backed tests (e.g. migration tests) later in the same worker.+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign.async_to_sync",+ lambda fn: fn,+ )+ def test_webhook_enabled_schema_reads_from_webhook_manager(self) -> None:+ webhook_manager = mock.MagicMock()+ webhook_manager.webhook_enabled = mock.MagicMock(return_value=True)+ webhook_manager.get_items.return_value = iter([])++ response = yousign_source(+ api_key="key",+ environment="production",+ endpoint="signature_requests",+ team_id=TEAM_ID,+ job_id=JOB_ID,+ resumable_source_manager=_make_manager(),+ webhook_source_manager=webhook_manager,+ )+ list(cast(Iterable[Any], response.items()))++ webhook_manager.get_items.assert_called_once()++ def test_webhook_manager_not_consulted_for_non_webhook_schema(self) -> None:+ webhook_manager = mock.MagicMock()+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=True)++ yousign_source(+ api_key="key",+ environment="production",+ endpoint="contacts",+ team_id=TEAM_ID,+ job_id=JOB_ID,+ resumable_source_manager=_make_manager(),+ webhook_source_manager=webhook_manager,+ )++ webhook_manager.webhook_enabled.assert_not_called()+++class TestWebhookTableTransformer:+ def _envelope(self, request_id: str, status: str, event_time: str) -> dict[str, Any]:+ return {+ "event_id": f"evt-{request_id}-{event_time}",+ "event_name": "signature_request.activated",+ "event_time": event_time,+ "sandbox": False,+ "data": {"signature_request": {"id": request_id, "status": status, "name": "Contract"}},+ }++ def test_reshapes_envelopes_and_keeps_latest_event_per_id(self) -> None:+ table = table_from_py_list(+ [+ self._envelope("sr-1", "ongoing", "100"),+ self._envelope("sr-1", "done", "200"),+ self._envelope("sr-2", "ongoing", "150"),+ ]+ )+ rows = make_webhook_table_transformer()(table).to_pylist()+ by_id = {row["id"]: row for row in rows}+ assert set(by_id) == {"sr-1", "sr-2"}+ assert by_id["sr-1"]["status"] == "done"+ # Envelope keys must not leak into the table — the rows merge with pulled API rows.+ assert "event_name" not in by_id["sr-1"]++ def test_strips_signer_signature_link_from_webhook_rows(self) -> None:+ # `signature_link` is a `no_otp`-usable signing URL — it must never reach the warehouse.+ envelope = {+ "event_name": "signature_request.activated",+ "event_time": "100",+ "data": {+ "signature_request": {+ "id": "sr-1",+ "status": "ongoing",+ "signers": [{"id": "s-1", "signature_link": "https://yousign.app/sign/abc"}],+ }+ },+ }+ rows = make_webhook_table_transformer()(table_from_py_list([envelope])).to_pylist()+ # Nested fields round-trip through parquet as JSON strings.+ signers = orjson.loads(rows[0]["signers"]) if isinstance(rows[0]["signers"], str) else rows[0]["signers"]+ assert signers[0].get("signature_link") is None+ assert signers[0]["id"] == "s-1"++ def test_parses_json_string_data_and_drops_malformed_rows(self) -> None:+ table = table_from_py_list(+ [+ {+ "event_name": "signature_request.done",+ "event_time": "100",+ "data": '{"signature_request": {"id": "sr-3", "status": "done"}}',+ },+ {"event_name": "signature_request.done", "event_time": "101", "data": None},+ {"event_name": "signature_request.done", "event_time": "102", "data": '{"signature_request": {}}'},+ ]+ )+ rows = make_webhook_table_transformer()(table).to_pylist()+ assert [row["id"] for row in rows] == ["sr-3"]+++def _static_resource(rows: list[dict[str, Any]]) -> Resource:+ return Resource(lambda: iter([rows]), name="r", hints={})+++def _flatten(response: Any) -> list[dict[str, Any]]:+ return [row for page in cast(Iterable[Any], response.items()) for row in page]+++class TestSignerCapabilityStripping:+ """`signature_link` (and other capability fields) must never reach the warehouse on any path."""++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign.build_dependent_resource"+ )+ def test_signers_fanout_strips_signature_link(self, mock_build: mock.MagicMock) -> None:+ mock_build.return_value = _static_resource(+ [{"signature_request_id": "sr-1", "id": "s-1", "status": "signed", "signature_link": "https://sign/abc"}]+ )+ response = yousign_source(+ api_key="key",+ environment="production",+ endpoint="signers",+ team_id=TEAM_ID,+ job_id=JOB_ID,+ resumable_source_manager=_make_manager(),+ )+ rows = _flatten(response)+ assert rows[0].get("signature_link") is None+ assert rows[0]["id"] == "s-1"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign.rest_api_resource")+ def test_signature_requests_strips_embedded_signer_links(self, mock_rest: mock.MagicMock) -> None:+ mock_rest.return_value = _static_resource(+ [{"id": "sr-1", "signers": [{"id": "s-1", "signature_link": "https://sign/abc"}]}]+ )+ response = yousign_source(+ api_key="key",+ environment="production",+ endpoint="signature_requests",+ team_id=TEAM_ID,+ job_id=JOB_ID,+ resumable_source_manager=_make_manager(),+ )+ rows = _flatten(response)+ assert rows[0]["signers"][0].get("signature_link") is None+ assert rows[0]["signers"][0]["id"] == "s-1"+++class TestWebhookManagement:+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign.make_tracked_session")+ def test_create_webhook_returns_signing_secret_as_extra_input(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.post.return_value = _resp({"id": "wh-1", "secret_key": "s" * 32}, status=201)+ result = create_webhook("key", "sandbox", "https://ph/webhook", mock.MagicMock())++ assert result.success is True+ assert result.extra_inputs == {"signing_secret": "s" * 32}+ body = mock_session.return_value.post.call_args.kwargs["json"]+ assert body["endpoint"] == "https://ph/webhook"+ assert body["sandbox"] is True+ assert body["subscribed_events"] == WEBHOOK_EVENTS++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign.make_tracked_session")+ def test_create_webhook_without_secret_marks_signing_secret_pending(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.post.return_value = _resp({"id": "wh-1"}, status=201)+ result = create_webhook("key", "production", "https://ph/webhook", mock.MagicMock())++ assert result.success is True+ assert result.pending_inputs == ["signing_secret"]++ @pytest.mark.parametrize("status", [401, 403])+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign.make_tracked_session")+ def test_create_webhook_permission_error_is_actionable(self, mock_session: mock.MagicMock, status: int) -> None:+ mock_session.return_value.post.return_value = _resp({}, status=status)+ result = create_webhook("key", "production", "https://ph/webhook", mock.MagicMock())++ assert result.success is False+ assert result.error is not None and "full-access" in result.error++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign.make_tracked_session")+ def test_delete_webhook_is_a_noop_success_when_absent(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _resp([{"id": "wh-1", "endpoint": "https://other/webhook"}])+ result = delete_webhook("key", "production", "https://ph/webhook", mock.MagicMock())++ assert result.success is True+ mock_session.return_value.delete.assert_not_called()++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign.make_tracked_session")+ def test_delete_webhook_deletes_the_matching_subscription(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _resp([{"id": "wh-1", "endpoint": "https://ph/webhook"}])+ mock_session.return_value.delete.return_value = _resp({}, status=204)+ result = delete_webhook("key", "production", "https://ph/webhook", mock.MagicMock())++ assert result.success is True+ assert mock_session.return_value.delete.call_args.args[0].endswith("/webhooks/wh-1")++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign.make_tracked_session")+ def test_update_webhook_events_skips_patch_when_already_in_sync(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _resp(+ [{"id": "wh-1", "endpoint": "https://ph/webhook", "subscribed_events": sorted(WEBHOOK_EVENTS)}]+ )+ result = update_webhook_events("key", "production", "https://ph/webhook", WEBHOOK_EVENTS, mock.MagicMock())++ assert result.success is True+ mock_session.return_value.patch.assert_not_called()++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign.make_tracked_session")+ def test_update_webhook_events_patches_drifted_subscription(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _resp(+ [{"id": "wh-1", "endpoint": "https://ph/webhook", "subscribed_events": ["signature_request.done"]}]+ )+ mock_session.return_value.patch.return_value = _resp({}, status=200)+ result = update_webhook_events("key", "production", "https://ph/webhook", WEBHOOK_EVENTS, mock.MagicMock())++ assert result.success is True+ patch_kwargs = mock_session.return_value.patch.call_args.kwargs+ assert patch_kwargs["json"] == {"subscribed_events": WEBHOOK_EVENTS}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/tests/test_yousign_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/tests/test_yousign_source.pynew file mode 100644index 000000000000..eea37eeb76a8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/tests/test_yousign_source.py@@ -0,0 +1,183 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.yousign import (+ YouSignSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.yousign.settings import ENDPOINTS, WEBHOOK_EVENTS+from products.warehouse_sources.backend.temporal.data_imports.sources.yousign.source import YouSignSource+from products.warehouse_sources.backend.temporal.data_imports.sources.yousign.yousign import YousignResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestYousignSource:+ def setup_method(self) -> None:+ self.source = YouSignSource()+ self.team_id = 123+ self.config = YouSignSourceConfig(api_key="key", environment="production")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.YOUSIGN++ def test_source_is_released_not_hidden(self) -> None:+ # A finished source must be visible: `unreleasedSource` hides it from every user.+ config = self.source.get_source_config+ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "YouSign"+ assert config.label == "Yousign"+ assert config.category == DataWarehouseSourceCategory.SALES+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/yousign"+ assert config.iconPath == "/static/services/yousign.png"++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_environment_options_match_yousign_hosts(self) -> None:+ config = self.source.get_source_config+ environment = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig))+ assert environment.name == "environment"+ assert {o.value for o in environment.options} == {"production", "sandbox"}+ assert environment.defaultValue == "production"++ def test_get_schemas_incremental_flags(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert set(schemas) == set(ENDPOINTS)++ # Only the signature requests list has server-side timestamp filters; rows arrive+ # newest-first, so it must be merge-only (never append).+ signature_requests = schemas.pop("signature_requests")+ assert signature_requests.supports_incremental is True+ assert signature_requests.supports_append is False+ assert signature_requests.supports_webhooks is True+ assert {f["field"] for f in signature_requests.incremental_fields} == {+ "created_at",+ "activated_at",+ "completed_at",+ }++ for schema in schemas.values():+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.supports_webhooks is False++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["contacts"])+ assert [s.name for s in schemas] == ["contacts"]++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O — powers the public docs table list.+ assert self.source.lists_tables_without_credentials is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.yousign.app/v3/signature_requests",+ "403 Client Error: Forbidden for url: https://api-sandbox.yousign.app/v3/users",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ def test_non_retryable_errors_ignore_transient(self) -> None:+ transient = "500 Server Error for url: https://api.yousign.app/v3/signature_requests"+ assert not any(key in transient for key in self.source.get_non_retryable_errors())++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.yousign.source.validate_yousign_credentials"+ )+ def test_validate_credentials_plumbs_config(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ assert self.source.validate_credentials(self.config, self.team_id, schema_name="users") == (True, None)+ mock_validate.assert_called_once_with("key", "production", "users")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is YousignResumeConfig++ def test_webhook_resource_map_matches_event_name_prefixes(self) -> None:+ # The hog template routes on the event name prefix (`signature_request.done` ->+ # `signature_request`), so the map values must be that prefix.+ assert self.source.webhook_resource_map == {"signature_requests": "signature_request"}+ assert all(event.split(".")[0] == "signature_request" for event in WEBHOOK_EVENTS)++ def test_webhook_template_shape(self) -> None:+ template = self.source.webhook_template+ assert template is not None+ assert template.type == "warehouse_source_webhook"+ assert template.id == "template-warehouse-source-yousign"+ input_keys = {schema_input["key"] for schema_input in template.inputs_schema or []}+ assert {"signing_secret", "schema_mapping", "source_id"} <= input_keys++ def test_desired_webhook_events_cover_all_mapped_events(self) -> None:+ assert self.source.get_desired_webhook_events(self.config, ["signature_requests"]) == WEBHOOK_EVENTS++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.yousign.source.create_yousign_webhook"+ )+ def test_create_webhook_plumbs_config(self, mock_create: mock.MagicMock) -> None:+ self.source.create_webhook(self.config, "https://ph/webhook", self.team_id)+ args = mock_create.call_args.args+ assert args[:3] == ("key", "production", "https://ph/webhook")++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yousign.source.yousign_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_yousign_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "signature_requests"+ inputs.team_id = self.team_id+ inputs.should_use_incremental_field = True+ inputs.incremental_field = "completed_at"+ inputs.db_incremental_field_last_value = "2025-03-02"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_yousign_source.call_args.kwargs+ assert kwargs["api_key"] == "key"+ assert kwargs["environment"] == "production"+ assert kwargs["endpoint"] == "signature_requests"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["webhook_source_manager"] is not None+ assert kwargs["incremental_field"] == "completed_at"+ assert kwargs["db_incremental_field_last_value"] == "2025-03-02"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yousign.source.yousign_source")+ def test_source_for_pipeline_drops_watermark_for_full_refresh(self, mock_yousign_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "signature_requests"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2025-03-02"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_yousign_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not-a-schema"+ with pytest.raises(ValueError, match="Unknown Yousign schema"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ def test_canonical_descriptions_cover_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions) == set(ENDPOINTS)+ for entry in descriptions.values():+ assert entry["description"]+ assert entry["docs_url"].startswith("https://")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/webhook_template.pynew file mode 100644index 000000000000..2c7ab70c738e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/webhook_template.py@@ -0,0 +1,125 @@+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC++# Yousign signs deliveries with X-Yousign-Signature-256: sha256=<hex hmac-sha256 of the raw+# request body>, keyed with the subscription's secret_key (returned on webhook creation and+# visible on the subscription in the Yousign app).+template: HogFunctionTemplateDC = HogFunctionTemplateDC(+ status="alpha",+ free=False,+ type="warehouse_source_webhook",+ id="template-warehouse-source-yousign",+ name="Yousign warehouse source webhook",+ description="Receive Yousign webhook events for data warehouse ingestion",+ icon_url="/static/services/yousign.png",+ category=["Data warehouse"],+ code_language="hog",+ code="""\+if (request.method != 'POST') {+ return {+ 'httpResponse': {+ 'status': 405,+ 'body': 'Method not allowed'+ }+ }+}++if (empty(inputs.signing_secret)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Signing secret not configured',+ }+ }+}++let body := request.stringBody+let signatureHeader := request.headers['x-yousign-signature-256']++if (empty(signatureHeader)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Missing signature',+ }+ }+}++if (not (signatureHeader like 'sha256=%')) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Could not parse signature',+ }+ }+}++let sigParts := splitByString('sha256=', signatureHeader, 2)+let providedSignature := sigParts[2]++let computedSignature := sha256HmacChainHex([inputs.signing_secret, body])++if (computedSignature != providedSignature) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Bad signature',+ }+ }+}++let eventName := request.body.event_name++if (empty(eventName)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'No event found, skipping'+ }+ }+}++// The event name prefix is the object type: signature_request.done -> signature_request.+let objectType := splitByString('.', eventName)[1]++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 Yousign",+ },+ {+ "type": "json",+ "key": "schema_mapping",+ "label": "Schema mapping",+ "description": "Maps Yousign 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,+ },+ ],+)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/yousign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/yousign.pynew file mode 100644index 000000000000..705a4a0e1e9c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yousign/yousign.py@@ -0,0 +1,471 @@+import dataclasses+from collections.abc import AsyncIterable, Callable, Iterable+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional, cast++import orjson+import pyarrow as pa+import requests+from asgiref.sync import async_to_sync+from dateutil import parser as dateutil_parser+from structlog.types import FilteringBoundLogger++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.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ 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.yousign.settings import (+ PRODUCTION_BASE_URL,+ SANDBOX_BASE_URL,+ YOUSIGN_ENDPOINTS,+ YousignEndpointConfig,+ all_webhook_events,+)++REQUEST_TIMEOUT_SECONDS = 30++SANDBOX_ENVIRONMENT = "sandbox"++WEBHOOK_PERMISSION_ERROR = (+ "Your Yousign API key isn't allowed to manage webhook subscriptions. Use an API key with "+ "full-access permissions, or create the webhook manually."+)+++class YousignResumeConfig:+ # `after` cursor of the next page to fetch on the endpoint being synced.+ cursor: str+++def base_url_for_environment(environment: str | None) -> str:+ return SANDBOX_BASE_URL if environment == SANDBOX_ENVIRONMENT else PRODUCTION_BASE_URL+++def _client_config(api_key: str, environment: str | None) -> ClientConfig:+ return {+ "base_url": base_url_for_environment(environment),+ "auth": {"type": "bearer", "token": api_key},+ "headers": {"Accept": "application/json"},+ }+++def _cursor_paginator() -> JSONResponseCursorPaginator:+ # Yousign paginates with an `after` query param; the body carries `meta.next_cursor`+ # (null on the last page).+ return JSONResponseCursorPaginator(cursor_path="meta.next_cursor", cursor_param="after")+++def _date_filter_value(value: Any) -> str | None:+ """Format an incremental watermark for Yousign's `<field>[after]=yyyy-mm-dd` filters.++ The filters are date-granular and it's undocumented whether `after` is inclusive, so back+ off one day from the watermark — the overlap re-syncs at most one extra day and merge+ dedupes on the primary key.+ """+ if value is None:+ return None+ if isinstance(value, datetime):+ as_date = value.date()+ elif isinstance(value, date):+ as_date = value+ elif isinstance(value, int | float):+ as_date = datetime.fromtimestamp(value, tz=UTC).date()+ else:+ try:+ as_date = dateutil_parser.parse(str(value)).date()+ except (ValueError, OverflowError):+ return None+ return (as_date - timedelta(days=1)).isoformat()+++# Signer fields that let the holder act as the signer. `signature_link` is the URL a signer+# follows to sign, and Yousign's `no_otp` authentication mode makes it directly usable without+# any second factor — so anyone granted access to the warehouse table (a broader set than the+# Yousign account) could open it and sign. Strip these before any row reaches the warehouse.+SIGNER_CAPABILITY_FIELDS = ("signature_link",)+++def _scrub_signer_capabilities(signer: dict[str, Any]) -> dict[str, Any]:+ for field_name in SIGNER_CAPABILITY_FIELDS:+ signer.pop(field_name, None)+ return signer+++def _scrub_signature_request_row(row: dict[str, Any]) -> dict[str, Any]:+ # Signature request rows embed a `signers` array whose entries carry the same signing links.+ signers = row.get("signers")+ if isinstance(signers, list):+ for signer in signers:+ if isinstance(signer, dict):+ _scrub_signer_capabilities(signer)+ return row+++def _row_transform_for(config: YousignEndpointConfig) -> Callable[[dict[str, Any]], dict[str, Any]] | None:+ if config.name == "signers":+ return _scrub_signer_capabilities+ if config.name == "signature_requests":+ return _scrub_signature_request_row+ return None+++def get_resource(+ config: YousignEndpointConfig,+ should_use_incremental_field: bool,+ incremental_field: str | None,+) -> EndpointResource:+ params: dict[str, Any] = {"limit": config.page_size, **config.params}++ if should_use_incremental_field:+ allowed_fields = {f["field"] for f in config.incremental_fields}+ field = incremental_field or config.default_incremental_field+ if field not in allowed_fields:+ raise ValueError(f"Yousign endpoint '{config.name}' does not support incremental field '{field}'")+ params[f"{field}[after]"] = {+ "type": "incremental",+ "cursor_path": field,+ "initial_value": None,+ "convert": _date_filter_value,+ }++ endpoint: Endpoint = {+ "path": config.path,+ "params": params,+ "data_selector": config.data_selector,+ "paginator": _cursor_paginator() if config.paginated else SinglePagePaginator(),+ }++ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}+ if should_use_incremental_field+ else "replace",+ "endpoint": endpoint,+ "table_format": "delta",+ }+++def _make_source_response(+ config: YousignEndpointConfig, items_fn: Callable[[], Iterable[Any] | AsyncIterable[Any]]+) -> SourceResponse:+ return SourceResponse(+ name=config.name,+ items=items_fn,+ primary_keys=config.primary_key if isinstance(config.primary_key, list) else [config.primary_key],+ # Yousign exposes no sort param and pages arrive newest-first (observed, undocumented),+ # so never declare "asc" — the pipeline would checkpoint the incremental watermark at+ # ≈now after the first batch.+ 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,+ )+++def yousign_source(+ api_key: str,+ environment: str | None,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[YousignResumeConfig],+ webhook_source_manager: Optional[WebhookSourceManager] = None,+ should_use_incremental_field: bool = False,+ incremental_field: str | None = None,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = YOUSIGN_ENDPOINTS[endpoint]+ client_config = _client_config(api_key, environment)+ row_transform = _row_transform_for(config)++ if webhook_source_manager is not None and config.supports_webhooks:+ if async_to_sync(webhook_source_manager.webhook_enabled)():+ manager = webhook_source_manager+ return _make_source_response(+ config, lambda: manager.get_items(table_transformer=make_webhook_table_transformer())+ )++ if config.fanout is not None:+ parent_config = YOUSIGN_ENDPOINTS[config.fanout.parent_name]+ # Fan-out syncs are full refresh (child endpoints have no timestamp filter) and are not+ # resumable — build_dependent_resource re-fetches the parent list on retry and merge+ # dedupes re-pulled rows.+ dependent_resource = cast(+ Resource,+ build_dependent_resource(+ endpoint_configs=YOUSIGN_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=client_config,+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ should_use_incremental_field=False,+ page_size_param="limit",+ parent_endpoint_extra={+ "paginator": _cursor_paginator(),+ "data_selector": parent_config.data_selector,+ },+ child_endpoint_extra={+ "paginator": SinglePagePaginator(),+ "data_selector": config.data_selector,+ },+ ),+ )+ if row_transform is not None:+ dependent_resource = dependent_resource.add_map(row_transform)+ items = cast(Iterable[Any], dependent_resource)+ return _make_source_response(config, lambda: items)++ rest_config: RESTAPIConfig = {+ "client": client_config,+ "resource_defaults": {},+ "resources": [get_resource(config, should_use_incremental_field, incremental_field)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"cursor": resume_config.cursor}++ 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.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(YousignResumeConfig(cursor=str(state["cursor"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value if should_use_incremental_field else None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+ if row_transform is not None:+ resource = resource.add_map(row_transform)+ return _make_source_response(config, lambda: resource)+++def validate_credentials(+ api_key: str, environment: str | None, schema_name: Optional[str] = None+) -> tuple[bool, str | None]:+ """Probe the users list — a cheap organization-scoped read available on every plan."""+ if not api_key:+ return False, "Missing Yousign API key"++ base_url = base_url_for_environment(environment)+ try:+ response = _make_session(api_key).get(f"{base_url}/users", params={"limit": 1}, timeout=REQUEST_TIMEOUT_SECONDS)+ except requests.RequestException as e:+ return False, f"Could not connect to Yousign: {e}"++ if response.status_code == 401:+ return False, (+ "Yousign rejected the API key. Check the key is correct, has not been revoked, and "+ "matches the selected environment — sandbox keys cannot access the production API "+ "and vice versa."+ )+ if response.status_code == 403:+ # Workspace-scoped keys may lack access to some endpoints; don't block source-create on+ # one missing permission.+ if schema_name is not None:+ return False, "Your Yousign API key does not have permission to read this data."+ return True, None+ if not response.ok:+ return False, f"Yousign returned an unexpected status ({response.status_code})"+ return True, None+++def _make_session(api_key: str) -> requests.Session:+ return make_tracked_session(+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ redact_values=(api_key,),+ )+++def _maybe_json_loads(value: Any) -> Any:+ """Nested webhook payload fields round-trip through parquet as JSON strings."""+ if isinstance(value, str):+ try:+ return orjson.loads(value)+ except orjson.JSONDecodeError:+ return value+ return value+++def _event_time(row: dict[str, Any]) -> int:+ try:+ return int(row.get("event_time") or 0)+ except (TypeError, ValueError):+ return 0+++def make_webhook_table_transformer() -> Callable[[pa.Table], pa.Table]:+ def transform(table: pa.Table) -> pa.Table:+ # Webhook rows are full event envelopes; reshape each to the signature request object so+ # they merge into the same table as pulled rows. Delta merge only dedupes across syncs,+ # so keep one row per id within the batch — the one with the greatest event_time (ties+ # go to arrival order, which the manager reads oldest-first).+ best_by_id: dict[Any, tuple[int, dict[str, Any]]] = {}+ for raw_row in table.to_pylist():+ data = _maybe_json_loads(raw_row.get("data"))+ if not isinstance(data, dict):+ continue+ signature_request = _maybe_json_loads(data.get("signature_request"))+ if not isinstance(signature_request, dict) or signature_request.get("id") is None:+ continue+ _scrub_signature_request_row(signature_request)+ event_time = _event_time(raw_row)+ existing = best_by_id.get(signature_request["id"])+ if existing is None or event_time >= existing[0]:+ best_by_id[signature_request["id"]] = (event_time, signature_request)+ return table_from_py_list([row for _, row in best_by_id.values()])++ return transform+++def _webhooks_url(environment: str | None) -> str:+ # Webhook management is documented against the production API (sandbox subscriptions are+ # created with `sandbox: true`), but keys are environment-scoped, so a sandbox key can only+ # reach the sandbox host. Use the host matching the source's environment; if Yousign rejects+ # management calls there, the failure surfaces and the user follows the manual setup steps.+ return f"{base_url_for_environment(environment)}/webhooks"+++def _list_webhooks(api_key: str, environment: str | None) -> list[dict[str, Any]]:+ response = _make_session(api_key).get(_webhooks_url(environment), timeout=REQUEST_TIMEOUT_SECONDS)+ response.raise_for_status()+ data = response.json()+ return data if isinstance(data, list) else []+++def _find_webhook_by_url(api_key: str, environment: str | None, webhook_url: str) -> dict[str, Any] | None:+ return next((wh for wh in _list_webhooks(api_key, environment) if wh.get("endpoint") == webhook_url), None)+++def create_webhook(+ api_key: str, environment: str | None, webhook_url: str, logger: FilteringBoundLogger+) -> WebhookCreationResult:+ try:+ body = {+ "endpoint": webhook_url,+ "description": "PostHog data warehouse",+ "sandbox": environment == SANDBOX_ENVIRONMENT,+ "subscribed_events": all_webhook_events(),+ "scopes": ["*"],+ "auto_retry": True,+ "enabled": True,+ }+ response = _make_session(api_key).post(_webhooks_url(environment), json=body, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code in (401, 403):+ return WebhookCreationResult(success=False, error=WEBHOOK_PERMISSION_ERROR)+ if not response.ok:+ raise Exception(f"Yousign webhook creation failed with HTTP {response.status_code}")++ data = response.json() if response.content else {}+ secret = data.get("secret_key") if isinstance(data, dict) else None+ if secret:+ return WebhookCreationResult(success=True, extra_inputs={"signing_secret": secret})+ # The signing key is visible on the subscription in the Yousign app if the API response+ # didn't carry it.+ return WebhookCreationResult(success=True, pending_inputs=["signing_secret"])+ except Exception as e:+ logger.exception(f"Yousign: failed to create webhook: {e}")+ return WebhookCreationResult(success=False, error=f"Failed to create Yousign webhook automatically: {e}")+++def update_webhook_events(+ api_key: str, environment: str | None, webhook_url: str, desired_events: list[str], logger: FilteringBoundLogger+) -> WebhookSyncResult:+ try:+ existing = _find_webhook_by_url(api_key, environment, webhook_url)+ if existing is None or existing.get("id") is None:+ return WebhookSyncResult(success=False, error="No Yousign webhook found for this source's webhook URL.")++ if sorted(existing.get("subscribed_events") or []) == sorted(desired_events):+ return WebhookSyncResult(success=True)++ response = _make_session(api_key).patch(+ f"{_webhooks_url(environment)}/{existing['id']}",+ json={"subscribed_events": desired_events},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ if response.status_code in (401, 403):+ return WebhookSyncResult(success=False, error=WEBHOOK_PERMISSION_ERROR)+ if not response.ok:+ raise Exception(f"Yousign webhook update failed with HTTP {response.status_code}")+ return WebhookSyncResult(success=True)+ except Exception as e:+ logger.exception(f"Yousign: failed to sync webhook events: {e}")+ return WebhookSyncResult(success=False, error=f"Failed to update Yousign webhook events: {e}")+++def get_external_webhook_info(api_key: str, environment: str | None, webhook_url: str) -> ExternalWebhookInfo:+ try:+ existing = _find_webhook_by_url(api_key, environment, webhook_url)+ if existing is None:+ return ExternalWebhookInfo(exists=False)+ subscribed_events = existing.get("subscribed_events")+ return ExternalWebhookInfo(+ exists=True,+ url=existing.get("endpoint"),+ enabled_events=subscribed_events if isinstance(subscribed_events, list) else None,+ status="enabled" if existing.get("enabled") else "disabled",+ description=existing.get("description"),+ created_at=existing.get("created_at"),+ )+ except Exception as e:+ return ExternalWebhookInfo(exists=False, error=f"Failed to check Yousign webhook: {e}")+++def delete_webhook(+ api_key: str, environment: str | None, webhook_url: str, logger: FilteringBoundLogger+) -> WebhookDeletionResult:+ try:+ existing = _find_webhook_by_url(api_key, environment, webhook_url)+ if existing is None or existing.get("id") is None:+ # Nothing to delete — the desired end state already holds.+ return WebhookDeletionResult(success=True)++ response = _make_session(api_key).delete(+ f"{_webhooks_url(environment)}/{existing['id']}", timeout=REQUEST_TIMEOUT_SECONDS+ )+ if response.status_code in (401, 403):+ return WebhookDeletionResult(success=False, error=WEBHOOK_PERMISSION_ERROR)+ if not response.ok and response.status_code != 404:+ raise Exception(f"Yousign webhook deletion failed with HTTP {response.status_code}")+ return WebhookDeletionResult(success=True)+ except Exception as e:+ logger.exception(f"Yousign: failed to delete webhook: {e}")+ return WebhookDeletionResult(success=False, error=f"Failed to delete Yousign webhook: {e}")