Skip to content

: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.

fix(legal-documents): re-send envelopes stranded in PandaDoc draft from the reconcile sweep (#88709)

Matt Brookerdbb225cc266a
diff --git a/products/legal_documents/backend/facade/api.py b/products/legal_documents/backend/facade/api.py
index 510188e0f3ee..193e7129701c 100644
--- a/products/legal_documents/backend/facade/api.py
+++ b/products/legal_documents/backend/facade/api.py
@@ -12,6 +12,7 @@ from collections.abc import Callable
from uuid import UUID
from django.db import transaction
+from django.utils import timezone
import structlog
@@ -297,7 +298,9 @@ def reconcile_pending_signatures() -> contracts.LegalDocumentReconcileResult:
Safety net for the whole completion path. Polls PandaDoc for every row we
still think is out for signature and marks the completed ones — recovering
dropped, throttled, or 204'd `document.completed` webhooks and clearing the
- backlog. Also re-enqueues the archive for signed rows whose PDF never landed.
+ backlog. Also re-sends envelopes stranded in `document.draft` — PandaDoc's
+ send call can 409 and never dispatch the signing email — and re-enqueues
+ the archive for signed rows whose PDF never landed.
Each row is processed independently: `list_pending_signature_documents` is
ordered oldest-first, so one row that deterministically errors (a bad
@@ -305,6 +308,7 @@ def reconcile_pending_signatures() -> contracts.LegalDocumentReconcileResult:
15-minute tick.
"""
newly_signed = 0
+ drafts_resent = 0
errors = 0
pending_seen = 0
# PandaDoc allows 100 downloads a minute across the whole account, shared with
@@ -320,13 +324,22 @@ def reconcile_pending_signatures() -> contracts.LegalDocumentReconcileResult:
for document in logic.list_pending_signature_documents():
pending_seen += 1
try:
- if logic.get_pandadoc_document_status(document) == logic.PANDADOC_COMPLETED_STATUS:
+ pandadoc_status = logic.get_pandadoc_document_status(document)
+ if pandadoc_status == logic.PANDADOC_COMPLETED_STATUS:
if _try_mark_signed_and_schedule_archive(
document, capture=capture, delay_seconds=scheduled_archives
):
newly_signed += 1
scheduled_archives += 1
signed_this_run.add(document.id)
+ elif (
+ pandadoc_status == logic.PANDADOC_DRAFT_STATUS
+ and timezone.now() - document.created_at >= logic.RECONCILE_DRAFT_MIN_AGE
+ ):
+ if logic.send_pandadoc_envelope(document):
+ drafts_resent += 1
+ else:
+ errors += 1
except Exception as exc:
errors += 1
logger.exception("legal_document_reconcile_pending_row_failed", document_id=str(document.id))
@@ -358,5 +371,6 @@ def reconcile_pending_signatures() -> contracts.LegalDocumentReconcileResult:
return contracts.LegalDocumentReconcileResult(
newly_signed=newly_signed,
archives_requeued=archives_requeued,
+ drafts_resent=drafts_resent,
errors=errors,
)
diff --git a/products/legal_documents/backend/facade/contracts.py b/products/legal_documents/backend/facade/contracts.py
index f92530e900f3..ce0965e3ea5d 100644
--- a/products/legal_documents/backend/facade/contracts.py
+++ b/products/legal_documents/backend/facade/contracts.py
@@ -37,6 +37,7 @@ class LegalDocumentReconcileResult:
newly_signed: int
archives_requeued: int
+ drafts_resent: int
errors: int
diff --git a/products/legal_documents/backend/logic/__init__.py b/products/legal_documents/backend/logic/__init__.py
index 4221cd35a9ef..f801bd81c23d 100644
--- a/products/legal_documents/backend/logic/__init__.py
+++ b/products/legal_documents/backend/logic/__init__.py
@@ -167,6 +167,15 @@ def mark_signed_pdf_stored(document: LegalDocument) -> LegalDocument:
# PandaDoc status string for a fully-signed envelope. Mirrors the webhook layer.
PANDADOC_COMPLETED_STATUS = "document.completed"
+# PandaDoc status string for an envelope stuck before its signing email ever went
+# out — the state the reconcile sweep re-sends from.
+PANDADOC_DRAFT_STATUS = "document.draft"
+
+# A row created moments ago is normally about to get its own document.draft webhook;
+# re-sending from the sweep at the same time would duplicate the send and produce a
+# spurious 409 in error tracking.
+RECONCILE_DRAFT_MIN_AGE = timedelta(minutes=5)
+
# The reconciliation sweep polls PandaDoc once per pending row every 15 minutes, so
# bound the set: only rows created inside this window, capped per run. Two weeks is
# where the returns stop. Of the pending envelopes older than that, 2 of 162 ever
diff --git a/products/legal_documents/backend/tasks/tasks.py b/products/legal_documents/backend/tasks/tasks.py
index c060093a21e7..3b7eacafe33e 100644
--- a/products/legal_documents/backend/tasks/tasks.py
+++ b/products/legal_documents/backend/tasks/tasks.py
@@ -45,5 +45,6 @@ def reconcile_pending_legal_documents() -> None:
"legal_documents.reconcile_swept",
newly_signed=result.newly_signed,
archives_requeued=result.archives_requeued,
+ drafts_resent=result.drafts_resent,
errors=result.errors,
)
diff --git a/products/legal_documents/backend/tests/test_api.py b/products/legal_documents/backend/tests/test_api.py
index 41151a8ce0e1..07cb6daaa5da 100644
--- a/products/legal_documents/backend/tests/test_api.py
+++ b/products/legal_documents/backend/tests/test_api.py
@@ -20,6 +20,7 @@ from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.organization import Organization, OrganizationMembership
from products.legal_documents.backend.facade import api as legal_api
+from products.legal_documents.backend.logic.pandadoc import PandaDocError
from products.legal_documents.backend.models import LegalDocument
BAA_PAYLOAD = {
@@ -919,6 +920,73 @@ class TestLegalDocumentReconciliation(APIBaseTest):
self.document.refresh_from_db()
self.assertEqual(self.document.status, "submitted_for_signature")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.send_document")
+ def test_reconcile_resends_stale_draft_document(self, send_mock, status_mock) -> None:
+ status_mock.return_value = "document.draft"
+ LegalDocument.objects.filter(id=self.document.id).update(created_at=timezone.now() - timedelta(minutes=6))
+
+ result = legal_api.reconcile_pending_signatures()
+
+ send_mock.assert_called_once()
+ self.assertEqual(result.drafts_resent, 1)
+ self.assertEqual(result.archives_requeued, 0)
+ self.document.refresh_from_db()
+ self.assertEqual(self.document.status, "submitted_for_signature")
+
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.send_document")
+ def test_reconcile_skips_freshly_created_draft_document(self, send_mock, status_mock) -> None:
+ status_mock.return_value = "document.draft"
+
+ result = legal_api.reconcile_pending_signatures()
+
+ send_mock.assert_not_called()
+ self.assertEqual(result.drafts_resent, 0)
+
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.send_document")
+ def test_reconcile_counts_error_when_draft_resend_fails_and_continues(self, send_mock, status_mock) -> None:
+ later_org = Organization.objects.create(name="Later Co")
+ later = LegalDocument.objects.create(
+ organization=later_org,
+ document_type="DPA",
+ company_name="Later Co",
+ company_address="Elsewhere",
+ representative_email="[email protected]",
+ pandadoc_document_id="doc_later",
+ created_by=self.user,
+ )
+ now = timezone.now()
+ LegalDocument.objects.filter(id=self.document.id).update(created_at=now - timedelta(minutes=10))
+ LegalDocument.objects.filter(id=later.id).update(created_at=now - timedelta(minutes=9))
+
+ def status_side_effect(*, document_id):
+ return "document.draft" if document_id == "doc_123" else "document.completed"
+
+ status_mock.side_effect = status_side_effect
+ send_mock.side_effect = PandaDocError("boom")
+
+ with self._fake_pdf_pipeline(), self.captureOnCommitCallbacks(execute=True):
+ result = legal_api.reconcile_pending_signatures()
+
+ self.assertEqual(result.errors, 1)
+ self.assertEqual(result.drafts_resent, 0)
+ self.assertEqual(result.newly_signed, 1)
+ later.refresh_from_db()
+ self.assertEqual(later.status, "signed")
+
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.send_document")
+ def test_reconcile_ignores_document_sent_status(self, send_mock, status_mock) -> None:
+ status_mock.return_value = "document.sent"
+
+ result = legal_api.reconcile_pending_signatures()
+
+ send_mock.assert_not_called()
+ self.assertEqual(result.drafts_resent, 0)
+ self.assertEqual(result.newly_signed, 0)
+
@patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
def test_reconcile_continues_past_a_row_that_raises(self, status_mock) -> None:
# Each org can only hold one DPA (unique constraint), so the extra pending