: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
fix(legal-documents): unwedge stranded DPA/BAA envelopes (#71698)
posthog[bot]02deaf3b6f0e
diff --git a/products/legal_documents/backend/admin.py b/products/legal_documents/backend/admin.pyindex 12774ed604b0..57560541949f 100644--- a/products/legal_documents/backend/admin.py+++ b/products/legal_documents/backend/admin.py@@ -94,6 +94,7 @@ class LegalDocumentAdmin(admin.ModelAdmin):ordering = ("-created_at",)show_full_result_count = Falselist_select_related = ("organization", "created_by")+ actions = ("resend_signing_email",)# Change view stays read-only — customer-submitted content can't be quietly# rewritten. The add view uses LegalDocumentAdminForm fields directly.@@ -234,6 +235,34 @@ class LegalDocumentAdmin(admin.ModelAdmin):f"This organization already has a {obj.document_type}. Delete the existing row first.") from exc+ @admin.action(description="Re-send PandaDoc signing email")+ def resend_signing_email(self, request: HttpRequest, queryset: Any) -> None:+ # Recovery path for envelopes stranded because the `document.draft`+ # webhook that normally triggers the send was missed: the envelope was+ # created but the signing email never went out. Re-dispatching the send+ # (idempotent on PandaDoc's side) gets the signer their link without+ # forcing a delete + regenerate. Signed rows and rows without an+ # envelope have nothing to send.+ sent = skipped = failed = 0+ for document in queryset:+ if document.status == LegalDocument.Status.SIGNED or not document.pandadoc_document_id:+ skipped += 1+ elif logic.send_pandadoc_envelope(document):+ sent += 1+ else:+ failed += 1++ if sent:+ messages.success(request, f"Re-sent the signing email for {sent} document(s).")+ if skipped:+ messages.warning(request, f"Skipped {skipped} document(s): already signed or no PandaDoc envelope.")+ if failed:+ messages.error(+ request,+ f"Couldn't re-send {failed} document(s). PandaDoc may still be processing the template, or the "+ "envelope is no longer sendable. Check the logs and try again shortly.",+ )+def delete_model(self, request: HttpRequest, obj: LegalDocument) -> None:# Shared helper voids the PandaDoc envelope, removes the S3 object,# and deletes the row (firing the activity-log entry viadiff --git a/products/legal_documents/backend/logic/__init__.py b/products/legal_documents/backend/logic/__init__.pyindex b10fd56b1aa5..efeef5570ef6 100644--- a/products/legal_documents/backend/logic/__init__.py+++ b/products/legal_documents/backend/logic/__init__.py@@ -413,8 +413,10 @@ def create_pandadoc_envelope(document: LegalDocument) -> str | None:def send_pandadoc_envelope(document: LegalDocument) -> bool:"""Dispatch the signing email for a previously-created PandaDoc envelope.- Called from the `document.draft` webhook once PandaDoc has finished- processing the template and the envelope is actually sendable.+ Normally called from the `document.draft` webhook once PandaDoc has+ finished processing the template and the envelope is actually sendable.+ Also driven manually from the Django admin re-send action to recover an+ envelope that was stranded because that webhook was missed.Returns True when the send succeeded, False otherwise. Never re-raises:PandaDoc will also reject a second send on a doc that's already pastdiff --git a/products/legal_documents/backend/logic/pandadoc.py b/products/legal_documents/backend/logic/pandadoc.pyindex f311ee5e9091..0d17ca0be05a 100644--- a/products/legal_documents/backend/logic/pandadoc.py+++ b/products/legal_documents/backend/logic/pandadoc.py@@ -1,8 +1,9 @@"""Thin client for the PandaDoc public API.-We hit three endpoints:+We hit these endpoints:POST /public/v1/documents -> create a document from a template+ GET /public/v1/documents/{id} -> read an envelope's current statusPOST /public/v1/documents/{id}/send -> email the signing envelopePATCH /public/v1/documents/{id}/status -> move an envelope to voided (no longer signable)@@ -36,6 +37,17 @@ DEFAULT_TIMEOUT_SECONDS = 30# See https://developers.pandadoc.com/reference/change-document-status-manually_PANDADOC_STATUS_VOIDED = 11+# The only PandaDoc states from which a void (→ `document.voided`) is both+# necessary and permitted: the envelope has actually been emailed to the signer+# and carries a live signing link a recipient could still complete. Every other+# state — never dispatched (`document.uploaded`/`document.draft`/`document.error`+# /`document.scheduled`), still in an internal approval/review/payment workflow,+# or already terminal (`document.completed`/`voided`/`declined`) — has no live+# link to invalidate, and PandaDoc rejects a void from those states anyway. We+# treat all of them as a no-op so a stranded row can always be cleaned up.+# https://developers.pandadoc.com/reference/document-status+_PANDADOC_VOIDABLE_STATUSES = frozenset({"document.sent", "document.viewed"})+class PandaDocError(Exception):"""Raised when the PandaDoc API returns a non-2xx response or we fail to reach it."""@@ -103,6 +115,28 @@ class PandaDocClient:except ValueError as exc:raise PandaDocError(f"PandaDoc {path} returned non-JSON body: {exc}") from exc+ def _get(self, path: str, *, allow_missing: bool = False) -> dict[str, Any] | None:+ """+ GET the given path and return the decoded JSON body. When+ `allow_missing` is set, a 404 returns None instead of raising — the+ caller treats an already-gone document as a no-op.+ """+ url = f"{self._base_url}{path}"+ try:+ response = requests.get(url, headers=self._headers(), timeout=self._timeout)+ except requests.RequestException as exc:+ raise PandaDocError(f"Network error calling PandaDoc {path}: {exc}") from exc+ if allow_missing and response.status_code == 404:+ return None+ if response.status_code >= 400:+ raise PandaDocError(f"PandaDoc {path} returned {response.status_code}: {response.text[:500]}")+ if not response.content:+ return {}+ try:+ return response.json()+ except ValueError as exc:+ raise PandaDocError(f"PandaDoc {path} returned non-JSON body: {exc}") from exc+def _patch(self, path: str, json: dict[str, Any]) -> int:"""PATCH the given path with a JSON body. Returns the HTTP status code so@@ -202,22 +236,43 @@ class PandaDocClient:payload["sender"] = {"email": sender_email}self._post(f"/public/v1/documents/{document_id}/send", payload)+ def get_document_status(self, *, document_id: str) -> str | None:+ """+ Return the envelope's current PandaDoc status string (e.g.+ `document.sent`), or None if the document no longer exists on+ PandaDoc's side. Backed by the lightweight status endpoint.+ """+ data = self._get(f"/public/v1/documents/{document_id}", allow_missing=True)+ if data is None:+ return None+ return data.get("status", "")+def void_document(self, *, document_id: str, notify_recipients: bool = True) -> None:"""- Move the envelope to `document.voided` so the recipient can no longer- complete it. Unlike a hard delete, the envelope stays in PandaDoc as- an audit record of the cancelled signing process — which is what we- want for documents that may end up in a legal review later.+ Move a *sent* envelope to `document.voided` so the recipient can no+ longer complete it. Unlike a hard delete, the envelope stays in+ PandaDoc as an audit record of the cancelled signing process — which+ is what we want for documents that may end up in a legal review later.`notify_recipients=True` sends PandaDoc's standard "this document wascancelled" email to the original signer, so they're not leftwondering why the link from earlier no longer works.- 404 is treated as success — the envelope is already gone, which is- the state we wanted anyway. Any other non-2xx (e.g., 423 if PandaDoc- has the document locked for editing) surfaces as PandaDocError so- the caller can decide whether to retry or log + move on.+ Only envelopes that were actually emailed to a signer+ (`document.sent`/`document.viewed`) are voided. An envelope that never+ left PandaDoc (still processing the template, or ready but never sent+ because the `document.draft` webhook was missed) has no live signing+ link, and PandaDoc rejects a void from those states anyway — so we skip+ it as a no-op rather than hard-failing. That keeps a stranded row+ deletable (and therefore regenerable) instead of wedging it. A+ document that's already gone (404) is a no-op for the same reason.++ A void that *is* attempted but fails (e.g., 423 if PandaDoc has the+ document locked for editing) surfaces as PandaDocError so the caller+ can decide whether to retry or log + move on."""+ if self.get_document_status(document_id=document_id) not in _PANDADOC_VOIDABLE_STATUSES:+ returnself._patch(f"/public/v1/documents/{document_id}/status",{"status": _PANDADOC_STATUS_VOIDED, "notify_recipients": notify_recipients},diff --git a/products/legal_documents/backend/tests/test_admin.py b/products/legal_documents/backend/tests/test_admin.pyindex ddb9ff5d697d..2e06ac7d8887 100644--- a/products/legal_documents/backend/tests/test_admin.py+++ b/products/legal_documents/backend/tests/test_admin.py@@ -5,6 +5,7 @@ from unittest.mock import patchfrom django.contrib.admin import AdminSitefrom django.contrib.admin.widgets import AutocompleteSelect+from django.contrib.messages.storage.fallback import FallbackStoragefrom django.core.exceptions import ValidationErrorfrom django.core.files.uploadedfile import SimpleUploadedFile, UploadedFilefrom django.test import RequestFactory@@ -34,6 +35,14 @@ def _files(pdf: UploadedFile | None = None) -> MultiValueDict[str, UploadedFile]return mvd+def _attach_messages(request) -> None:+ # Give a RequestFactory request the messages-framework plumbing admin+ # actions rely on. Untyped param on purpose so the attribute assignments+ # don't trip the type checker on WSGIRequest.+ request.session = {}+ request._messages = FallbackStorage(request)++class TestLegalDocumentAdminForm(APIBaseTest):def _form_data(self, **overrides: Any) -> dict[str, Any]:data = {@@ -90,6 +99,9 @@ class TestLegalDocumentAdminSave(APIBaseTest):def _request(self) -> Any:request = self.request_factory.post("/admin/posthog/legaldocument/add/")request.user = self.user+ # Admin actions write user-facing feedback via the messages framework,+ # which needs a storage backend attached to the request.+ _attach_messages(request)return requestdef _bound_form(self, document_type: str = "DPA") -> LegalDocumentAdminForm:@@ -327,6 +339,46 @@ class TestLegalDocumentAdminSave(APIBaseTest):self.assertEqual(called_ids, {"doc_111", "doc_222"})self.assertFalse(LegalDocument.objects.filter(id__in=[first.id, second.id]).exists())+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ def test_resend_signing_email_dispatches_only_for_unsent_rows(self, mock_pandadoc_cls: Any) -> None:+ # The recovery action re-triggers the signing email for in-flight rows+ # whose `document.draft` webhook was missed. It must skip signed rows+ # (already complete) and rows with no PandaDoc envelope (nothing to+ # send), and only call /send for the unsigned, enveloped row.+ stranded = LegalDocument.objects.create(+ organization=self.organization,+ document_type="DPA",+ company_name="Acme, Inc.",+ company_address="1 Analytics Way",+ representative_email="[email protected]",+ status=LegalDocument.Status.SUBMITTED_FOR_SIGNATURE,+ pandadoc_document_id="doc_stranded",+ )+ signed = LegalDocument.objects.create(+ organization=self.organization,+ document_type="BAA",+ company_name="Acme, Inc.",+ company_address="1 Analytics Way",+ representative_email="[email protected]",+ status=LegalDocument.Status.SIGNED,+ pandadoc_document_id="doc_signed",+ )+ no_envelope = LegalDocument.objects.create(+ organization=self.organization,+ document_type="MSA",+ company_name="Acme, Inc.",+ company_address="1 Analytics Way",+ representative_email="[email protected]",+ status=LegalDocument.Status.SUBMITTED_FOR_SIGNATURE,+ pandadoc_document_id="",+ )++ queryset = LegalDocument.objects.filter(id__in=[stranded.id, signed.id, no_envelope.id])+ self.admin.resend_signing_email(self._request(), queryset)++ mock_pandadoc_cls.return_value.send_document.assert_called_once()+ self.assertEqual(mock_pandadoc_cls.return_value.send_document.call_args.kwargs["document_id"], "doc_stranded")+class TestLegalDocumentAdminPermissions(APIBaseTest):def setUp(self) -> None:diff --git a/products/legal_documents/backend/tests/test_pandadoc.py b/products/legal_documents/backend/tests/test_pandadoc.pyindex 872f50abce00..f80c31dd62b8 100644--- a/products/legal_documents/backend/tests/test_pandadoc.py+++ b/products/legal_documents/backend/tests/test_pandadoc.py@@ -189,59 +189,113 @@ class TestPandaDocClient(TestCase):posthog = pandadoc.PandaDocRecipient(email="[email protected]", role=pandadoc.PandaDocRole.POSTHOG)self.assertEqual(pandadoc._serialize_recipient(posthog), {"email": "[email protected]", "role": "PostHog"})+ @staticmethod+ def _status_response(document_status: str) -> MagicMock:+ response = MagicMock()+ response.status_code = 200+ response.content = b'{"status": "..."}'+ response.json.return_value = {"id": "doc_123", "status": document_status}+ return response++ @parameterized.expand(+ [+ # Only envelopes actually emailed to a signer carry a live signing+ # link, and PandaDoc only permits voiding from these two states.+ ("sent_is_voided", "document.sent", True),+ ("viewed_is_voided", "document.viewed", True),+ # Never dispatched: still processing, ready-but-unsent (the stranded+ # webhook case), or errored. Nothing to void — must be a no-op so+ # the row stays deletable instead of wedging.+ ("uploaded_is_noop", "document.uploaded", False),+ ("draft_is_noop", "document.draft", False),+ ("error_is_noop", "document.error", False),+ # Already terminal — a second void would 4xx and re-wedge the row.+ ("completed_is_noop", "document.completed", False),+ ("already_voided_is_noop", "document.voided", False),+ ]+ )@override_settings(PANDADOC_API_KEY="key", PANDADOC_API_BASE_URL="https://api.pandadoc.com")- def test_void_document_patches_status_endpoint_with_voided_code(self) -> None:- # Voided is PandaDoc's "no longer signable" status. We hit the status- # endpoint with the numeric code (11) rather than deleting the doc so+ def test_void_document_only_voids_sent_or_viewed_envelopes(+ self, _name: str, document_status: str, should_void: bool+ ) -> None:+ # Voided is PandaDoc's "no longer signable" status (numeric code 11 on+ # the status endpoint) — a status transition rather than a delete so# PandaDoc retains the audit record of the cancelled signing process.- fake_response = MagicMock()- fake_response.status_code = 204+ patch_response = MagicMock()+ patch_response.status_code = 204++ with (+ patch(+ "products.legal_documents.backend.logic.pandadoc.requests.get",+ return_value=self._status_response(document_status),+ ),+ patch(+ "products.legal_documents.backend.logic.pandadoc.requests.patch", return_value=patch_response+ ) as mock_patch,+ ):+ pandadoc.PandaDocClient().void_document(document_id="doc_123")- with patch(- "products.legal_documents.backend.logic.pandadoc.requests.patch", return_value=fake_response- ) as mock_patch:+ if should_void:+ mock_patch.assert_called_once()+ args, kwargs = mock_patch.call_args+ self.assertEqual(args[0], "https://api.pandadoc.com/public/v1/documents/doc_123/status")+ self.assertEqual(kwargs["headers"]["Authorization"], "API-Key key")+ self.assertEqual(kwargs["json"], {"status": 11, "notify_recipients": True})+ else:+ mock_patch.assert_not_called()++ @override_settings(PANDADOC_API_KEY="key", PANDADOC_API_BASE_URL="https://api.pandadoc.com")+ def test_void_document_noop_when_envelope_already_gone(self) -> None:+ # A 404 from the status lookup means the envelope no longer exists on+ # PandaDoc's side — the state we wanted — so we skip the void entirely.+ get_response = MagicMock()+ get_response.status_code = 404+ get_response.text = "not found"++ with (+ patch("products.legal_documents.backend.logic.pandadoc.requests.get", return_value=get_response),+ patch("products.legal_documents.backend.logic.pandadoc.requests.patch") as mock_patch,+ ):pandadoc.PandaDocClient().void_document(document_id="doc_123")- mock_patch.assert_called_once()- args, kwargs = mock_patch.call_args- self.assertEqual(args[0], "https://api.pandadoc.com/public/v1/documents/doc_123/status")- self.assertEqual(kwargs["headers"]["Authorization"], "API-Key key")- self.assertEqual(kwargs["json"], {"status": 11, "notify_recipients": True})+ mock_patch.assert_not_called()- @override_settings(PANDADOC_API_KEY="key")+ @override_settings(PANDADOC_API_KEY="key", PANDADOC_API_BASE_URL="https://api.pandadoc.com")def test_void_document_can_opt_out_of_recipient_notification(self) -> None:# The caller may want to suppress the "your document was cancelled"# email — e.g., the recipient is wrong and we don't want them to even# know the original existed.- fake_response = MagicMock()- fake_response.status_code = 204-- with patch(- "products.legal_documents.backend.logic.pandadoc.requests.patch", return_value=fake_response- ) as mock_patch:+ patch_response = MagicMock()+ patch_response.status_code = 204++ with (+ patch(+ "products.legal_documents.backend.logic.pandadoc.requests.get",+ return_value=self._status_response("document.sent"),+ ),+ patch(+ "products.legal_documents.backend.logic.pandadoc.requests.patch", return_value=patch_response+ ) as mock_patch,+ ):pandadoc.PandaDocClient().void_document(document_id="doc_123", notify_recipients=False)self.assertEqual(mock_patch.call_args.kwargs["json"]["notify_recipients"], False)- @parameterized.expand(- [- # 404 = envelope already gone on PandaDoc's side; that's the state- # we wanted, so the helper treats it as success.- ("404_not_found_treated_as_success", 404, "not found", False),- # 423 = PandaDoc has the document locked for editing; surface to- # the caller so it can decide whether to retry or log + move on.- ("423_locked_raises", 423, "Document is locked for editing", True),- ]- )- @override_settings(PANDADOC_API_KEY="key")- def test_void_document_status_handling(self, _name: str, status_code: int, text: str, should_raise: bool) -> None:- fake_response = MagicMock()- fake_response.status_code = status_code- fake_response.text = text-- with patch("products.legal_documents.backend.logic.pandadoc.requests.patch", return_value=fake_response):- if should_raise:- with self.assertRaises(pandadoc.PandaDocError):- pandadoc.PandaDocClient().void_document(document_id="doc_123")- else:+ @override_settings(PANDADOC_API_KEY="key", PANDADOC_API_BASE_URL="https://api.pandadoc.com")+ def test_void_document_raises_when_void_of_live_envelope_fails(self) -> None:+ # A sent envelope PandaDoc refuses to void (e.g. 423 locked for editing)+ # must surface so the caller doesn't delete a row whose signing link is+ # still completable.+ patch_response = MagicMock()+ patch_response.status_code = 423+ patch_response.text = "Document is locked for editing"++ with (+ patch(+ "products.legal_documents.backend.logic.pandadoc.requests.get",+ return_value=self._status_response("document.sent"),+ ),+ patch("products.legal_documents.backend.logic.pandadoc.requests.patch", return_value=patch_response),+ ):+ with self.assertRaises(pandadoc.PandaDocError):pandadoc.PandaDocClient().void_document(document_id="doc_123")