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-create PandaDoc envelopes the sweep finds missing (#95342)

Matt Brookerb869308cf6d6
diff --git a/products/legal_documents/backend/facade/api.py b/products/legal_documents/backend/facade/api.py
index ee1f438e9c2a..c2ce42950b0e 100644
--- a/products/legal_documents/backend/facade/api.py
+++ b/products/legal_documents/backend/facade/api.py
@@ -9,6 +9,7 @@ output, and never leaks ORM instances or QuerySets across the boundary.
from __future__ import annotations
from collections.abc import Callable
+from datetime import timedelta
from uuid import UUID
from django.db import transaction
@@ -315,6 +316,37 @@ def archive_signed_pdf(document_id: UUID) -> None:
logic.mark_signed_pdf_stored(document)
+def _time_since_touched(document: LegalDocument) -> timedelta:
+ # updated_at is nullable on the model.
+ return timezone.now() - (document.updated_at or document.created_at)
+
+
+def _recreate_lost_envelope(document: LegalDocument) -> bool:
+ """
+ PandaDoc no longer has the envelope for a row still out for signature, so
+ the customer can never be emailed from it. Confirms the envelope is truly
+ gone before superseding it, records that in error tracking, then creates a
+ fresh envelope from the row's own data.
+ """
+ if not logic.confirm_pandadoc_envelope_gone(document):
+ return False
+ lost_pandadoc_document_id = document.pandadoc_document_id
+ logger.warning(
+ "legal_document_pandadoc_envelope_lost",
+ document_id=str(document.id),
+ pandadoc_document_id=lost_pandadoc_document_id,
+ )
+ capture_exception(
+ Exception("PandaDoc envelope no longer exists for a legal document still out for signature"),
+ additional_properties={
+ "legal_document_id": str(document.id),
+ "pandadoc_document_id": lost_pandadoc_document_id,
+ "organization_id": str(document.organization_id),
+ },
+ )
+ return logic.retry_pandadoc_envelope(document)
+
+
def reconcile_pending_signatures() -> contracts.LegalDocumentReconcileResult:
"""
Safety net for the whole completion path. Polls PandaDoc for every row we
@@ -327,16 +359,19 @@ def reconcile_pending_signatures() -> contracts.LegalDocumentReconcileResult:
Each row is processed independently: `list_pending_signature_documents` is
ordered oldest-first, so one row that deterministically errors (a bad
PandaDoc response, a DB hiccup) must not block every row behind it on every
- 15-minute tick.
+ 15-minute tick. Also retries envelope creation for rows whose PandaDoc
+ envelope disappeared or was never created.
"""
newly_signed = 0
drafts_resent = 0
+ envelopes_recreated = 0
errors = 0
pending_seen = 0
# PandaDoc allows 100 downloads a minute across the whole account, shared with
# live signings. Staggering one archive per second keeps a backlog drain from
# starving a customer signing right now, and holds regardless of worker count.
scheduled_archives = 0
+ recreate_attempts = 0
signed_this_run: set[UUID] = set()
# One scoped client for the whole loop, not one per row: this runs in a Celery
# worker, where the global client's background flush may never run before the
@@ -356,12 +391,23 @@ def reconcile_pending_signatures() -> contracts.LegalDocumentReconcileResult:
signed_this_run.add(document.id)
elif (
pandadoc_status == logic.PANDADOC_DRAFT_STATUS
- and timezone.now() - document.created_at >= logic.RECONCILE_DRAFT_MIN_AGE
+ and _time_since_touched(document) >= logic.RECONCILE_DRAFT_MIN_AGE
):
if logic.send_pandadoc_envelope(document):
drafts_resent += 1
else:
errors += 1
+ elif (
+ pandadoc_status == logic.PANDADOC_ENVELOPE_MISSING
+ and _time_since_touched(document) >= logic.RECONCILE_RECREATE_MIN_AGE
+ and recreate_attempts < logic.RECONCILE_MAX_RECREATES_PER_RUN
+ ):
+ if logic.claim_pandadoc_envelope_retry(document):
+ recreate_attempts += 1
+ if _recreate_lost_envelope(document):
+ envelopes_recreated += 1
+ else:
+ errors += 1
except Exception as exc:
errors += 1
logger.exception("legal_document_reconcile_pending_row_failed", document_id=str(document.id))
@@ -377,6 +423,29 @@ def reconcile_pending_signatures() -> contracts.LegalDocumentReconcileResult:
cap=logic.RECONCILE_MAX_PER_RUN,
)
+ for document in logic.list_pending_documents_missing_envelope():
+ if recreate_attempts >= logic.RECONCILE_MAX_RECREATES_PER_RUN:
+ logger.warning(
+ "legal_document_reconcile_recreate_cap_reached",
+ attempted=recreate_attempts,
+ cap=logic.RECONCILE_MAX_RECREATES_PER_RUN,
+ )
+ break
+ if _time_since_touched(document) < logic.RECONCILE_RECREATE_MIN_AGE:
+ continue
+ try:
+ if not logic.claim_pandadoc_envelope_retry(document):
+ continue
+ recreate_attempts += 1
+ if logic.retry_pandadoc_envelope(document):
+ envelopes_recreated += 1
+ else:
+ errors += 1
+ except Exception as exc:
+ errors += 1
+ logger.exception("legal_document_reconcile_missing_envelope_row_failed", document_id=str(document.id))
+ capture_exception(exc, additional_properties={"legal_document_id": str(document.id)})
+
# Rows this run just signed and already scheduled an archive for above.
# excluding them here is what keeps the archive from being `.delay()`'d twice.
archives_requeued = 0
@@ -394,5 +463,6 @@ def reconcile_pending_signatures() -> contracts.LegalDocumentReconcileResult:
newly_signed=newly_signed,
archives_requeued=archives_requeued,
drafts_resent=drafts_resent,
+ envelopes_recreated=envelopes_recreated,
errors=errors,
)
diff --git a/products/legal_documents/backend/facade/contracts.py b/products/legal_documents/backend/facade/contracts.py
index ce0965e3ea5d..6b727175d94a 100644
--- a/products/legal_documents/backend/facade/contracts.py
+++ b/products/legal_documents/backend/facade/contracts.py
@@ -38,6 +38,7 @@ class LegalDocumentReconcileResult:
newly_signed: int
archives_requeued: int
drafts_resent: int
+ envelopes_recreated: int
errors: int
diff --git a/products/legal_documents/backend/logic/__init__.py b/products/legal_documents/backend/logic/__init__.py
index f1cd56e76b61..7704d6759944 100644
--- a/products/legal_documents/backend/logic/__init__.py
+++ b/products/legal_documents/backend/logic/__init__.py
@@ -194,11 +194,19 @@ PANDADOC_COMPLETED_STATUS = "document.completed"
# out — the state the reconcile sweep re-sends from.
PANDADOC_DRAFT_STATUS = "document.draft"
+# Pseudo-status returned by get_pandadoc_document_status when PandaDoc 404s the
+# envelope. PandaDoc never sends this string itself.
+PANDADOC_ENVELOPE_MISSING = "envelope.missing"
+
# 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)
+# Throttles envelope re-creation per row so a still-processing create isn't
+# mistaken for a lost envelope and retried on every 15-minute tick.
+RECONCILE_RECREATE_MIN_AGE = timedelta(hours=1)
+
# 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
@@ -206,6 +214,10 @@ RECONCILE_DRAFT_MIN_AGE = timedelta(minutes=5)
_RECONCILE_LOOKBACK = timedelta(days=14)
RECONCILE_MAX_PER_RUN = 500
+# Spreads a burst of re-creates across ticks so one tick stays under PandaDoc's
+# per-minute rate limit.
+RECONCILE_MAX_RECREATES_PER_RUN = 20
+
def list_pending_signature_documents() -> QuerySet[LegalDocument]:
"""
@@ -224,6 +236,21 @@ def list_pending_signature_documents() -> QuerySet[LegalDocument]:
)
+def list_pending_documents_missing_envelope() -> QuerySet[LegalDocument]:
+ """
+ Rows still submitted for signature whose PandaDoc envelope was never
+ created: the initial create call failed and left the id empty.
+ `list_pending_signature_documents` excludes these forever, so the sweep
+ retries their creation from here instead.
+ """
+ cutoff = timezone.now() - _RECONCILE_LOOKBACK
+ return LegalDocument.objects.filter(
+ status=LegalDocument.Status.SUBMITTED_FOR_SIGNATURE,
+ pandadoc_document_id="",
+ created_at__gte=cutoff,
+ ).order_by("created_at")[:RECONCILE_MAX_PER_RUN]
+
+
def list_signed_documents_missing_pdf(exclude_ids: Iterable[UUID] = ()) -> QuerySet[LegalDocument]:
"""
Signed rows whose PDF never made it to object storage — the background
@@ -246,15 +273,16 @@ def list_signed_documents_missing_pdf(exclude_ids: Iterable[UUID] = ()) -> Query
def get_pandadoc_document_status(document: LegalDocument) -> str | None:
"""
- Ask PandaDoc for the envelope's current status. Returns None when we can't
- reach PandaDoc or the envelope is gone — the caller skips the row this round
- and retries on the next tick.
+ Ask PandaDoc for the envelope's current status. Returns
+ PANDADOC_ENVELOPE_MISSING when PandaDoc 404s the envelope, or None when we
+ can't tell because the call itself failed; the caller retries a None on
+ the next tick rather than treating a transient error as a gone envelope.
"""
if not document.pandadoc_document_id:
return None
client = pandadoc_client.PandaDocClient()
try:
- return client.get_document_status(document_id=document.pandadoc_document_id)
+ status = client.get_document_status(document_id=document.pandadoc_document_id)
except pandadoc_client.PandaDocError as exc:
logger.warning(
"legal_document_pandadoc_status_poll_failed",
@@ -263,6 +291,7 @@ def get_pandadoc_document_status(document: LegalDocument) -> str | None:
error=str(exc),
)
return None
+ return status if status is not None else PANDADOC_ENVELOPE_MISSING
def delete_document(document: LegalDocument, *, strict_pandadoc: bool = False) -> None:
@@ -551,6 +580,59 @@ def create_pandadoc_envelope(document: LegalDocument) -> str | None:
return None
+def confirm_pandadoc_envelope_gone(document: LegalDocument) -> bool:
+ """
+ A 404 from the status GET isn't proof the envelope is actually gone; a
+ transient or false 404 looks identical. Attempting the void write is the
+ second opinion: a 404 there confirms PandaDoc purged it, a 2xx means it
+ was still live and is now voided, and any other response means it still
+ exists in a state PandaDoc won't void, so the caller must not supersede it.
+ """
+ client = pandadoc_client.PandaDocClient()
+ try:
+ status_code = client.force_void_document(document_id=document.pandadoc_document_id)
+ except pandadoc_client.PandaDocError as exc:
+ logger.warning(
+ "legal_document_pandadoc_envelope_not_confirmed_gone",
+ document_id=str(document.id),
+ pandadoc_document_id=document.pandadoc_document_id,
+ error=str(exc),
+ )
+ return False
+ if status_code == 404:
+ return True
+ logger.warning(
+ "legal_document_pandadoc_envelope_voided_before_recreate",
+ document_id=str(document.id),
+ pandadoc_document_id=document.pandadoc_document_id,
+ )
+ return True
+
+
+def claim_pandadoc_envelope_retry(document: LegalDocument) -> bool:
+ """
+ Stamp `updated_at` only when it still holds the value this run loaded.
+ Overlapping sweep runs race on this one conditional update, so only the
+ winner goes on to call PandaDoc. The stamp doubles as the throttle that
+ `RECONCILE_RECREATE_MIN_AGE` measures from.
+ """
+ claimed = LegalDocument.objects.filter(id=document.id, updated_at=document.updated_at).update(
+ updated_at=timezone.now()
+ )
+ if claimed:
+ document.refresh_from_db(fields=["updated_at"])
+ return bool(claimed)
+
+
+def retry_pandadoc_envelope(document: LegalDocument) -> bool:
+ """
+ Re-attempt envelope creation for a row whose PandaDoc envelope is missing
+ or was never created. The caller claims the row with
+ `claim_pandadoc_envelope_retry` first.
+ """
+ return create_pandadoc_envelope(document) is not None
+
+
def send_pandadoc_envelope(document: LegalDocument) -> bool:
"""
Dispatch the signing email for a previously-created PandaDoc envelope.
diff --git a/products/legal_documents/backend/logic/pandadoc.py b/products/legal_documents/backend/logic/pandadoc.py
index cb2e3f3096d4..88313a47b92b 100644
--- a/products/legal_documents/backend/logic/pandadoc.py
+++ b/products/legal_documents/backend/logic/pandadoc.py
@@ -286,6 +286,20 @@ class PandaDocClient:
{"status": _PANDADOC_STATUS_VOIDED, "notify_recipients": notify_recipients},
)
+ def force_void_document(self, *, document_id: str) -> int:
+ """
+ Void an envelope without the status pre-check `void_document` does. Use
+ this when the status GET's answer is itself suspect and a definitive
+ second opinion is needed: a 404 here confirms PandaDoc has genuinely
+ purged the envelope, a 2xx confirms it was still live and is now
+ voided, and any other response raises PandaDocError because PandaDoc
+ still holds it in a state it refuses to void (e.g. still rendering).
+ """
+ return self._patch(
+ f"/public/v1/documents/{document_id}/status",
+ {"status": _PANDADOC_STATUS_VOIDED, "notify_recipients": False},
+ )
+
@contextmanager
def stream_document(self, *, document_id: str) -> Iterator[IO[bytes]]:
"""
diff --git a/products/legal_documents/backend/presentation/webhook.py b/products/legal_documents/backend/presentation/webhook.py
index 03133dffa494..60baf1864e75 100644
--- a/products/legal_documents/backend/presentation/webhook.py
+++ b/products/legal_documents/backend/presentation/webhook.py
@@ -122,7 +122,7 @@ def legal_document_pandadoc_webhook(request: Request) -> Response:
processed_any = True
continue
- # Other states (document.sent, document.viewed, …) — nothing to do.
+ logger.info("pandadoc_webhook_state_ignored", status=event_status, pandadoc_document_id=pandadoc_document_id)
if processed_any:
return Response({"status": "ok"}, status=status.HTTP_200_OK)
diff --git a/products/legal_documents/backend/tasks/tasks.py b/products/legal_documents/backend/tasks/tasks.py
index 3b7eacafe33e..65265e83e360 100644
--- a/products/legal_documents/backend/tasks/tasks.py
+++ b/products/legal_documents/backend/tasks/tasks.py
@@ -46,5 +46,6 @@ def reconcile_pending_legal_documents() -> None:
newly_signed=result.newly_signed,
archives_requeued=result.archives_requeued,
drafts_resent=result.drafts_resent,
+ envelopes_recreated=result.envelopes_recreated,
errors=result.errors,
)
diff --git a/products/legal_documents/backend/tests/test_api.py b/products/legal_documents/backend/tests/test_api.py
index 07cb6daaa5da..206d100782e8 100644
--- a/products/legal_documents/backend/tests/test_api.py
+++ b/products/legal_documents/backend/tests/test_api.py
@@ -19,7 +19,9 @@ from rest_framework import status
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.organization import Organization, OrganizationMembership
+from products.legal_documents.backend import logic
from products.legal_documents.backend.facade import api as legal_api
+from products.legal_documents.backend.logic import pandadoc as pandadoc_module
from products.legal_documents.backend.logic.pandadoc import PandaDocError
from products.legal_documents.backend.models import LegalDocument
@@ -628,16 +630,23 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):
response = self._post_raw(body, self._sign(body))
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
- def test_uninteresting_state_event_is_noop(self) -> None:
- # document.sent / document.viewed / etc. — we only act on draft + completed.
+ @parameterized.expand([("document.sent",), ("document.viewed",), ("document.error",)])
+ def test_uninteresting_state_event_is_noop(self, event_status: str) -> None:
+ # Only draft and completed change state; everything else is logged and dropped.
payload = self._completed_payload()
- payload[0]["data"]["status"] = "document.sent"
+ payload[0]["data"]["status"] = event_status
body = json.dumps(payload).encode("utf-8")
- with self._override():
+ with (
+ self._override(),
+ patch("products.legal_documents.backend.presentation.webhook.logger") as logger_mock,
+ ):
response = self._post_raw(body, self._sign(body))
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
self.document.refresh_from_db()
self.assertEqual(self.document.status, "submitted_for_signature")
+ logger_mock.info.assert_any_call(
+ "pandadoc_webhook_state_ignored", status=event_status, pandadoc_document_id="doc_123"
+ )
def test_draft_event_dispatches_send(self) -> None:
body = json.dumps(self._draft_payload()).encode("utf-8")
@@ -924,7 +933,7 @@ class TestLegalDocumentReconciliation(APIBaseTest):
@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))
+ LegalDocument.objects.filter(id=self.document.id).update(updated_at=timezone.now() - timedelta(minutes=6))
result = legal_api.reconcile_pending_signatures()
@@ -944,6 +953,23 @@ class TestLegalDocumentReconciliation(APIBaseTest):
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_skips_draft_document_recently_updated_despite_old_created_at(
+ self, send_mock, status_mock
+ ) -> None:
+ # A re-created envelope gets its own grace window, measured from updated_at.
+ status_mock.return_value = "document.draft"
+ LegalDocument.objects.filter(id=self.document.id).update(
+ created_at=timezone.now() - timedelta(days=1),
+ updated_at=timezone.now() - timedelta(minutes=1),
+ )
+
+ 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:
@@ -958,7 +984,7 @@ class TestLegalDocumentReconciliation(APIBaseTest):
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=self.document.id).update(updated_at=now - timedelta(minutes=10))
LegalDocument.objects.filter(id=later.id).update(created_at=now - timedelta(minutes=9))
def status_side_effect(*, document_id):
@@ -1036,6 +1062,189 @@ class TestLegalDocumentReconciliation(APIBaseTest):
self.assertEqual(middle.status, "submitted_for_signature")
self.assertEqual(last.status, "signed")
+ @parameterized.expand(
+ [
+ ("old_enough", timedelta(hours=2), 1),
+ ("too_recent", timedelta(minutes=10), 0),
+ ]
+ )
+ @override_settings(PANDADOC_DPA_TEMPLATE_ID="tpl_dpa")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.force_void_document")
+ @patch("products.legal_documents.backend.facade.api.capture_exception")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.create_document_from_template")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ def test_reconcile_recreates_envelope_when_pandadoc_reports_it_missing(
+ self, _name, age, expected_recreated, status_mock, create_mock, capture_mock, void_mock
+ ) -> None:
+ status_mock.return_value = None
+ void_mock.return_value = 404
+ create_mock.return_value = pandadoc_module.PandaDocDocument(id="doc_new", status="document.uploaded", name="x")
+ LegalDocument.objects.filter(id=self.document.id).update(updated_at=timezone.now() - age)
+
+ result = legal_api.reconcile_pending_signatures()
+
+ self.assertEqual(result.envelopes_recreated, expected_recreated)
+ self.assertEqual(create_mock.called, bool(expected_recreated))
+ self.assertEqual(capture_mock.called, bool(expected_recreated))
+ self.assertEqual(void_mock.called, bool(expected_recreated))
+ if expected_recreated:
+ create_kwargs = create_mock.call_args.kwargs
+ self.assertEqual(create_kwargs["tokens"]["Client.Company"], self.document.company_name)
+ self.assertEqual(create_kwargs["tokens"]["Client.StreetAddress"], self.document.company_address)
+ self.assertIn(
+ self.document.representative_email,
+ [recipient.email for recipient in create_kwargs["recipients"]],
+ )
+ captured_exc = capture_mock.call_args.args[0]
+ self.assertEqual(
+ str(captured_exc), "PandaDoc envelope no longer exists for a legal document still out for signature"
+ )
+ additional = capture_mock.call_args.kwargs["additional_properties"]
+ self.assertEqual(additional["legal_document_id"], str(self.document.id))
+ self.assertEqual(additional["pandadoc_document_id"], "doc_123")
+ self.document.refresh_from_db()
+ self.assertEqual(self.document.pandadoc_document_id, "doc_new")
+ else:
+ self.document.refresh_from_db()
+ self.assertEqual(self.document.pandadoc_document_id, "doc_123")
+
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.create_document_from_template")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.force_void_document")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ def test_reconcile_skips_recreate_claimed_by_another_run(self, status_mock, void_mock, create_mock) -> None:
+ # An overlapping sweep run stamps updated_at (its own successful claim,
+ # or a fresh webhook) between this run loading the row and reaching the
+ # recreate branch. This run's claim must lose the race and do nothing.
+ LegalDocument.objects.filter(id=self.document.id).update(updated_at=timezone.now() - timedelta(hours=2))
+
+ def status_side_effect(*, document_id): # noqa: ARG001
+ LegalDocument.objects.filter(id=self.document.id).update(updated_at=timezone.now())
+ return None
+
+ status_mock.side_effect = status_side_effect
+
+ result = legal_api.reconcile_pending_signatures()
+
+ void_mock.assert_not_called()
+ create_mock.assert_not_called()
+ self.assertEqual(result.envelopes_recreated, 0)
+ self.assertEqual(result.errors, 0)
+ self.document.refresh_from_db()
+ self.assertEqual(self.document.pandadoc_document_id, "doc_123")
+
+ @override_settings(PANDADOC_DPA_TEMPLATE_ID="tpl_dpa")
+ @patch("products.legal_documents.backend.facade.api.capture_exception")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.create_document_from_template")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.force_void_document")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ def test_reconcile_keeps_envelope_when_void_says_it_still_exists(
+ self, status_mock, void_mock, create_mock, capture_mock
+ ) -> None:
+ status_mock.return_value = None
+ void_mock.side_effect = PandaDocError(
+ "PandaDoc /public/v1/documents/doc_123/status returned 409: still rendering"
+ )
+ LegalDocument.objects.filter(id=self.document.id).update(updated_at=timezone.now() - timedelta(hours=2))
+
+ result = legal_api.reconcile_pending_signatures()
+
+ create_mock.assert_not_called()
+ capture_mock.assert_not_called()
+ self.assertEqual(result.envelopes_recreated, 0)
+ self.assertEqual(result.errors, 1)
+ self.document.refresh_from_db()
+ self.assertEqual(self.document.pandadoc_document_id, "doc_123")
+ assert self.document.updated_at is not None
+ self.assertGreaterEqual(self.document.updated_at, timezone.now() - timedelta(minutes=1))
+
+ @override_settings(PANDADOC_DPA_TEMPLATE_ID="tpl_dpa")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.create_document_from_template")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.force_void_document")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ def test_reconcile_recreates_after_voiding_live_envelope(self, status_mock, void_mock, create_mock) -> None:
+ status_mock.return_value = None
+ void_mock.return_value = 204
+ create_mock.return_value = pandadoc_module.PandaDocDocument(id="doc_new", status="document.uploaded", name="x")
+ LegalDocument.objects.filter(id=self.document.id).update(updated_at=timezone.now() - timedelta(hours=2))
+
+ result = legal_api.reconcile_pending_signatures()
+
+ create_mock.assert_called_once()
+ self.assertEqual(result.envelopes_recreated, 1)
+
+ @parameterized.expand(
+ [
+ ("old_enough", timedelta(hours=2), 1),
+ ("too_recent", timedelta(minutes=10), 0),
+ ]
+ )
+ @override_settings(PANDADOC_DPA_TEMPLATE_ID="tpl_dpa")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.create_document_from_template")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ def test_reconcile_creates_envelope_for_row_missing_pandadoc_id(
+ self, _name, age, expected_recreated, status_mock, create_mock
+ ) -> None:
+ status_mock.return_value = "document.sent"
+ create_mock.return_value = pandadoc_module.PandaDocDocument(id="doc_new", status="document.uploaded", name="x")
+ org = self.create_organization_with_features([])
+ document = LegalDocument.objects.create(
+ organization=org,
+ document_type="DPA",
+ company_name="No Envelope Co",
+ company_address="Nowhere",
+ representative_email="[email protected]",
+ pandadoc_document_id="",
+ created_by=self.user,
+ )
+ LegalDocument.objects.filter(id=document.id).update(updated_at=timezone.now() - age)
+
+ result = legal_api.reconcile_pending_signatures()
+
+ self.assertEqual(result.envelopes_recreated, expected_recreated)
+ self.assertEqual(create_mock.called, bool(expected_recreated))
+ document.refresh_from_db()
+ self.assertEqual(document.pandadoc_document_id, "doc_new" if expected_recreated else "")
+
+ @override_settings(PANDADOC_DPA_TEMPLATE_ID="tpl_dpa")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.create_document_from_template")
+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
+ def test_reconcile_caps_envelope_recreates_per_run(self, status_mock, create_mock) -> None:
+ status_mock.return_value = "document.sent"
+ create_mock.return_value = pandadoc_module.PandaDocDocument(id="doc_new", status="document.uploaded", name="x")
+ documents = []
+ for i, created_age in enumerate((timedelta(hours=4), timedelta(hours=3), timedelta(hours=2))):
+ org = self.create_organization_with_features([])
+ document = LegalDocument.objects.create(
+ organization=org,
+ document_type="DPA",
+ company_name=f"No Envelope Co {i}",
+ company_address="Nowhere",
+ representative_email=f"noenv{i}@other.example",
+ pandadoc_document_id="",
+ created_by=self.user,
+ )
+ LegalDocument.objects.filter(id=document.id).update(
+ updated_at=timezone.now() - timedelta(hours=2),
+ created_at=timezone.now() - created_age,
+ )
+ documents.append(document)
+
+ with patch.object(logic, "RECONCILE_MAX_RECREATES_PER_RUN", 2):
+ result = legal_api.reconcile_pending_signatures()
+
+ self.assertEqual(create_mock.call_count, 2)
+ self.assertEqual(result.envelopes_recreated, 2)
+ documents[2].refresh_from_db()
+ self.assertEqual(documents[2].pandadoc_document_id, "")
+
+ create_mock.reset_mock()
+ with patch.object(logic, "RECONCILE_MAX_RECREATES_PER_RUN", 2):
+ legal_api.reconcile_pending_signatures()
+
+ self.assertEqual(create_mock.call_count, 1)
+ documents[2].refresh_from_db()
+ self.assertEqual(documents[2].pandadoc_document_id, "doc_new")
+
@patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status")
def test_reconcile_schedules_archive_once_for_newly_signed_row(self, status_mock) -> None:
status_mock.return_value = "document.completed"
@@ -1106,16 +1315,26 @@ class TestLegalDocumentReconciliation(APIBaseTest):
self.assertTrue(self.organization.is_ai_data_processing_approved)
def test_reconcile_leaves_pending_document_alone_when_pandadoc_unreachable(self) -> None:
+ # A transient failure is not a gone envelope; re-creating would strand a live signer.
from products.legal_documents.backend.logic import pandadoc as pandadoc_module
- with patch(
- "products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status",
- side_effect=pandadoc_module.PandaDocError("network boom"),
+ with (
+ patch(
+ "products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.get_document_status",
+ side_effect=pandadoc_module.PandaDocError("network boom"),
+ ),
+ patch(
+ "products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.create_document_from_template"
+ ) as create_mock,
+ patch("products.legal_documents.backend.facade.api.capture_exception") as capture_mock,
):
result = legal_api.reconcile_pending_signatures()
self.assertEqual(result.newly_signed, 0)
+ self.assertEqual(result.envelopes_recreated, 0)
self.assertEqual(result.errors, 0)
+ create_mock.assert_not_called()
+ capture_mock.assert_not_called()
self.document.refresh_from_db()
self.assertEqual(self.document.status, "submitted_for_signature")
diff --git a/products/legal_documents/backend/tests/test_logic.py b/products/legal_documents/backend/tests/test_logic.py
index 10c086a1505f..31c7bc0d6fcd 100644
--- a/products/legal_documents/backend/tests/test_logic.py
+++ b/products/legal_documents/backend/tests/test_logic.py
@@ -4,8 +4,10 @@ from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.test import override_settings
+from django.utils import timezone
from products.legal_documents.backend.logic import (
+ claim_pandadoc_envelope_retry,
delete_document,
pandadoc as pandadoc_module,
)
@@ -128,3 +130,41 @@ class TestDeleteDocument(APIBaseTest):
delete_document(document)
mock_pandadoc_cls.assert_not_called()
+
+
+class TestClaimPandadocEnvelopeRetry(APIBaseTest):
+ def _document(self, **overrides: Any) -> LegalDocument:
+ defaults: dict[str, Any] = {
+ "organization": self.organization,
+ "document_type": "DPA",
+ "company_name": "Acme, Inc.",
+ "company_address": "1 Analytics Way",
+ "representative_email": "[email protected]",
+ "pandadoc_document_id": "doc_123",
+ }
+ defaults.update(overrides)
+ return LegalDocument.objects.create(**defaults)
+
+ def test_claims_and_advances_updated_at_when_in_memory_value_matches_db(self) -> None:
+ document = self._document()
+ original_updated_at = document.updated_at
+ assert original_updated_at is not None
+
+ claimed = claim_pandadoc_envelope_retry(document)
+
+ self.assertTrue(claimed)
+ assert document.updated_at is not None
+ self.assertGreater(document.updated_at, original_updated_at)
+ document.refresh_from_db()
+ assert document.updated_at is not None
+ self.assertGreater(document.updated_at, original_updated_at)
+
+ def test_loses_claim_when_row_was_stamped_after_this_run_loaded_it(self) -> None:
+ document = self._document()
+ LegalDocument.objects.filter(id=document.id).update(updated_at=timezone.now())
+ db_updated_at = LegalDocument.objects.get(id=document.id).updated_at
+
+ claimed = claim_pandadoc_envelope_retry(document)
+
+ self.assertFalse(claimed)
+ self.assertEqual(LegalDocument.objects.get(id=document.id).updated_at, db_updated_at)
diff --git a/products/legal_documents/backend/tests/test_pandadoc.py b/products/legal_documents/backend/tests/test_pandadoc.py
index 74ac24326085..6685412b9657 100644
--- a/products/legal_documents/backend/tests/test_pandadoc.py
+++ b/products/legal_documents/backend/tests/test_pandadoc.py
@@ -319,3 +319,46 @@ class TestPandaDocClient(TestCase):
):
with self.assertRaises(pandadoc.PandaDocError):
pandadoc.PandaDocClient().void_document(document_id="doc_123")
+
+ @override_settings(PANDADOC_API_KEY="key", PANDADOC_API_BASE_URL="https://api.pandadoc.com")
+ def test_force_void_document_returns_404_without_status_pre_check(self) -> None:
+ patch_response = MagicMock()
+ patch_response.status_code = 404
+ patch_response.text = "not found"
+
+ with (
+ patch("products.legal_documents.backend.logic.pandadoc.requests.get") as mock_get,
+ patch(
+ "products.legal_documents.backend.logic.pandadoc.requests.patch", return_value=patch_response
+ ) as mock_patch,
+ ):
+ result = pandadoc.PandaDocClient().force_void_document(document_id="doc_123")
+
+ self.assertEqual(result, 404)
+ mock_get.assert_not_called()
+ mock_patch.assert_called_once()
+
+ @override_settings(PANDADOC_API_KEY="key", PANDADOC_API_BASE_URL="https://api.pandadoc.com")
+ def test_force_void_document_voids_a_live_envelope(self) -> None:
+ patch_response = MagicMock()
+ patch_response.status_code = 204
+
+ with patch(
+ "products.legal_documents.backend.logic.pandadoc.requests.patch", return_value=patch_response
+ ) as mock_patch:
+ result = pandadoc.PandaDocClient().force_void_document(document_id="doc_123")
+
+ self.assertEqual(result, 204)
+ args, kwargs = mock_patch.call_args
+ self.assertEqual(args[0], "https://api.pandadoc.com/public/v1/documents/doc_123/status")
+ self.assertEqual(kwargs["json"], {"status": 11, "notify_recipients": False})
+
+ @override_settings(PANDADOC_API_KEY="key", PANDADOC_API_BASE_URL="https://api.pandadoc.com")
+ def test_force_void_document_raises_when_pandadoc_refuses(self) -> None:
+ patch_response = MagicMock()
+ patch_response.status_code = 409
+ patch_response.text = "Document is still rendering"
+
+ with patch("products.legal_documents.backend.logic.pandadoc.requests.patch", return_value=patch_response):
+ with self.assertRaises(pandadoc.PandaDocError):
+ pandadoc.PandaDocClient().force_void_document(document_id="doc_123")