: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(subscriptions): bring subscriptions to the free tier (freemium, synced to alerts) (#59624)
Vasco de Krijger576915ea536d
diff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex bff98b24506d..9a3f28d70b6e 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -26,13 +26,12 @@ from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer-from posthog.constants import SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE_FEATURE_FLAG_KEY, AvailableFeature+from posthog.constants import SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE_FEATURE_FLAG_KEYfrom posthog.event_usage import groupsfrom posthog.exceptions import QuotaLimitExceededfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.integration import Integrationfrom posthog.models.subscription import Subscription, SubscriptionDelivery, unsubscribe_using_token-from posthog.permissions import PremiumFeaturePermissionfrom posthog.rate_limit import SubscriptionTestDeliveryThrottlefrom posthog.resource_limits import LimitKey, check_count_limit, get_organization_limitfrom posthog.security.url_validation import is_url_allowed@@ -189,6 +188,18 @@ class SubscriptionSerializer(serializers.ModelSerializer):return info.name if info else Nonedef validate(self, attrs):+ request = self.context.get("request")+ # Re-run the free-tier cap on create AND on restore (deleted: true → false) —+ # a soft-deleted row frees its slot, so PATCHing one back to active re-occupies+ # one and must respect the limit, otherwise a free-tier team could soft-delete ++ # create + restore its way past the cap.+ is_create = request is not None and request.method == "POST"+ is_restoring = self.instance is not None and self.instance.deleted and attrs.get("deleted") is False+ if is_create or is_restoring:+ msg = Subscription.check_subscription_limit(self.context["team_id"], self.context["get_organization"]())+ if msg:+ raise ValidationError({"subscription": [msg]})+if not self.initial_data:# Createif not attrs.get("dashboard") and not attrs.get("insight"):@@ -625,8 +636,6 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Mscope_object = "subscription"queryset = Subscription.objects.all()serializer_class = SubscriptionSerializer- permission_classes = [PremiumFeaturePermission]- premium_feature = AvailableFeature.SUBSCRIPTIONSfilter_backends = [filters.SearchFilter, filters.OrderingFilter]search_fields = ["title",@@ -889,8 +898,6 @@ class SubscriptionDeliveryViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModelscope_object = "subscription"queryset = SubscriptionDelivery.objects.all()serializer_class = SubscriptionDeliverySerializer- permission_classes = [PremiumFeaturePermission]- premium_feature = AvailableFeature.SUBSCRIPTIONSpagination_class = SubscriptionDeliveryCursorPaginationordering = "-created_at"diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex 5f9988fe20ac..10aeb8e39b73 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -16,7 +16,7 @@ from posthog.models import Teamfrom posthog.models.filters.filter import Filterfrom posthog.models.integration import Integrationfrom posthog.models.personal_api_key import PersonalAPIKey-from posthog.models.subscription import Subscription, SubscriptionDelivery+from posthog.models.subscription import SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER, Subscription, SubscriptionDeliveryfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.temporal.subscriptions.types import ProcessSubscriptionWorkflowInputs, SubscriptionTriggerType@@ -73,14 +73,11 @@ class TestSubscriptionTemporal(APILicensedTest):self.addCleanup(self._sync_connect_patcher.stop)@pytest.mark.skip_on_multitenancy- def test_cannot_list_subscriptions_without_proper_license(self):+ def test_free_org_can_list_subscriptions_without_license(self):self.organization.available_product_features = []self.organization.save()response = self.client.get(f"/api/projects/{self.team.id}/subscriptions/")- assert response.status_code == status.HTTP_402_PAYMENT_REQUIRED- assert response.json() == self.license_required_response(- "Subscriptions is part of the premium PostHog offering. Self-hosted licenses are no longer available for purchase. Please contact [email protected] to discuss options."- )+ assert response.status_code == status.HTTP_200_OKdef test_can_create_new_subscription(self):response = self._create_subscription()@@ -1444,6 +1441,189 @@ class TestSubscriptionTemporal(APILicensedTest):temporal_mock.return_value.start_workflow.assert_not_called()+class TestSubscriptionFreeTierLimit(APILicensedTest):+ # creation is blocked for free orgs at/over their limit;+ # edits and deletes are always allowed; paid orgs are never blocked.+ insight: Insight = None # type: ignore++ @classmethod+ def setUpTestData(cls):+ super().setUpTestData()+ cls.insight = Insight.objects.create(+ filters={"events": [{"id": "$pageview"}]},+ team=cls.team,+ created_by=cls.user,+ )++ def setUp(self):+ super().setUp()+ self._sync_connect_patcher = patch("ee.api.subscription.sync_connect")+ self.mock_sync = self._sync_connect_patcher.start()+ self.mock_temporal_client = MagicMock()+ self.mock_temporal_client.start_workflow = AsyncMock()+ self.mock_sync.return_value = self.mock_temporal_client+ self.addCleanup(self._sync_connect_patcher.stop)++ def _minimal_payload(self, **overrides):+ base = {+ "insight": self.insight.id,+ "target_type": "email",+ "target_value": "[email protected]",+ "frequency": "daily",+ "interval": 1,+ "start_date": "2022-01-01T00:00:00",+ }+ base.update(overrides)+ return base++ def _seed_subscriptions(self, count: int) -> list[Subscription]:+ return [+ Subscription.objects.create(+ team=self.team,+ insight=self.insight,+ target_type="email",+ target_value=f"seed-{i}@b.com",+ frequency="daily",+ interval=1,+ start_date=datetime(2022, 1, 1, tzinfo=UTC),+ title=f"seeded {i}",+ created_by=self.user,+ )+ for i in range(count)+ ]++ @pytest.mark.skip_on_multitenancy+ def test_free_org_can_create_up_to_limit_then_6th_is_blocked(self):+ # each of the first 5 returns 201; 6th returns 400.++ self.organization.available_product_features = []+ self.organization.save()++ for i in range(SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER):+ response = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions/",+ self._minimal_payload(target_value=f"user{i}@b.com"),+ )+ assert response.status_code == status.HTTP_201_CREATED, (+ f"subscription {i + 1} should be created, got {response.status_code}: {response.content}"+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions/",+ self._minimal_payload(target_value="[email protected]"),+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ data = response.json()+ assert data.get("attr") == "subscription", data+ assert str(SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER) in data.get("detail", ""), (+ f"Expected limit number in error message, got: {data}"+ )++ @pytest.mark.skip_on_multitenancy+ def test_free_org_at_limit_patch_is_not_blocked(self):+ # edits must always be allowed, even at/over the limit.+ self.organization.available_product_features = []+ self.organization.save()++ existing = self._seed_subscriptions(SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER)+ subscription_id = existing[0].id++ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription_id}/",+ {"title": "updated title"},+ )+ assert response.status_code == status.HTTP_200_OK, response.content+ assert response.json()["title"] == "updated title"++ @pytest.mark.skip_on_multitenancy+ def test_free_org_soft_delete_recovers_slot(self):+ # deleting one frees a slot, so a subsequent POST succeeds.+ self.organization.available_product_features = []+ self.organization.save()++ existing = self._seed_subscriptions(SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER)+ subscription_to_delete = existing[0].id++ # Soft-delete one subscription+ self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription_to_delete}/",+ {"deleted": True},+ )++ # Now only 4 active remain — a new POST should succeed+ response = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions/",+ self._minimal_payload(target_value="[email protected]"),+ )+ assert response.status_code == status.HTTP_201_CREATED, response.content++ @pytest.mark.skip_on_multitenancy+ def test_free_org_restore_blocked_when_at_limit(self):+ # restoring a soft-deleted subscription re-occupies a slot, so it must+ # respect the cap — otherwise soft-delete + create + restore bypasses it.+ self.organization.available_product_features = []+ self.organization.save()++ existing = self._seed_subscriptions(SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER)+ to_restore = existing[0]++ # Soft-delete one (4 active), then refill to the cap with a fresh POST.+ delete_response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{to_restore.id}/",+ {"deleted": True},+ )+ assert delete_response.status_code == status.HTTP_200_OK, delete_response.content+ response = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions/",+ self._minimal_payload(target_value="[email protected]"),+ )+ assert response.status_code == status.HTTP_201_CREATED, response.content++ # Now at the cap again — restoring the deleted one would push to 6.+ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{to_restore.id}/",+ {"deleted": False},+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert response.json().get("attr") == "subscription", response.json()++ @pytest.mark.skip_on_multitenancy+ def test_free_org_restore_allowed_when_under_limit(self):+ # with a free slot available, restoring a soft-deleted subscription succeeds.+ self.organization.available_product_features = []+ self.organization.save()++ existing = self._seed_subscriptions(SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER)+ to_restore = existing[0]++ delete_response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{to_restore.id}/",+ {"deleted": True},+ )+ assert delete_response.status_code == status.HTTP_200_OK, delete_response.content++ # 4 active remain — restoring brings it back to 5, within the cap.+ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{to_restore.id}/",+ {"deleted": False},+ )+ assert response.status_code == status.HTTP_200_OK, response.content+ assert response.json()["deleted"] is False++ def test_paid_org_can_create_beyond_free_tier_limit(self):+ # licensed org (enterprise, no numeric cap) can create 7+ subscriptions.+ # APILicensedTest provides an enterprise license with AvailableFeature.SUBSCRIPTIONS,+ # no numeric limit — so check_subscription_limit returns None.+ for i in range(7):+ response = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions/",+ self._minimal_payload(target_value=f"paid{i}@b.com"),+ )+ assert response.status_code == status.HTTP_201_CREATED, (+ f"subscription {i + 1} failed for paid org: {response.status_code} {response.content}"+ )++class TestSubscriptionDeliveryAPI(APILicensedTest):subscription: Subscription = None # type: ignoreinsight: Insight = None # type: ignore@@ -1589,11 +1769,11 @@ class TestSubscriptionDeliveryAPI(APILicensedTest):assert response.status_code == status.HTTP_400_BAD_REQUEST@pytest.mark.skip_on_multitenancy- def test_deliveries_require_premium_feature(self):+ def test_free_org_can_access_deliveries_without_premium_feature(self):self.organization.available_product_features = []self.organization.save()response = self.client.get(f"/api/environments/{self.team.id}/subscriptions/{self.subscription.id}/deliveries/")- assert response.status_code == status.HTTP_402_PAYMENT_REQUIRED+ assert response.status_code == status.HTTP_200_OKdef test_deliveries_not_available_on_legacy_project_path(self):self._create_delivery(idempotency_key="legacy-test")@@ -1656,3 +1836,56 @@ class TestSubscriptionDeliveryAPI(APILicensedTest):assert first_ids | second_ids == {str(d.id) for d in SubscriptionDelivery.objects.filter(subscription=self.subscription)}+++class TestSubscriptionFreeTierAccess(APILicensedTest):+ # free-tier orgs can retrieve subscriptions and read deliveries without a premium gate.+ insight: Insight = None # type: ignore+ subscription: Subscription = None # type: ignore++ @classmethod+ def setUpTestData(cls):+ super().setUpTestData()+ cls.insight = Insight.objects.create(+ filters={"events": [{"id": "$pageview"}]},+ team=cls.team,+ created_by=cls.user,+ )+ cls.subscription = Subscription.objects.create(+ team=cls.team,+ insight=cls.insight,+ created_by=cls.user,+ target_type="email",+ target_value="[email protected]",+ frequency="weekly",+ interval=1,+ start_date=datetime(2022, 1, 1, 0, 0, 0, tzinfo=UTC),+ title="Free Tier Sub",+ )++ def _make_free_org(self):+ self.organization.available_product_features = []+ self.organization.save()++ @pytest.mark.skip_on_multitenancy+ def test_free_org_can_retrieve_subscription(self):+ self._make_free_org()+ response = self.client.get(f"/api/projects/{self.team.id}/subscriptions/{self.subscription.id}/")+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["id"] == self.subscription.id++ @pytest.mark.skip_on_multitenancy+ def test_free_org_can_list_deliveries(self):+ self._make_free_org()+ SubscriptionDelivery.objects.create(+ subscription=self.subscription,+ team=self.team,+ temporal_workflow_id="wf-free-access-test",+ idempotency_key="free-access-key",+ trigger_type="scheduled",+ target_type="email",+ target_value="[email protected]",+ status=SubscriptionDelivery.Status.COMPLETED,+ )+ response = self.client.get(f"/api/environments/{self.team.id}/subscriptions/{self.subscription.id}/deliveries/")+ assert response.status_code == status.HTTP_200_OKdiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 387697e297c4..8155bbd68082 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1325,33 +1325,37 @@ snapshots:components-sso-select--sso-select--light:hash: v1.k794b7964.ae3ecf63f33e98350bb2cc9aa9b9458e0985c910f97b3251d837ee30b97a3c48.HKoN2BOvJoiBCjXKNt17mEo4yuzNnN3XmyVO9nAwgjccomponents-subscriptions--subscription-at-ai-summary-limit--dark:- hash: v1.k794b7964.4b1fe224f34652580b8e6be6c6ae294bf0ee828417aed5dfd8d04505bbbdfa7a.vp-YJxXUVeUtmYuc8hwJZ6ZMbr41Wa8mey8-Sgdo5zI+ hash: v1.k794b7964.92f7fad37e5e129f4e290cf7819fbbda2a1aecde28aa922e3f0830457ee7883e.vSvF32AnSnWQaebof1ANN5wOZ0g-yrl3yRvgwiTY0Bccomponents-subscriptions--subscription-at-ai-summary-limit--light:- hash: v1.k794b7964.8f8007ae1b5ab0172d712cc15f25209eae133ed35654bd5dcc0cb28cadb4ab26.RNun_WV1Ku_UFh-OOt-brcTUtr6YQGHsgAxmlCD1m_w+ hash: v1.k794b7964.331f445d42e7e0cb3479bef1e3f6f136b7f12983c967c85da744293bb9290f8f.J8_pLlDHwFpX9olAZJGP-I5Hek1Fnzo9aBi8Ntp7IQkcomponents-subscriptions--subscription-no-integrations--dark:- hash: v1.k794b7964.4b1fe224f34652580b8e6be6c6ae294bf0ee828417aed5dfd8d04505bbbdfa7a.jUXTpsX4PKOrM6J-AVLKCcNMgvT2g76heDlY0HxyFnA+ hash: v1.k794b7964.92f7fad37e5e129f4e290cf7819fbbda2a1aecde28aa922e3f0830457ee7883e.ZHzTWqAuYaOXXOgY5p6AWX-KxPN9kml4iYjPrQWFsWgcomponents-subscriptions--subscription-no-integrations--light:- hash: v1.k794b7964.8f8007ae1b5ab0172d712cc15f25209eae133ed35654bd5dcc0cb28cadb4ab26.gfUikgw-8dTVjsbjyWEacCXOryHig3nYxPXawLAASCk+ hash: v1.k794b7964.331f445d42e7e0cb3479bef1e3f6f136b7f12983c967c85da744293bb9290f8f.XvBu19cSofYY2lsPCe_ewNNF5mxMhkpX9nTjubZ1HL0components-subscriptions--subscriptions--dark:- hash: v1.k794b7964.082845593b2e52a22ef6507121892c687ecff5d6a5e89bc34be223bcc7b4e36f.seRD-FY4GQ5SjM2dNbRRg4Yu73_8XwWqDiANOBrWkoY+ hash: v1.k794b7964.8614051ff069d5013d37ec55f43914b4cb0e2febaf7eca391160dbbf975a8cd1.60iwFDjNz7mN3PWlv-7RgUKQDDMES-TcKco1z5lchescomponents-subscriptions--subscriptions--light:- hash: v1.k794b7964.071c4fc424b657719457f9e4c3b5db2e34747cfeb25dff48c3361985b2910d85.U65Y0BofkdullYeRp_RjRTmA1gW-LZEr3qhfCo_9i6E+ hash: v1.k794b7964.a68f8114516c772209dc583c5e63a5cfb756038bccc021d0691936ae9e8316c3.JZt-O8k5lLZe5U2loXdiBjyElSV2W2_DSy6rninPkxQcomponents-subscriptions--subscriptions-edit--dark:- hash: v1.k794b7964.35a1273a84ddde8080dfe8b898933b4d92af1172a4618b65950f180b68c6db05.8E1FzSjqa7ATA3Sfg3rFoMq8Y0lom5D86dBp76YD4YY+ hash: v1.k794b7964.9943f3fadbe661883eb6c14c5ca57313d218f320ada14f3153e7133468c99b14.HthuxGX7QhEasr1SBVwblRoRWMft319faBZau1s4YYAcomponents-subscriptions--subscriptions-edit--light:- hash: v1.k794b7964.1cad424f58f55f231afc51c27132abc3116ab9c8af1f6e28ece58dbc70d2f99e.PYPimXiHRQMmA-raU08djPk9fdHyzRg4LtLqaI2AI8I+ hash: v1.k794b7964.4b321ca0a2ea8649ce9bd717b0ac85715a1bcf6e470f0915cb1d8e64462d6402.sk2CvNCz0z-TL3BxKZiubZaR-v0r3WDRbgN7Ohs0RdYcomponents-subscriptions--subscriptions-empty--dark:- hash: v1.k794b7964.85fadbbc70dd384ae9d9ab3e4fd6e457c29b44cd8b61da73c5b3b95d32768a3c.O8-Fq1EHqtqKWTk8d_jvuDosKefJpEKFCe62dRH5lOQ+ hash: v1.k794b7964.e6ae8b1b4c2b61548551026e9accc6d130cd01eef5d13b20a76d76a796a04885.zUX4AUA1o4J6PaC21nrkauuy09JCWm3H4oyYFSSP35ocomponents-subscriptions--subscriptions-empty--light:- hash: v1.k794b7964.28d9eec369064a7c512a377437b436e2de85ea4618d333b84934bb44a0088f86.9zUV6RM5LiLgQ1Ri0vgGqBq9TAExpSPqnks-pgW-8AY+ hash: v1.k794b7964.d3ac25f014933ad581ac80175f70182325f3c38ae42e4cf5144512187cbc2d99.mvGWV50rkervhGPp1HvFAoBIM6EAgUuEcTVe8aEpPkccomponents-subscriptions--subscriptions-new--dark:- hash: v1.k794b7964.4b1fe224f34652580b8e6be6c6ae294bf0ee828417aed5dfd8d04505bbbdfa7a.yfFcsfxK0--KtPVYa_0VO1z9TYwe2pFTxdZ89NtHKGQ+ hash: v1.k794b7964.92f7fad37e5e129f4e290cf7819fbbda2a1aecde28aa922e3f0830457ee7883e.H7rXKSe1B3oE1Cu773Tk1773rYCf0hiGCvZiSRi8Zvscomponents-subscriptions--subscriptions-new--light:- hash: v1.k794b7964.8f8007ae1b5ab0172d712cc15f25209eae133ed35654bd5dcc0cb28cadb4ab26.g1eWhU7rYjoFYiQTwKWbPnxMPoihGVclJdZTemFZxw8- components-subscriptions--subscriptions-unavailable--dark:- hash: v1.k794b7964.fa5eafea974f45e62ac440d3732d0f0acbda1a7aacf125dec663a87c65d872ba.eykPwk9A9d5Hoi99gtxSEuH9HDohm2dAfSJouSazHc8- components-subscriptions--subscriptions-unavailable--light:- hash: v1.k794b7964.8f9604b3af471dccefc9137144394374861f0d7dec7650a94e71b3967ab648a3.GLitcghcwxARXeiCv9eiarEBtP9acsrRu5juOxwnF7E+ hash: v1.k794b7964.331f445d42e7e0cb3479bef1e3f6f136b7f12983c967c85da744293bb9290f8f.-tMF-9VuRPOBZ8Q5JrPDGfAKDGNcOhjlVwgnBfl_PLU+ components-subscriptions--subscriptions-new-free-at-limit--dark:+ hash: v1.k794b7964.1a679529b000f8ac6cf2a3b7649f4db71480fa69eedae51713934d9a287c5840.Tu5uuBjMCLtwiNCL82qmr75C-Ul4jhpmUPot6A-qtTM+ components-subscriptions--subscriptions-new-free-at-limit--light:+ hash: v1.k794b7964.ce8bcf73af0c598b24419f65507e6c638de9ca17d966d2336293fb4a1d3a9133.dFo8-PgeKw-hnYQ22mfoTkHjVbAMb7ndJOURmhbBfYM+ components-subscriptions--subscriptions-new-free-under-limit--dark:+ hash: v1.k794b7964.92f7fad37e5e129f4e290cf7819fbbda2a1aecde28aa922e3f0830457ee7883e.re2rQDhY90ryc-0npIdbHq-EhKlg9Ay2JxeOpsIWePA+ components-subscriptions--subscriptions-new-free-under-limit--light:+ hash: v1.k794b7964.331f445d42e7e0cb3479bef1e3f6f136b7f12983c967c85da744293bb9290f8f.TybX1qL3ZHhovwVh9cqrQqsBmu6hud-ukFsL8cu9eXgcomponents-table-preview--default--dark:hash: v1.k794b7964.66db3bad84f3c80f0c6974a863d7fb1e701b89ef18926ec7189e0baeecf17a30.xefl1qy7L9CwTFzc6t6a-CaNuBtvO-U1dVnc27h2Pnkcomponents-table-preview--default--light:diff --git a/frontend/src/lib/components/Subscriptions/SubscriptionsModal.stories.tsx b/frontend/src/lib/components/Subscriptions/SubscriptionsModal.stories.tsxindex e84b7060f6cb..1c7ef8c6dad4 100644--- a/frontend/src/lib/components/Subscriptions/SubscriptionsModal.stories.tsx+++ b/frontend/src/lib/components/Subscriptions/SubscriptionsModal.stories.tsx@@ -9,17 +9,17 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { uuid } from 'lib/utils'import { useStorybookMocks } from '~/mocks/browser'-import { useAvailableFeatures } from '~/mocks/features'import preflightJson from '~/mocks/fixtures/_preflight.json'import { createMockSubscription, mockIntegration, mockSlackChannels } from '~/test/mocks'-import { AvailableFeature, InsightShortId, Realm } from '~/types'+import { InsightShortId, Realm } from '~/types'import { SubscriptionsModal, SubscriptionsModalProps } from './SubscriptionsModal'type StoryArgs = SubscriptionsModalProps & {noIntegrations?: boolean- featureAvailable?: booleanaiSummaryAtLimit?: boolean+ // Team-wide subscription count for the free-tier create gate (under the limit → form, at/over → upsell).+ freeTierSubscriptionCount?: number}const meta: Meta<StoryArgs> = {@@ -31,12 +31,10 @@ const meta: Meta<StoryArgs> = {mockDate: '2023-01-31 12:00:00',},render: (args) => {- const { noIntegrations = false, featureAvailable = true, aiSummaryAtLimit = false, ...props } = args+ const { noIntegrations = false, aiSummaryAtLimit = false, freeTierSubscriptionCount, ...props } = argsconst insightShortIdRef = useRef(props.insightShortId || (uuid() as InsightShortId))const [modalOpen, setModalOpen] = useState(false)- useAvailableFeatures(featureAvailable ? [AvailableFeature.SUBSCRIPTIONS] : [])-useEffect(() => {if (!aiSummaryAtLimit) {return@@ -95,6 +93,9 @@ const meta: Meta<StoryArgs> = {],},'/api/environments/:id/subscriptions/:subId': createMockSubscription(),+ ...(freeTierSubscriptionCount !== undefined+ ? { '/api/projects/:id/subscriptions/': { count: freeTierSubscriptionCount, results: [] } }+ : {}),'/api/projects/:id/subscriptions/summary_quota': aiSummaryAtLimit? { active_count: 10, limit: 10, at_limit: true }: { active_count: 0, limit: 10, at_limit: false },@@ -156,10 +157,16 @@ export const SubscriptionsEdit: Story = {args: { subscriptionId: 1 },}-export const SubscriptionsUnavailable: Story = {- args: { featureAvailable: false },-}-export const SubscriptionAtAISummaryLimit: Story = {args: { subscriptionId: 'new', aiSummaryAtLimit: true },}++// Freemium gate: a free org under the 5-subscription limit sees the normal create form.+export const SubscriptionsNewFreeUnderLimit: Story = {+ args: { subscriptionId: 'new', freeTierSubscriptionCount: 2 },+}++// Freemium gate: a free org at the limit sees the upgrade paywall instead of the create form.+export const SubscriptionsNewFreeAtLimit: Story = {+ args: { subscriptionId: 'new', freeTierSubscriptionCount: 5 },+}diff --git a/frontend/src/lib/components/Subscriptions/SubscriptionsModal.tsx b/frontend/src/lib/components/Subscriptions/SubscriptionsModal.tsxindex 8e9dc1de1d93..cc68a4559966 100644--- a/frontend/src/lib/components/Subscriptions/SubscriptionsModal.tsx+++ b/frontend/src/lib/components/Subscriptions/SubscriptionsModal.tsx@@ -5,9 +5,8 @@ import { LemonModal } from 'lib/lemon-ui/LemonModal'import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'import { userLogic } from 'scenes/userLogic'-import { AvailableFeature, DashboardType, InsightShortId } from '~/types'+import { DashboardType, InsightShortId } from '~/types'-import { PayGateMini } from '../PayGateMini/PayGateMini'import { SubscriptionBaseProps, urlForSubscription, urlForSubscriptions } from './utils'import { EditSubscription } from './views/EditSubscription'import { ManageSubscriptions } from './views/ManageSubscriptions'@@ -43,29 +42,21 @@ export function SubscriptionsModal(props: SubscriptionsModalProps): JSX.Elementinline={inline}data-attr={dataAttr}>- <PayGateMini- feature={AvailableFeature.SUBSCRIPTIONS}- handleSubmit={closeModal}- background={false}- className="py-8 flex-1 min-h-0 flex flex-col"- docsLink="https://posthog.com/docs/user-guides/subscriptions"- >- {!subscriptionId ? (- <ManageSubscriptions- {...baseProps}- onCancel={closeModal}- onSelect={(id) => push(urlForSubscription(id, baseProps))}- />- ) : (- <EditSubscription- id={subscriptionId}- insightShortId={insightShortId}- dashboard={dashboard}- onCancel={() => push(urlForSubscriptions(baseProps))}- onDelete={() => push(urlForSubscriptions(baseProps))}- />- )}- </PayGateMini>+ {!subscriptionId ? (+ <ManageSubscriptions+ {...baseProps}+ onCancel={closeModal}+ onSelect={(id) => push(urlForSubscription(id, baseProps))}+ />+ ) : (+ <EditSubscription+ id={subscriptionId}+ insightShortId={insightShortId}+ dashboard={dashboard}+ onCancel={() => push(urlForSubscriptions(baseProps))}+ onDelete={() => push(urlForSubscriptions(baseProps))}+ />+ )}</LemonModal>)}diff --git a/frontend/src/lib/components/Subscriptions/subscriptionCountLogic.test.ts b/frontend/src/lib/components/Subscriptions/subscriptionCountLogic.test.tsnew file mode 100644index 000000000000..4dbbbe82d64a--- /dev/null+++ b/frontend/src/lib/components/Subscriptions/subscriptionCountLogic.test.ts@@ -0,0 +1,52 @@+import { expectLogic } from 'kea-test-utils'++import { subscriptionsList } from '~/generated/core/api'+import { initKeaTests } from '~/test/init'++import { subscriptionCountLogic } from './subscriptionCountLogic'++jest.mock('~/generated/core/api', () => ({+ subscriptionsList: jest.fn(),+}))++const mockSubscriptionsList = subscriptionsList as jest.Mock++describe('subscriptionCountLogic', () => {+ let logic: ReturnType<typeof subscriptionCountLogic.build>++ beforeEach(() => {+ initKeaTests()+ mockSubscriptionsList.mockReset()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('loads the team-wide count from the response count field on mount', async () => {+ // count (full team total) differs from results.length to catch a results.length regression.+ mockSubscriptionsList.mockResolvedValue({ count: 3, results: [{ id: 1 }] })+ logic = subscriptionCountLogic()+ logic.mount()++ await expectLogic(logic).toFinishAllListeners().toMatchValues({ subscriptionCount: 3 })+ // Lock in the limit=1 invariant — we only need the count, not the rows.+ expect(subscriptionsList).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ limit: 1 }))+ })++ it('loads zero for a team with no subscriptions', async () => {+ mockSubscriptionsList.mockResolvedValue({ count: 0, results: [] })+ logic = subscriptionCountLogic()+ logic.mount()++ await expectLogic(logic).toFinishAllListeners().toMatchValues({ subscriptionCount: 0 })+ })++ it('falls back to 0 when the response omits count', async () => {+ mockSubscriptionsList.mockResolvedValue({ results: [] })+ logic = subscriptionCountLogic()+ logic.mount()++ await expectLogic(logic).toFinishAllListeners().toMatchValues({ subscriptionCount: 0 })+ })+})diff --git a/frontend/src/lib/components/Subscriptions/subscriptionCountLogic.ts b/frontend/src/lib/components/Subscriptions/subscriptionCountLogic.tsnew file mode 100644index 000000000000..a6315280a97d--- /dev/null+++ b/frontend/src/lib/components/Subscriptions/subscriptionCountLogic.ts@@ -0,0 +1,28 @@+import { afterMount, kea, path } from 'kea'+import { loaders } from 'kea-loaders'++import { getCurrentTeamId } from 'lib/utils/getAppContext'++import { subscriptionsList } from '~/generated/core/api'++import type { subscriptionCountLogicType } from './subscriptionCountLogicType'++export const subscriptionCountLogic = kea<subscriptionCountLogicType>([+ path(['lib', 'components', 'Subscriptions', 'subscriptionCountLogic']),+ loaders({+ // null = not loaded yet; consumers treat null as "unknown" and fail open.+ subscriptionCount: [+ null as number | null,+ {+ loadSubscriptionCount: async (): Promise<number> => {+ // limit=1 keeps the payload tiny; `count` reflects the full team total.+ const response = await subscriptionsList(String(getCurrentTeamId()), { limit: 1 })+ return response.count ?? 0+ },+ },+ ],+ }),+ afterMount(({ actions }) => {+ actions.loadSubscriptionCount()+ }),+])diff --git a/frontend/src/lib/components/Subscriptions/views/EditSubscription.gate.test.tsx b/frontend/src/lib/components/Subscriptions/views/EditSubscription.gate.test.tsxnew file mode 100644index 000000000000..7693905189a8--- /dev/null+++ b/frontend/src/lib/components/Subscriptions/views/EditSubscription.gate.test.tsx@@ -0,0 +1,20 @@+import { SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'++import { isFreeTierCreateAtLimit } from './EditSubscription'++const LIMIT = SubscriptionFreeTierLimit.COUNT++describe('EditSubscription free-tier gate', () => {+ it.each([+ ['empty (first use)', 0, false],+ ['one below the limit boundary', LIMIT - 1, false],+ ['at the limit', LIMIT, true],+ ['over the limit', LIMIT + 1, true],+ ])('blocks the next create when %s (count=%i) -> %s', (_desc, count, expected) => {+ expect(isFreeTierCreateAtLimit(count)).toBe(expected)+ })++ it('fails open while the count is unknown (null) so the form shows; backend enforces the hard limit', () => {+ expect(isFreeTierCreateAtLimit(null)).toBe(false)+ })+})diff --git a/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx b/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsxindex a042a4518ba0..4fa88abd4626 100644--- a/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx+++ b/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx@@ -22,14 +22,19 @@ import { LemonModal } from 'lib/lemon-ui/LemonModal'import { LemonSelect } from 'lib/lemon-ui/LemonSelect'import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'+import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'import { membersLogic } from 'scenes/organization/membersLogic'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'+import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'-import { DashboardType, InsightShortId } from '~/types'+import { SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'+import { AvailableFeature, DashboardType, InsightShortId } from '~/types'import { InsightSelector } from '../InsightSelector'+import { subscriptionCountLogic } from '../subscriptionCountLogic'import { subscriptionLogic } from '../subscriptionLogic'import { subscriptionsLogic } from '../subscriptionsLogic'import {@@ -53,7 +58,67 @@ interface EditSubscriptionProps {onDelete: () => void}-export function EditSubscription({+// A null count (loading or fetch failed) fails open — the backend POST check is the hard limit.+export function isFreeTierCreateAtLimit(subscriptionCount: number | null): boolean {+ return subscriptionCount !== null && subscriptionCount >= SubscriptionFreeTierLimit.COUNT+}++export function EditSubscription(props: EditSubscriptionProps): JSX.Element {+ const { hasAvailableFeature } = useValues(userLogic)+ const isCreating = props.id === 'new'+ const hasSubscriptionsFeature = hasAvailableFeature(AvailableFeature.SUBSCRIPTIONS)++ // Editing existing subscriptions, and any paid org, are never gated and never fetch the count.+ if (!isCreating || hasSubscriptionsFeature) {+ return <EditSubscriptionForm {...props} />+ }+ return <FreeTierCreateGate {...props} />+}++function FreeTierCreateGate(props: EditSubscriptionProps): JSX.Element {+ const { subscriptionCount, subscriptionCountLoading } = useValues(subscriptionCountLogic)++ // Wait for the count before deciding form-vs-paywall, otherwise the form flashes during the+ // in-flight fetch and is yanked away once the count arrives. On fetch failure the loader settles+ // with a null count and loading=false, so we fall through and fail open to the form.+ if (subscriptionCount === null && subscriptionCountLoading) {+ return (+ <div className="py-8 flex-1 min-h-0 flex items-center justify-center">+ <Spinner className="text-2xl" />+ </div>+ )+ }++ if (isFreeTierCreateAtLimit(subscriptionCount)) {+ return (+ <div className="flex flex-1 flex-col min-h-0">+ <LemonModal.Header>+ <div className="flex items-center gap-2">+ <LemonButton icon={<IconChevronLeft />} onClick={props.onCancel} size="xsmall" />+ <h3>New Subscription</h3>+ </div>+ </LemonModal.Header>+ <UsageLimitPaywall+ title="Subscription limit reached"+ description={+ <>+ <Link to={urls.subscriptions()}>Delete an existing subscription</Link> or upgrade your plan+ to add more.+ </>+ }+ limit={SubscriptionFreeTierLimit.COUNT}+ currentUsage={subscriptionCount ?? undefined}+ unit="subscriptions allowed on your plan"+ background={false}+ className="py-8 flex-1 min-h-0 justify-center"+ />+ </div>+ )+ }+ return <EditSubscriptionForm {...props} />+}++function EditSubscriptionForm({id,insightShortId,dashboard,diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 0b208ef795bb..d8864f17b614 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -38681,6 +38681,11 @@"enum": ["last_event", "after_dropoff_period"],"type": "string"},+ "SubscriptionFreeTierLimit": {+ "const": 5,+ "description": "Subscriptions a free-tier team may create.",+ "type": "number"+ },"SuggestedQuestionsQuery": {"additionalProperties": false,"properties": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex ccdddc32be04..9160342d951b 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -6311,6 +6311,11 @@ export enum DashboardAutoRefreshInterval {SECONDS = 1800,}+/** Subscriptions a free-tier team may create. */+export enum SubscriptionFreeTierLimit {+ COUNT = 5,+}+export type UsageMetricFormat = 'numeric' | 'currency'export type UsageMetricDisplay = 'number' | 'sparkline'diff --git a/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx b/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsxindex 266858a4c2dc..332c67472fac 100644--- a/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx+++ b/frontend/src/scenes/insights/SidePanel/InsightSceneMenuBar.tsx@@ -113,7 +113,6 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: InhogQL != null &&(isDataTableNode(query) || isDataVisualizationNode(query) || isHogQLQuery(query) || isEventsQuery(query))const canShowDebugPanel = isSavedInsight && (user?.is_staff || user?.is_impersonated || !preflight?.cloud)- const hasSubscriptionsFeature = hasAvailableFeature(AvailableFeature.SUBSCRIPTIONS)const showMetalytics =isSavedInsight &&metalyticsInstanceId != null &&@@ -199,7 +198,7 @@ function InsightSceneMenuBarInner({ insightLogicProps }: { insightLogicProps: InStatic cohort</SceneMenuBarItem>)}- {isSavedInsight && hasSubscriptionsFeature && (+ {isSavedInsight && (<SceneMenuBarItemonClick={() => push(urlForSubscriptions({ insightShortId: insight.short_id }))}data-attr={`${RESOURCE_TYPE}-menubar-subscribe`}diff --git a/frontend/src/scenes/subscriptions/SubscriptionScene.tsx b/frontend/src/scenes/subscriptions/SubscriptionScene.tsxindex 2b63fdac5b40..c684e9d50fc5 100644--- a/frontend/src/scenes/subscriptions/SubscriptionScene.tsx+++ b/frontend/src/scenes/subscriptions/SubscriptionScene.tsx@@ -4,7 +4,6 @@ import { router } from 'kea-router'import { LemonButton, LemonTag } from '@posthog/lemon-ui'import { NotFound } from 'lib/components/NotFound'-import { PayGateMini } from 'lib/components/PayGateMini/PayGateMini'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'import { getCurrentTeamId } from 'lib/utils/getAppContext'import { sceneLogic } from 'scenes/sceneLogic'@@ -14,10 +13,8 @@ import { urls } from 'scenes/urls'import type { SubscriptionApi } from '~/generated/core/api.schemas'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'-import { AvailableFeature } from '~/types'import { SubscriptionDeliveryHistory } from './components/SubscriptionDeliveryHistory'-import { SubscriptionsLoadingSkeleton } from './components/SubscriptionsLoadingSkeleton'import { isSubscriptionEnabled, subscriptionEditHref, subscriptionName } from './components/SubscriptionsTable'import { SubscriptionSummary } from './components/SubscriptionSummary'import { subscriptionSceneLogic } from './subscriptionSceneLogic'@@ -95,56 +92,39 @@ export function SubscriptionScene({ tabId }: SceneProps): JSX.Element {return (<SceneContent>- <PayGateMini- feature={AvailableFeature.SUBSCRIPTIONS}- handleSubmit={() => undefined}- background={false}- className="py-8 flex-1 min-h-0 flex flex-col"- docsLink="https://posthog.com/docs/user-guides/subscriptions"- loadingSkeleton={- <div className="py-8 flex-1 min-h-0 flex flex-col w-full">- <SubscriptionsLoadingSkeleton />- </div>- }- >- {showNotFound ? (- <NotFound object="subscription" />- ) : (- <div className="flex flex-col gap-6 max-w-full">- <SceneTitleSection- name={subscription ? subscriptionName(subscription) : 'Subscription'}- description={null}- resourceType={{ type: 'inbox' }}- isLoading={subscriptionLoading}- actions={- subscription ? (- <SubscriptionDetailActions sub={subscription} tabId={tabId} />- ) : undefined- }+ {showNotFound ? (+ <NotFound object="subscription" />+ ) : (+ <div className="py-8 flex-1 min-h-0 flex flex-col gap-6 max-w-full">+ <SceneTitleSection+ name={subscription ? subscriptionName(subscription) : 'Subscription'}+ description={null}+ resourceType={{ type: 'inbox' }}+ isLoading={subscriptionLoading}+ actions={+ subscription ? <SubscriptionDetailActions sub={subscription} tabId={tabId} /> : undefined+ }+ />+ {subscription ? (+ // Mute the body when the subscription is paused — the LemonTag in the+ // header is the explicit signal; this is the at-a-glance reinforcement.+ <div className={isSubscriptionEnabled(subscription) ? '' : 'opacity-60'}>+ <SubscriptionSummary sub={subscription} />+ </div>+ ) : null}+ {deliveriesEnabled ? (+ <SubscriptionDeliveryHistory+ deliveriesPage={deliveriesPage}+ deliveriesPageLoading={deliveriesPageLoading}+ loadDeliveriesPage={loadDeliveriesPage}+ deliveryStatusFilter={deliveryStatusFilter}+ onDeliveryStatusFilterChange={setDeliveryStatusFilter}+ onTestDelivery={subscription ? () => deliverSubscription(subscription.id) : undefined}+ testDeliveryLoading={Boolean(subscription && deliveringSubscriptionId === subscription.id)}/>- {subscription ? (- // Mute the body when the subscription is paused — the LemonTag in the- // header is the explicit signal; this is the at-a-glance reinforcement.- <div className={isSubscriptionEnabled(subscription) ? '' : 'opacity-60'}>- <SubscriptionSummary sub={subscription} />- </div>- ) : null}- {deliveriesEnabled ? (- <SubscriptionDeliveryHistory- deliveriesPage={deliveriesPage}- deliveriesPageLoading={deliveriesPageLoading}- loadDeliveriesPage={loadDeliveriesPage}- deliveryStatusFilter={deliveryStatusFilter}- onDeliveryStatusFilterChange={setDeliveryStatusFilter}- onTestDelivery={subscription ? () => deliverSubscription(subscription.id) : undefined}- testDeliveryLoading={Boolean(- subscription && deliveringSubscriptionId === subscription.id- )}- />- ) : null}- </div>- )}- </PayGateMini>+ ) : null}+ </div>+ )}</SceneContent>)}diff --git a/frontend/src/scenes/subscriptions/SubscriptionsScene.tsx b/frontend/src/scenes/subscriptions/SubscriptionsScene.tsxindex a167de7e746d..61b6c037ee65 100644--- a/frontend/src/scenes/subscriptions/SubscriptionsScene.tsx+++ b/frontend/src/scenes/subscriptions/SubscriptionsScene.tsx@@ -5,7 +5,6 @@ import { IconEllipsis } from '@posthog/icons'import { LemonButton, LemonMenu, Link } from '@posthog/lemon-ui'import { DetectiveHog } from 'lib/components/hedgehogs'-import { PayGateMini } from 'lib/components/PayGateMini/PayGateMini'import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'import { Spinner } from 'lib/lemon-ui/Spinner'@@ -19,10 +18,8 @@ import type { SubscriptionApi } from '~/generated/core/api.schemas'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'-import { AvailableFeature } from '~/types'import { SubscriptionsFiltersBar } from './components/SubscriptionsFiltersBar'-import { SubscriptionsLoadingSkeleton } from './components/SubscriptionsLoadingSkeleton'import {SubscriptionsTable,isSubscriptionEnabled,@@ -135,54 +132,41 @@ export function SubscriptionsScene(): JSX.Element {tabs={subscriptionTabs}sceneInset/>- <PayGateMini- feature={AvailableFeature.SUBSCRIPTIONS}- handleSubmit={() => undefined}- background={false}- className="py-8 flex-1 min-h-0 flex flex-col"- docsLink="https://posthog.com/docs/user-guides/subscriptions"- loadingSkeleton={- <div className="py-8 flex-1 min-h-0 flex flex-col w-full">- <SubscriptionsLoadingSkeleton />- </div>- }- >- <div className="flex flex-col gap-4 max-w-full">- {showProductIntroduction ? (- <ProductIntroduction- productName="Subscriptions"- productKey={ProductKey.SUBSCRIPTIONS}- thingName="subscription"- titleOverride="No subscriptions yet"- description="Get recurring email or Slack digests, or scheduled exports from insights and dashboards. Use them for weekly rollups, stakeholder updates, or wiring metrics into your own systems."- isEmpty- customHog={DetectiveHog}- hogLayout="responsive"- useMainContentContainerQueries- docsURL="https://posthog.com/docs/user-guides/subscriptions"- actionElementOverride={- <span className="italic">- Open a <Link to={urls.dashboards()}>dashboard</Link> or{' '}- <Link to={urls.insights()}>saved insight</Link>, open the side panel, and click{' '}- "Subscribe" to configure the options.- </span>- }+ <div className="py-8 flex-1 min-h-0 flex flex-col gap-4 max-w-full">+ {showProductIntroduction ? (+ <ProductIntroduction+ productName="Subscriptions"+ productKey={ProductKey.SUBSCRIPTIONS}+ thingName="subscription"+ titleOverride="No subscriptions yet"+ description="Get recurring email or Slack digests, or scheduled exports from insights and dashboards. Use them for weekly rollups, stakeholder updates, or wiring metrics into your own systems."+ isEmpty+ customHog={DetectiveHog}+ hogLayout="responsive"+ useMainContentContainerQueries+ docsURL="https://posthog.com/docs/user-guides/subscriptions"+ actionElementOverride={+ <span className="italic">+ Open a <Link to={urls.dashboards()}>dashboard</Link> or{' '}+ <Link to={urls.insights()}>saved insight</Link>, open the side panel, and click{' '}+ "Subscribe" to configure the options.+ </span>+ }+ />+ ) : (+ <>+ <SubscriptionsFiltersBar />+ <SubscriptionsTable+ dataSource={subscriptions}+ loading={subscriptionsLoading}+ pagination={pagination}+ sorting={subscriptionsSorting}+ onSort={setSubscriptionsSorting}+ renderRowActions={(sub) => <SubscriptionsRowActions sub={sub} />}/>- ) : (- <>- <SubscriptionsFiltersBar />- <SubscriptionsTable- dataSource={subscriptions}- loading={subscriptionsLoading}- pagination={pagination}- sorting={subscriptionsSorting}- onSort={setSubscriptionsSorting}- renderRowActions={(sub) => <SubscriptionsRowActions sub={sub} />}- />- </>- )}- </div>- </PayGateMini>+ </>+ )}+ </div></SceneContent>)}diff --git a/frontend/src/scenes/subscriptions/components/SubscriptionsLoadingSkeleton.tsx b/frontend/src/scenes/subscriptions/components/SubscriptionsLoadingSkeleton.tsxdeleted file mode 100644index 95a1143aa403..000000000000--- a/frontend/src/scenes/subscriptions/components/SubscriptionsLoadingSkeleton.tsx+++ /dev/null@@ -1,46 +0,0 @@-import { LemonSkeleton } from '@posthog/lemon-ui'--const TABLE_COLUMN_COUNT = 10--export function SubscriptionsLoadingSkeleton(): JSX.Element {- return (- <div className="flex flex-col gap-4 max-w-full w-full">- <div className="flex justify-between gap-2 flex-wrap items-center">- <div className="flex-1 min-w-0 max-w-3xl">- <LemonSkeleton className="h-10 w-full rounded" />- </div>- <div className="flex items-center gap-2">- <LemonSkeleton className="h-4 w-20" />- <LemonSkeleton className="h-10 w-44" />- </div>- </div>- <div className="border rounded bg-primary overflow-hidden">- <div className="flex gap-3 px-3 py-2 border-b border-primary">- {Array.from({ length: TABLE_COLUMN_COUNT }).map((_, i) => (- <LemonSkeleton- key={`h-${i}`}- className={i === TABLE_COLUMN_COUNT - 1 ? 'h-4 w-8 shrink-0' : 'h-4 flex-1 min-w-[2.5rem]'}- />- ))}- </div>- {Array.from({ length: 8 }).map((_, row) => (- <div- key={row}- className="flex gap-3 px-3 py-2.5 border-b border-primary last:border-b-0 items-center"- >- {Array.from({ length: TABLE_COLUMN_COUNT }).map((_, col) => (- <LemonSkeleton- key={col}- className={- col === TABLE_COLUMN_COUNT - 1- ? 'h-8 w-8 shrink-0 rounded'- : 'h-4 flex-1 min-w-[2.5rem]'- }- />- ))}- </div>- ))}- </div>- </div>- )-}diff --git a/posthog/models/subscription.py b/posthog/models/subscription.pyindex 26ed2d74511a..408203c4ab1d 100644--- a/posthog/models/subscription.py+++ b/posthog/models/subscription.py@@ -1,6 +1,6 @@from dataclasses import dataclassfrom datetime import datetime, timedelta-from typing import Any, Literal, Optional, cast+from typing import TYPE_CHECKING, Any, Literal, Optional, castfrom django.contrib.postgres.fields import ArrayFieldfrom django.db import models@@ -10,13 +10,22 @@ from django.utils import timezonefrom dateutil.rrule import DAILY, FR, MO, MONTHLY, SA, SU, TH, TU, WE, WEEKLY, YEARLY, rrule+from posthog.schema import SubscriptionFreeTierLimit++from posthog.constants import AvailableFeaturefrom posthog.exceptions_capture import capture_exceptionfrom posthog.jwt import PosthogJwtAudience, decode_jwt, encode_jwtfrom posthog.models.utils import UUIDModelfrom posthog.utils import absolute_uri+if TYPE_CHECKING:+ from posthog.models.organization import Organization+UNSUBSCRIBE_TOKEN_EXP_DAYS = 30+# Single source of truth shared with the frontend create gate via generated schema (SubscriptionFreeTierLimit.COUNT).+SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER: int = SubscriptionFreeTierLimit.model_fields["root"].default+RRULE_WEEKDAY_MAP = {"monday": MO,"tuesday": TU,@@ -200,6 +209,23 @@ class Subscription(models.Model):return None # DRF field validation should reject before we get here.return cls._compute_next_delivery_date(**merged)+ @classmethod+ def check_subscription_limit(cls, team_id: int, organization: "Organization") -> str | None:+ """Return an error message if the team has reached its subscription limit, else None."""+ feature = organization.get_available_feature(AvailableFeature.SUBSCRIPTIONS)+ # Soft-deleted subscriptions free their slot.+ existing_count = cls.objects.filter(team_id=team_id, deleted=False).count()++ if feature:+ allowed = feature.get("limit")+ # A None limit means unlimited (paid plans without a numeric cap).+ if allowed is not None and existing_count >= allowed:+ return f"Your team has reached the limit of {allowed} subscriptions on your plan."+ elif existing_count >= SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER:+ return f"Your plan is limited to {SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER} subscriptions."++ return None+@propertydef url(self):if self.insight:diff --git a/posthog/models/test/test_subscription_model.py b/posthog/models/test/test_subscription_model.pyindex 38396125b9e2..bbfe9794cdd3 100644--- a/posthog/models/test/test_subscription_model.py+++ b/posthog/models/test/test_subscription_model.py@@ -13,8 +13,10 @@ from django.utils import timezoneimport jwtfrom parameterized import parameterized+from posthog.constants import AvailableFeaturefrom posthog.jwt import PosthogJwtAudiencefrom posthog.models.subscription import (+ SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER,UNSUBSCRIBE_TOKEN_EXP_DAYS,Subscription,SubscriptionDelivery,@@ -433,3 +435,82 @@ class TestSubscription(BaseTest):)subscription.set_next_delivery_date()assert subscription.next_delivery_date == expected_next+++class TestSubscriptionLimit(BaseTest):+ def _create_subscriptions(self, count: int) -> None:+ insight = Insight.objects.create(team=self.team)+ for i in range(count):+ Subscription.objects.create(+ team=self.team,+ insight=insight,+ target_type="email",+ target_value=f"user{i}@posthog.com",+ frequency="daily",+ start_date=datetime(2022, 1, 1, 0, 0, 0, tzinfo=ZoneInfo("UTC")),+ )++ @parameterized.expand(+ [+ ("zero", 0, False),+ ("below_limit", SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER - 1, False),+ ("at_limit", SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER, True),+ ("over_limit", SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER + 1, True),+ ]+ )+ def test_free_org_limit(self, _name: str, count: int, blocked: bool) -> None:+ self.organization.available_product_features = []+ self.organization.save()+ self._create_subscriptions(count)+ result = Subscription.check_subscription_limit(self.team.id, self.organization)+ if blocked:+ assert result is not None+ assert str(SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER) in result+ else:+ assert result is None++ def test_free_org_limit_reads_constant(self) -> None:+ self.organization.available_product_features = []+ self.organization.save()+ self._create_subscriptions(2)+ with patch("posthog.models.subscription.SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER", 2):+ result = Subscription.check_subscription_limit(self.team.id, self.organization)+ assert result is not None+ assert "2" in result++ def test_paid_org_unlimited_returns_none(self) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.SUBSCRIPTIONS, "name": "subscriptions", "limit": None}+ ]+ self.organization.save()+ self._create_subscriptions(50)+ assert Subscription.check_subscription_limit(self.team.id, self.organization) is None++ @parameterized.expand(+ [+ ("under_limit", 3, 2, None),+ ("at_limit", 3, 3, "3"),+ ("over_limit", 3, 4, "3"),+ ("zero_allowance", 0, 0, "0"),+ ]+ )+ def test_paid_org_numeric_limit(self, _name: str, limit: int, count: int, expected_in_msg: str | None) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.SUBSCRIPTIONS, "name": "subscriptions", "limit": limit}+ ]+ self.organization.save()+ self._create_subscriptions(count)+ result = Subscription.check_subscription_limit(self.team.id, self.organization)+ if expected_in_msg is None:+ assert result is None+ else:+ assert result is not None+ assert expected_in_msg in result++ def test_soft_deleted_excluded_from_count(self) -> None:+ self.organization.available_product_features = []+ self.organization.save()+ self._create_subscriptions(5)+ assert Subscription.check_subscription_limit(self.team.id, self.organization) is not None+ Subscription.objects.filter(team=self.team).update(deleted=True)+ assert Subscription.check_subscription_limit(self.team.id, self.organization) is Nonediff --git a/posthog/schema.py b/posthog/schema.pyindex 4acdf39a7932..e3d13cbc5fc7 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -4804,6 +4804,10 @@ class SubscriptionDropoffMode(StrEnum):AFTER_DROPOFF_PERIOD = "after_dropoff_period"+class SubscriptionFreeTierLimit(RootModel[Literal[5]]):+ root: Literal[5] = Field(5, description="Subscriptions a free-tier team may create.")++class SuggestedQuestionsQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",