: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 5 missing tables to the DocuSign source (#120024)
Tom Owers48912b83f128
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex d68db45db6a4..aa9fb4c43a61 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -3895,12 +3895,12 @@ Diffed against: <https://raw.githubusercontent.com/docusign/OpenAPI-Specificatio- [x] `Envelope audit events (GET /v2.1/accounts/{accountId}/envelopes/{envelopeId}/audit_events)` — reconstruct envelope activity and signing history beyond the latest status (high)- [x] `Envelope form data (GET /v2.1/accounts/{accountId}/envelopes/{envelopeId}/form_data)` — analyze submitted contract fields and recipient responses across envelopes (high)-- [ ] `Envelope custom fields (GET /v2.1/accounts/{accountId}/envelopes/{envelopeId}/custom_fields)` — join envelopes to business records using sender-defined field values (medium)+- [x] `Envelope custom fields (GET /v2.1/accounts/{accountId}/envelopes/{envelopeId}/custom_fields)` — join envelopes to business records using sender-defined field values (medium)- [x] `Envelope templates (GET /v2.1/accounts/{accountId}/envelopes/{envelopeId}/templates)` — associate imported envelopes with templates to compare completion rates and turnaround times (medium)- [x] `Bulk send batch summaries (GET /v2.1/accounts/{accountId}/bulk_send_batch)` — measure bulk signing campaign volume, delivery progress, and errors (medium)-- [ ] `Bulk send batch envelopes (GET /v2.1/accounts/{accountId}/bulk_send_batch/{bulkSendBatchId}/envelopes)` — associate imported envelopes with bulk campaigns for campaign completion analysis (medium)-- [ ] `PowerForms and form data (GET /v2.1/accounts/{accountId}/powerforms; GET /v2.1/accounts/{accountId}/powerforms/{powerFormId}/form_data)` — analyze self-service form submissions and their envelope outcomes (medium)-- [ ] `Billing invoices (GET /v2.1/accounts/{accountId}/billing_invoices)` — compare account charges and invoice balances with envelope activity (medium)+- [x] `Bulk send batch envelopes (GET /v2.1/accounts/{accountId}/bulk_send_batch/{bulkSendBatchId}/envelopes)` — associate imported envelopes with bulk campaigns for campaign completion analysis (medium)+- [x] `PowerForms and form data (GET /v2.1/accounts/{accountId}/powerforms; GET /v2.1/accounts/{accountId}/powerforms/{powerFormId}/form_data)` — analyze self-service form submissions and their envelope outcomes (medium)+- [x] `Billing invoices (GET /v2.1/accounts/{accountId}/billing_invoices)` — compare account charges and invoice balances with envelope activity (medium)Note: Parsed all GET operations in the official eSignature v2.1 Swagger specification, including nested envelope resources. Recipient and document tables already extract inline collections from envelope listings. Missing audit events, form data, and template associations need parent-ID fan-out; form downloads need an account setting, and billing needs administrator access. Settings, signature images, binary downloads, and webhooks were excluded.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/canonical_descriptions.pyindex 0afd587d6904..fc7c98f66f78 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/canonical_descriptions.py@@ -129,6 +129,20 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"pageCount": "Number of pages across the template's documents.",},},+ "envelope_custom_fields": {+ "description": "One row per envelope custom field, the sender-defined text or list values DocuSign stores on an envelope but does not show to recipients.",+ "docs_url": "https://developers.docusign.com/docs/esign-rest-api/reference/envelopes/envelopecustomfields/list/",+ "columns": {+ "envelopeId": "Envelope this custom field belongs to.",+ "customFieldType": "Kind of custom field: text for a free-text value, or list for a value picked from a set of options.",+ "fieldId": "Identifier of the custom field. Falls back to the field name when DocuSign returns no ID.",+ "name": "Name of the custom field.",+ "value": "Value the sender entered or selected for the field.",+ "listItems": "Options the sender could choose from, for list custom fields.",+ "required": "Whether the sender had to fill in the field before sending.",+ "show": "Whether the field is shown to the sender when they create or send an envelope.",+ },+ },"users": {"description": "Users belonging to the DocuSign account.","docs_url": "https://developers.docusign.com/docs/esign-rest-api/reference/users/users/list/",@@ -176,4 +190,63 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"batchUri": "Relative URI of the batch details.",},},+ "bulk_send_batch_envelopes": {+ "description": "Envelopes sent as part of each bulk send batch, one row per batch and envelope.",+ "docs_url": "https://developers.docusign.com/docs/esign-rest-api/reference/bulkenvelopes/bulksend/getbulksendbatchenvelopes/",+ "columns": {+ "bulkSendBatchId": "Bulk send batch the envelope was sent in.",+ "envelopeId": "Unique identifier of the envelope.",+ "status": "Current status of the envelope, such as sent, delivered, completed, declined, or voided.",+ "createdDateTime": "Date and time the envelope was created.",+ "sentDateTime": "Date and time the envelope was sent.",+ "completedDateTime": "Date and time every recipient finished their required actions.",+ "statusChangedDateTime": "Date and time the envelope's status last changed.",+ },+ },+ "powerforms": {+ "description": "PowerForms on the account: self-service signing links that create an envelope from a template each time someone fills them in.",+ "docs_url": "https://developers.docusign.com/docs/esign-rest-api/reference/powerforms/powerforms/list/",+ "columns": {+ "powerFormId": "Unique identifier of the PowerForm.",+ "name": "Name of the PowerForm.",+ "templateId": "Template the PowerForm creates envelopes from.",+ "templateName": "Name of the template the PowerForm creates envelopes from.",+ "isActive": "Whether the PowerForm can currently be used.",+ "signingMode": "How recipients are verified before they sign, such as email or direct.",+ "timesUsed": "Number of times the PowerForm has been used.",+ "usesRemaining": "Number of times the PowerForm can still be used.",+ "lastUsed": "Date and time the PowerForm was last used.",+ "createdDateTime": "Date and time the PowerForm was created.",+ "createdBy": "User who created the PowerForm.",+ "senderUserId": "User the PowerForm sends envelopes as.",+ "powerFormUrl": "Link recipients open to fill in the PowerForm.",+ },+ },+ "powerform_form_data": {+ "description": "Data each recipient entered into a PowerForm, one row per PowerForm, envelope, and recipient.",+ "docs_url": "https://developers.docusign.com/docs/esign-rest-api/reference/powerforms/powerformdata/list/",+ "columns": {+ "powerFormId": "PowerForm the data was submitted through.",+ "envelopeId": "Envelope the PowerForm submission created.",+ "recipientId": "Identifier of the recipient within its envelope.",+ "name": "Name of the recipient.",+ "email": "Email address of the recipient.",+ "formData": "Name and value pairs for each field the recipient filled in.",+ },+ },+ "billing_invoices": {+ "description": "Invoices billed to the DocuSign account.",+ "docs_url": "https://developers.docusign.com/docs/esign-rest-api/reference/billing/invoices/list/",+ "columns": {+ "invoiceId": "Unique identifier of the invoice.",+ "invoiceNumber": "Invoice number shown on the invoice.",+ "amount": "Total amount of the invoice.",+ "balance": "Amount of the invoice that is still unpaid.",+ "dueDate": "Date the invoice is due.",+ "taxableAmount": "Part of the invoice amount that is taxable.",+ "nonTaxableAmount": "Part of the invoice amount that is not taxable.",+ "invoiceItems": "Line items on the invoice, with charge names, quantities, and amounts.",+ "pdfAvailable": "Whether a PDF copy of the invoice can be downloaded.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/docusign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/docusign.pyindex 500dfe3094ce..57d075c3145b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/docusign.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/docusign.py@@ -22,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.docusign.sDOCUSIGN_ENDPOINTS,PAGE_SIZE,DocusignEndpointConfig,+ DocusignFanOutConfig,)# DocuSign runs completely separate demo and production stacks: an integration key only works@@ -256,6 +257,24 @@ def _flatten_recipients(envelope: dict[str, Any], parent: dict[str, Any]) -> lisreturn rows+def _flatten_custom_fields(envelope: dict[str, Any], parent: dict[str, Any]) -> list[dict[str, Any]]:+ custom_fields = envelope.get("customFields")+ if not isinstance(custom_fields, dict):+ return []++ rows: list[dict[str, Any]] = []+ for field_type, bucket_key in (("text", "textCustomFields"), ("list", "listCustomFields")):+ for custom_field in custom_fields.get(bucket_key) or []:+ if not isinstance(custom_field, dict):+ continue+ # The field id is part of the primary key, so fall back to the name when it is absent.+ field_id = custom_field.get("fieldId") or custom_field.get("name")+ if not field_id:+ continue+ rows.append({**custom_field, **parent, "customFieldType": field_type, "fieldId": str(field_id)})+ return rows++def _flatten_envelope_children(endpoint: DocusignEndpointConfig, envelopes: list[dict[str, Any]]) -> list[dict[str, Any]]:@@ -272,6 +291,10 @@ def _flatten_envelope_children(rows.extend(_flatten_recipients(envelope, parent))continue+ if endpoint.derived_from_envelopes == "custom_fields":+ rows.extend(_flatten_custom_fields(envelope, parent))+ continue+for key in endpoint.envelope_child_keys:children = envelope.get(key)if isinstance(children, list):@@ -329,6 +352,22 @@ def _shape_envelope_sub_resource(return list(templates.values())+def _shape_fan_out_rows(fan_out: DocusignFanOutConfig, body: dict[str, Any], parent_id: str) -> list[dict[str, Any]]:+ items = [item for item in (body.get(fan_out.data_key) or []) if isinstance(item, dict)]+ if not fan_out.flatten_envelope_recipients:+ return [{**item, fan_out.parent_id_column: parent_id} for item in items]++ rows: list[dict[str, Any]] = []+ for envelope in items:+ envelope_id = envelope.get("envelopeId")+ if not envelope_id:+ continue+ for recipient in envelope.get("recipients") or []:+ if isinstance(recipient, dict):+ rows.append({**recipient, "envelopeId": str(envelope_id), fan_out.parent_id_column: parent_id})+ return rows++def get_rows(credentials: DocusignCredentials,endpoint_name: str,@@ -382,6 +421,42 @@ def get_rows(body = response.json()return body if isinstance(body, dict) else {}+ def pause_if_quota_low() -> None:+ wait_seconds = _quota_wait_seconds(last_headers, time.time())+ if wait_seconds > 0:+ logger.info(f"DocuSign hourly API quota is low, pausing {wait_seconds:.0f}s until it resets")+ interruptible_wait(wait_seconds, safe_point=resumable_source_manager.safe_point)++ def fan_out_rows(fan_out: DocusignFanOutConfig, parent_id: str) -> Iterator[list[dict[str, Any]]]:+ path = fan_out.path.format(parent_id=quote(parent_id, safe=""))+ child_position = 0+ for _ in range(MAX_PAGES):+ params = dict(fan_out.params)+ if fan_out.paginated:+ params.update({"count": str(PAGE_SIZE), "start_position": str(child_position)})++ pause_if_quota_low()+ try:+ body = request(path, params)+ except requests.HTTPError as e:+ if e.response is None or e.response.status_code not in fan_out.skip_statuses:+ raise+ logger.warning(f"Skipping DocuSign {endpoint_name} for {parent_id}: status={e.response.status_code}")+ resumable_source_manager.safe_point()+ return++ rows = _shape_fan_out_rows(fan_out, body, parent_id)+ if rows:+ yield rows+ else:+ # The staged cursor is the start of the parent page, so resuming re-reads it whole.+ resumable_source_manager.safe_point()++ page = body.get(fan_out.data_key) or []+ if not fan_out.paginated or not page or not _has_next_page(body, page):+ return+ child_position += len(page)+for _ in range(MAX_PAGES):body = request(endpoint.path, _build_params(endpoint, start_position, from_date))page = [item for item in (body.get(endpoint.data_key) or []) if isinstance(item, dict)]@@ -390,10 +465,7 @@ def get_rows(for envelope in page:if not envelope.get("envelopeId"):continue- wait_seconds = _quota_wait_seconds(last_headers, time.time())- if wait_seconds > 0:- logger.info(f"DocuSign hourly API quota is low, pausing {wait_seconds:.0f}s until it resets")- interruptible_wait(wait_seconds, safe_point=resumable_source_manager.safe_point)+ pause_if_quota_low()parent = _envelope_parent(envelope)sub_resource_path = (@@ -407,6 +479,11 @@ def get_rows(else:# The staged cursor is the start of this page, so resuming re-reads it whole.resumable_source_manager.safe_point()+ elif endpoint.fan_out:+ for parent_row in page:+ parent_id = parent_row.get(endpoint.fan_out.parent_id_key)+ if parent_id:+ yield from fan_out_rows(endpoint.fan_out, str(parent_id))else:rows = _flatten_envelope_children(endpoint, page) if endpoint.derived_from_envelopes else pageif rows:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/settings.pyindex 97da1242e2fd..2c0452c41d44 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/settings.py@@ -16,6 +16,24 @@ PAGE_SIZE = 100DEFAULT_LOOKBACK_DAYS = 730+@dataclass(frozen=True)+class DocusignFanOutConfig:+ """A per-parent request made for each row of the endpoint's own listing."""++ # Path under the account base URL, with `{parent_id}` standing in for the listed parent's id.+ path: str+ parent_id_key: str+ # Column the parent id is copied into on every child row.+ parent_id_column: str+ data_key: str+ params: dict[str, str] = field(default_factory=dict)+ paginated: bool = False+ # PowerForm form data nests one recipient list per submitted envelope.+ flatten_envelope_recipients: bool = False+ # Statuses that mean only this one parent is unreadable, so the table skips it instead of failing.+ skip_statuses: tuple[int, ...] = ()++@dataclass(frozen=True)class DocusignEndpointConfig:name: str@@ -45,6 +63,7 @@ class DocusignEndpointConfig:# API quota, so these endpoints should be synced incrementally.envelope_sub_resource: Optional[str] = Noneenvelope_sub_resource_params: dict[str, str] = field(default_factory=dict)+ fan_out: Optional[DocusignFanOutConfig] = None# False for endpoints that return everything in one response and ignore `start_position` —# re-requesting with an advanced offset would replay the same rows forever.supports_pagination: bool = True@@ -108,6 +127,19 @@ DOCUSIGN_ENDPOINTS: dict[str, DocusignEndpointConfig] = {derived_from_envelopes="documents",envelope_child_keys=("envelopeDocuments", "documents"),),+ "envelope_custom_fields": DocusignEndpointConfig(+ name="envelope_custom_fields",+ path="/envelopes",+ data_key="envelopes",+ # Text and list custom fields are separate collections, so the type is part of the key.+ primary_key=["envelopeId", "customFieldType", "fieldId"],+ params={"order_by": "status_changed", "order": "asc", "include": "custom_fields"},+ date_filter_param="from_date",+ incremental_fields=_DERIVED_INCREMENTAL_FIELDS,+ partition_key="envelopeCreatedDateTime",+ derived_from_envelopes="custom_fields",+ envelope_child_keys=("customFields",),+ ),"envelope_form_data": DocusignEndpointConfig(name="envelope_form_data",path="/envelopes",@@ -190,6 +222,61 @@ DOCUSIGN_ENDPOINTS: dict[str, DocusignEndpointConfig] = {date_filter_param="from_date",partition_key="submittedDate",),+ "bulk_send_batch_envelopes": DocusignEndpointConfig(+ name="bulk_send_batch_envelopes",+ path="/bulk_send_batch",+ data_key="bulkBatchSummaries",+ primary_key=["bulkSendBatchId", "envelopeId"],+ # Same batch listing as `bulk_send_batches`. Full refresh only: envelope statuses keep+ # changing after the batch is submitted, and the batch filter is on submission time.+ date_filter_param="from_date",+ partition_key="createdDateTime",+ fan_out=DocusignFanOutConfig(+ path="/bulk_send_batch/{parent_id}/envelopes",+ parent_id_key="batchId",+ parent_id_column="bulkSendBatchId",+ data_key="envelopes",+ params={"order_by": "created", "order": "asc"},+ paginated=True,+ ),+ ),+ "powerforms": DocusignEndpointConfig(+ name="powerforms",+ path="/powerforms",+ data_key="powerForms",+ primary_key=["powerFormId"],+ # No from_date: DocuSign then applies no date filter, and usage counters change anyway.+ params={"order_by": "created", "order": "asc"},+ partition_key="createdDateTime",+ ),+ "powerform_form_data": DocusignEndpointConfig(+ name="powerform_form_data",+ path="/powerforms",+ data_key="powerForms",+ primary_key=["powerFormId", "envelopeId", "recipientId"],+ params={"order_by": "created", "order": "asc"},+ fan_out=DocusignFanOutConfig(+ path="/powerforms/{parent_id}/form_data",+ parent_id_key="powerFormId",+ parent_id_column="powerFormId",+ data_key="envelopes",+ params={"data_layout": "Native"},+ flatten_envelope_recipients=True,+ # Only PowerForm administrators and the PowerForm's sender can read its form data, and+ # the listing also returns PowerForms the user can see but not download.+ skip_statuses=(403, 404),+ ),+ ),+ "billing_invoices": DocusignEndpointConfig(+ name="billing_invoices",+ path="/billing_invoices",+ data_key="billingInvoices",+ primary_key=["invoiceId"],+ # Without from_date DocuSign returns only the last 365 days. Full refresh only, because+ # an invoice's balance changes when it is paid.+ date_filter_param="from_date",+ supports_pagination=False,+ ),}ENDPOINTS = tuple(DOCUSIGN_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/source.pyindex c7c7d3db091b..63561c494609 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/source.py@@ -93,11 +93,13 @@ class DocusignSource(ResumableSource[DocusignSourceConfig, DocusignResumeConfig]name=ExternalDataSourceType.DOCUSIGN,category=DataWarehouseSourceCategory.SALES,label="DocuSign",- caption="""Connect your DocuSign account to pull envelopes, recipients, documents, form data, audit events, templates, bulk send batches, users, and folders into the PostHog Data warehouse.+ caption="""Connect your DocuSign account to pull envelopes, recipients, documents, custom fields, form data, audit events, templates, bulk send batches and their envelopes, PowerForms and their form data, billing invoices, users, and folders into the PostHog Data warehouse.Create an integration key in [DocuSign Apps and Keys](https://apps.docusign.com/admin/apps-and-keys). JWT grant is the option to pick: add an RSA keypair to the key, grant consent once for the user you want to impersonate, and paste that user's API user ID. Production keys have to pass DocuSign's go-live review before they work outside the demo environment.-The form data, audit events, and envelope templates tables make one API request per envelope, which counts toward your DocuSign hourly API limit. Sync them incrementally. Form data also needs the "Allow sender to download form data" sending setting turned on.""",+The form data, audit events, and envelope templates tables make one API request per envelope, which counts toward your DocuSign hourly API limit. Sync them incrementally. Form data also needs the "Allow sender to download form data" sending setting turned on.++The bulk send batch envelopes and PowerForm form data tables make one API request per batch or PowerForm. PowerForm form data only includes PowerForms that the connected user sent or administers. The billing invoices table needs an account administrator.""",iconPath="/static/services/docusign.png",docsUrl="https://posthog.com/docs/cdp/sources/docusign",releaseStatus=ReleaseStatus.ALPHA,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/tests/test_docusign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/tests/test_docusign.pyindex bf851a4adb47..04e7c0a9b9d5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/tests/test_docusign.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/tests/test_docusign.py@@ -247,6 +247,28 @@ class TestDocusignTransport:}]+ def test_custom_fields_are_flattened_from_both_field_types(self, logger: FilteringBoundLogger) -> None:+ page = envelope_page(1)+ page["envelopes"][0]["customFields"] = {+ "textCustomFields": [+ {"fieldId": "11", "name": "Deal ID", "value": "D-42"},+ {"name": "Ad hoc", "value": "x"},+ {"value": "no name or id"},+ ],+ "listCustomFields": [{"fieldId": "11", "name": "Region", "value": "EMEA", "listItems": ["EMEA", "APAC"]}],+ }+ result = driver().run("envelope_custom_fields", [*auth_responses(), ScriptedResponse(json=page)], logger=logger)++ assert result.raised is None+ assert [(row["customFieldType"], row["fieldId"], row["value"]) for row in result.rows] == [+ ("text", "11", "D-42"),+ ("text", "Ad hoc", "x"),+ ("list", "11", "EMEA"),+ ]+ assert {row["envelopeId"] for row in result.rows} == {"env-0"}+ assert result.rows[0]["envelopeCreatedDateTime"] == "2024-01-01T00:00:00.0000000Z"+ assert result.requests[-1].param("include") == "custom_fields"+def test_envelopes_without_children_yield_no_rows_but_still_paginate(self, logger: FilteringBoundLogger) -> None:result = driver().run("envelope_recipients",@@ -373,20 +395,140 @@ class TestDocusignTransport:else:assert waits == []- def test_bulk_send_batches_always_send_from_date(self, logger: FilteringBoundLogger) -> None:+ @pytest.mark.parametrize(+ "endpoint_name,body,expected_rows",+ [+ (+ "bulk_send_batches",+ {"bulkBatchSummaries": [{"batchId": "b-1", "submittedDate": "2024-01-01"}]},+ [{"batchId": "b-1", "submittedDate": "2024-01-01"}],+ ),+ (+ # The invoice listing is one response, so a `nextUri` must not start a second request.+ "billing_invoices",+ {"billingInvoices": [{"invoiceId": "inv-1", "balance": "0.00"}], "nextUri": "/restapi/next"},+ [{"invoiceId": "inv-1", "balance": "0.00"}],+ ),+ ],+ )+ def test_date_scoped_full_refresh_endpoints_always_send_from_date(+ self,+ endpoint_name: str,+ body: dict[str, Any],+ expected_rows: list[dict[str, Any]],+ logger: FilteringBoundLogger,+ ) -> None:+ result = driver().run(endpoint_name, [*auth_responses(), ScriptedResponse(json=body)], logger=logger)++ assert result.raised is None+ assert result.rows == expected_rows+ # Without from_date DocuSign narrows the result: an account-wide batch summary with no batch+ # list, or only the last 365 days of invoices.+ assert result.requests[-1].param("from_date") is not None++ def test_bulk_send_batch_envelopes_page_through_each_batch(self, logger: FilteringBoundLogger) -> None:+ batches = {"bulkBatchSummaries": [{"batchId": "b-1"}, {"batchId": ""}, {"batchId": "b-2"}]}result = driver().run(- "bulk_send_batches",+ "bulk_send_batch_envelopes",[*auth_responses(),- ScriptedResponse(json={"bulkBatchSummaries": [{"batchId": "b-1", "submittedDate": "2024-01-01"}]}),+ ScriptedResponse(json=batches),+ ScriptedResponse(json=envelope_page(PAGE_SIZE, next_uri="/restapi/next")),+ ScriptedResponse(json=envelope_page(1, offset=PAGE_SIZE)),+ ScriptedResponse(json={"envelopes": [], "resultSetSize": "0"}),],logger=logger,)assert result.raised is None- assert result.rows == [{"batchId": "b-1", "submittedDate": "2024-01-01"}]- # Without from_date DocuSign answers with an account-wide summary that has no batch list.- assert result.requests[-1].param("from_date") is not None+ assert len(result.rows) == PAGE_SIZE + 1+ assert {row["bulkSendBatchId"] for row in result.rows} == {"b-1"}+ assert result.rows[-1]["envelopeId"] == f"env-{PAGE_SIZE}"+ assert result.paths[-4:] == [+ "/restapi/v2.1/accounts/222/bulk_send_batch",+ "/restapi/v2.1/accounts/222/bulk_send_batch/b-1/envelopes",+ "/restapi/v2.1/accounts/222/bulk_send_batch/b-1/envelopes",+ "/restapi/v2.1/accounts/222/bulk_send_batch/b-2/envelopes",+ ]+ assert result.params("start_position")[-3:] == ["0", str(PAGE_SIZE), "0"]+ assert result.requests[-4].param("from_date") is not None+ assert result.requests[-1].param("from_date") is None+ assert result.final_state is None++ def test_powerform_form_data_flattens_recipients_and_skips_unreadable_powerforms(+ self, logger: FilteringBoundLogger+ ) -> None:+ powerforms = {"powerForms": [{"powerFormId": "pf-1"}, {"powerFormId": "pf-2"}, {"powerFormId": "pf-3"}]}+ form_data = {+ "envelopes": [+ {+ "envelopeId": "env-a",+ "recipients": [+ {"recipientId": "1", "email": "[email protected]", "formData": [{"name": "Plan", "value": "Pro"}]},+ {"recipientId": "2", "email": "[email protected]", "formData": []},+ ],+ },+ {"envelopeId": "env-b", "recipients": []},+ {"recipients": [{"recipientId": "9"}]},+ ]+ }+ result = driver().run(+ "powerform_form_data",+ [+ *auth_responses(),+ ScriptedResponse(json=powerforms),+ ScriptedResponse(status=403, json={"errorCode": "USER_LACKS_PERMISSIONS"}),+ ScriptedResponse(json=form_data),+ ScriptedResponse(status=404, json={"errorCode": "POWERFORM_DOES_NOT_EXIST"}),+ ],+ logger=logger,+ )++ assert result.raised is None+ assert result.rows == [+ {+ "recipientId": "1",+ "email": "[email protected]",+ "formData": [{"name": "Plan", "value": "Pro"}],+ "envelopeId": "env-a",+ "powerFormId": "pf-2",+ },+ {+ "recipientId": "2",+ "email": "[email protected]",+ "formData": [],+ "envelopeId": "env-a",+ "powerFormId": "pf-2",+ },+ ]+ assert [path.rsplit("/", 2)[-2:] for path in result.paths[-3:]] == [+ ["pf-1", "form_data"],+ ["pf-2", "form_data"],+ ["pf-3", "form_data"],+ ]+ assert result.requests[-1].param("data_layout") == "Native"++ @pytest.mark.parametrize(+ "endpoint_name,parent_body,status",+ [+ ("bulk_send_batch_envelopes", {"bulkBatchSummaries": [{"batchId": "b-1"}]}, 403),+ ("powerform_form_data", {"powerForms": [{"powerFormId": "pf-1"}]}, 400),+ ],+ )+ def test_fan_out_errors_outside_the_skip_list_fail_the_table(+ self, endpoint_name: str, parent_body: dict[str, Any], status: int, logger: FilteringBoundLogger+ ) -> None:+ result = driver().run(+ endpoint_name,+ [+ *auth_responses(),+ ScriptedResponse(json=parent_body),+ ScriptedResponse(status=status, json={"errorCode": "INVALID_REQUEST_PARAMETER"}),+ ],+ logger=logger,+ )++ assert isinstance(result.raised, requests.HTTPError)@pytest.mark.parametrize("value,expected",