: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(legal-documents): refetch a signed PDF from PandaDoc in the admin (#94177)
Rafael Audiberte411cc92808b
diff --git a/products/legal_documents/backend/admin.py b/products/legal_documents/backend/admin.pyindex cae4bfd5ad74..9946a5c167a9 100644--- a/products/legal_documents/backend/admin.py+++ b/products/legal_documents/backend/admin.py@@ -2,12 +2,13 @@ from typing import IO, Any, castfrom django import formsfrom django.contrib import admin, messages-from django.core.exceptions import ValidationError+from django.contrib.admin.utils import unquote+from django.core.exceptions import PermissionDenied, ValidationErrorfrom django.core.files.uploadedfile import UploadedFilefrom django.core.validators import FileExtensionValidatorfrom django.db import IntegrityError, transaction-from django.http import HttpRequest, HttpResponse-from django.urls import reverse+from django.http import Http404, HttpRequest, HttpResponse, HttpResponseRedirect+from django.urls import URLPattern, path, reversefrom django.utils.html import format_htmlfrom django.utils.safestring import SafeString@@ -68,6 +69,28 @@ class LegalDocumentAdminForm(forms.ModelForm):return pdf+# What a delete does depends on the row's status, and the signed case is the one+# staff get wrong: `logic.delete_document` skips the PandaDoc void for signed rows,+# and nothing restores the AI opt-out that a signed BAA applied.+_SIGNED_DELETE_NOTE = (+ "Deleting a signed document removes the PostHog record and the stored PDF. "+ "It does not change the document in PandaDoc, because PandaDoc cannot void a completed document. "+ "Delete or archive it in PandaDoc yourself. "+ "For a BAA, the organization keeps AI data processing and AI training turned off after the delete. "+ "An owner can turn them back on in organization settings."+)++_UNSIGNED_DELETE_NOTE = (+ "Deleting a document that is out for signature voids its PandaDoc envelope. "+ "PandaDoc tells the signer that the document is canceled, so the old signing link stops working."+)++_REFETCH_UNAVAILABLE_NOTE = (+ "PandaDoc only serves a final PDF once a document is signed, and this document has no PandaDoc envelope "+ "or is still out for signature. There is nothing to refetch."+)++@admin.register(LegalDocument)class LegalDocumentAdmin(admin.ModelAdmin):# FK to posthog.Organization — without this the add view renders a <select>@@ -93,6 +116,7 @@ class LegalDocumentAdmin(admin.ModelAdmin):)ordering = ("-created_at",)show_full_result_count = False+ change_form_template = "admin/legal_documents/legaldocument_change_form.html"list_select_related = ("organization", "created_by")actions = ("resend_signing_email",)@@ -265,6 +289,57 @@ class LegalDocumentAdmin(admin.ModelAdmin):"envelope is no longer sendable. Check the logs and try again shortly.",)+ @staticmethod+ def _can_refetch_pdf(document: LegalDocument) -> bool:+ # PandaDoc only has a final PDF for a completed envelope. Storing anything+ # else would put an unsigned document behind the customer download link.+ return document.status == LegalDocument.Status.SIGNED and bool(document.pandadoc_document_id)++ def get_urls(self) -> list[URLPattern]:+ # Custom route first: the admin's own `<path:object_id>/` catch-all+ # would otherwise swallow it and redirect to the change page.+ return [+ path(+ "<path:object_id>/refetch-pdf/",+ self.admin_site.admin_view(self.refetch_pdf_view),+ name=f"{self.opts.app_label}_{self.opts.model_name}_refetch_pdf",+ ),+ *super().get_urls(),+ ]++ def refetch_pdf_view(self, request: HttpRequest, object_id: str) -> HttpResponse:+ """+ Pull the document PandaDoc serves right now and overwrite our stored+ copy. Recovers a row whose archive job failed every retry, and refreshes+ a copy that no longer matches PandaDoc (e.g., a counter-signature added+ after we archived).+ """+ if request.method != "POST":+ raise PermissionDenied+ document = cast(LegalDocument | None, self.get_object(request, unquote(object_id)))+ if document is None:+ raise Http404+ change_url = reverse(+ f"admin:{self.opts.app_label}_{self.opts.model_name}_change",+ args=[document.pk],+ current_app=self.admin_site.name,+ )++ if not self._can_refetch_pdf(document):+ messages.warning(request, _REFETCH_UNAVAILABLE_NOTE)+ return HttpResponseRedirect(change_url)++ if logic.download_and_store_signed_pdf(document):+ logic.mark_signed_pdf_stored(document)+ messages.success(request, "Refetched the PDF from PandaDoc. The stored copy now matches PandaDoc.")+ else:+ messages.error(+ request,+ "Could not refetch the PDF from PandaDoc. PandaDoc may be unreachable, or object storage may be "+ "unavailable. The stored copy is unchanged. Check the logs and try again.",+ )+ return HttpResponseRedirect(change_url)+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 via@@ -300,8 +375,34 @@ class LegalDocumentAdmin(admin.ModelAdmin):"deployments, listed rows (if any) are read-only historical records and ""the PandaDoc integration is disabled.",)+ document = cast(LegalDocument | None, self.get_object(request, unquote(object_id)))+ self._note_delete_behavior(request, document)+ extra_context = {**(extra_context or {}), "refetch_pdf_url": self._refetch_pdf_url(document)}return super().change_view(request, object_id, form_url, extra_context=extra_context)+ def _refetch_pdf_url(self, document: LegalDocument | None) -> str | None:+ if document is None or not self._can_refetch_pdf(document):+ return None+ return reverse(+ f"admin:{self.opts.app_label}_{self.opts.model_name}_refetch_pdf",+ args=[document.pk],+ current_app=self.admin_site.name,+ )++ def delete_view(+ self, request: HttpRequest, object_id: str, extra_context: dict[str, Any] | None = None+ ) -> HttpResponse:+ self._note_delete_behavior(request, cast(LegalDocument | None, self.get_object(request, unquote(object_id))))+ return super().delete_view(request, object_id, extra_context=extra_context)++ def _note_delete_behavior(self, request: HttpRequest, document: LegalDocument | None) -> None:+ if document is None:+ return+ if document.status == LegalDocument.Status.SIGNED:+ messages.warning(request, _SIGNED_DELETE_NOTE)+ else:+ messages.info(request, _UNSIGNED_DELETE_NOTE)+@admin.display(description="Organization", ordering="organization__name")def organization_link(self, document: LegalDocument) -> SafeString:url = reverse("admin:posthog_organization_change", args=[document.organization_id])diff --git a/products/legal_documents/backend/templates/admin/legal_documents/legaldocument_change_form.html b/products/legal_documents/backend/templates/admin/legal_documents/legaldocument_change_form.htmlnew file mode 100644index 000000000000..937672e5406c--- /dev/null+++ b/products/legal_documents/backend/templates/admin/legal_documents/legaldocument_change_form.html@@ -0,0 +1,38 @@+{% extends "admin/change_form.html" %}+{% block extrastyle %}{{ block.super }}+ <style>+ /* Django styles object-tools entries as anchors. The refetch control changes+ state, so it is a POST form, and it borrows those styles to match. */+ .object-tools form { display: inline; }+ .object-tools form button {+ /* Match the anchor box exactly: buttons default to border-box and a normal+ line-height, which makes the pill shorter than its neighbors. */+ box-sizing: content-box;+ line-height: 20px;+ padding: 3px 12px;+ border: none;+ border-radius: 15px;+ background: var(--object-tools-bg);+ color: var(--object-tools-fg);+ font-family: inherit;+ font-size: 0.6875rem;+ font-weight: 400;+ letter-spacing: 0.5px;+ text-transform: uppercase;+ cursor: pointer;+ }+ .object-tools form button:hover,+ .object-tools form button:focus { background: var(--object-tools-hover-bg); }+ </style>+{% endblock %}+{% block object-tools-items %}+ {% if refetch_pdf_url %}+ <li>+ <form method="post" action="{{ refetch_pdf_url }}">+ {% csrf_token %}+ <button type="submit">Refetch PDF from PandaDoc</button>+ </form>+ </li>+ {% endif %}+ {{ block.super }}+{% endblock %}diff --git a/products/legal_documents/backend/tests/test_admin.py b/products/legal_documents/backend/tests/test_admin.pyindex 2e06ac7d8887..9e21ad392759 100644--- a/products/legal_documents/backend/tests/test_admin.py+++ b/products/legal_documents/backend/tests/test_admin.py@@ -1,13 +1,15 @@-from typing import Any+from typing import Any, castfrom posthog.test.base import APIBaseTestfrom unittest.mock import patchfrom django.contrib.admin import AdminSitefrom django.contrib.admin.widgets import AutocompleteSelect+from django.contrib.messages import get_messagesfrom django.contrib.messages.storage.fallback import FallbackStorage-from django.core.exceptions import ValidationError+from django.core.exceptions import PermissionDenied, ValidationErrorfrom django.core.files.uploadedfile import SimpleUploadedFile, UploadedFile+from django.template.response import TemplateResponsefrom django.test import RequestFactoryfrom django.utils.datastructures import MultiValueDict@@ -379,6 +381,120 @@ class TestLegalDocumentAdminSave(APIBaseTest):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")+ def _signed_document(self, **overrides: Any) -> LegalDocument:+ fields: dict[str, Any] = {+ "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_123",+ }+ fields.update(overrides)+ return LegalDocument.objects.create(**fields)++ def _refetch_request(self, document: LegalDocument, method: str = "post") -> Any:+ request = getattr(self.request_factory, method)(f"/admin/posthog/legaldocument/{document.id}/refetch-pdf/")+ request.user = self.user+ _attach_messages(request)+ return request++ @patch("products.legal_documents.backend.admin.logic.download_and_store_signed_pdf", return_value=True)+ def test_refetch_stores_the_pandadoc_pdf_and_marks_the_row_stored(self, mock_download: Any) -> None:+ document = self._signed_document(signed_pdf_stored=False)++ response = self.admin.refetch_pdf_view(self._refetch_request(document), str(document.id))++ mock_download.assert_called_once()+ document.refresh_from_db()+ self.assertTrue(document.signed_pdf_stored)+ self.assertEqual(response.status_code, 302)++ @patch("products.legal_documents.backend.admin.logic.download_and_store_signed_pdf", return_value=False)+ def test_refetch_failure_leaves_the_stored_copy_alone(self, _mock_download: Any) -> None:+ document = self._signed_document(signed_pdf_stored=True)+ request = self._refetch_request(document)++ self.admin.refetch_pdf_view(request, str(document.id))++ self.assertIn("Could not refetch", " ".join(str(message) for message in get_messages(request)))++ @parameterized.expand(+ [+ ("out_for_signature", {"status": LegalDocument.Status.SUBMITTED_FOR_SIGNATURE}),+ ("no_envelope", {"pandadoc_document_id": ""}),+ ]+ )+ @patch("products.legal_documents.backend.admin.logic.download_and_store_signed_pdf")+ def test_refetch_never_downloads_what_pandadoc_cannot_serve(+ self, _name: str, overrides: dict[str, Any], mock_download: Any+ ) -> None:+ # A PDF pulled for anything but a completed envelope would land behind+ # the customer-facing download link as if it were the signed document.+ document = self._signed_document(signed_pdf_stored=False, **overrides)++ self.admin.refetch_pdf_view(self._refetch_request(document), str(document.id))++ mock_download.assert_not_called()+ document.refresh_from_db()+ self.assertFalse(document.signed_pdf_stored)++ @patch("products.legal_documents.backend.admin.logic.download_and_store_signed_pdf")+ def test_refetch_rejects_a_get(self, mock_download: Any) -> None:+ # A refetch overwrites stored bytes, so a prefetched or crawled link+ # must not trigger one.+ document = self._signed_document()++ with self.assertRaises(PermissionDenied):+ self.admin.refetch_pdf_view(self._refetch_request(document, method="get"), str(document.id))++ mock_download.assert_not_called()++ @parameterized.expand(+ [+ ("signed_with_envelope", {}, True),+ ("out_for_signature", {"status": LegalDocument.Status.SUBMITTED_FOR_SIGNATURE}, False),+ ("no_envelope", {"pandadoc_document_id": ""}, False),+ ]+ )+ def test_change_view_offers_the_refetch_button_only_when_pandadoc_can_serve(+ self, _name: str, overrides: dict[str, Any], expected: bool+ ) -> None:+ document = self._signed_document(**overrides)+ request = self.request_factory.get(f"/admin/posthog/legaldocument/{document.id}/")+ request.user = self.user+ _attach_messages(request)++ response = cast(TemplateResponse, self.admin.change_view(request, str(document.id)))+ response.render()++ self.assertEqual(b"Refetch PDF from PandaDoc" in response.content, expected)++ @parameterized.expand(+ [+ (LegalDocument.Status.SIGNED, "cannot void a completed document"),+ (LegalDocument.Status.SUBMITTED_FOR_SIGNATURE, "voids its PandaDoc envelope"),+ ]+ )+ def test_delete_confirmation_explains_what_the_delete_does(self, status: str, expected_fragment: str) -> None:+ document = LegalDocument.objects.create(+ organization=self.organization,+ document_type="BAA",+ company_name="Acme, Inc.",+ company_address="1 Analytics Way",+ representative_email="[email protected]",+ status=status,+ pandadoc_document_id="doc_123",+ )+ request = self.request_factory.get(f"/admin/posthog/legaldocument/{document.id}/delete/")+ request.user = self.user+ _attach_messages(request)++ self.admin.delete_view(request, str(document.id))++ self.assertIn(expected_fragment, " ".join(str(message) for message in get_messages(request)))+class TestLegalDocumentAdminPermissions(APIBaseTest):def setUp(self) -> None: