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): block baa generation for startup program orgs (#96306)

Eleftheria Trivyzaki16937a6ad818
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f589d938ea16..5e1cccd5de6e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -12438,6 +12438,10 @@ snapshots:
hash: v1.k794b7964.9cb90971cdadb1eadf912754aeb2a82d4fcaf5d91aa716a39bed7b324e8f03be.M6963VTBjXD11KLz9OLd6vbdx2IBcrzUYEli26SO2as
scenes-app-legal-documents--legal-documents-list--light:
hash: v1.k794b7964.05b6c56f4cef8f9b8386948abbb0bdc4b680e9be79d184b3da0330c8dd5f9b60.2HkDspfdkpfRhBhGBKCuOMuhVQ3Zz3Mp4cxaQ9j3Xig
+ scenes-app-legal-documents--list-startup-program--dark:
+ hash: v1.k794b7964.ac0e6aa19a876bf0bf0a3a342e3b801f127b250456bc51c17addf092bd459453.uH3oMa4M1SgNx7rMysiA7zy6FuOeyHSXKvcFhGQQITI
+ scenes-app-legal-documents--list-startup-program--light:
+ hash: v1.k794b7964.6531ca3805af309ceb47b8f3dd2dc3e0300781e929717a291ecadffb8d6e95a7.fHGbeS5ZcgC7R1XSYdiCI5W47puNnvQWcjigUU5HPA4
scenes-app-legal-documents--new-baa--dark:
hash: v1.k794b7964.d27bc51ca3eb6558516096bed27c8a9635b9959772740b9f50ad859b30a2cb21.c38V0VJ_FmXrfFFH5MG0wgq0RkS6v2fbwNEf28xYwm4
scenes-app-legal-documents--new-baa--light:
@@ -12446,6 +12450,10 @@ snapshots:
hash: v1.k794b7964.d7c9c6dc61e5545dc7709f650ec2ffb6e961ac48c93dcca9f295138e55b73590.Ilivb1eK3IGtnTNiza4nZh7qi7-PUAqbNZIPJhQtdCs
scenes-app-legal-documents--new-baa-enterprise-trial--light:
hash: v1.k794b7964.b5493e7322be4db73d91d553c1f4b68dd7c65e15431b3bc1e5ed36607d1b830e.DM7BWrnwtC92aImFuFRI5KJVOk3kdTn4ZVfNyUNr2Pc
+ scenes-app-legal-documents--new-baa-startup-program--dark:
+ hash: v1.k794b7964.117303f77bda2ab6794dac8893d5b01403fa7c47c9d4819199b450ab7b65ed51.3cTYv1wK4EZLrz_FfCmvMo0qvpDrvoSJrYRQQ06o4wc
+ scenes-app-legal-documents--new-baa-startup-program--light:
+ hash: v1.k794b7964.d3d9673ef819048d4a894757d7227d2f472356bcedf7d8ddd65885a4ecfc3a03.5FKMeIvGHY7txt3_RKc9rfgUgex0-4Eo125J3Nk3LcA
scenes-app-legal-documents--new-baa-trial--dark:
hash: v1.k794b7964.d108d937d14385e29055ed9cc3f03c6a51359c00942bdbda7d014be239ad2b1a.l6rOQ4qR0MHyMZwbUGAj_FrYrBkXFxer1FpW7iloGnY
scenes-app-legal-documents--new-baa-trial--light:
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 06f7380e8fa7..bde3f7843640 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3930,6 +3930,10 @@ importers:
react:
specifier: 18.3.1
version: 18.3.1
+ devDependencies:
+ kea-test-utils:
+ specifier: 'catalog:'
+ version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
products/links: {}
diff --git a/products/legal_documents/backend/facade/api.py b/products/legal_documents/backend/facade/api.py
index 4e76414db849..65ab09d71fa5 100644
--- a/products/legal_documents/backend/facade/api.py
+++ b/products/legal_documents/backend/facade/api.py
@@ -31,7 +31,7 @@ from ..logic import (
from ..logic.pandadoc import PandaDocError
from ..models import LegalDocument
from . import contracts
-from .enums import LegalDocumentStatus
+from .enums import BaaBlockReason, LegalDocumentStatus
logger = structlog.get_logger(__name__)
@@ -84,8 +84,8 @@ def get_signed_pdf_download_url(document_id: UUID, organization_id: UUID) -> str
return logic.get_signed_pdf_presigned_url(document)
-def has_qualifying_baa_addon(organization: Organization) -> bool:
- return logic.has_qualifying_baa_addon(organization)
+def get_baa_block_reason(organization: Organization, impersonated: bool) -> BaaBlockReason | None:
+ return logic.get_baa_block_reason(organization, impersonated)
def has_signed_baa(organization_id: UUID) -> bool:
diff --git a/products/legal_documents/backend/facade/enums.py b/products/legal_documents/backend/facade/enums.py
index e5b535ff5451..722a4cab2112 100644
--- a/products/legal_documents/backend/facade/enums.py
+++ b/products/legal_documents/backend/facade/enums.py
@@ -12,3 +12,8 @@ class DocumentType(StrEnum):
class LegalDocumentStatus(StrEnum):
SUBMITTED_FOR_SIGNATURE = "submitted_for_signature"
SIGNED = "signed"
+
+
+class BaaBlockReason(StrEnum):
+ STARTUP_PROGRAM = "startup_program"
+ NO_QUALIFYING_ADDON = "no_qualifying_addon"
diff --git a/products/legal_documents/backend/logic/__init__.py b/products/legal_documents/backend/logic/__init__.py
index ac5e0b6bde1f..df0df408fe6e 100644
--- a/products/legal_documents/backend/logic/__init__.py
+++ b/products/legal_documents/backend/logic/__init__.py
@@ -26,9 +26,9 @@ from posthog.exceptions_capture import capture_exception
from posthog.models.organization import Organization, OrganizationMembership
from posthog.storage import object_storage
-from ee.billing.billing_manager import BillingManager
+from ee.billing.billing_manager import BillingManager, StartupProgramLabel
-from ..facade.enums import DocumentType
+from ..facade.enums import BaaBlockReason, DocumentType
from ..models import LegalDocument
from ..storage import signed_pdf_storage_key
from . import pandadoc as pandadoc_client
@@ -38,6 +38,11 @@ logger = structlog.get_logger(__name__)
# Addon types that entitle an organization to a BAA.
BAA_ADDON_TYPES = frozenset({"boost", "scale", "enterprise"})
+# Startup program organizations always pay with credits, and credits do not cover
+# a BAA, whatever addon they hold. YC organizations keep BAA access. Staff who
+# impersonate a startup organization that pays for a BAA generate it on its behalf.
+BAA_BLOCKED_STARTUP_PROGRAM_LABEL: StartupProgramLabel = "Startup"
+
# Attribute `annotate_signed_baa` writes onto each Organization row.
SIGNED_BAA_ANNOTATION = "has_signed_baa"
@@ -76,13 +81,16 @@ def template_id_matches_document(document: LegalDocument, template_id: str) -> b
return not expected or expected == template_id
-def has_qualifying_baa_addon(organization: Organization) -> bool:
+def get_baa_block_reason(organization: Organization, impersonated: bool) -> BaaBlockReason | None:
billing = BillingManager(get_cached_instance_license()).get_billing(organization)
+ on_startup_program = billing.get("startup_program_label") == BAA_BLOCKED_STARTUP_PROGRAM_LABEL
+ if on_startup_program and not impersonated:
+ return BaaBlockReason.STARTUP_PROGRAM
for product in billing.get("products") or []:
for addon in product.get("addons") or []:
if addon.get("type") in BAA_ADDON_TYPES and addon.get("subscribed"):
- return True
- return False
+ return None
+ return BaaBlockReason.NO_QUALIFYING_ADDON
def _signed_baa_subquery() -> QuerySet[LegalDocument]:
diff --git a/products/legal_documents/backend/presentation/serializers.py b/products/legal_documents/backend/presentation/serializers.py
index 32a828f3a2d1..c92b828b663a 100644
--- a/products/legal_documents/backend/presentation/serializers.py
+++ b/products/legal_documents/backend/presentation/serializers.py
@@ -4,11 +4,12 @@ from rest_framework import serializers
from rest_framework.exceptions import PermissionDenied
from rest_framework_dataclasses.serializers import DataclassSerializer
+from posthog.helpers.impersonation import is_impersonated
from posthog.models.organization import Organization
from ..facade import api
from ..facade.contracts import LegalDocumentDTO
-from ..facade.enums import DocumentType
+from ..facade.enums import BaaBlockReason, DocumentType
class LegalDocumentSerializer(DataclassSerializer):
@@ -18,6 +19,12 @@ class LegalDocumentSerializer(DataclassSerializer):
dataclass = LegalDocumentDTO
+BAA_BLOCK_MESSAGES: dict[BaaBlockReason, str] = {
+ BaaBlockReason.STARTUP_PROGRAM: "BAAs aren't covered by startup program credits. Contact us to discuss options.",
+ BaaBlockReason.NO_QUALIFYING_ADDON: "A Boost, Scale, or Enterprise add-on is required to generate a BAA.",
+}
+
+
class CreateLegalDocumentSerializer(serializers.Serializer):
"""
Input serializer for POST. Mirrors the submittable fields on the model plus
@@ -45,8 +52,12 @@ class CreateLegalDocumentSerializer(serializers.Serializer):
document_type = attrs["document_type"]
organization: Organization = self.context["view"].organization
- if document_type == DocumentType.BAA and not api.has_qualifying_baa_addon(organization):
- raise PermissionDenied("A Boost, Scale, or Enterprise add-on is required to generate a BAA.")
+ if document_type == DocumentType.BAA:
+ block_reason = api.get_baa_block_reason(organization, is_impersonated(self.context.get("request")))
+ if block_reason is not None:
+ raise PermissionDenied(
+ BAA_BLOCK_MESSAGES.get(block_reason, BAA_BLOCK_MESSAGES[BaaBlockReason.NO_QUALIFYING_ADDON])
+ )
# Only one BAA and one DPA per organization. If they need a new one, a staff
# member deletes the old row from Django admin. The DB-level unique constraint
diff --git a/products/legal_documents/backend/tests/test_api.py b/products/legal_documents/backend/tests/test_api.py
index 991bc6a943d0..767d9a715050 100644
--- a/products/legal_documents/backend/tests/test_api.py
+++ b/products/legal_documents/backend/tests/test_api.py
@@ -6,7 +6,7 @@ from datetime import timedelta
from typing import Any
from posthog.test.base import APIBaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.db import IntegrityError
from django.test import override_settings
@@ -40,15 +40,16 @@ DPA_PAYLOAD = {
}
-def _billing_with_addons(addon_types_subscribed: set[str]) -> dict[str, Any]:
+def _billing_with_addons(addon_types_subscribed: set[str], startup_program_label: str | None = None) -> dict[str, Any]:
return {
+ "startup_program_label": startup_program_label,
"products": [
{
"type": "platform_and_support",
"addons": [{"type": addon_type, "subscribed": True} for addon_type in addon_types_subscribed]
+ [{"type": "unrelated", "subscribed": False}],
}
- ]
+ ],
}
@@ -83,6 +84,48 @@ class TestLegalDocumentAPI(APIBaseTest):
self.assertIn("Boost, Scale, or Enterprise", response.json()["detail"])
self.assertFalse(LegalDocument.objects.exists())
+ @parameterized.expand(
+ [
+ ("startup_with_boost", "Startup", {"boost"}, False, status.HTTP_403_FORBIDDEN, "startup program credits"),
+ ("startup_without_addon", "Startup", set(), False, status.HTTP_403_FORBIDDEN, "startup program credits"),
+ (
+ "startup_impersonated_without_addon",
+ "Startup",
+ set(),
+ True,
+ status.HTTP_403_FORBIDDEN,
+ "Boost, Scale, or Enterprise",
+ ),
+ ("startup_impersonated", "Startup", {"boost"}, True, status.HTTP_201_CREATED, None),
+ ("yc", "YC", {"boost"}, False, status.HTTP_201_CREATED, None),
+ ]
+ )
+ @patch("products.legal_documents.backend.presentation.serializers.is_impersonated")
+ @patch("products.legal_documents.backend.logic.BillingManager")
+ def test_create_baa_respects_startup_program(
+ self,
+ _name: str,
+ startup_program_label: str | None,
+ addons: set[str],
+ impersonated: bool,
+ expected_status: int,
+ expected_error: str | None,
+ mock_manager_cls: MagicMock,
+ mock_is_impersonated: MagicMock,
+ ) -> None:
+ mock_manager_cls.return_value.get_billing.return_value = _billing_with_addons(addons, startup_program_label)
+ mock_is_impersonated.return_value = impersonated
+
+ response = self.client.post(self.url, BAA_PAYLOAD, format="json")
+
+ self.assertEqual(response.status_code, expected_status, response.json())
+ created = LegalDocument.objects.filter(document_type="BAA").exists()
+ if expected_error is not None:
+ self.assertIn(expected_error, response.json()["detail"])
+ self.assertFalse(created)
+ else:
+ self.assertTrue(created)
+
def test_create_dpa_succeeds(self) -> None:
response = self.client.post(self.url, DPA_PAYLOAD, format="json")
self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
@@ -168,8 +211,8 @@ class TestLegalDocumentAPI(APIBaseTest):
@patch("products.legal_documents.backend.logic.posthoganalytics.capture")
def test_create_baa_fires_submitted_event(self, mock_capture) -> None:
with patch(
- "products.legal_documents.backend.logic.has_qualifying_baa_addon",
- return_value=True,
+ "products.legal_documents.backend.logic.get_baa_block_reason",
+ return_value=None,
):
response = self.client.post(self.url, BAA_PAYLOAD, format="json")
@@ -209,7 +252,7 @@ class TestLegalDocumentAPI(APIBaseTest):
self.assertIn("already has a DPA", second.json()["detail"])
self.assertEqual(LegalDocument.objects.filter(document_type="DPA").count(), 1)
- @patch("products.legal_documents.backend.logic.has_qualifying_baa_addon", return_value=True)
+ @patch("products.legal_documents.backend.logic.get_baa_block_reason", return_value=None)
def test_only_one_baa_per_organization(self, _mock_addon) -> None:
first = self.client.post(self.url, BAA_PAYLOAD, format="json")
self.assertEqual(first.status_code, status.HTTP_201_CREATED)
@@ -219,7 +262,7 @@ class TestLegalDocumentAPI(APIBaseTest):
self.assertIn("already has a BAA", second.json()["detail"])
self.assertEqual(LegalDocument.objects.filter(document_type="BAA").count(), 1)
- @patch("products.legal_documents.backend.logic.has_qualifying_baa_addon", return_value=True)
+ @patch("products.legal_documents.backend.logic.get_baa_block_reason", return_value=None)
def test_baa_and_dpa_can_coexist_in_same_organization(self, _mock_addon) -> None:
baa_response = self.client.post(self.url, BAA_PAYLOAD, format="json")
dpa_response = self.client.post(self.url, DPA_PAYLOAD, format="json")
diff --git a/products/legal_documents/frontend/components/ContactBillingSupportLink.tsx b/products/legal_documents/frontend/components/ContactBillingSupportLink.tsx
new file mode 100644
index 000000000000..4c123298b382
--- /dev/null
+++ b/products/legal_documents/frontend/components/ContactBillingSupportLink.tsx
@@ -0,0 +1,24 @@
+import { useActions } from 'kea'
+
+import { Link } from '@posthog/lemon-ui'
+
+import { supportLogic } from 'lib/components/Support/supportLogic'
+
+export function ContactBillingSupportLink({
+ children,
+ 'data-attr': dataAttr = 'legal-documents-contact-billing-support',
+}: {
+ children: React.ReactNode
+ 'data-attr'?: string
+}): JSX.Element {
+ const { openSupportForm } = useActions(supportLogic)
+ return (
+ <Link
+ to=""
+ onClick={() => openSupportForm({ billing_issue: true, isEmailFormOpen: true })}
+ data-attr={dataAttr}
+ >
+ {children}
+ </Link>
+ )
+}
diff --git a/products/legal_documents/frontend/scenes/LegalDocumentNewScene.tsx b/products/legal_documents/frontend/scenes/LegalDocumentNewScene.tsx
index 7750a7d9aeb1..450c370fadd7 100644
--- a/products/legal_documents/frontend/scenes/LegalDocumentNewScene.tsx
+++ b/products/legal_documents/frontend/scenes/LegalDocumentNewScene.tsx
@@ -4,7 +4,6 @@ import { Form } from 'kea-forms'
import { IconBalance, IconSend } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonInput, LemonSelect, Link } from '@posthog/lemon-ui'
-import { supportLogic } from 'lib/components/Support/supportLogic'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonRadio } from 'lib/lemon-ui/LemonRadio'
import { organizationLogic } from 'scenes/organizationLogic'
@@ -15,9 +14,10 @@ import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import { ContactBillingSupportLink } from '../components/ContactBillingSupportLink'
import { LegalDocumentsPreview } from '../components/LegalDocumentsPreview'
import { FIELD_IDS } from './legalDocumentsConstants'
-import { DPAMode, LegalDocumentType, legalDocumentsLogic } from './legalDocumentsLogic'
+import { BAA_BLOCK_REASON_MESSAGES, DPAMode, LegalDocumentType, legalDocumentsLogic } from './legalDocumentsLogic'
function buildDocumentTypeOptions(
existingTypes: Set<LegalDocumentType>
@@ -73,7 +73,7 @@ export function LegalDocumentNewScene(): JSX.Element {
legalDocument,
legalDocumentHasErrors,
isLegalDocumentSubmitting,
- hasQualifyingBaaAddon,
+ baaBlockReason: organizationBaaBlockReason,
isOnQualifyingAddonTrial,
isOnEnterpriseStandardTrial,
isDpaModeSubmittable,
@@ -83,7 +83,6 @@ export function LegalDocumentNewScene(): JSX.Element {
const { isAdminOrOwner } = useValues(organizationLogic)
const { isCloudOrDev } = useValues(preflightLogic)
const { setDocumentType, setDpaMode } = useActions(legalDocumentsLogic)
- const { openSupportForm } = useActions(supportLogic)
if (!isCloudOrDev) {
return (
@@ -127,14 +126,14 @@ export function LegalDocumentNewScene(): JSX.Element {
}
const documentType = legalDocument.document_type
- const baaBlocked = documentType === 'BAA' && !hasQualifyingBaaAddon
+ const baaBlockReason = documentType === 'BAA' ? organizationBaaBlockReason : null
const headingLabel = documentType === 'BAA' ? 'New Business Associate Agreement' : 'New Data Processing Agreement'
const submitDisabledReason = isLegalDocumentSubmitting
? 'Creating the PandaDoc envelope…'
: existingDocumentOfCurrentType
? `Your organization already has a ${documentType}. Contact support if you need a new one.`
- : baaBlocked
- ? 'Subscribe to Boost, Scale, or Enterprise to generate a BAA'
+ : baaBlockReason
+ ? BAA_BLOCK_REASON_MESSAGES[baaBlockReason]
: documentType === 'DPA' && !isDpaModeSubmittable
? 'Switch to one of the legally binding formats to submit for signature'
: legalDocumentHasErrors
@@ -179,23 +178,23 @@ export function LegalDocumentNewScene(): JSX.Element {
/>
</LemonField>
- {baaBlocked && (
+ {baaBlockReason && (
<LemonBanner type="warning">
- {isOnEnterpriseStandardTrial ? (
+ {baaBlockReason === 'startup_program' ? (
+ <>
+ BAAs aren't covered by startup program credits.{' '}
+ <ContactBillingSupportLink data-attr="legal-documents-startup-banner-contact-support">
+ Contact us
+ </ContactBillingSupportLink>{' '}
+ to discuss options for adding a BAA to your plan.
+ </>
+ ) : isOnEnterpriseStandardTrial ? (
<>
A BAA requires an active paid subscription. Your Enterprise trial is
sales-managed, so please{' '}
- <Link
- to=""
- onClick={() =>
- openSupportForm({
- billing_issue: true,
- isEmailFormOpen: true,
- })
- }
- >
+ <ContactBillingSupportLink data-attr="legal-documents-enterprise-trial-contact-support">
contact billing support
- </Link>{' '}
+ </ContactBillingSupportLink>{' '}
to convert your trial into a subscription, then come back here to generate your
BAA.
</>
diff --git a/products/legal_documents/frontend/scenes/LegalDocuments.stories.tsx b/products/legal_documents/frontend/scenes/LegalDocuments.stories.tsx
index e89dd63feada..14c1ebe2638e 100644
--- a/products/legal_documents/frontend/scenes/LegalDocuments.stories.tsx
+++ b/products/legal_documents/frontend/scenes/LegalDocuments.stories.tsx
@@ -6,6 +6,8 @@ import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
import { mswDecorator } from '~/mocks/browser'
+import { EMPTY_PAGINATED_RESPONSE } from '~/mocks/handlers'
+import { StartupProgramLabel } from '~/types'
const SUBMITTER = {
first_name: 'Ada',
@@ -35,6 +37,18 @@ const LEGAL_DOCUMENT_LIST = [
},
]
+/** Billing payload for an org whose Boost add-on is paid with startup program credits. */
+const startupProgramBilling = (label: StartupProgramLabel): Record<string, unknown> => ({
+ products: [
+ {
+ type: 'platform_and_support',
+ addons: [{ type: 'boost', subscribed: true }],
+ },
+ ],
+ has_active_subscription: true,
+ startup_program_label: label,
+})
+
/**
* Mounts the legal documents scene(s) against a mocked API. A single shared
* decorator is enough because the list endpoint is the only API call the
@@ -164,6 +178,41 @@ export const NewBAAEnterpriseTrial: Story = {
],
}
+/**
+ * Landing screen at `/legal` for an organization on the Startup program with no
+ * BAA yet. The Boost add-on is active (paid with credits), but the BAA menu item
+ * is disabled and the note explains that credits don't cover a BAA.
+ */
+export const ListStartupProgram: Story = {
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/organizations/:org_id/legal_documents': EMPTY_PAGINATED_RESPONSE,
+ '/api/billing/': startupProgramBilling(StartupProgramLabel.Startup),
+ },
+ }),
+ ],
+}
+
+/**
+ * New-document page for a BAA when the org is on the Startup program and has no
+ * BAA yet. The banner replaces the paywall copy and the submit button is
+ * disabled by the startup block rather than by an existing document.
+ */
+export const NewBAAStartupProgram: Story = {
+ parameters: {
+ pageUrl: urls.legalDocumentNew('BAA'),
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/organizations/:org_id/legal_documents': EMPTY_PAGINATED_RESPONSE,
+ '/api/billing/': startupProgramBilling(StartupProgramLabel.Startup),
+ },
+ }),
+ ],
+}
+
/**
* New-document page for a DPA in the default "pretty" mode (legally binding,
* rendered with a color PostHog logo at the top).
diff --git a/products/legal_documents/frontend/scenes/LegalDocumentsScene.tsx b/products/legal_documents/frontend/scenes/LegalDocumentsScene.tsx
index f9184a696d38..cb103f1be179 100644
--- a/products/legal_documents/frontend/scenes/LegalDocumentsScene.tsx
+++ b/products/legal_documents/frontend/scenes/LegalDocumentsScene.tsx
@@ -15,10 +15,11 @@ import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import { ContactBillingSupportLink } from '../components/ContactBillingSupportLink'
import { getLegalDocumentsDownloadRetrieveUrl } from '../generated/api'
-import { LegalDocument, LegalDocumentType, legalDocumentsLogic } from './legalDocumentsLogic'
+import { BAA_BLOCK_REASON_MESSAGES, LegalDocument, LegalDocumentType, legalDocumentsLogic } from './legalDocumentsLogic'
-function buildNewMenuItems(existingTypes: Set<LegalDocumentType>): LemonMenuItems {
+function buildNewMenuItems(existingTypes: Set<LegalDocumentType>, baaBlockedReason?: string): LemonMenuItems {
const alreadyExistsReason = (type: LegalDocumentType): string | undefined =>
existingTypes.has(type)
? `Your organization already has a ${type}. Contact support if you need a new one.`
@@ -45,12 +46,12 @@ function buildNewMenuItems(existingTypes: Set<LegalDocumentType>): LemonMenuItem
<div className="flex flex-col text-sm py-1">
<strong>Business Associate Agreement (BAA)</strong>
<span className="text-xs font-normal text-muted">
- HIPAA BAA — requires a Boost, Scale, or Enterprise add-on.
+ HIPAA BAA. Requires a Boost, Scale, or Enterprise add-on.
</span>
</div>
),
to: urls.legalDocumentNew('BAA'),
- disabledReason: alreadyExistsReason('BAA'),
+ disabledReason: alreadyExistsReason('BAA') ?? baaBlockedReason,
'data-attr': 'new-legal-document-menu-baa',
},
{
@@ -76,7 +77,8 @@ export const scene: SceneExport = {
}
export function LegalDocumentsScene(): JSX.Element {
- const { legalDocuments, legalDocumentsLoading, existingDocumentTypes, deletingId } = useValues(legalDocumentsLogic)
+ const { legalDocuments, legalDocumentsLoading, existingDocumentTypes, deletingId, baaBlockReason } =
+ useValues(legalDocumentsLogic)
const { deleteLegalDocument } = useActions(legalDocumentsLogic)
const { isAdminOrOwner, currentOrganizationId } = useValues(organizationLogic)
const { isCloudOrDev } = useValues(preflightLogic)
@@ -116,6 +118,10 @@ export function LegalDocumentsScene(): JSX.Element {
)
}
+ const startupProgramBlocked = baaBlockReason === 'startup_program'
+ const baaBlockedReason = startupProgramBlocked ? BAA_BLOCK_REASON_MESSAGES.startup_program : undefined
+ const showStartupProgramNote = startupProgramBlocked && !legalDocumentsLoading && !existingDocumentTypes.has('BAA')
+
return (
<SceneContent>
<SceneTitleSection
@@ -124,7 +130,10 @@ export function LegalDocumentsScene(): JSX.Element {
resourceType={{ type: 'default_icon_type', forceIcon: <IconBalance /> }}
scope={settingsSectionSceneScope('organization-legal-documents')}
actions={
- <LemonMenu items={buildNewMenuItems(existingDocumentTypes)} placement="bottom-end">
+ <LemonMenu
+ items={buildNewMenuItems(existingDocumentTypes, baaBlockedReason)}
+ placement="bottom-end"
+ >
<LemonButton
type="primary"
icon={<IconPlusSmall />}
@@ -138,6 +147,18 @@ export function LegalDocumentsScene(): JSX.Element {
}
/>
+ {showStartupProgramNote && (
+ <div data-attr="legal-documents-startup-program-note">
+ <LemonBanner type="info">
+ BAAs aren't covered by startup program credits. If you need a HIPAA BAA,{' '}
+ <ContactBillingSupportLink data-attr="legal-documents-startup-note-contact-support">
+ contact us
+ </ContactBillingSupportLink>{' '}
+ to discuss options.
+ </LemonBanner>
+ </div>
+ )}
+
<LemonTable
dataSource={legalDocuments}
loading={legalDocumentsLoading}
diff --git a/products/legal_documents/frontend/scenes/legalDocumentsLogic.test.ts b/products/legal_documents/frontend/scenes/legalDocumentsLogic.test.ts
new file mode 100644
index 000000000000..d2b164d444d3
--- /dev/null
+++ b/products/legal_documents/frontend/scenes/legalDocumentsLogic.test.ts
@@ -0,0 +1,62 @@
+import { MOCK_DEFAULT_USER } from 'lib/api.mock'
+
+import { expectLogic } from 'kea-test-utils'
+
+import { billingLogic } from 'scenes/billing/billingLogic'
+import { userLogic } from 'scenes/userLogic'
+
+import { billingJson } from '~/mocks/fixtures/_billing'
+import { defaultPlatformAddons } from '~/mocks/fixtures/_billing_platform_addons'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { BillingPlan, BillingType, StartupProgramLabel } from '~/types'
+
+import { legalDocumentsLogic } from './legalDocumentsLogic'
+
+function billingFor(startupProgramLabel: StartupProgramLabel | null, boostSubscribed: boolean): BillingType {
+ return {
+ ...billingJson,
+ startup_program_label: startupProgramLabel,
+ products: billingJson.products.map((product) =>
+ product.type === 'platform_and_support'
+ ? {
+ ...product,
+ addons: defaultPlatformAddons.map((addon) => ({
+ ...addon,
+ subscribed: boostSubscribed && addon.type === BillingPlan.Boost,
+ })),
+ }
+ : product
+ ),
+ }
+}
+
+describe('legalDocumentsLogic', () => {
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/organizations/:organization_id/legal_documents/': { count: 0, results: [] },
+ },
+ })
+ initKeaTests()
+ userLogic.mount()
+ billingLogic.mount()
+ })
+
+ it.each([
+ ['Startup', StartupProgramLabel.Startup, true, false, 'startup_program'],
+ ['Startup while impersonated', StartupProgramLabel.Startup, true, true, null],
+ ['Startup while impersonated but no add-on', StartupProgramLabel.Startup, false, true, 'no_qualifying_addon'],
+ ['YC', StartupProgramLabel.YC, true, false, null],
+ ['no program', null, true, false, null],
+ ['no program without an add-on', null, false, false, 'no_qualifying_addon'],
+ ])('resolves baaBlockReason for a %s org', async (_name, label, boostSubscribed, impersonated, expected) => {
+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, is_impersonated: impersonated })
+ billingLogic.actions.loadBillingSuccess(billingFor(label, boostSubscribed))
+ const logic = legalDocumentsLogic()
+ logic.mount()
+
+ await expectLogic(logic).toMatchValues({ baaBlockReason: expected })
+ expect(logic.values.baaBlockReason).toBe(expected)
+ })
+})
diff --git a/products/legal_documents/frontend/scenes/legalDocumentsLogic.ts b/products/legal_documents/frontend/scenes/legalDocumentsLogic.ts
index 7d198e9de7e7..7a45d261f754 100644
--- a/products/legal_documents/frontend/scenes/legalDocumentsLogic.ts
+++ b/products/legal_documents/frontend/scenes/legalDocumentsLogic.ts
@@ -9,8 +9,9 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { billingLogic } from 'scenes/billing/billingLogic'
import { organizationLogic } from 'scenes/organizationLogic'
import { urls } from 'scenes/urls'
+import { userLogic } from 'scenes/userLogic'
-import { BillingType } from '~/types'
+import { BillingType, StartupProgramLabel, UserType } from '~/types'
import type { OrganizationType } from '../../../../frontend/src/types'
import * as api from '../generated/api'
@@ -18,6 +19,12 @@ import * as api from '../generated/api'
export type LegalDocumentType = 'BAA' | 'DPA'
export type DPAMode = 'pretty' | 'lawyer' | 'fairytale' | 'tswift'
export type LegalDocumentStatus = 'submitted_for_signature' | 'signed'
+export type BaaBlockReason = 'startup_program' | 'no_qualifying_addon'
+
+export const BAA_BLOCK_REASON_MESSAGES: Record<BaaBlockReason, string> = {
+ startup_program: "BAAs aren't covered by startup program credits. Contact us to discuss options.",
+ no_qualifying_addon: 'Subscribe to Boost, Scale, or Enterprise to generate a BAA',
+}
export interface LegalDocumentCreator {
first_name: string
@@ -65,6 +72,8 @@ export interface legalDocumentsLogicValues {
currentOrganization: OrganizationType | null // organizationLogic
currentOrganizationId: string // organizationLogic
isAdminOrOwner: boolean | null // organizationLogic
+ user: UserType | null // userLogic
+ baaBlockReason: BaaBlockReason | null
deletingId: string | null
existingDocumentOfCurrentType: LegalDocument | null
existingDocumentTypes: Set<LegalDocumentType>
@@ -169,6 +178,11 @@ export interface legalDocumentsLogicActions {
export interface legalDocumentsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
hasQualifyingBaaAddon: (billing: BillingType | null) => boolean
+ baaBlockReason: (
+ billing: BillingType | null,
+ user: UserType | null,
+ hasQualifyingBaaAddon: boolean
+ ) => BaaBlockReason | null
isOnQualifyingAddonTrial: (billing: BillingType | null) => boolean
isOnEnterpriseStandardTrial: (billing: BillingType | null) => boolean
isDpaModeSubmittable: (legalDocument: LegalDocumentFormValues) => boolean
@@ -195,6 +209,8 @@ export const legalDocumentsLogic = kea<legalDocumentsLogicType>([
['currentOrganization', 'currentOrganizationId', 'isAdminOrOwner'],
billingLogic,
['billing'],
+ userLogic,
+ ['user'],
],
actions: [organizationLogic, ['loadCurrentOrganizationSuccess']],
})),
@@ -328,6 +344,22 @@ export const legalDocumentsLogic = kea<legalDocumentsLogicType>([
)
},
],
+ // Startup program organizations always pay with credits, and credits do not
+ // cover a BAA, whatever addon they hold. YC organizations keep BAA access.
+ // Staff who impersonate a startup organization that pays for a BAA generate it on its behalf.
+ baaBlockReason: [
+ (s) => [s.billing, s.user, s.hasQualifyingBaaAddon],
+ (
+ billing: BillingType | null,
+ user: UserType | null,
+ hasQualifyingBaaAddon: boolean
+ ): BaaBlockReason | null => {
+ if (billing?.startup_program_label === StartupProgramLabel.Startup && !user?.is_impersonated) {
+ return 'startup_program'
+ }
+ return hasQualifyingBaaAddon ? null : 'no_qualifying_addon'
+ },
+ ],
isOnQualifyingAddonTrial: [
(s) => [s.billing],
(billing: BillingType | null): boolean => {
diff --git a/products/legal_documents/package.json b/products/legal_documents/package.json
index ba786583c1a8..7c960c506f37 100644
--- a/products/legal_documents/package.json
+++ b/products/legal_documents/package.json
@@ -10,6 +10,9 @@
"kea-loaders": "catalog:",
"kea-router": "catalog:"
},
+ "devDependencies": {
+ "kea-test-utils": "catalog:"
+ },
"peerDependencies": {
"@posthog/icons": "catalog:",
"@posthog/lemon-ui": "*",