: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): allow self-serve deletion of unsigned DPAs/BAAs (#58879)
Christiaan Hendriksenb66d6d53eb46
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5b55aa83e25f..5e35240216bf 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5343,9 +5343,9 @@ snapshots:scenes-app-insights-worldmap--default--light:hash: v1.k794b7964.c19ba4d6c010a3d6756839b4b26d00017492a4fdd0b6df8e483ba7b7a3c0c979.AHuX5vDwY0FLv9I5NuvPfoazaytArdUqYZLmhQO8Pa0scenes-app-legal-documents--legal-documents-list--dark:- hash: v1.k794b7964.53a4adc4cee3db5800ff22ea70e7ad0263d0d79604c95aad6b0d0f7375969494.WTab5X5FpLy3EDzY_A7khji_n-wnEs0BqMDlVLhzG0c+ hash: v1.k794b7964.588a97be73b42aec3fdd93e4535f7046702b31c49cd197738720260eef417602.bl7OWu-_oywQ7s9QyNn-Hw3oN2K7Ag1nnX7rkaLJGTUscenes-app-legal-documents--legal-documents-list--light:- hash: v1.k794b7964.1c74e9536c8d013978f304ebadafd9abf96fc5e66fae962cda2bfac8c33ac525.qiSUCbPI8cuqvQ0kn8C9E-E96XVkl35xUz25yZg7llc+ hash: v1.k794b7964.fcbaffa042d1a0609a3ee9de8588e783bd6a433ce30942f7a66dc069c22b5ba4.U0N2LiTM14gAHi85SHCoKGXXUgS-ywvlh_gfHond_cEscenes-app-legal-documents--new-baa--dark:hash: v1.k794b7964.e4f0d779732dd74b9be51cfcb33fb6e1fb2f7a462856f47326fc73c901e36dad.dxNpZGOmoLe6EMM6_RKD1bgh2c-49vADarjT0sum8JQscenes-app-legal-documents--new-baa--light:diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambrindex 5baa5600e7e2..85ef7482f958 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr@@ -179,6 +179,60 @@use_hive_partitioning=0'''# ---+# name: TestExperimentMeanMetric.test_conversion_window_extends_to_last_exposure_1_precomputed+ '''+ WITH exposures AS+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,+ if(ifNull(greater(uniqExact(t.variant), 1), 0), '$multiple', argMin(t.variant, toTimeZone(t.first_exposure_time, 'UTC'))) AS variant,+ min(toTimeZone(t.first_exposure_time, 'UTC')) AS first_exposure_time,+ max(toTimeZone(t.last_exposure_time, 'UTC')) AS last_exposure_time,+ argMin(t.exposure_event_uuid, toTimeZone(t.first_exposure_time, 'UTC')) AS exposure_event_uuid,+ argMin(t.exposure_session_id, toTimeZone(t.first_exposure_time, 'UTC')) AS exposure_session_id+ FROM experiment_exposures_preaggregated AS t+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), greaterOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-10 00:00:00', 'UTC'))))+ GROUP BY entity_id),+ metric_events AS+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,+ toTimeZone(events.timestamp, 'UTC') AS timestamp,+ coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'amount'), ''), 'null'), '^"|"$', ''), 'Float64'), 0) AS value+ FROM events+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-10 00:00:00', 'UTC')), toIntervalSecond(86400))), equals(events.event, 'purchase'))),+ entity_metrics AS+ (SELECT exposures.entity_id AS entity_id,+ exposures.variant AS variant,+ sum(coalesce(accurateCastOrNull(metric_events.value, 'Float64'), 0)) AS value+ FROM exposures+ LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), exposures.first_exposure_time), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(exposures.last_exposure_time, toIntervalSecond(86400)))))+ GROUP BY exposures.entity_id,+ exposures.variant)+ SELECT entity_metrics.variant AS variant,+ count(entity_metrics.entity_id) AS num_users,+ sum(entity_metrics.value) AS total_sum,+ sum(power(entity_metrics.value, 2)) AS total_sum_of_squares+ FROM entity_metrics+ GROUP BY entity_metrics.variant+ LIMIT 50000 SETTINGS join_algorithm='grace_hash',+ grace_hash_join_initial_buckets=2,+ load_balancing='in_order',+ readonly=2,+ max_execution_time=600,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=39728447488,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestExperimentMeanMetric.test_count_distinct_property_values_via_hogql_0_direct'''WITH exposures ASdiff --git a/products/legal_documents/backend/admin.py b/products/legal_documents/backend/admin.pyindex 331b43c456c6..0d8cd04fef51 100644--- a/products/legal_documents/backend/admin.py+++ b/products/legal_documents/backend/admin.py@@ -16,6 +16,7 @@ import structlogfrom posthog.cloud_utils import is_cloud, is_dev_modefrom posthog.storage import object_storage+from . import logicfrom .models import LegalDocumentfrom .storage import signed_pdf_storage_key@@ -232,26 +233,19 @@ class LegalDocumentAdmin(admin.ModelAdmin):) from excdef delete_model(self, request: HttpRequest, obj: LegalDocument) -> None:- self._delete_signed_pdf(obj)- super().delete_model(request, obj)+ # Shared helper voids the PandaDoc envelope, removes the S3 object,+ # and deletes the row (firing the activity-log entry via+ # ModelActivityMixin). The same helper backs the public DELETE+ # endpoint — admin keeps the privilege of deleting signed rows by+ # calling the helper directly rather than going through the facade.+ logic.delete_document(obj)def delete_queryset(self, request: HttpRequest, queryset: Any) -> None:+ # Per-row delete (rather than queryset.delete()) so each row fires its+ # own activity-log delete and so the shared helper can run its+ # PandaDoc + S3 cleanup against each envelope individually.for obj in queryset:- self._delete_signed_pdf(obj)- super().delete_queryset(request, queryset)-- @staticmethod- def _delete_signed_pdf(obj: LegalDocument) -> None:- try:- object_storage.delete(signed_pdf_storage_key(obj))- except Exception as exc:- # Best effort — the row is going away regardless. Worst case a stale- # PDF lingers in S3 with no row referencing it.- logger.warning(- "legal_document_admin_pdf_delete_failed",- document_id=str(obj.id),- error=str(exc),- )+ logic.delete_document(obj)def changelist_view(self, request: HttpRequest, extra_context: dict[str, Any] | None = None) -> HttpResponse:if not (is_cloud() or is_dev_mode()):diff --git a/products/legal_documents/backend/facade/api.py b/products/legal_documents/backend/facade/api.pyindex c7baffe06b3c..55539b15ad14 100644--- a/products/legal_documents/backend/facade/api.py+++ b/products/legal_documents/backend/facade/api.py@@ -10,10 +10,15 @@ from __future__ import annotationsfrom uuid import UUID+from django.db import transaction+from posthog.models.organization import Organizationfrom .. import logic-from ..logic.pandadoc import verify_webhook_signature as _verify_pandadoc_webhook_signature+from ..logic.pandadoc import (+ PandaDocError,+ verify_webhook_signature as _verify_pandadoc_webhook_signature,+)from ..models import LegalDocumentfrom . import contractsfrom .enums import LegalDocumentStatus@@ -79,6 +84,78 @@ def exists_for_organization_and_type(organization_id: UUID, document_type: str)return logic.exists_for_organization_and_type(organization_id, document_type)+class LegalDocumentNotFound(Exception):+ """Raised when a delete targets a row that doesn't exist (or belongs to a different org)."""+++class LegalDocumentAlreadySigned(Exception):+ """Raised when a delete targets a row in `signed` state, which is admin-only."""+++class LegalDocumentVoidFailed(Exception):+ """+ Raised when the PandaDoc envelope void during a self-serve delete fails.+ The row was not deleted (the surrounding transaction rolled back). The+ caller should surface a retriable error to the user so they don't end up+ in the broken state where the row is gone but the envelope is still+ signable.+ """+++def delete_document(document_id: UUID, organization_id: UUID) -> None:+ """+ Self-serve deletion entry point for org admins.++ Wrapped in a transaction with `select_for_update` so we can't race a+ concurrent `document.completed` webhook flipping status to signed+ between the gate check and the delete. The lock is held for the+ duration of the PandaDoc void (normally subsecond, up to a 30s timeout+ in the worst case). Webhooks landing concurrently either lose the race+ and see the row gone (404 → no-op in the webhook handler) or win and+ flip status before our `select_for_update` resolves; in that second+ case our re-check raises LegalDocumentAlreadySigned and rolls back.++ PandaDoc void runs in strict mode here: a PandaDoc error rolls back the+ whole transaction (row stays, frontend retries). Better than telling+ the user the envelope was cancelled when it wasn't and leaving the+ original signer with a still-completable document.++ Refuses signed documents — those are completed legal artifacts and stay+ admin-only (Django admin bypasses this guard by calling+ `logic.delete_document` directly with `strict_pandadoc=False`).++ Raises:+ LegalDocumentNotFound: row doesn't exist or belongs to a different org.+ LegalDocumentAlreadySigned: row is signed at lock time.+ LegalDocumentVoidFailed: PandaDoc void failed; row was not deleted.+ """+ try:+ with transaction.atomic():+ try:+ document = LegalDocument.objects.select_for_update().get(+ id=document_id, organization_id=organization_id+ )+ except LegalDocument.DoesNotExist:+ raise LegalDocumentNotFound(+ f"Legal document {document_id} not found for organization {organization_id}"+ )+ if document.status == LegalDocumentStatus.SIGNED:+ raise LegalDocumentAlreadySigned(+ f"Legal document {document_id} is already signed and can't be deleted from the self-serve UI"+ )+ # The PandaDoc void runs inside the row lock on purpose: if it+ # ran after commit, a void failure would leave the row deleted+ # but the envelope still signable. Holding the lock through a+ # (rare, slow-path) HTTP call is the deliberate trade for+ # making the row delete and the void atomic from the user's+ # perspective.+ logic.delete_document(document, strict_pandadoc=True)+ except PandaDocError as exc:+ raise LegalDocumentVoidFailed(+ f"Failed to cancel the PandaDoc envelope for legal document {document_id}: {exc}"+ ) from exc++def create_document(data: contracts.CreateLegalDocumentInput) -> contracts.LegalDocumentDTO:document = logic.create_document(organization_id=data.organization_id,diff --git a/products/legal_documents/backend/logic/__init__.py b/products/legal_documents/backend/logic/__init__.pyindex 0aab93791ca0..b10fd56b1aa5 100644--- a/products/legal_documents/backend/logic/__init__.py+++ b/products/legal_documents/backend/logic/__init__.py@@ -130,6 +130,71 @@ def mark_document_signed(document: LegalDocument) -> LegalDocument:return document+def delete_document(document: LegalDocument, *, strict_pandadoc: bool = False) -> None:+ """+ Remove a legal document end-to-end.++ Three things may need to go away depending on document state: the PandaDoc+ envelope (only meaningful for in-flight, unsigned envelopes — completed+ envelopes can't be voided and PandaDoc returns 423), the signed PDF in+ object storage (only present once the row is signed), and the database+ row itself. The row delete triggers `ModelActivityMixin` since+ `LegalDocument` has `activity_logging_on_delete = True`, so the audit+ trail is automatic.++ `strict_pandadoc` controls failure handling on the PandaDoc void:+ - True (self-serve path): re-raise PandaDocError so the facade's+ transaction rolls back. The user gets a 503 and can retry. The+ row stays put — better that than telling the user the envelope+ was cancelled when it wasn't.+ - False (admin path, default): log + capture and continue. Staff+ can verify envelope state manually, and best-effort matches the+ historic admin contract.+ """+ # Only call PandaDoc for in-flight envelopes. Signed envelopes have+ # already completed on PandaDoc's side; voiding them would 409/423 and+ # generate Sentry noise on every staff delete of a counter-signed+ # document. Voiding (status transition) is preferred over a hard delete+ # so PandaDoc retains the audit record of the cancelled signing process.+ if document.pandadoc_document_id and document.status != LegalDocument.Status.SIGNED:+ try:+ pandadoc_client.PandaDocClient().void_document(document_id=document.pandadoc_document_id)+ except pandadoc_client.PandaDocError as exc:+ if strict_pandadoc:+ raise+ logger.warning(+ "legal_document_pandadoc_void_failed",+ document_id=str(document.id),+ pandadoc_document_id=document.pandadoc_document_id,+ error=str(exc),+ )+ capture_exception(+ exc,+ additional_properties={+ "legal_document_id": str(document.id),+ "pandadoc_document_id": document.pandadoc_document_id,+ },+ )++ # S3 only holds the PDF once the row is signed (PandaDoc webhook streams+ # it in on completion, or admin uploads it directly). Skip the round-trip+ # for unsigned rows that never had a PDF in the first place.+ if document.status == LegalDocument.Status.SIGNED and settings.OBJECT_STORAGE_ENABLED:+ try:+ object_storage.delete(signed_pdf_storage_key(document))+ except Exception as exc:+ # No capture_exception here: object_storage.delete already+ # captures the underlying boto error, and double-capturing+ # pollutes Sentry without adding signal.+ logger.warning(+ "legal_document_signed_pdf_delete_failed",+ document_id=str(document.id),+ error=str(exc),+ )++ document.delete()++# Customer.io template name for the email sent to org owners when we auto opt# them out of AI data processing because they signed a BAA. Wired through# CUSTOMER_IO_TEMPLATE_ID_MAP in posthog/email.py.diff --git a/products/legal_documents/backend/logic/pandadoc.py b/products/legal_documents/backend/logic/pandadoc.pyindex ddda8cb8053a..f311ee5e9091 100644--- a/products/legal_documents/backend/logic/pandadoc.py+++ b/products/legal_documents/backend/logic/pandadoc.py@@ -1,9 +1,10 @@"""Thin client for the PandaDoc public API.-We only hit two endpoints:- POST /public/v1/documents -> create a document from a template- POST /public/v1/documents/{id}/send -> email the signing envelope+We hit three endpoints:+ POST /public/v1/documents -> create a document from a template+ POST /public/v1/documents/{id}/send -> email the signing envelope+ PATCH /public/v1/documents/{id}/status -> move an envelope to voided (no longer signable)Plus one helper for verifying the HMAC signature on inbound webhooks. Keepingthis file free of Django/DRF imports so it's straightforward to unit test.@@ -29,6 +30,12 @@ logger = structlog.get_logger(__name__)DEFAULT_TIMEOUT_SECONDS = 30+# PandaDoc encodes document statuses as small integers in the status-change API.+# 11 is `document.voided` — the document is no longer available for signature+# but stays in PandaDoc as an audit record of the cancelled signing process.+# See https://developers.pandadoc.com/reference/change-document-status-manually+_PANDADOC_STATUS_VOIDED = 11+class PandaDocError(Exception):"""Raised when the PandaDoc API returns a non-2xx response or we fail to reach it."""@@ -96,6 +103,23 @@ class PandaDocClient: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+ callers can distinguish a successful change (204) from a "no-op,+ already gone" (404) without inspecting an exception.+ """+ url = f"{self._base_url}{path}"+ try:+ response = requests.patch(url, headers=self._headers(), json=json, timeout=self._timeout)+ except requests.RequestException as exc:+ raise PandaDocError(f"Network error calling PandaDoc {path}: {exc}") from exc+ if response.status_code == 404:+ return response.status_code+ if response.status_code >= 400:+ raise PandaDocError(f"PandaDoc {path} returned {response.status_code}: {response.text[:500]}")+ return response.status_code+@contextmanagerdef _get_stream(self, path: str) -> Iterator[IO[bytes]]:"""@@ -178,6 +202,27 @@ class PandaDocClient:payload["sender"] = {"email": sender_email}self._post(f"/public/v1/documents/{document_id}/send", payload)+ 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.++ `notify_recipients=True` sends PandaDoc's standard "this document was+ cancelled" email to the original signer, so they're not left+ wondering 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.+ """+ self._patch(+ f"/public/v1/documents/{document_id}/status",+ {"status": _PANDADOC_STATUS_VOIDED, "notify_recipients": notify_recipients},+ )+@contextmanagerdef stream_document(self, *, document_id: str) -> Iterator[IO[bytes]]:"""diff --git a/products/legal_documents/backend/presentation/views.py b/products/legal_documents/backend/presentation/views.pyindex 286bae9193db..f02d03150c57 100644--- a/products/legal_documents/backend/presentation/views.py+++ b/products/legal_documents/backend/presentation/views.py@@ -18,6 +18,16 @@ from .permissions import IsCloudOrDevDeployment, IsOrganizationAdminOrOwnerfrom .serializers import CreateLegalDocumentSerializer, LegalDocumentSerializer+class _PandaDocUnavailable(exceptions.APIException):+ """503 surfaced when a self-serve delete couldn't cancel the PandaDoc envelope."""++ status_code = status.HTTP_503_SERVICE_UNAVAILABLE+ default_detail = (+ "Couldn't cancel the PandaDoc envelope. Please try again, or contact PostHog support if this keeps happening."+ )+ default_code = "legal_document_void_failed"++class LegalDocumentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "legal_document"permission_classes = [IsCloudOrDevDeployment, permissions.IsAuthenticated, IsOrganizationAdminOrOwner]@@ -90,3 +100,32 @@ class LegalDocumentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):if not presigned_url:raise exceptions.NotFound()return HttpResponseRedirect(presigned_url)++ @extend_schema(responses={204: None, 403: None, 404: None, 503: None})+ def destroy(self, request: Request, pk: str, **kwargs) -> Response:+ """+ Delete an unsigned legal document. The PandaDoc envelope is voided+ first so the original signer can no longer complete it; only if that+ succeeds is the row removed, freeing the unique-per-org-per-type+ constraint so a fresh document can be generated.++ Returns 503 if the PandaDoc void fails — the row stays in that case+ and the frontend should prompt the user to retry. Returns 403 for+ signed documents (legal artifacts; staff can still delete signed+ rows from Django admin).+ """+ try:+ document_id = UUID(pk)+ except (ValueError, DjangoValidationError):+ raise exceptions.NotFound()+ try:+ api.delete_document(document_id, self.organization.id)+ except api.LegalDocumentNotFound:+ raise exceptions.NotFound()+ except api.LegalDocumentAlreadySigned:+ raise exceptions.PermissionDenied(+ "Signed documents can't be deleted from the UI. Contact PostHog support if you need to remove a signed record."+ )+ except api.LegalDocumentVoidFailed:+ raise _PandaDocUnavailable()+ return Response(status=status.HTTP_204_NO_CONTENT)diff --git a/products/legal_documents/backend/tests/test_admin.py b/products/legal_documents/backend/tests/test_admin.pyindex aba345efdc3e..2508878c197d 100644--- a/products/legal_documents/backend/tests/test_admin.py+++ b/products/legal_documents/backend/tests/test_admin.py@@ -165,8 +165,14 @@ class TestLegalDocumentAdminSave(APIBaseTest):self.assertFalse(form.is_valid())self.assertEqual(LegalDocument.objects.filter(document_type="DPA").count(), 1)- @patch("products.legal_documents.backend.admin.object_storage")- def test_delete_model_cleans_up_s3(self, mock_storage: Any) -> None:+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ @patch("products.legal_documents.backend.logic.object_storage")+ def test_delete_model_for_signed_row_cleans_up_s3_and_skips_pandadoc(+ self, mock_storage: Any, mock_pandadoc_cls: Any+ ) -> None:+ # Signed rows have a PDF in S3 (PandaDoc completion webhook stashed it,+ # or admin uploaded it) and a completed envelope on PandaDoc that can't+ # be voided. Helper deletes the S3 object and skips the PandaDoc call.document = LegalDocument.objects.create(organization=self.organization,document_type="MSA",@@ -174,6 +180,7 @@ class TestLegalDocumentAdminSave(APIBaseTest):company_address="1 Analytics Way",representative_email="[email protected]",status=LegalDocument.Status.SIGNED,+ pandadoc_document_id="doc_123",)# Snapshot before delete: obj.delete() clears the pk on the in-memory# instance, so signed_pdf_storage_key(document) would compute against@@ -183,8 +190,53 @@ class TestLegalDocumentAdminSave(APIBaseTest):self.admin.delete_model(self._request(), document)mock_storage.delete.assert_called_once_with(expected_key)+ mock_pandadoc_cls.assert_not_called()+ self.assertFalse(LegalDocument.objects.filter(id=document_id).exists())++ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ @patch("products.legal_documents.backend.logic.object_storage")+ def test_delete_model_for_unsigned_row_voids_pandadoc_and_skips_s3(+ self, mock_storage: Any, mock_pandadoc_cls: Any+ ) -> None:+ # Unsigned rows have an in-flight PandaDoc envelope that should be+ # voided so the original recipient can't still complete it. No PDF+ # exists in S3 until completion, so the S3 call is skipped.+ document = 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_123",+ )+ document_id = document.id+ self.admin.delete_model(self._request(), document)++ mock_pandadoc_cls.return_value.void_document.assert_called_once_with(document_id="doc_123")+ mock_storage.delete.assert_not_called()self.assertFalse(LegalDocument.objects.filter(id=document_id).exists())+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ @patch("products.legal_documents.backend.logic.object_storage")+ def test_delete_model_skips_pandadoc_void_when_no_envelope_id(+ self, _mock_storage: Any, mock_pandadoc_cls: Any+ ) -> None:+ # If the row was never bound to a PandaDoc envelope (e.g., admin-uploaded+ # MSA, or PandaDoc create failed during the original flow) there's+ # nothing to void — the client shouldn't even be instantiated.+ document = 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.SIGNED,+ pandadoc_document_id="",+ )+ self.admin.delete_model(self._request(), document)+ mock_pandadoc_cls.assert_not_called()+def test_add_form_uses_autocomplete_for_organization(self) -> None:# The organization FK must render an autocomplete widget, not the default# <select> — the latter loads every org row into the page and times out@@ -214,9 +266,12 @@ class TestLegalDocumentAdminSave(APIBaseTest):# subclass returned by modelform_factory has no extra non-model fields.)self.assertNotIn("signed_pdf", change_form_class.base_fields)- @patch("products.legal_documents.backend.admin.object_storage")- def test_delete_model_swallows_s3_errors(self, mock_storage: Any) -> None:+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ @patch("products.legal_documents.backend.logic.object_storage")+ def test_delete_model_swallows_s3_errors(self, mock_storage: Any, _mock_pandadoc_cls: Any) -> None:# If S3 cleanup fails the row should still be deleted — best-effort cleanup.+ # PandaDocClient is patched as defense-in-depth so this test never makes+ # a real network call if the fixture sprouts a pandadoc_document_id.mock_storage.delete.side_effect = RuntimeError("s3 down")document = LegalDocument.objects.create(organization=self.organization,@@ -232,6 +287,45 @@ class TestLegalDocumentAdminSave(APIBaseTest):self.assertFalse(LegalDocument.objects.filter(id=document_id).exists())+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ @patch("products.legal_documents.backend.logic.object_storage")+ def test_delete_queryset_fires_per_row_pandadoc_voids_and_deletes_rows(+ self, _mock_storage: Any, mock_pandadoc_cls: Any+ ) -> None:+ # Bulk delete via the changelist must call the shared logic helper+ # once per row (not queryset.delete()) so each envelope gets voided+ # individually and each row fires its own activity-log entry.+ other_org = type(self.organization).objects.create(name="Other Co")+ first = 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_111",+ )+ second = LegalDocument.objects.create(+ organization=other_org,+ document_type="DPA",+ company_name="Other Co",+ company_address="Elsewhere",+ representative_email="[email protected]",+ status=LegalDocument.Status.SUBMITTED_FOR_SIGNATURE,+ pandadoc_document_id="doc_222",+ )++ queryset = LegalDocument.objects.filter(id__in=[first.id, second.id])+ self.admin.delete_queryset(self._request(), queryset)++ # Two distinct PandaDoc void calls, one per row.+ self.assertEqual(mock_pandadoc_cls.return_value.void_document.call_count, 2)+ called_ids = {+ call.kwargs["document_id"] for call in mock_pandadoc_cls.return_value.void_document.call_args_list+ }+ self.assertEqual(called_ids, {"doc_111", "doc_222"})+ self.assertFalse(LegalDocument.objects.filter(id__in=[first.id, second.id]).exists())+class TestLegalDocumentAdminPermissions(APIBaseTest):def setUp(self) -> None:diff --git a/products/legal_documents/backend/tests/test_api.py b/products/legal_documents/backend/tests/test_api.pyindex 077842a91ad5..abf833332223 100644--- a/products/legal_documents/backend/tests/test_api.py+++ b/products/legal_documents/backend/tests/test_api.py@@ -330,6 +330,144 @@ class TestLegalDocumentDownloadEndpoint(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_302_FOUND)+@override_settings(CLOUD_DEPLOYMENT="US")+class TestLegalDocumentDeleteEndpoint(APIBaseTest):+ """+ Self-serve DELETE for an unsigned legal document. Voids the underlying+ PandaDoc envelope, removes the row, and frees the+ unique-per-org-per-type constraint so a fresh document can be generated+ (e.g., with a different signer). Signed documents stay admin-only.+ """++ def setUp(self) -> None:+ super().setUp()+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ self.document = LegalDocument.objects.create(+ organization=self.organization,+ document_type="DPA",+ company_name="Acme, Inc.",+ company_address="1 Analytics Way",+ representative_email="[email protected]",+ pandadoc_document_id="doc_123",+ created_by=self.user,+ )+ self.url = f"/api/organizations/{self.organization.id}/legal_documents/{self.document.id}/"++ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ def test_unsigned_document_deletes_and_voids_pandadoc(self, mock_pandadoc_cls) -> None:+ response = self.client.delete(self.url)++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT, response.content)+ self.assertFalse(LegalDocument.objects.filter(id=self.document.id).exists())+ mock_pandadoc_cls.return_value.void_document.assert_called_once_with(document_id="doc_123")++ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ def test_delete_frees_unique_constraint_so_new_dpa_can_be_created(self, _mock_pandadoc_cls) -> None:+ # The whole point of the feature: after deleting an unsigned DPA, a+ # second POST with a corrected signer should succeed.+ list_url = f"/api/organizations/{self.organization.id}/legal_documents/"+ blocked = self.client.post(list_url, DPA_PAYLOAD, format="json")+ self.assertEqual(blocked.status_code, status.HTTP_400_BAD_REQUEST)++ deleted = self.client.delete(self.url)+ self.assertEqual(deleted.status_code, status.HTTP_204_NO_CONTENT, deleted.content)++ replacement = self.client.post(+ list_url,+ {**DPA_PAYLOAD, "representative_email": "[email protected]"},+ format="json",+ )+ self.assertEqual(replacement.status_code, status.HTTP_201_CREATED, replacement.content)+ new_row = LegalDocument.objects.get(id=replacement.json()["id"])+ self.assertEqual(new_row.representative_email, "[email protected]")++ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ def test_signed_document_cannot_be_deleted_via_api(self, mock_pandadoc_cls) -> None:+ # The facade re-reads the row under select_for_update inside the+ # delete transaction, so a webhook that flips status to signed+ # between request start and lock acquisition lands here too — the+ # gate is enforced on the locked row, not on a stale read.+ self.document.status = LegalDocument.Status.SIGNED+ self.document.save()++ response = self.client.delete(self.url)++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)+ self.assertTrue(LegalDocument.objects.filter(id=self.document.id).exists())+ mock_pandadoc_cls.return_value.void_document.assert_not_called()++ @parameterized.expand(+ [+ ("unknown_uuid", "00000000-0000-0000-0000-000000000000"),+ ("invalid_uuid", "not-a-uuid"),+ ]+ )+ def test_nonexistent_or_invalid_pk_returns_404(self, _name: str, pk: str) -> None:+ url = f"/api/organizations/{self.organization.id}/legal_documents/{pk}/"+ response = self.client.delete(url)+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ def test_cross_organization_delete_is_blocked(self, mock_pandadoc_cls) -> None:+ # Same document id, accessed from another org the user happens to+ # also admin. The lookup is org-scoped so the row should look 404 from+ # that path — and the actual row stays put.+ other_org = Organization.objects.create(name="Other Co")+ OrganizationMembership.objects.create(+ user=self.user, organization=other_org, level=OrganizationMembership.Level.ADMIN+ )+ url = f"/api/organizations/{other_org.id}/legal_documents/{self.document.id}/"++ response = self.client.delete(url)++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ self.assertTrue(LegalDocument.objects.filter(id=self.document.id).exists())+ mock_pandadoc_cls.return_value.void_document.assert_not_called()++ def test_regular_member_cannot_delete(self) -> None:+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()++ response = self.client.delete(self.url)++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertTrue(LegalDocument.objects.filter(id=self.document.id).exists())++ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ def test_pandadoc_void_failure_returns_503_and_keeps_row(self, mock_pandadoc_cls) -> None:+ # Self-serve delete runs PandaDoc void in strict mode: if void fails,+ # the facade's transaction rolls back and the row stays. The+ # alternative (deleting the row anyway) would mean telling the user+ # the envelope was cancelled when it wasn't, leaving the original+ # signer with a still-completable document.+ from products.legal_documents.backend.logic import pandadoc as pandadoc_module++ mock_pandadoc_cls.return_value.void_document.side_effect = pandadoc_module.PandaDocError("boom")++ response = self.client.delete(self.url)++ self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)+ self.assertEqual(response.json()["code"], "legal_document_void_failed")+ self.assertTrue(LegalDocument.objects.filter(id=self.document.id).exists())++ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ def test_activity_log_row_is_written_on_delete(self, _mock_pandadoc_cls) -> None:+ response = self.client.delete(self.url)+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)++ log = ActivityLog.objects.filter(scope="LegalDocument", activity="deleted").first()+ self.assertIsNotNone(log, "expected a deleted-activity log entry from ModelActivityMixin")+ assert log is not None # mypy+ self.assertEqual(str(log.organization_id), str(self.organization.id))++ def test_anonymous_user_cannot_delete(self) -> None:+ self.client.logout()+ response = self.client.delete(self.url)+ self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN))+ self.assertTrue(LegalDocument.objects.filter(id=self.document.id).exists())++@override_settings(CLOUD_DEPLOYMENT="US")class TestLegalDocumentPandaDocWebhook(APIBaseTest):SECRET = "pandadoc-test-secret"@@ -686,6 +824,20 @@ class TestLegalDocumentsSelfHostedGate(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)self.assertFalse(LegalDocument.objects.exists())+ def test_delete_404s_on_self_hosted(self) -> None:+ # Rows shouldn't exist on self-hosted but we still want the gate to+ # respond 404 regardless of what's in the DB — never reach PandaDoc.+ document = LegalDocument.objects.create(+ organization=self.organization,+ document_type="DPA",+ company_name="Acme, Inc.",+ company_address="1 Analytics Way",+ representative_email="[email protected]",+ )+ response = self.client.delete(f"/api/organizations/{self.organization.id}/legal_documents/{document.id}/")+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ self.assertTrue(LegalDocument.objects.filter(id=document.id).exists())+def test_pandadoc_webhook_404s_on_self_hosted_even_with_valid_signature(self) -> None:self.client.logout()secret = "any-secret"diff --git a/products/legal_documents/backend/tests/test_logic.py b/products/legal_documents/backend/tests/test_logic.pyindex e69de29bb2d1..10c086a1505f 100644--- a/products/legal_documents/backend/tests/test_logic.py+++ b/products/legal_documents/backend/tests/test_logic.py@@ -0,0 +1,130 @@+from typing import Any++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.test import override_settings++from products.legal_documents.backend.logic import (+ delete_document,+ pandadoc as pandadoc_module,+)+from products.legal_documents.backend.models import LegalDocument+++class TestDeleteDocument(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)++ # --- Signed (admin path) ---++ @override_settings(OBJECT_STORAGE_ENABLED=True)+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ @patch("products.legal_documents.backend.logic.object_storage")+ def test_signed_document_skips_pandadoc_and_deletes_s3_pdf(self, mock_storage: Any, mock_pandadoc_cls: Any) -> None:+ # PandaDoc envelopes for signed documents are already complete; calling+ # void on them returns 423 and is pure Sentry noise.+ document = self._document(status=LegalDocument.Status.SIGNED)+ document_id = document.id++ delete_document(document)++ mock_pandadoc_cls.assert_not_called()+ mock_storage.delete.assert_called_once()+ self.assertFalse(LegalDocument.objects.filter(id=document_id).exists())++ # --- Unsigned (both paths) ---++ @override_settings(OBJECT_STORAGE_ENABLED=True)+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ @patch("products.legal_documents.backend.logic.object_storage")+ def test_unsigned_document_voids_pandadoc_and_skips_s3(self, mock_storage: Any, mock_pandadoc_cls: Any) -> None:+ # Unsigned rows never have a PDF in object storage — only PandaDoc+ # webhook completion writes one — so the S3 round-trip is skipped.+ document = self._document()+ document_id = document.id++ delete_document(document)++ mock_pandadoc_cls.return_value.void_document.assert_called_once_with(document_id="doc_123")+ mock_storage.delete.assert_not_called()+ self.assertFalse(LegalDocument.objects.filter(id=document_id).exists())++ @override_settings(OBJECT_STORAGE_ENABLED=True)+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ @patch("products.legal_documents.backend.logic.object_storage")+ def test_pandadoc_failure_in_admin_mode_is_swallowed(self, _mock_storage: Any, mock_pandadoc_cls: Any) -> None:+ # Admin (default `strict_pandadoc=False`) path: PandaDoc unreachable or+ # locked envelope shouldn't block staff from removing a row. Stale+ # envelope on PandaDoc is preferable to staff being unable to delete.+ mock_pandadoc_cls.return_value.void_document.side_effect = pandadoc_module.PandaDocError("boom")+ document = self._document()+ document_id = document.id++ delete_document(document)++ self.assertFalse(LegalDocument.objects.filter(id=document_id).exists())++ @override_settings(OBJECT_STORAGE_ENABLED=True)+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ @patch("products.legal_documents.backend.logic.object_storage")+ def test_strict_pandadoc_raises_and_does_not_delete_row(self, _mock_storage: Any, mock_pandadoc_cls: Any) -> None:+ # Self-serve path (`strict_pandadoc=True`): a PandaDoc failure must+ # bubble up so the surrounding facade transaction rolls back. The row+ # stays; the API surfaces 503 and the user can retry.+ mock_pandadoc_cls.return_value.void_document.side_effect = pandadoc_module.PandaDocError("boom")+ document = self._document()+ document_id = document.id++ with self.assertRaises(pandadoc_module.PandaDocError):+ delete_document(document, strict_pandadoc=True)++ self.assertTrue(LegalDocument.objects.filter(id=document_id).exists())++ @override_settings(OBJECT_STORAGE_ENABLED=True)+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ @patch("products.legal_documents.backend.logic.object_storage")+ def test_s3_failure_in_signed_path_is_swallowed(self, mock_storage: Any, _mock_pandadoc_cls: Any) -> None:+ # S3 only runs for signed rows. If it fails, the row still goes —+ # a stale PDF orphan in S3 is preferable to an undeletable row.+ mock_storage.delete.side_effect = RuntimeError("s3 down")+ document = self._document(status=LegalDocument.Status.SIGNED)+ document_id = document.id++ delete_document(document)++ self.assertFalse(LegalDocument.objects.filter(id=document_id).exists())++ @override_settings(OBJECT_STORAGE_ENABLED=False)+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ @patch("products.legal_documents.backend.logic.object_storage")+ def test_signed_path_skips_s3_when_storage_disabled(self, mock_storage: Any, _mock_pandadoc_cls: Any) -> None:+ # Self-hosted / local dev without OBJECT_STORAGE_ENABLED: the helper+ # shouldn't touch object_storage even for signed rows.+ document = self._document(status=LegalDocument.Status.SIGNED)++ delete_document(document)++ mock_storage.delete.assert_not_called()++ @override_settings(OBJECT_STORAGE_ENABLED=True)+ @patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient")+ @patch("products.legal_documents.backend.logic.object_storage")+ def test_unsigned_without_envelope_id_skips_pandadoc(self, _mock_storage: Any, mock_pandadoc_cls: Any) -> None:+ # PandaDoc create may have failed during the original flow, leaving+ # pandadoc_document_id blank. Nothing to void; don't even instantiate+ # the client.+ document = self._document(pandadoc_document_id="")++ delete_document(document)++ mock_pandadoc_cls.assert_not_called()diff --git a/products/legal_documents/backend/tests/test_pandadoc.py b/products/legal_documents/backend/tests/test_pandadoc.pyindex 94c05c4686a2..872f50abce00 100644--- a/products/legal_documents/backend/tests/test_pandadoc.py+++ b/products/legal_documents/backend/tests/test_pandadoc.py@@ -5,6 +5,8 @@ from unittest.mock import MagicMock, patchfrom django.test import TestCase, override_settings+from parameterized import parameterized+from products.legal_documents.backend.logic import pandadoc@@ -186,3 +188,60 @@ class TestPandaDocClient(TestCase):self.assertEqual(pandadoc._serialize_recipient(client), {"email": "[email protected]", "role": "Client"})posthog = pandadoc.PandaDocRecipient(email="[email protected]", role=pandadoc.PandaDocRole.POSTHOG)self.assertEqual(pandadoc._serialize_recipient(posthog), {"email": "[email protected]", "role": "PostHog"})++ @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+ # PandaDoc retains the audit record of the cancelled signing process.+ 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:+ 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})++ @override_settings(PANDADOC_API_KEY="key")+ 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:+ 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:+ pandadoc.PandaDocClient().void_document(document_id="doc_123")diff --git a/products/legal_documents/frontend/generated/api.ts b/products/legal_documents/frontend/generated/api.tsindex b75c796a752e..9c44306981dc 100644--- a/products/legal_documents/frontend/generated/api.ts+++ b/products/legal_documents/frontend/generated/api.ts@@ -74,6 +74,32 @@ export const legalDocumentsRetrieve = async (})}+export const getLegalDocumentsDestroyUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/legal_documents/${id}/`+}++/**+ * Delete an unsigned legal document. The PandaDoc envelope is voided+first so the original signer can no longer complete it; only if that+succeeds is the row removed, freeing the unique-per-org-per-type+constraint so a fresh document can be generated.++Returns 503 if the PandaDoc void fails — the row stays in that case+and the frontend should prompt the user to retry. Returns 403 for+signed documents (legal artifacts; staff can still delete signed+rows from Django admin).+ */+export const legalDocumentsDestroy = async (+ organizationId: string,+ id: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getLegalDocumentsDestroyUrl(organizationId, id), {+ ...options,+ method: 'DELETE',+ })+}+export const getLegalDocumentsDownloadRetrieveUrl = (organizationId: string, id: string) => {return `/api/organizations/${organizationId}/legal_documents/${id}/download/`}diff --git a/products/legal_documents/frontend/scenes/LegalDocumentsScene.tsx b/products/legal_documents/frontend/scenes/LegalDocumentsScene.tsxindex 0498699b5a9c..0149e721cdad 100644--- a/products/legal_documents/frontend/scenes/LegalDocumentsScene.tsx+++ b/products/legal_documents/frontend/scenes/LegalDocumentsScene.tsx@@ -1,7 +1,7 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'-import { IconBalance, IconDownload, IconPlusSmall } from '@posthog/icons'-import { LemonBanner, LemonButton, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'+import { IconBalance, IconDownload, IconPlusSmall, IconTrash } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonDialog, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'@@ -76,7 +76,8 @@ export const scene: SceneExport = {}export function LegalDocumentsScene(): JSX.Element {- const { legalDocuments, legalDocumentsLoading, existingDocumentTypes } = useValues(legalDocumentsLogic)+ const { legalDocuments, legalDocumentsLoading, existingDocumentTypes, deletingId } = useValues(legalDocumentsLogic)+ const { deleteLegalDocument } = useActions(legalDocumentsLogic)const { isAdminOrOwner, currentOrganizationId } = useValues(organizationLogic)const { isCloudOrDev } = useValues(preflightLogic)const isEnabled = useFeatureFlag('LEGAL_DOCUMENTS')@@ -208,6 +209,46 @@ export function LegalDocumentsScene(): JSX.Element {render: (_: any, row: LegalDocument) =>row.created_by?.first_name || row.created_by?.email || '—',},+ {+ title: '',+ width: 48,+ render: (_: any, row: LegalDocument) =>+ row.status === 'submitted_for_signature' ? (+ <LemonButton+ icon={<IconTrash />}+ status="danger"+ size="small"+ loading={deletingId === row.id}+ disabledReason={+ deletingId && deletingId !== row.id+ ? 'Another document is being deleted'+ : undefined+ }+ data-attr={`delete-legal-document-${row.id}`}+ tooltip={`Delete this ${row.document_type} and cancel the PandaDoc envelope`}+ onClick={() =>+ LemonDialog.open({+ title: `Delete this ${row.document_type}?`,+ description: (+ <>+ We'll cancel the pending PandaDoc envelope sent to{' '}+ <strong>{row.representative_email}</strong> first. The{' '}+ {row.document_type} is only deleted if the cancellation succeeds, so+ you can safely retry if PandaDoc is unreachable. Once it's deleted+ you can generate a fresh {row.document_type}.+ </>+ ),+ primaryButton: {+ children: 'Delete',+ status: 'danger',+ onClick: () => deleteLegalDocument(row.id, row.document_type),+ },+ secondaryButton: { children: 'Cancel' },+ })+ }+ />+ ) : null,+ },]}/></SceneContent>diff --git a/products/legal_documents/frontend/scenes/legalDocumentsLogic.ts b/products/legal_documents/frontend/scenes/legalDocumentsLogic.tsindex e994bced15b8..4c63073152c3 100644--- a/products/legal_documents/frontend/scenes/legalDocumentsLogic.ts+++ b/products/legal_documents/frontend/scenes/legalDocumentsLogic.ts@@ -1,4 +1,4 @@-import { actions, afterMount, connect, kea, listeners, path, selectors } from 'kea'+import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { forms } from 'kea-forms'import { loaders } from 'kea-loaders'import { router, urlToAction } from 'kea-router'@@ -69,6 +69,17 @@ export const legalDocumentsLogic = kea<legalDocumentsLogicType>([actions({setDocumentType: (documentType: LegalDocumentType) => ({ documentType }),setDpaMode: (dpaMode: DPAMode) => ({ dpaMode }),+ deleteLegalDocument: (id: string, documentType: LegalDocumentType) => ({ id, documentType }),+ // Internal — used by the listener to drive the per-row spinner.+ setDeletingId: (id: string | null) => ({ id }),+ }),+ reducers({+ deletingId: [+ null as string | null,+ {+ setDeletingId: (_, { id }) => id,+ },+ ],}),loaders(({ values }) => ({legalDocuments: [@@ -146,6 +157,27 @@ export const legalDocumentsLogic = kea<legalDocumentsLogicType>([setDpaMode: ({ dpaMode }) => {actions.setLegalDocumentValue('dpa_mode', dpaMode)},+ deleteLegalDocument: async ({ id, documentType }) => {+ if (!values.currentOrganizationId) {+ return+ }+ actions.setDeletingId(id)+ try {+ await api.legalDocumentsDestroy(values.currentOrganizationId, id)+ actions.loadLegalDocuments()+ lemonToast.success(`${documentType} deleted. You can now generate a new ${documentType}.`)+ } catch (error: any) {+ // 503 from the backend means the PandaDoc envelope couldn't be+ // cancelled and the row was NOT deleted — surface the backend's+ // detail so the user knows to retry rather than assuming success.+ lemonToast.error(+ error?.detail ||+ `Could not delete the ${documentType}. Please try again, or contact PostHog support.`+ )+ } finally {+ actions.setDeletingId(null)+ }+ },loadCurrentOrganizationSuccess: () => {if (values.legalDocuments.length === 0 && values.isAdminOrOwner && !values.legalDocumentsLoading) {actions.loadLegalDocuments()