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.

feat(legal-documents): add MSA document type with staff admin upload flow (#57907)

Rafael Audibert2497d6ec09cb
diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.py
index 86540b257fa9..398c4d97f7a9 100644
--- a/posthog/admin/admins/organization_admin.py
+++ b/posthog/admin/admins/organization_admin.py
@@ -20,6 +20,8 @@ from posthog.admin.inlines.team_inline import TeamInline
from posthog.admin.paginators.no_count_paginator import NoCountPaginator
from posthog.models.organization import Organization
+from products.legal_documents.backend.admin import LegalDocumentInline
+
# Registry of models to count for bulk-delete report.
# Format: (model_import_path, filter_field, display_name)
# This mirrors delete_bulky_postgres_data() in posthog/models/team/util.py
@@ -155,7 +157,14 @@ class OrganizationAdmin(admin.ModelAdmin):
"is_platform",
"members_can_invite",
]
- inlines = [ProjectInline, TeamInline, OrganizationMemberInline, OrganizationInviteInline, OrganizationDomainInline]
+ inlines = [
+ ProjectInline,
+ TeamInline,
+ OrganizationMemberInline,
+ OrganizationInviteInline,
+ OrganizationDomainInline,
+ LegalDocumentInline,
+ ]
readonly_fields = [
"id",
"created_at",
diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.py
index 711baadc069e..a4b156db5f5c 100644
--- a/posthog/settings/integrations.py
+++ b/posthog/settings/integrations.py
@@ -106,9 +106,3 @@ PANDADOC_API_KEY = get_from_env("PANDADOC_API_KEY", "")
PANDADOC_WEBHOOK_SECRET = get_from_env("PANDADOC_WEBHOOK_SECRET", "")
PANDADOC_BAA_TEMPLATE_ID = get_from_env("PANDADOC_BAA_TEMPLATE_ID", "")
PANDADOC_DPA_TEMPLATE_ID = get_from_env("PANDADOC_DPA_TEMPLATE_ID", "")
-
-# Slack incoming-webhook URL for internal legal-document notifications. The URL
-# is bound to a single channel at creation time in Slack's app admin, so there's
-# no channel to configure and no bot token to manage. Separate from the per-org
-# Slack integration used in products/slack_app.
-SLACK_LEGAL_DOCUMENTS_WEBHOOK_URL = get_from_env("SLACK_LEGAL_DOCUMENTS_WEBHOOK_URL", "")
diff --git a/products/legal_documents/backend/admin.py b/products/legal_documents/backend/admin.py
index 92570af829a5..3ac1bd450130 100644
--- a/products/legal_documents/backend/admin.py
+++ b/products/legal_documents/backend/admin.py
@@ -1,14 +1,69 @@
-from typing import Any
+from typing import IO, Any, cast
+from django import forms
from django.contrib import admin, messages
+from django.core.exceptions import ValidationError
+from django.core.files.uploadedfile import UploadedFile
+from django.core.validators import FileExtensionValidator
+from django.db import IntegrityError, transaction
from django.http import HttpRequest, HttpResponse
from django.urls import reverse
from django.utils.html import format_html
from django.utils.safestring import SafeString
+import structlog
+from django_admin_inline_paginator.admin import TabularInlinePaginated
+
from posthog.cloud_utils import is_cloud, is_dev_mode
+from posthog.storage import object_storage
from .models import LegalDocument
+from .storage import signed_pdf_storage_key
+
+logger = structlog.get_logger(__name__)
+
+# 25 MiB. PandaDoc-signed PDFs are ~100 KiB; counter-signed scans uploaded by sales
+# can be larger but rarely come close to this. Anything bigger is almost certainly
+# the wrong file.
+_MAX_UPLOAD_BYTES = 25 * 1024 * 1024
+
+
+class LegalDocumentAdminForm(forms.ModelForm):
+ """
+ Admin upload form for documents signed outside the PandaDoc flow (sales /
+ legal-ops dropping a counter-signed PDF). The PDF lives in object storage
+ under the same key the public download endpoint already serves from, so the
+ customer can download it via /api/.../legal_documents/{id}/download just
+ like a PandaDoc-originated row.
+ """
+
+ signed_pdf = forms.FileField(
+ required=True,
+ validators=[FileExtensionValidator(allowed_extensions=["pdf"])],
+ help_text="Counter-signed PDF (max 25 MiB). The row will be created with status='signed'.",
+ )
+
+ class Meta:
+ model = LegalDocument
+ fields = (
+ "organization",
+ "document_type",
+ "company_name",
+ "company_address",
+ "representative_email",
+ )
+
+ def clean_signed_pdf(self) -> UploadedFile:
+ pdf: UploadedFile = self.cleaned_data["signed_pdf"]
+ if pdf.size and pdf.size > _MAX_UPLOAD_BYTES:
+ raise ValidationError(f"PDF is too large ({pdf.size} bytes). Limit is {_MAX_UPLOAD_BYTES} bytes.")
+
+ # Browsers populate content_type from the multipart upload; we only reject
+ # obvious mismatches. The .pdf extension validator above is the primary check.
+ if pdf.content_type and pdf.content_type != "application/pdf":
+ raise ValidationError(f"File must be a PDF (got content-type {pdf.content_type!r}).")
+
+ return pdf
class LegalDocumentAdmin(admin.ModelAdmin):
@@ -33,8 +88,8 @@ class LegalDocumentAdmin(admin.ModelAdmin):
show_full_result_count = False
list_select_related = ("organization", "created_by")
- # Only the signed URL is editable by admins. Everything else is read-only so
- # customer-submitted content can't be quietly rewritten.
+ # Change view stays read-only — customer-submitted content can't be quietly
+ # rewritten. The add view uses LegalDocumentAdminForm fields directly.
readonly_fields = (
"id",
"organization",
@@ -48,6 +103,29 @@ class LegalDocumentAdmin(admin.ModelAdmin):
"created_at",
"updated_at",
)
+
+ add_fieldsets = (
+ (
+ "Upload signed document",
+ {
+ "description": (
+ "Use this form when a document was signed outside the PandaDoc flow "
+ "(e.g., counter-signed offline, DocuSign, or an MSA negotiated by sales). "
+ "The row is saved as 'signed' and the PDF goes to object storage at the "
+ "same key the customer-facing download endpoint reads from."
+ ),
+ "fields": (
+ "organization",
+ "document_type",
+ "company_name",
+ "company_address",
+ "representative_email",
+ "signed_pdf",
+ ),
+ },
+ ),
+ )
+
fieldsets = (
(
"Document",
@@ -77,11 +155,97 @@ class LegalDocumentAdmin(admin.ModelAdmin):
),
)
+ def get_fieldsets(self, request: HttpRequest, obj: LegalDocument | None = None) -> Any:
+ if obj is None:
+ return self.add_fieldsets
+ return self.fieldsets
+
+ def get_form(
+ self, request: HttpRequest, obj: LegalDocument | None = None, change: bool = False, **kwargs: Any
+ ) -> Any:
+ # Add view uses LegalDocumentAdminForm (with the required signed_pdf
+ # FileField). The change view falls back to Django's default ModelForm
+ # for the model — `signed_pdf` is a non-model class attribute, so it
+ # would otherwise be inherited by modelform_factory's subclass and
+ # block "Save" with a "This field is required" error even though the
+ # change view renders no upload widget.
+ if obj is None:
+ kwargs["form"] = LegalDocumentAdminForm
+ return super().get_form(request, obj, change, **kwargs)
+
+ def get_readonly_fields(
+ self, request: HttpRequest, obj: LegalDocument | None = None
+ ) -> tuple[str, ...] | list[str]:
+ # On the change view every customer-submitted field is read-only so it
+ # can't be quietly rewritten. On the add view (obj is None) the upload
+ # form needs the fields to be editable so return an empty tuple.
+ if obj is None:
+ return ()
+ return self.readonly_fields
+
def has_add_permission(self, request: HttpRequest) -> bool:
- return False
+ return bool(request.user and request.user.is_staff)
def has_delete_permission(self, request: HttpRequest, obj: LegalDocument | None = None) -> bool:
- return False
+ # Needed so admins can clear an existing row (the unique-per-org-per-type
+ # constraint blocks re-uploads otherwise). Best-effort S3 cleanup runs
+ # alongside the row delete.
+ return bool(request.user and request.user.is_staff)
+
+ def save_model(self, request: HttpRequest, obj: LegalDocument, form: Any, change: bool) -> None:
+ if change:
+ super().save_model(request, obj, form, change)
+ return
+
+ # Add path: row + S3 upload happen together so we never leave a row
+ # pointing at a missing PDF (and never leave a PDF without a row).
+ obj.status = LegalDocument.Status.SIGNED
+ obj.created_by = request.user if request.user.is_authenticated else None
+ try:
+ with transaction.atomic():
+ obj.save()
+ pdf: UploadedFile = form.cleaned_data["signed_pdf"]
+ try:
+ object_storage.write_stream(
+ signed_pdf_storage_key(obj),
+ cast(IO[bytes], pdf),
+ extras={"ContentType": "application/pdf"},
+ )
+ except Exception as exc:
+ logger.exception(
+ "legal_document_admin_upload_failed",
+ document_id=str(obj.id),
+ error=str(exc),
+ )
+ raise ValidationError(f"Failed to upload PDF to object storage: {exc}") from exc
+ except IntegrityError as exc:
+ # Surface the unique-per-org-per-type constraint as a form error
+ # instead of a 500.
+ raise ValidationError(
+ f"This organization already has a {obj.document_type}. Delete the existing row first."
+ ) from exc
+
+ def delete_model(self, request: HttpRequest, obj: LegalDocument) -> None:
+ self._delete_signed_pdf(obj)
+ super().delete_model(request, obj)
+
+ def delete_queryset(self, request: HttpRequest, queryset: Any) -> None:
+ 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),
+ )
def changelist_view(self, request: HttpRequest, extra_context: dict[str, Any] | None = None) -> HttpResponse:
if not (is_cloud() or is_dev_mode()):
@@ -89,7 +253,7 @@ class LegalDocumentAdmin(admin.ModelAdmin):
request,
"Legal documents are only generated on PostHog Cloud. On self-hosted "
"deployments, listed rows (if any) are read-only historical records and "
- "the PandaDoc / Slack integrations are disabled.",
+ "the PandaDoc integration is disabled.",
)
return super().changelist_view(request, extra_context=extra_context)
@@ -101,7 +265,7 @@ class LegalDocumentAdmin(admin.ModelAdmin):
request,
"Legal documents are only generated on PostHog Cloud. On self-hosted "
"deployments, listed rows (if any) are read-only historical records and "
- "the PandaDoc / Slack integrations are disabled.",
+ "the PandaDoc integration is disabled.",
)
return super().change_view(request, object_id, form_url, extra_context=extra_context)
@@ -118,3 +282,51 @@ class LegalDocumentAdmin(admin.ModelAdmin):
'<a href="https://app.pandadoc.com/a/#/documents/{id}" target="_blank" rel="noopener">{id}</a>',
id=document.pandadoc_document_id,
)
+
+
+class LegalDocumentInline(TabularInlinePaginated):
+ """
+ Read-only list of an organization's legal documents, rendered as an inline
+ on the Organization admin page. The "Upload signed document" button in the
+ inline header links to the LegalDocumentAdmin add view with the
+ organization pre-filled via `?organization=<id>`.
+ """
+
+ model = LegalDocument
+ extra = 0
+ per_page = 20
+ pagination_key = "page-legal-document"
+ show_change_link = True
+ template = "admin/legal_documents/edit_inline/tabular.html"
+
+ fields = (
+ "document_type",
+ "company_name",
+ "status",
+ "pandadoc_link",
+ "created_at",
+ )
+ readonly_fields = fields
+
+ can_delete = False
+ max_num = 0
+
+ def has_add_permission(self, request: HttpRequest, obj: Any = None) -> bool:
+ # Adding goes through the LegalDocumentAdmin add view via the upload
+ # button rendered in the inline template — never inline.
+ return False
+
+ def has_change_permission(self, request: HttpRequest, obj: Any = None) -> bool:
+ return False
+
+ def has_delete_permission(self, request: HttpRequest, obj: Any = None) -> bool:
+ return False
+
+ @admin.display(description="PandaDoc")
+ def pandadoc_link(self, document: LegalDocument) -> str | SafeString:
+ if not document.pandadoc_document_id:
+ return "—"
+ return format_html(
+ '<a href="https://app.pandadoc.com/a/#/documents/{id}" target="_blank" rel="noopener">{id}</a>',
+ id=document.pandadoc_document_id,
+ )
diff --git a/products/legal_documents/backend/facade/api.py b/products/legal_documents/backend/facade/api.py
index 313b809f6bfe..e25e73ad69a5 100644
--- a/products/legal_documents/backend/facade/api.py
+++ b/products/legal_documents/backend/facade/api.py
@@ -91,7 +91,7 @@ def create_document(data: contracts.CreateLegalDocumentInput) -> contracts.Legal
# Fire and forget: PandaDoc never blocks the response. The envelope lands
# in `document.uploaded` state and becomes dispatchable asynchronously —
- # the `document.draft` webhook triggers the actual send + Slack ping via
+ # the `document.draft` webhook triggers the actual send via
# `mark_envelope_ready_by_pandadoc_document_id`.
logic.create_pandadoc_envelope(document)
logic.fire_legal_document_submitted_event(document, distinct_id=data.distinct_id)
@@ -107,11 +107,11 @@ def mark_envelope_ready_by_pandadoc_document_id(
"""
Entry point from the PandaDoc `document.draft` webhook — the envelope
finished template processing and is ready to send. Dispatch the signing
- email and fire the Slack "submitted" notification.
+ email.
Idempotent: if the envelope has already been dispatched (row is already
signed, or the send call fails because PandaDoc has moved past draft)
- we quietly skip the side effects.
+ we quietly skip.
"""
document = logic.get_by_pandadoc_document_id(pandadoc_document_id)
if document is None:
@@ -122,9 +122,7 @@ def mark_envelope_ready_by_pandadoc_document_id(
# Envelope already completed — the draft event is a late/replayed
# delivery; nothing left for us to do.
return _to_dto(document)
- sent = logic.send_pandadoc_envelope(document)
- if sent:
- logic.notify_slack_on_submit(document)
+ logic.send_pandadoc_envelope(document)
return _to_dto(document)
@@ -141,10 +139,10 @@ def mark_signed_by_pandadoc_document_id(
- Double-checks the template matches the stored document variant, to guard
against misconfigured PandaDoc templates flipping the wrong row.
- Downloads the signed PDF from PandaDoc and stashes it in object storage.
- - Flips status to signed, fires analytics + Slack.
+ - Flips status to signed, fires analytics.
Idempotent: if the row is already signed we return the existing DTO
- without re-downloading or re-firing Slack/analytics. If the download or
+ without re-downloading or re-firing analytics. If the download or
upload fails we leave the row unsigned and return None so the webhook
handler can surface 5xx; PandaDoc will retry.
"""
@@ -158,6 +156,5 @@ def mark_signed_by_pandadoc_document_id(
if not logic.download_and_store_signed_pdf(document):
raise LegalDocumentDownloadFailed(f"Failed to retrieve signed PDF for legal_document {document.id}")
document = logic.mark_document_signed(document)
- logic.notify_slack_on_signed(document)
logic.fire_legal_document_signed_event(document)
return _to_dto(document)
diff --git a/products/legal_documents/backend/facade/enums.py b/products/legal_documents/backend/facade/enums.py
index d690763ceb88..e5b535ff5451 100644
--- a/products/legal_documents/backend/facade/enums.py
+++ b/products/legal_documents/backend/facade/enums.py
@@ -6,6 +6,7 @@ from enum import StrEnum
class DocumentType(StrEnum):
BAA = "BAA"
DPA = "DPA"
+ MSA = "MSA"
class LegalDocumentStatus(StrEnum):
diff --git a/products/legal_documents/backend/logic/__init__.py b/products/legal_documents/backend/logic/__init__.py
index 4e2d72debd31..b48a1bc3a2dd 100644
--- a/products/legal_documents/backend/logic/__init__.py
+++ b/products/legal_documents/backend/logic/__init__.py
@@ -25,19 +25,18 @@ from ee.billing.billing_manager import BillingManager
from ..facade.enums import DocumentType
from ..models import LegalDocument
-from . import (
- pandadoc as pandadoc_client,
- slack as slack_notifier,
-)
+from ..storage import signed_pdf_storage_key
+from . import pandadoc as pandadoc_client
logger = structlog.get_logger(__name__)
# Addon types that entitle an organization to a BAA.
BAA_ADDON_TYPES = frozenset({"boost", "scale", "enterprise"})
-# PostHog-side CC on every signing envelope. Lives here rather than on the
-# PandaDoc client so the client stays generic and reusable.
-POSTHOG_SIGNING_CC_EMAIL = "[email protected]"
+# PostHog-side mailbox used both as the CC recipient on every signing envelope
+# and as the document owner. PandaDoc sends the signing email on behalf of the
+# owner, so this is the From address the signer sees.
+POSTHOG_SIGNING_EMAIL = "[email protected]"
def _pandadoc_template_id_for(document_type: str) -> str:
@@ -45,6 +44,10 @@ def _pandadoc_template_id_for(document_type: str) -> str:
Resolve the PandaDoc template id for a given document type. One template
per type, configured via env. Returns an empty string if the matching env
var isn't set, which surfaces as a clear PandaDocError at send time.
+
+ MSAs intentionally have no PandaDoc template — they can only originate from
+ a staff upload in Django admin, so this function returning empty for MSA
+ short-circuits the unreachable PandaDoc branch with a clear log line.
"""
if document_type == DocumentType.BAA:
return settings.PANDADOC_BAA_TEMPLATE_ID
@@ -126,15 +129,6 @@ def mark_document_signed(document: LegalDocument) -> LegalDocument:
return document
-def signed_pdf_storage_key(document: LegalDocument) -> str:
- """
- Canonical key under which the signed PDF lives in object storage. The
- document uuid is the natural identifier and never changes, so admins
- regenerating the envelope for the same row just overwrite the old object.
- """
- return f"{settings.OBJECT_STORAGE_LEGAL_DOCUMENTS_FOLDER}/{document.id}.pdf"
-
-
# Short-enough that leaked URLs stop working on a human timescale, long enough
# that slow network conditions or a distracted user can still complete the
# download without the presigned URL expiring mid-stream.
@@ -245,7 +239,7 @@ def create_pandadoc_envelope(document: LegalDocument) -> str | None:
name=f"PostHog {document.document_type} — {document.company_name}",
recipients=[
pandadoc_client.PandaDocRecipient(
- email=POSTHOG_SIGNING_CC_EMAIL, role=pandadoc_client.PandaDocRole.POSTHOG
+ email=POSTHOG_SIGNING_EMAIL, role=pandadoc_client.PandaDocRole.POSTHOG
),
pandadoc_client.PandaDocRecipient(
email=document.representative_email, role=pandadoc_client.PandaDocRole.CLIENT
@@ -260,6 +254,7 @@ def create_pandadoc_envelope(document: LegalDocument) -> str | None:
"organization_id": str(document.organization_id),
"document_type": document.document_type,
},
+ owner_email=POSTHOG_SIGNING_EMAIL,
)
set_pandadoc_document_id(document, created.id)
return created.id
@@ -317,33 +312,6 @@ def send_pandadoc_envelope(document: LegalDocument) -> bool:
return False
-def notify_slack_on_submit(document: LegalDocument) -> None:
- try:
- slack_notifier.notify_submitted(
- document_type=document.document_type,
- company_name=document.company_name,
- representative_email=document.representative_email,
- pandadoc_document_id=document.pandadoc_document_id or None,
- )
- except Exception as exc:
- # Slack errors are already swallowed inside the notifier, but protect
- # the submit path from unexpected import/attr errors too.
- logger.exception("legal_document_slack_submit_notify_failed", error=str(exc))
- capture_exception(exc, additional_properties={"legal_document_id": str(document.id)})
-
-
-def notify_slack_on_signed(document: LegalDocument) -> None:
- try:
- slack_notifier.notify_signed(
- document_type=document.document_type,
- company_name=document.company_name,
- pandadoc_document_id=document.pandadoc_document_id or None,
- )
- except Exception as exc:
- logger.exception("legal_document_slack_signed_notify_failed", error=str(exc))
- capture_exception(exc, additional_properties={"legal_document_id": str(document.id)})
-
-
SUBMITTED_EVENT = "legal document submitted"
SIGNED_EVENT = "legal document signed"
@@ -351,8 +319,8 @@ SIGNED_EVENT = "legal document signed"
def fire_legal_document_submitted_event(document: LegalDocument, distinct_id: str) -> None:
"""
Capture the submission to PostHog for analytics. No longer a critical path —
- the customer-facing work (PandaDoc + Slack) is driven directly by the
- submit handler. This event is kept for product analytics on the
+ the customer-facing work (PandaDoc) is driven directly by the submit
+ handler. This event is kept for product analytics on the
`/legal/new/:type` funnel.
"""
_capture_lifecycle_event(document, SUBMITTED_EVENT, distinct_id)
diff --git a/products/legal_documents/backend/logic/pandadoc.py b/products/legal_documents/backend/logic/pandadoc.py
index 5048546a0136..b7b1cd1d390f 100644
--- a/products/legal_documents/backend/logic/pandadoc.py
+++ b/products/legal_documents/backend/logic/pandadoc.py
@@ -123,6 +123,7 @@ class PandaDocClient:
recipients: list[PandaDocRecipient],
tokens: dict[str, str] | None = None,
metadata: dict[str, str] | None = None,
+ owner_email: str | None = None,
) -> PandaDocDocument:
"""
Create a new document from a PandaDoc template. The returned document is in
@@ -132,6 +133,10 @@ class PandaDocClient:
placeholders (`[Client.Company]`, `[Client.StreetAddress]`, etc.). Only
`Client.Email` is auto-populated from the recipient — everything else
the template references has to be passed explicitly here.
+
+ `owner_email` overrides the document owner. PandaDoc sends the signing
+ envelope on behalf of the owner, so this also controls the From address
+ the signer sees. Defaults to the user that owns the API key.
"""
payload: dict[str, Any] = {
"name": name,
@@ -142,6 +147,8 @@ class PandaDocClient:
payload["tokens"] = [{"name": name, "value": value} for name, value in tokens.items()]
if metadata:
payload["metadata"] = metadata
+ if owner_email:
+ payload["owner"] = {"email": owner_email}
data = self._post("/public/v1/documents", payload)
return PandaDocDocument(
id=data["id"],
diff --git a/products/legal_documents/backend/logic/slack.py b/products/legal_documents/backend/logic/slack.py
deleted file mode 100644
index 542b79655f2b..000000000000
--- a/products/legal_documents/backend/logic/slack.py
+++ /dev/null
@@ -1,119 +0,0 @@
-"""
-Slack notifications for legal document lifecycle events.
-
-Uses a Slack incoming webhook URL (SLACK_LEGAL_DOCUMENTS_WEBHOOK_URL) bound to
-a single channel at creation time — no bot token, no per-channel config, no
-install flow. The slack-app product handles per-org Slack integrations; this
-is intentionally separate — we own both sides.
-
-Every public function is safe to call unconditionally: if the webhook isn't
-configured or the call fails, we log and move on so the customer's submit/sign
-flow never breaks because Slack is flaky.
-"""
-
-from __future__ import annotations
-
-from typing import Any
-
-from django.conf import settings
-
-import requests
-import structlog
-
-from posthog.exceptions_capture import capture_exception
-
-logger = structlog.get_logger(__name__)
-
-DEFAULT_TIMEOUT_SECONDS = 10
-
-
-def _post(text: str, blocks: list[dict[str, Any]]) -> None:
- webhook_url = settings.SLACK_LEGAL_DOCUMENTS_WEBHOOK_URL
- if not webhook_url:
- logger.info("slack_legal_documents_not_configured", reason="missing webhook URL")
- return
- try:
- response = requests.post(
- webhook_url,
- json={"text": text, "blocks": blocks},
- timeout=DEFAULT_TIMEOUT_SECONDS,
- )
- if response.status_code >= 400:
- logger.warning(
- "slack_legal_documents_post_non_2xx",
- status=response.status_code,
- body=response.text[:500],
- )
- capture_exception(
- RuntimeError(f"Slack webhook returned {response.status_code}: {response.text[:200]}"),
- )
- except requests.RequestException as exc:
- logger.exception("slack_legal_documents_post_failed", error=str(exc))
- capture_exception(exc)
-
-
-def _fields_block(fields: list[tuple[str, str]]) -> dict[str, Any]:
- return {
- "type": "section",
- "fields": [{"type": "mrkdwn", "text": f"*{label}*\n{value or '_unknown_'}"} for label, value in fields],
- }
-
-
-def notify_submitted(
- *,
- document_type: str,
- company_name: str,
- representative_email: str,
- pandadoc_document_id: str | None,
-) -> None:
- header = f":scroll: New {document_type} submitted"
- blocks: list[dict[str, Any]] = [
- {"type": "header", "text": {"type": "plain_text", "text": header, "emoji": True}},
- _fields_block(
- [
- ("Company", company_name),
- ("Signer email", representative_email),
- ]
- ),
- ]
- if pandadoc_document_id:
- blocks.append(
- {
- "type": "actions",
- "elements": [
- {
- "type": "button",
- "text": {"type": "plain_text", "text": "Open in PandaDoc", "emoji": True},
- "url": f"https://app.pandadoc.com/a/#/documents/{pandadoc_document_id}",
- }
- ],
- }
- )
- _post(header, blocks)
-
-
-def notify_signed(
- *,
- document_type: str,
- company_name: str,
- pandadoc_document_id: str | None,
-) -> None:
- header = f":white_check_mark: {document_type} signed"
- blocks: list[dict[str, Any]] = [
- {"type": "header", "text": {"type": "plain_text", "text": header, "emoji": True}},
- _fields_block([("Company", company_name)]),
- ]
- if pandadoc_document_id:
- blocks.append(
- {
- "type": "actions",
- "elements": [
- {
- "type": "button",
- "text": {"type": "plain_text", "text": "Open in PandaDoc", "emoji": True},
- "url": f"https://app.pandadoc.com/a/#/documents/{pandadoc_document_id}",
- }
- ],
- }
- )
- _post(header, blocks)
diff --git a/products/legal_documents/backend/migrations/0004_alter_legaldocument_document_type.py b/products/legal_documents/backend/migrations/0004_alter_legaldocument_document_type.py
new file mode 100644
index 000000000000..fc31c74207e9
--- /dev/null
+++ b/products/legal_documents/backend/migrations/0004_alter_legaldocument_document_type.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.13 on 2026-05-07 04:35
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("legal_documents", "0003_legaldocument_drop_signed_document_url"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="legaldocument",
+ name="document_type",
+ field=models.CharField(
+ choices=[
+ ("BAA", "Business Associate Agreement"),
+ ("DPA", "Data Processing Agreement"),
+ ("MSA", "Master Service Agreement"),
+ ],
+ max_length=8,
+ ),
+ ),
+ ]
diff --git a/products/legal_documents/backend/migrations/max_migration.txt b/products/legal_documents/backend/migrations/max_migration.txt
index 389ce7484362..12ab0aec871e 100644
--- a/products/legal_documents/backend/migrations/max_migration.txt
+++ b/products/legal_documents/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0003_legaldocument_drop_signed_document_url
+0004_alter_legaldocument_document_type
diff --git a/products/legal_documents/backend/models.py b/products/legal_documents/backend/models.py
index ea2506e4d10d..a458a4161175 100644
--- a/products/legal_documents/backend/models.py
+++ b/products/legal_documents/backend/models.py
@@ -9,6 +9,10 @@ class LegalDocument(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UU
BAA = "BAA", "Business Associate Agreement"
DPA = "DPA", "Data Processing Agreement"
+ # MSA can only be created by staff via Django admin (uploads a counter-signed
+ # PDF directly). The public API serializer does not list MSA as a valid choice.
+ MSA = "MSA", "Master Service Agreement"
+
class Status(models.TextChoices):
SUBMITTED_FOR_SIGNATURE = "submitted_for_signature", "Submitted for signature"
SIGNED = "signed", "Signed"
diff --git a/products/legal_documents/backend/presentation/permissions.py b/products/legal_documents/backend/presentation/permissions.py
index ea1c9fa4c1a0..c1d1c17bcede 100644
--- a/products/legal_documents/backend/presentation/permissions.py
+++ b/products/legal_documents/backend/presentation/permissions.py
@@ -14,8 +14,8 @@ class IsCloudOrDevDeployment(BasePermission):
"""
Gates the legal-documents API to cloud (or a local DEBUG environment, so
we can test the flow). Self-hosted production deployments don't have the
- PandaDoc / Slack credentials and the feature is a PostHog-owned workflow,
- not something customers run on their own infrastructure.
+ PandaDoc credentials and the feature is a PostHog-owned workflow, not
+ something customers run on their own infrastructure.
"""
message = "Legal documents are only available on PostHog Cloud."
diff --git a/products/legal_documents/backend/presentation/webhook.py b/products/legal_documents/backend/presentation/webhook.py
index 8dc0d5250d0d..1523ea18c74c 100644
--- a/products/legal_documents/backend/presentation/webhook.py
+++ b/products/legal_documents/backend/presentation/webhook.py
@@ -47,8 +47,8 @@ _PANDADOC_COMPLETED_STATUS = "document.completed"
description=(
"PandaDoc webhook receiver. Authenticates via HMAC-SHA256 over the raw "
"body. Handles two `document_state_changed` events: `document.draft` "
- "dispatches the signing email + Slack ping, and `document.completed` "
- "pulls the signed PDF and stores it in object storage. Returns 200 "
+ "dispatches the signing email, and `document.completed` pulls the "
+ "signed PDF and stores it in object storage. Returns 200 "
"when an event applied, 204 when the request is valid but the "
"document doesn't live on this cloud instance (PandaDoc fans the "
"webhook out to every instance, only one of which owns the row), "
diff --git a/products/legal_documents/backend/storage.py b/products/legal_documents/backend/storage.py
new file mode 100644
index 000000000000..ec300ff7c8d7
--- /dev/null
+++ b/products/legal_documents/backend/storage.py
@@ -0,0 +1,20 @@
+"""
+Object storage helpers for legal documents — kept separate from logic/ so
+admin.py (autodiscovered very early by django.contrib.admin) doesn't transitively
+pull ee.billing.BillingManager and trigger an import cycle.
+"""
+
+from __future__ import annotations
+
+from django.conf import settings
+
+from .models import LegalDocument
+
+
+def signed_pdf_storage_key(document: LegalDocument) -> str:
+ """
+ Canonical key under which the signed PDF lives in object storage. The
+ document uuid is the natural identifier and never changes, so admins
+ regenerating the envelope for the same row just overwrite the old object.
+ """
+ return f"{settings.OBJECT_STORAGE_LEGAL_DOCUMENTS_FOLDER}/{document.id}.pdf"
diff --git a/products/legal_documents/backend/templates/admin/legal_documents/edit_inline/tabular.html b/products/legal_documents/backend/templates/admin/legal_documents/edit_inline/tabular.html
new file mode 100644
index 000000000000..d7d748104906
--- /dev/null
+++ b/products/legal_documents/backend/templates/admin/legal_documents/edit_inline/tabular.html
@@ -0,0 +1,63 @@
+{% load i18n admin_urls static admin_modify %}
+<div class="inline-group" id="{{ inline_admin_formset.formset.prefix }}-group">
+ <div class="tabular inline-related {% if forloop.last %}last-related{% endif %}">
+{{ inline_admin_formset.formset.management_form }}
+<fieldset class="module {{ inline_admin_formset.classes }}">
+ <h2 style="display: flex; align-items: center; justify-content: space-between; gap: 12px;">
+ <span>{{ inline_admin_formset.opts.verbose_name_plural|capfirst }}</span>
+ {% if inline_admin_formset.formset.instance.pk %}
+ <a class="button" style="font-weight: normal;" href="{% url 'admin:legal_documents_legaldocument_add' %}?organization={{ inline_admin_formset.formset.instance.pk }}">
+ {% translate "Upload signed document" %}
+ </a>
+ {% endif %}
+ </h2>
+ {{ inline_admin_formset.formset.non_form_errors }}
+ {% if inline_admin_formset|length %}
+ <table>
+ <thead><tr>
+ {% for field in inline_admin_formset.fields %}
+ {% if not field.widget.is_hidden %}
+ <th class="column-{{ field.name }}">{{ field.label|capfirst }}
+ {% if field.help_text %}<img src="{% static "admin/img/icon-unknown.svg" %}" class="help help-tooltip" width="10" height="10" alt="({{ field.help_text|striptags }})" title="{{ field.help_text|striptags }}">{% endif %}
+ </th>
+ {% endif %}
+ {% endfor %}
+ {% if inline_admin_formset.opts.show_change_link %}<th></th>{% endif %}
+ </tr></thead>
+
+ <tbody>
+ {% for inline_admin_form in inline_admin_formset %}
+ {% if inline_admin_form.form.non_field_errors %}
+ <tr class="row-form-errors"><td colspan="{{ inline_admin_form|cell_count }}">{{ inline_admin_form.form.non_field_errors }}</td></tr>
+ {% endif %}
+ <tr class="form-row" id="{{ inline_admin_formset.formset.prefix }}-{{ forloop.counter0 }}">
+ {% for fieldset in inline_admin_form %}
+ {% for line in fieldset %}
+ {% for field in line %}
+ {% if not field.field.is_hidden %}
+ <td class="{% if field.field.name %}field-{{ field.field.name }}{% endif %}">
+ {% if field.is_readonly %}
+ <p>{{ field.contents }}</p>
+ {% else %}
+ {{ field.field }}
+ {% endif %}
+ </td>
+ {% endif %}
+ {% endfor %}
+ {% endfor %}
+ {% endfor %}
+ {% if inline_admin_formset.opts.show_change_link and inline_admin_form.original %}
+ <td class="original">
+ <a href="{% url inline_admin_formset.opts.opts|admin_urlname:'change' inline_admin_form.original.pk|admin_urlquote %}" class="inlinechangelink">{% translate "Change" %}</a>
+ </td>
+ {% endif %}
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ {% else %}
+ <p style="margin: 8px 0; color: var(--body-quiet-color);">{% translate "No legal documents yet for this organization." %}</p>
+ {% endif %}
+</fieldset>
+ </div>
+</div>
diff --git a/products/legal_documents/backend/tests/test_admin.py b/products/legal_documents/backend/tests/test_admin.py
new file mode 100644
index 000000000000..a61c6b1d1e04
--- /dev/null
+++ b/products/legal_documents/backend/tests/test_admin.py
@@ -0,0 +1,246 @@
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.contrib.admin import AdminSite
+from django.core.exceptions import ValidationError
+from django.core.files.uploadedfile import SimpleUploadedFile, UploadedFile
+from django.test import RequestFactory
+from django.utils.datastructures import MultiValueDict
+
+from parameterized import parameterized
+
+from posthog.models.organization import OrganizationMembership
+
+from products.legal_documents.backend.admin import LegalDocumentAdmin, LegalDocumentAdminForm
+from products.legal_documents.backend.models import LegalDocument
+from products.legal_documents.backend.storage import signed_pdf_storage_key
+
+_VALID_PDF_BYTES = b"%PDF-1.4\nfake pdf bytes for testing\n%%EOF"
+
+
+def _pdf_file(name: str = "agreement.pdf", content: bytes = _VALID_PDF_BYTES) -> SimpleUploadedFile:
+ return SimpleUploadedFile(name, content, content_type="application/pdf")
+
+
+def _files(pdf: UploadedFile | None = None) -> MultiValueDict[str, UploadedFile]:
+ """Build the typed MultiValueDict the form constructor expects."""
+ mvd: MultiValueDict[str, UploadedFile] = MultiValueDict()
+ if pdf is not None:
+ mvd["signed_pdf"] = pdf
+ return mvd
+
+
+class TestLegalDocumentAdminForm(APIBaseTest):
+ def _form_data(self, **overrides: Any) -> dict[str, Any]:
+ data = {
+ "organization": str(self.organization.id),
+ "document_type": "DPA",
+ "company_name": "Acme, Inc.",
+ "company_address": "1 Analytics Way, SF CA",
+ "representative_email": "[email protected]",
+ }
+ data.update(overrides)
+ return data
+
+ def test_valid_pdf_passes_validation(self) -> None:
+ form = LegalDocumentAdminForm(data=self._form_data(), files=_files(_pdf_file()))
+ self.assertTrue(form.is_valid(), form.errors)
+
+ def test_non_pdf_extension_is_rejected(self) -> None:
+ bad_file = SimpleUploadedFile("agreement.txt", b"not a pdf", content_type="text/plain")
+ form = LegalDocumentAdminForm(data=self._form_data(), files=_files(bad_file))
+ self.assertFalse(form.is_valid())
+ self.assertIn("signed_pdf", form.errors)
+
+ def test_wrong_content_type_is_rejected(self) -> None:
+ # .pdf extension passes the FileExtensionValidator, but if the browser
+ # reports a non-application/pdf content type the form should still reject.
+ bad_file = SimpleUploadedFile("agreement.pdf", _VALID_PDF_BYTES, content_type="image/png")
+ form = LegalDocumentAdminForm(data=self._form_data(), files=_files(bad_file))
+ self.assertFalse(form.is_valid())
+ self.assertIn("signed_pdf", form.errors)
+
+ def test_oversized_pdf_is_rejected(self) -> None:
+ # 26 MiB — over the 25 MiB cap.
+ oversized = SimpleUploadedFile("big.pdf", b"x" * (26 * 1024 * 1024), content_type="application/pdf")
+ form = LegalDocumentAdminForm(data=self._form_data(), files=_files(oversized))
+ self.assertFalse(form.is_valid())
+ self.assertIn("signed_pdf", form.errors)
+
+ def test_missing_pdf_is_rejected(self) -> None:
+ form = LegalDocumentAdminForm(data=self._form_data(), files=_files())
+ self.assertFalse(form.is_valid())
+ self.assertIn("signed_pdf", form.errors)
+
+
+class TestLegalDocumentAdminSave(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.user.is_staff = True
+ self.user.save()
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ self.admin = LegalDocumentAdmin(LegalDocument, AdminSite())
+ self.request_factory = RequestFactory()
+
+ def _request(self) -> Any:
+ request = self.request_factory.post("/admin/posthog/legaldocument/add/")
+ request.user = self.user
+ return request
+
+ def _bound_form(self, document_type: str = "DPA") -> LegalDocumentAdminForm:
+ form = LegalDocumentAdminForm(
+ data={
+ "organization": str(self.organization.id),
+ "document_type": document_type,
+ "company_name": "Acme, Inc.",
+ "company_address": "1 Analytics Way, SF CA",
+ "representative_email": "[email protected]",
+ },
+ files=_files(_pdf_file()),
+ )
+ self.assertTrue(form.is_valid(), form.errors)
+ return form
+
+ @parameterized.expand([("DPA",), ("BAA",), ("MSA",)])
+ @patch("products.legal_documents.backend.admin.object_storage")
+ def test_admin_upload_creates_signed_row_and_writes_to_s3(self, document_type: str, mock_storage: Any) -> None:
+ form = self._bound_form(document_type=document_type)
+ instance = form.save(commit=False)
+
+ self.admin.save_model(self._request(), instance, form, change=False)
+
+ row = LegalDocument.objects.get(id=instance.id)
+ self.assertEqual(row.document_type, document_type)
+ self.assertEqual(row.status, LegalDocument.Status.SIGNED)
+ self.assertEqual(row.created_by_id, self.user.id)
+ self.assertEqual(row.organization_id, self.organization.id)
+
+ mock_storage.write_stream.assert_called_once()
+ write_args, write_kwargs = mock_storage.write_stream.call_args
+ # Key matches the canonical legal_documents/{id}.pdf shape used by the
+ # public download endpoint.
+ self.assertTrue(write_args[0].endswith(f"{row.id}.pdf"))
+ self.assertEqual(write_kwargs.get("extras"), {"ContentType": "application/pdf"})
+
+ @patch("products.legal_documents.backend.admin.object_storage")
+ def test_s3_failure_rolls_back_row(self, mock_storage: Any) -> None:
+ mock_storage.write_stream.side_effect = RuntimeError("s3 unreachable")
+
+ form = self._bound_form()
+ instance = form.save(commit=False)
+ with self.assertRaises(ValidationError):
+ self.admin.save_model(self._request(), instance, form, change=False)
+
+ # Row was not persisted — transaction.atomic rolled it back when ValidationError fired.
+ self.assertFalse(LegalDocument.objects.filter(id=instance.id).exists())
+
+ def test_pre_existing_row_blocks_form_validation(self) -> None:
+ # Django's ModelForm.validate_unique catches the unique-per-org-per-type
+ # constraint at form-validation time, so the admin user sees a clean
+ # form error instead of a 500. (save_model also handles IntegrityError
+ # as defense in depth for race conditions, but the normal path stops
+ # at form.is_valid().)
+ LegalDocument.objects.create(
+ organization=self.organization,
+ document_type="DPA",
+ company_name="Already there",
+ company_address="elsewhere",
+ representative_email="[email protected]",
+ status=LegalDocument.Status.SIGNED,
+ )
+ form = LegalDocumentAdminForm(
+ data={
+ "organization": str(self.organization.id),
+ "document_type": "DPA",
+ "company_name": "Acme, Inc.",
+ "company_address": "1 Analytics Way, SF CA",
+ "representative_email": "[email protected]",
+ },
+ files=_files(_pdf_file()),
+ )
+ 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:
+ 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,
+ )
+ # Snapshot before delete: obj.delete() clears the pk on the in-memory
+ # instance, so signed_pdf_storage_key(document) would compute against
+ # id=None afterwards.
+ expected_key = signed_pdf_storage_key(document)
+ document_id = document.id
+ self.admin.delete_model(self._request(), document)
+
+ mock_storage.delete.assert_called_once_with(expected_key)
+ self.assertFalse(LegalDocument.objects.filter(id=document_id).exists())
+
+ def test_change_view_form_saves_without_signed_pdf(self) -> None:
+ # The add form (LegalDocumentAdminForm) declares signed_pdf
+ # as a required FileField. If it leaks into the change view's form,
+ # "Save" on an existing row fails with "This field is required" even
+ # though no upload widget is rendered.
+ 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.SIGNED,
+ )
+ change_form_class = self.admin.get_form(self._request(), obj=document, change=True)
+
+ # The change-view form must not declare signed_pdf. (Plain ModelForm
+ # 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:
+ # If S3 cleanup fails the row should still be deleted — best-effort cleanup.
+ mock_storage.delete.side_effect = RuntimeError("s3 down")
+ 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,
+ )
+ document_id = document.id
+
+ self.admin.delete_model(self._request(), document)
+
+ self.assertFalse(LegalDocument.objects.filter(id=document_id).exists())
+
+
+class TestLegalDocumentAdminPermissions(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.admin = LegalDocumentAdmin(LegalDocument, AdminSite())
+ self.request_factory = RequestFactory()
+
+ def _request_for(self, *, is_staff: bool) -> Any:
+ request = self.request_factory.get("/admin/posthog/legaldocument/")
+ self.user.is_staff = is_staff
+ self.user.save()
+ request.user = self.user
+ return request
+
+ def test_staff_can_add_and_delete(self) -> None:
+ request = self._request_for(is_staff=True)
+ self.assertTrue(self.admin.has_add_permission(request))
+ self.assertTrue(self.admin.has_delete_permission(request))
+
+ def test_non_staff_cannot_add_or_delete(self) -> None:
+ request = self._request_for(is_staff=False)
+ self.assertFalse(self.admin.has_add_permission(request))
+ self.assertFalse(self.admin.has_delete_permission(request))
diff --git a/products/legal_documents/backend/tests/test_api.py b/products/legal_documents/backend/tests/test_api.py
index 4901bdf305df..20bc5183a8cd 100644
--- a/products/legal_documents/backend/tests/test_api.py
+++ b/products/legal_documents/backend/tests/test_api.py
@@ -92,6 +92,15 @@ class TestLegalDocumentAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn("company_address", response.json()["attr"])
+ def test_create_msa_is_rejected_from_public_api(self) -> None:
+ # MSAs only exist via Django admin upload — the public serializer's
+ # ChoiceField does not list MSA, so a POST should 400 on document_type.
+ payload = {**DPA_PAYLOAD, "document_type": "MSA"}
+ response = self.client.post(self.url, payload, format="json")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("document_type", response.json()["attr"])
+ self.assertFalse(LegalDocument.objects.exists())
+
def test_list_is_scoped_to_current_organization(self) -> None:
other_org = Organization.objects.create(name="Other")
LegalDocument.objects.create(
@@ -453,20 +462,18 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):
self.document.refresh_from_db()
self.assertEqual(self.document.status, "submitted_for_signature")
- def test_draft_event_dispatches_send_and_fires_slack(self) -> None:
+ def test_draft_event_dispatches_send(self) -> None:
body = json.dumps(self._draft_payload()).encode("utf-8")
with (
self._override(),
patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.send_document") as send_mock,
- patch("products.legal_documents.backend.logic.notify_slack_on_submit") as slack_mock,
):
response = self._post_raw(body, self._sign(body))
self.assertEqual(response.status_code, status.HTTP_200_OK)
send_mock.assert_called_once()
self.assertEqual(send_mock.call_args.kwargs["document_id"], "doc_123")
- slack_mock.assert_called_once()
- def test_draft_event_skips_slack_if_pandadoc_send_fails(self) -> None:
+ def test_draft_event_swallows_pandadoc_send_failure(self) -> None:
from products.legal_documents.backend.logic import pandadoc as pandadoc_client
body = json.dumps(self._draft_payload()).encode("utf-8")
@@ -476,12 +483,10 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):
"products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.send_document",
side_effect=pandadoc_client.PandaDocError("boom"),
),
- patch("products.legal_documents.backend.logic.notify_slack_on_submit") as slack_mock,
):
response = self._post_raw(body, self._sign(body))
- # Endpoint still 2xx (we don't want PandaDoc to retry) but Slack is skipped.
+ # Endpoint still 2xx — we don't want PandaDoc to retry.
self.assertEqual(response.status_code, status.HTTP_200_OK)
- slack_mock.assert_not_called()
def test_draft_event_for_already_signed_document_is_a_noop(self) -> None:
self.document.status = "signed"
@@ -491,12 +496,10 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):
with (
self._override(),
patch("products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.send_document") as send_mock,
- patch("products.legal_documents.backend.logic.notify_slack_on_submit") as slack_mock,
):
response = self._post_raw(body, self._sign(body))
self.assertEqual(response.status_code, status.HTTP_200_OK)
send_mock.assert_not_called()
- slack_mock.assert_not_called()
def test_template_mismatch_does_not_flip_row(self) -> None:
# Completed event with BAA template id for what's actually a DPA row in the DB
@@ -534,8 +537,8 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):
self.document.refresh_from_db()
self.assertEqual(self.document.status, "signed")
- # Replay: must not re-stream the PDF, re-upload, or re-fire Slack /
- # analytics. PandaDoc retries / cross-instance fan-out both land here.
+ # Replay: must not re-stream the PDF, re-upload, or re-fire analytics.
+ # PandaDoc retries / cross-instance fan-out both land here.
replay_body = json.dumps(self._completed_payload()).encode("utf-8")
with (
self._override(),
@@ -543,22 +546,20 @@ class TestLegalDocumentPandaDocWebhook(APIBaseTest):
"products.legal_documents.backend.logic.pandadoc_client.PandaDocClient.stream_document"
) as stream_spy,
patch("products.legal_documents.backend.logic.object_storage.write_stream") as write_spy,
- patch("products.legal_documents.backend.logic.notify_slack_on_signed") as slack_spy,
patch("products.legal_documents.backend.logic.fire_legal_document_signed_event") as event_spy,
):
response = self._post_raw(replay_body, self._sign(replay_body))
self.assertEqual(response.status_code, status.HTTP_200_OK)
stream_spy.assert_not_called()
write_spy.assert_not_called()
- slack_spy.assert_not_called()
event_spy.assert_not_called()
@override_settings(CLOUD_DEPLOYMENT=None, DEBUG=False)
class TestLegalDocumentsSelfHostedGate(APIBaseTest):
"""
- Self-hosted instances must never hit the PandaDoc / Slack integrations. The
- API should 404 regardless of auth, and the PandaDoc webhook should 404 even
+ Self-hosted instances must never hit the PandaDoc integration. The API
+ should 404 regardless of auth, and the PandaDoc webhook should 404 even
with a valid signature.
"""
diff --git a/products/legal_documents/backend/tests/test_pandadoc.py b/products/legal_documents/backend/tests/test_pandadoc.py
index 443ebfd252d1..5f1af6d6cac7 100644
--- a/products/legal_documents/backend/tests/test_pandadoc.py
+++ b/products/legal_documents/backend/tests/test_pandadoc.py
@@ -36,6 +36,7 @@ class TestPandaDocClient(TestCase):
recipients=[pandadoc.PandaDocRecipient(email="[email protected]", role=pandadoc.PandaDocRole.CLIENT)],
tokens={"Client.Company": "Acme, Inc.", "Client.StreetAddress": "1 Analytics Way"},
metadata={"legal_document_id": "lid-1"},
+ owner_email="[email protected]",
)
mock_post.assert_called_once()
@@ -54,8 +55,30 @@ class TestPandaDocClient(TestCase):
],
)
self.assertEqual(body["metadata"], {"legal_document_id": "lid-1"})
+ self.assertEqual(body["owner"], {"email": "[email protected]"})
self.assertEqual(result.id, "doc_123")
+ @override_settings(PANDADOC_API_KEY="key", PANDADOC_API_BASE_URL="https://api.pandadoc.com")
+ def test_create_document_omits_owner_when_not_provided(self) -> None:
+ # When `owner_email` is None we leave the field off so PandaDoc falls
+ # back to the API key's owning user.
+ fake_response = MagicMock()
+ fake_response.status_code = 201
+ fake_response.content = b'{"id": "doc_123", "status": "document.uploaded", "name": "doc"}'
+ fake_response.json.return_value = {"id": "doc_123", "status": "document.uploaded", "name": "doc"}
+
+ with patch(
+ "products.legal_documents.backend.logic.pandadoc.requests.post", return_value=fake_response
+ ) as mock_post:
+ pandadoc.PandaDocClient().create_document_from_template(
+ template_id="tpl",
+ name="doc",
+ recipients=[pandadoc.PandaDocRecipient(email="[email protected]", role=pandadoc.PandaDocRole.CLIENT)],
+ )
+
+ body = mock_post.call_args.kwargs["json"]
+ self.assertNotIn("owner", body)
+
@override_settings(PANDADOC_API_KEY="key", PANDADOC_API_BASE_URL="https://api.pandadoc.com")
def test_stream_document_yields_raw_binary_stream(self) -> None:
fake_response = MagicMock()
@@ -122,5 +145,5 @@ class TestPandaDocClient(TestCase):
# minimal shape; tokens carry all template content.
client = pandadoc.PandaDocRecipient(email="[email protected]", role=pandadoc.PandaDocRole.CLIENT)
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"})
+ posthog = pandadoc.PandaDocRecipient(email="[email protected]", role=pandadoc.PandaDocRole.POSTHOG)
+ self.assertEqual(pandadoc._serialize_recipient(posthog), {"email": "[email protected]", "role": "PostHog"})
diff --git a/products/legal_documents/frontend/scenes/LegalDocumentsScene.tsx b/products/legal_documents/frontend/scenes/LegalDocumentsScene.tsx
index 91f2b1b9dfb1..0498699b5a9c 100644
--- a/products/legal_documents/frontend/scenes/LegalDocumentsScene.tsx
+++ b/products/legal_documents/frontend/scenes/LegalDocumentsScene.tsx
@@ -53,6 +53,18 @@ function buildNewMenuItems(existingTypes: Set<LegalDocumentType>): LemonMenuItem
disabledReason: alreadyExistsReason('BAA'),
'data-attr': 'new-legal-document-menu-baa',
},
+ {
+ label: (
+ <div className="flex flex-col text-sm py-1">
+ <strong>Master Service Agreement (MSA)</strong>
+ <span className="text-xs font-normal text-muted">
+ Negotiated with sales — contact your TAM or PostHog support to sign one.
+ </span>
+ </div>
+ ),
+ disabledReason: 'MSAs are negotiated by sales. Contact your TAM or PostHog support to sign an MSA.',
+ 'data-attr': 'new-legal-document-menu-msa',
+ },
],
},
]
diff --git a/tools/hogli-commands/hogli_commands/product/checks.py b/tools/hogli-commands/hogli_commands/product/checks.py
index d848ee89fca5..33ed4ed5a18b 100644
--- a/tools/hogli-commands/hogli_commands/product/checks.py
+++ b/tools/hogli-commands/hogli_commands/product/checks.py
@@ -473,6 +473,9 @@ class MisplacedFilesCheck(ProductCheck):
# Directories allowed in backend/ for strict products.
# Anything else won't be covered by import-linter's wildcard contracts.
+ # `templates` is allowed because Django's app_directories loader requires
+ # the folder to live at <app>/templates/, and templates aren't Python
+ # imports so import-linter contracts don't apply.
_KNOWN_DIRS = {
"facade",
"presentation",
@@ -483,6 +486,7 @@ class MisplacedFilesCheck(ProductCheck):
"management",
"models",
"logic",
+ "templates",
"__pycache__",
}