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(code): stop seat creation, upgrades, and reactivation (#70790)

Pawel Cebulaa22eba63a48d
diff --git a/frontend/src/scenes/billing/Billing.tsx b/frontend/src/scenes/billing/Billing.tsx
index 57ebabccb32c..8e25edb6d393 100644
--- a/frontend/src/scenes/billing/Billing.tsx
+++ b/frontend/src/scenes/billing/Billing.tsx
@@ -267,7 +267,7 @@ export function Billing(): JSX.Element {
<div>{getProductIcon('IconTerminal', { className: 'text-2xl shrink-0' })}</div>
<div>
<h3 className="font-bold mb-0">Code</h3>
- <div>Seat-based billing for PostHog Code.</div>
+ <div>Manage existing PostHog Code seats.</div>
</div>
</div>
<LemonButton
diff --git a/frontend/src/scenes/billing/CodeSeatsSection.tsx b/frontend/src/scenes/billing/CodeSeatsSection.tsx
index 7d7f894cbf6f..9c2838c2e46a 100644
--- a/frontend/src/scenes/billing/CodeSeatsSection.tsx
+++ b/frontend/src/scenes/billing/CodeSeatsSection.tsx
@@ -6,19 +6,9 @@ import { dayjs } from 'lib/dayjs'
import { More } from 'lib/lemon-ui/LemonButton/More'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { billingLogic } from './billingLogic'
-import { CODE_PLAN_PRO } from './constants'
-import {
- canReactivateSeat,
- isAlphaPlanKey,
- isProPlanKey,
- seatBillingLogic,
- seatPriceFromPlanKey,
-} from './seatBillingLogic'
+import { canCancelSeat, isAlphaPlanKey, isProPlanKey, seatBillingLogic, seatPriceFromPlanKey } from './seatBillingLogic'
import type { SeatData, SeatStatus } from './types'
-const ALPHA_PLAN_MIGRATION_DATE = 'June 4, 2026'
-
function planLabel(planKey: string): string {
if (isAlphaPlanKey(planKey)) {
return 'Alpha'
@@ -55,18 +45,9 @@ function statusColor(status: SeatStatus): 'success' | 'warning' | 'muted' | 'pri
}
export function CodeSeatsSection(): JSX.Element {
- const {
- displaySeats,
- orgSeatsLoading,
- isAdmin,
- members,
- activeCount,
- cancelingCount,
- monthlyTotal,
- hasAlphaSeats,
- } = useValues(seatBillingLogic)
- const { adminCancelSeat, adminUpgradeSeat, adminReactivateSeat } = useActions(seatBillingLogic)
- const { billing } = useValues(billingLogic)
+ const { displaySeats, orgSeatsLoading, isAdmin, members, activeCount, cancelingCount, monthlyTotal } =
+ useValues(seatBillingLogic)
+ const { adminCancelSeat } = useActions(seatBillingLogic)
function getUserInfo(seat: SeatData): { name: string; email: string } | null {
if (!members) {
@@ -94,17 +75,15 @@ export function CodeSeatsSection(): JSX.Element {
)}
</div>
</div>
- {hasAlphaSeats && (
- <LemonBanner type="info" className="mb-4">
- Alpha plan seats will be moved to the free plan automatically on {ALPHA_PLAN_MIGRATION_DATE}. After
- that, you'll be able to upgrade them to the Pro plan.
- </LemonBanner>
- )}
+ <LemonBanner type="info" className="mb-4">
+ PostHog Code with usage-based billing is launching shortly. New seats, upgrades, and reactivations are
+ no longer available. You can still cancel active seats below.
+ </LemonBanner>
<LemonTable
loading={orgSeatsLoading}
dataSource={displaySeats}
defaultSorting={{ columnKey: 'user', order: 1 }}
- emptyState="No Code seats have been provisioned yet"
+ emptyState="No Code seats"
columns={[
{
title: 'User',
@@ -132,17 +111,16 @@ export function CodeSeatsSection(): JSX.Element {
key: 'plan',
align: 'center',
render: (_, seat: SeatData) => {
- if (isAlphaPlanKey(seat.plan_key)) {
- return (
- <Tooltip
- title={`Alpha seats will be migrated to the free plan on ${ALPHA_PLAN_MIGRATION_DATE}.`}
- >
- <LemonTag type="completion">{planLabel(seat.plan_key)}</LemonTag>
- </Tooltip>
- )
- }
return (
- <LemonTag type={isProPlanKey(seat.plan_key) ? 'primary' : 'muted'}>
+ <LemonTag
+ type={
+ isAlphaPlanKey(seat.plan_key)
+ ? 'completion'
+ : isProPlanKey(seat.plan_key)
+ ? 'primary'
+ : 'muted'
+ }
+ >
{planLabel(seat.plan_key)}
</LemonTag>
)
@@ -179,76 +157,31 @@ export function CodeSeatsSection(): JSX.Element {
key: 'actions',
width: 0,
render: (_, seat: SeatData) => {
- if (!billing?.has_active_subscription || !isAdmin) {
- return null
- }
- const canUpgrade =
- seat.status === 'active' &&
- !isProPlanKey(seat.plan_key) &&
- !isAlphaPlanKey(seat.plan_key)
- const canCancel = seat.status === 'active'
- const canReactivate = canReactivateSeat(seat)
-
- if (!canUpgrade && !canCancel && !canReactivate) {
+ if (!canCancelSeat(seat, isAdmin)) {
return null
}
return (
<More
overlay={
- <>
- {canUpgrade && (
- <LemonButton
- fullWidth
- onClick={() => {
- LemonDialog.open({
- title: 'Upgrade this seat to Pro?',
- description:
- 'A prorated charge will be applied for the remainder of the billing period. This cannot be reverted without canceling.',
- primaryButton: {
- children: 'Upgrade to Pro',
- onClick: () =>
- adminUpgradeSeat(
- seat.user_distinct_id,
- CODE_PLAN_PRO
- ),
- },
- secondaryButton: { children: 'Cancel' },
- })
- }}
- >
- Upgrade to Pro
- </LemonButton>
- )}
- {canReactivate && (
- <LemonButton
- fullWidth
- onClick={() => adminReactivateSeat(seat.user_distinct_id)}
- >
- Reactivate
- </LemonButton>
- )}
- {canCancel && (
- <LemonButton
- fullWidth
- onClick={() => {
- LemonDialog.open({
- title: 'Cancel this seat?',
- description:
- 'The seat will remain active until the end of the current billing period.',
- primaryButton: {
- children: 'Cancel seat',
- status: 'danger',
- onClick: () => adminCancelSeat(seat.user_distinct_id),
- },
- secondaryButton: { children: 'Keep seat' },
- })
- }}
- >
- Cancel seat
- </LemonButton>
- )}
- </>
+ <LemonButton
+ fullWidth
+ onClick={() => {
+ LemonDialog.open({
+ title: 'Cancel this seat?',
+ description:
+ 'The seat will remain active until the end of the current billing period.',
+ primaryButton: {
+ children: 'Cancel seat',
+ status: 'danger',
+ onClick: () => adminCancelSeat(seat.user_distinct_id),
+ },
+ secondaryButton: { children: 'Keep seat' },
+ })
+ }}
+ >
+ Cancel seat
+ </LemonButton>
}
/>
)
diff --git a/frontend/src/scenes/billing/constants.ts b/frontend/src/scenes/billing/constants.ts
index 1f58e814e97f..174b1fbc6b9e 100644
--- a/frontend/src/scenes/billing/constants.ts
+++ b/frontend/src/scenes/billing/constants.ts
@@ -29,8 +29,6 @@ export const ALL_USAGE_TYPES: UsageTypeValue[] = USAGE_TYPES.map((opt) => opt.va
export const CODE_PRODUCT_KEY = 'posthog_code'
// TODO: Replace hardcoded plan keys with dynamic plan metadata from billing service
-export const CODE_PLAN_FREE = 'posthog-code-free-20260301'
-export const CODE_PLAN_PRO = 'posthog-code-pro-200-20260301'
export const CODE_PLAN_ALPHA_PRO = 'posthog-code-pro-0-20260422'
export const CODE_PRO_PLAN_PREFIX = 'posthog-code-pro-'
diff --git a/frontend/src/scenes/billing/seatBillingLogic.spec.ts b/frontend/src/scenes/billing/seatBillingLogic.spec.ts
index 544e3267e69a..7b60921d50e1 100644
--- a/frontend/src/scenes/billing/seatBillingLogic.spec.ts
+++ b/frontend/src/scenes/billing/seatBillingLogic.spec.ts
@@ -1,10 +1,4 @@
-import {
- canReactivateSeat,
- isAlphaPlanKey,
- isFreePlanKey,
- isProPlanKey,
- seatPriceFromPlanKey,
-} from './seatBillingLogic'
+import { canCancelSeat, isAlphaPlanKey, isFreePlanKey, isProPlanKey, seatPriceFromPlanKey } from './seatBillingLogic'
describe('seatBillingLogic plan key helpers', () => {
describe('isProPlanKey', () => {
@@ -65,16 +59,14 @@ describe('seatBillingLogic plan key helpers', () => {
})
})
- describe('canReactivateSeat', () => {
+ describe('canCancelSeat', () => {
it.each([
- [{ status: 'canceling' as const, plan_key: 'posthog-code-pro-0-20260422' }, false],
- [{ status: 'canceling' as const, plan_key: 'posthog-code-pro-200-20260301' }, true],
- [{ status: 'canceling' as const, plan_key: 'posthog-code-free-20260301' }, true],
- [{ status: 'active' as const, plan_key: 'posthog-code-pro-0-20260422' }, false],
- [null, false],
- [undefined, false],
- ])('canReactivateSeat(%p) === %p', (seat, expected) => {
- expect(canReactivateSeat(seat)).toBe(expected)
+ ['active', true, true],
+ ['active', false, false],
+ ['canceling', true, false],
+ ['expired', true, false],
+ ] as const)('canCancelSeat({ status: %p }, %p) === %p', (status, isAdmin, expected) => {
+ expect(canCancelSeat({ status }, isAdmin)).toBe(expected)
})
})
})
diff --git a/frontend/src/scenes/billing/seatBillingLogic.ts b/frontend/src/scenes/billing/seatBillingLogic.ts
index 6234f4029f04..62bb1139e320 100644
--- a/frontend/src/scenes/billing/seatBillingLogic.ts
+++ b/frontend/src/scenes/billing/seatBillingLogic.ts
@@ -8,7 +8,6 @@ import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { membersLogic } from 'scenes/organization/membersLogic'
import { organizationLogic } from 'scenes/organizationLogic'
-import { userLogic } from 'scenes/userLogic'
import { CODE_FREE_PLAN_PREFIX, CODE_PLAN_ALPHA_PRO, CODE_PRO_PLAN_PREFIX, CODE_PRODUCT_KEY } from './constants'
import type { seatBillingLogicType } from './seatBillingLogicType'
@@ -26,8 +25,8 @@ export function isAlphaPlanKey(planKey: string | null | undefined): boolean {
return planKey === CODE_PLAN_ALPHA_PRO
}
-export function canReactivateSeat(seat: Pick<SeatData, 'plan_key' | 'status'> | null | undefined): boolean {
- return !!seat && seat.status === 'canceling' && !isAlphaPlanKey(seat.plan_key)
+export function canCancelSeat(seat: Pick<SeatData, 'status'>, isAdmin: boolean): boolean {
+ return isAdmin && seat.status === 'active'
}
// TODO: Replace with `seat.price` once billing exposes it via SeatSerializer
@@ -52,8 +51,6 @@ export const seatBillingLogic = kea<seatBillingLogicType>([
values: [
organizationLogic,
['currentOrganization'],
- userLogic,
- ['user'],
membersLogic,
['members'],
featureFlagLogic,
@@ -62,30 +59,9 @@ export const seatBillingLogic = kea<seatBillingLogicType>([
actions: [membersLogic, ['ensureAllMembersLoaded']],
})),
actions({
- upgradeSeat: (planKey: string) => ({ planKey }),
- cancelSeat: true,
- reactivateSeat: true,
- createSeat: (planKey: string) => ({ planKey }),
adminCancelSeat: (userDistinctId: string) => ({ userDistinctId }),
- adminUpgradeSeat: (userDistinctId: string, planKey: string) => ({ userDistinctId, planKey }),
- adminReactivateSeat: (userDistinctId: string) => ({ userDistinctId }),
}),
loaders(() => ({
- mySeat: [
- null as SeatData | null,
- {
- loadMySeat: async (): Promise<SeatData | null> => {
- try {
- return await api.get(`api/seats/me/?product_key=${CODE_PRODUCT_KEY}`)
- } catch (e) {
- if (e instanceof ApiError && e.status === 404) {
- return null
- }
- throw e
- }
- },
- },
- ],
orgSeats: [
[] as SeatData[],
{
@@ -113,19 +89,6 @@ export const seatBillingLogic = kea<seatBillingLogicType>([
currentOrganization.membership_level >= OrganizationMembershipLevel.Admin
),
],
- isPro: [(s) => [s.mySeat], (mySeat): boolean => isProPlanKey(mySeat?.plan_key)],
- isFree: [(s) => [s.mySeat], (mySeat): boolean => isFreePlanKey(mySeat?.plan_key)],
- isAlpha: [(s) => [s.mySeat], (mySeat): boolean => isAlphaPlanKey(mySeat?.plan_key)],
- canUpgrade: [
- (s) => [s.mySeat],
- (mySeat): boolean =>
- !!mySeat &&
- mySeat.status === 'active' &&
- isFreePlanKey(mySeat.plan_key) &&
- !isAlphaPlanKey(mySeat.plan_key),
- ],
- canCancel: [(s) => [s.mySeat], (mySeat): boolean => !!mySeat && mySeat.status === 'active'],
- canReactivate: [(s) => [s.mySeat], (mySeat): boolean => canReactivateSeat(mySeat)],
displaySeats: [
(s) => [s.orgSeats],
(orgSeats): SeatData[] => {
@@ -155,11 +118,6 @@ export const seatBillingLogic = kea<seatBillingLogicType>([
(s) => [s.displaySeats],
(displaySeats): number => displaySeats.filter((s: SeatData) => s.status === 'active').length,
],
- hasAlphaSeats: [
- (s) => [s.displaySeats, s.mySeat],
- (displaySeats, mySeat): boolean =>
- displaySeats.some((s: SeatData) => isAlphaPlanKey(s.plan_key)) || isAlphaPlanKey(mySeat?.plan_key),
- ],
cancelingCount: [
(s) => [s.displaySeats],
(displaySeats): number => displaySeats.filter((s: SeatData) => s.status === 'canceling').length,
@@ -172,106 +130,21 @@ export const seatBillingLogic = kea<seatBillingLogicType>([
.reduce((sum: number, s: SeatData) => sum + seatPriceFromPlanKey(s.plan_key), 0),
],
}),
- listeners(({ actions, values }) => ({
- upgradeSeat: async ({ planKey }) => {
- try {
- await api.update(`api/seats/me/`, { product_key: CODE_PRODUCT_KEY, plan_key: planKey })
- lemonToast.success('Seat upgraded successfully')
- actions.loadMySeat()
- if (values.isAdmin) {
- actions.loadOrgSeats()
- }
- } catch (e) {
- lemonToast.error(seatErrorMessage(e, 'Failed to upgrade seat'))
- }
- },
- cancelSeat: async () => {
- try {
- await api.delete(`api/seats/me/?product_key=${CODE_PRODUCT_KEY}`)
- lemonToast.success('Seat canceled')
- actions.loadMySeat()
- if (values.isAdmin) {
- actions.loadOrgSeats()
- }
- } catch (e) {
- lemonToast.error(seatErrorMessage(e, 'Failed to cancel seat'))
- }
- },
- reactivateSeat: async () => {
- try {
- await api.create(`api/seats/me/reactivate/`, { product_key: CODE_PRODUCT_KEY })
- lemonToast.success('Seat reactivated')
- actions.loadMySeat()
- if (values.isAdmin) {
- actions.loadOrgSeats()
- }
- } catch (e) {
- lemonToast.error(seatErrorMessage(e, 'Failed to reactivate seat'))
- }
- },
- createSeat: async ({ planKey }) => {
- try {
- await api.create(`api/seats/`, {
- product_key: CODE_PRODUCT_KEY,
- plan_key: planKey,
- user_distinct_id: values.user?.distinct_id,
- })
- lemonToast.success('Seat created')
- actions.loadMySeat()
- if (values.isAdmin) {
- actions.loadOrgSeats()
- }
- } catch (e) {
- lemonToast.error(seatErrorMessage(e, 'Failed to create seat'))
- }
- },
+ listeners(({ actions }) => ({
adminCancelSeat: async ({ userDistinctId }) => {
try {
await api.delete(`api/seats/${userDistinctId}/?product_key=${CODE_PRODUCT_KEY}`)
lemonToast.success('Seat canceled')
actions.loadOrgSeats()
- if (userDistinctId === values.user?.distinct_id) {
- actions.loadMySeat()
- }
} catch (e) {
lemonToast.error(seatErrorMessage(e, 'Failed to cancel seat'))
}
},
- adminUpgradeSeat: async ({ userDistinctId, planKey }) => {
- try {
- await api.update(`api/seats/${userDistinctId}/`, {
- product_key: CODE_PRODUCT_KEY,
- plan_key: planKey,
- })
- lemonToast.success('Seat upgraded')
- actions.loadOrgSeats()
- if (userDistinctId === values.user?.distinct_id) {
- actions.loadMySeat()
- }
- } catch (e) {
- lemonToast.error(seatErrorMessage(e, 'Failed to upgrade seat'))
- }
- },
- adminReactivateSeat: async ({ userDistinctId }) => {
- try {
- await api.create(`api/seats/${userDistinctId}/reactivate/`, {
- product_key: CODE_PRODUCT_KEY,
- })
- lemonToast.success('Seat reactivated')
- actions.loadOrgSeats()
- if (userDistinctId === values.user?.distinct_id) {
- actions.loadMySeat()
- }
- } catch (e) {
- lemonToast.error(seatErrorMessage(e, 'Failed to reactivate seat'))
- }
- },
})),
afterMount(({ actions, values }) => {
if (!values.featureFlags[FEATURE_FLAGS.POSTHOG_CODE_BILLING]) {
return
}
- actions.loadMySeat()
actions.ensureAllMembersLoaded()
if (values.isAdmin) {
actions.loadOrgSeats()
diff --git a/products/tasks/backend/presentation/views/seat_api.py b/products/tasks/backend/presentation/views/seat_api.py
index e114f5ea4628..f76591279f7e 100644
--- a/products/tasks/backend/presentation/views/seat_api.py
+++ b/products/tasks/backend/presentation/views/seat_api.py
@@ -5,6 +5,7 @@ from typing import Any, cast
import requests
import structlog
+from drf_spectacular.utils import extend_schema
from rest_framework import status, viewsets
from rest_framework.authentication import SessionAuthentication
from rest_framework.decorators import action
@@ -25,6 +26,11 @@ from ee.settings import BILLING_SERVICE_URL
# Duplicated in services/llm-gateway/src/llm_gateway/services/plan_resolver.py
PRO_PLAN_PREFIXES = ("posthog-code-200", "posthog-code-pro-")
+RETIRED_SEAT_PRODUCT_MESSAGE = (
+ "You can no longer create, upgrade, or reactivate PostHog Code seats. "
+ "PostHog Code with usage-based billing is launching shortly."
+)
+RETIRED_SEAT_PRODUCTS = {"posthog_code": RETIRED_SEAT_PRODUCT_MESSAGE}
def _seat_priority(seat: dict[str, Any]) -> tuple[bool, int, float]:
@@ -62,6 +68,7 @@ def _is_org_admin(user: Any) -> bool:
).exists()
+@extend_schema(exclude=True)
class SeatViewSet(viewsets.ViewSet):
"""
Proxy for seat management through the billing service.
@@ -180,6 +187,22 @@ class SeatViewSet(viewsets.ViewSet):
self._require_org_member(request, distinct_id)
return distinct_id
+ @staticmethod
+ def _retired_product_response(request: Request) -> Response | None:
+ product_key = request.data.get("product_key")
+ if not isinstance(product_key, str):
+ product_key = request.query_params.get("product_key")
+ message = RETIRED_SEAT_PRODUCTS.get(product_key) if isinstance(product_key, str) else None
+ if message is None:
+ return None
+ return Response(
+ {
+ "error": message,
+ "code": "seat_product_retired",
+ },
+ status=status.HTTP_410_GONE,
+ )
+
@staticmethod
def _filtered_query_params(request: Request) -> dict[str, str]:
product_key = request.query_params.get("product_key", "")
@@ -218,6 +241,9 @@ class SeatViewSet(viewsets.ViewSet):
self._require_admin(request)
self._require_org_member(request, str(body_distinct_id))
+ if retired_response := self._retired_product_response(request):
+ return retired_response
+
headers = self._get_billing_headers(request)
if not headers:
return Response({"detail": "No organization or license found"}, status=status.HTTP_400_BAD_REQUEST)
@@ -322,11 +348,14 @@ class SeatViewSet(viewsets.ViewSet):
if pk != "me":
self._require_admin(request)
+ distinct_id = self._resolve_and_check_membership(request, pk)
+ if retired_response := self._retired_product_response(request):
+ return retired_response
+
headers = self._get_billing_headers(request)
if not headers:
return Response({"detail": "No organization or license found"}, status=status.HTTP_400_BAD_REQUEST)
- distinct_id = self._resolve_and_check_membership(request, pk)
resp = self._billing_request(
"PATCH",
f"/api/v2/seats/{distinct_id}/",
@@ -359,11 +388,14 @@ class SeatViewSet(viewsets.ViewSet):
if pk != "me":
self._require_admin(request)
+ distinct_id = self._resolve_and_check_membership(request, pk)
+ if retired_response := self._retired_product_response(request):
+ return retired_response
+
headers = self._get_billing_headers(request)
if not headers:
return Response({"detail": "No organization or license found"}, status=status.HTTP_400_BAD_REQUEST)
- distinct_id = self._resolve_and_check_membership(request, pk)
resp = self._billing_request(
"POST",
f"/api/v2/seats/{distinct_id}/reactivate/",
diff --git a/products/tasks/backend/tests/test_seat_api.py b/products/tasks/backend/tests/test_seat_api.py
index e89fecf11efb..7356beb5fd10 100644
--- a/products/tasks/backend/tests/test_seat_api.py
+++ b/products/tasks/backend/tests/test_seat_api.py
@@ -1,9 +1,11 @@
-from typing import ClassVar
+import json
+from typing import ClassVar, Protocol
from unittest.mock import MagicMock, patch
from django.test import TestCase
+from parameterized import parameterized
from rest_framework import status
from rest_framework.exceptions import NotAuthenticated
from rest_framework.test import APIClient
@@ -26,6 +28,12 @@ MOCK_SEAT = {
}
+class _JsonTestResponse(Protocol):
+ status_code: int
+
+ def json(self) -> dict[str, object]: ...
+
+
def _billing_response(data=None, status_code=200, ok=True):
resp = MagicMock()
resp.status_code = status_code
@@ -145,8 +153,8 @@ class TestSeatAPIAdminPermissions(BaseSeatAPITest):
response = self.client.post(
"/api/seats/",
{
- "product_key": "posthog_code",
- "plan_key": "posthog-code-free-20260301",
+ "product_key": "other_product",
+ "plan_key": "other-plan",
"user_distinct_id": str(self.user.distinct_id),
},
format="json",
@@ -198,7 +206,11 @@ class TestSeatAPIAdminPermissions(BaseSeatAPITest):
@patch("products.tasks.backend.presentation.views.seat_api.requests.request")
def test_reactivate_non_org_member_rejected(self, mock_request, _mock_license, _mock_token):
self._auth_as_admin()
- response = self.client.post(f"/api/seats/{self.external_user.distinct_id}/reactivate/", format="json")
+ response = self.client.post(
+ f"/api/seats/{self.external_user.distinct_id}/reactivate/",
+ {"product_key": "posthog_code"},
+ format="json",
+ )
assert response.status_code == status.HTTP_403_FORBIDDEN
@@ -229,7 +241,7 @@ class TestSeatAPIMeResolution(BaseSeatAPITest):
self._auth_as_member()
self.client.patch(
"/api/seats/me/",
- {"product_key": "posthog_code", "plan_key": "posthog-code-200-20260301"},
+ {"product_key": "other_product", "plan_key": "other-plan"},
format="json",
)
_, kwargs = mock_request.call_args
@@ -239,11 +251,120 @@ class TestSeatAPIMeResolution(BaseSeatAPITest):
def test_reactivate_me_resolves_distinct_id(self, mock_request, _mock_license, _mock_token):
mock_request.return_value = _billing_response({"seat": MOCK_SEAT})
self._auth_as_member()
- self.client.post("/api/seats/me/reactivate/", format="json")
+ self.client.post("/api/seats/me/reactivate/", {"product_key": "other_product"}, format="json")
_, kwargs = mock_request.call_args
assert str(self.user.distinct_id) in kwargs["url"]
+class TestSeatAPIRetiredProducts(BaseSeatAPITest):
+ def _assert_retired(self, response: _JsonTestResponse) -> None:
+ assert response.status_code == status.HTTP_410_GONE
+ assert response.json() == {
+ "error": (
+ "You can no longer create, upgrade, or reactivate PostHog Code seats. "
+ "PostHog Code with usage-based billing is launching shortly."
+ ),
+ "code": "seat_product_retired",
+ }
+
+ @parameterized.expand(
+ [
+ (
+ "create",
+ "POST",
+ "/api/seats/",
+ {
+ "product_key": "posthog_code",
+ "plan_key": "posthog-code-free-20260301",
+ "user_distinct_id": "me",
+ },
+ ),
+ (
+ "upgrade",
+ "PATCH",
+ "/api/seats/me/",
+ {"product_key": "posthog_code", "plan_key": "posthog-code-pro-200-20260301"},
+ ),
+ (
+ "reactivate",
+ "POST",
+ "/api/seats/me/reactivate/",
+ {"product_key": "posthog_code"},
+ ),
+ ]
+ )
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ def test_posthog_code_mutation_is_rejected_locally(
+ self,
+ _name: str,
+ method: str,
+ path: str,
+ payload: dict[str, str],
+ mock_request: MagicMock,
+ ) -> None:
+ self._auth_as_member()
+ request_payload = payload.copy()
+ if request_payload.get("user_distinct_id") == "me":
+ request_payload["user_distinct_id"] = str(self.user.distinct_id)
+ response = self.client.generic(
+ method,
+ path,
+ json.dumps(request_payload),
+ content_type="application/json",
+ )
+
+ self._assert_retired(response)
+ mock_request.assert_not_called()
+
+ @parameterized.expand(
+ [
+ (
+ "create",
+ "POST",
+ "/api/seats/?product_key=posthog_code",
+ {
+ "plan_key": "posthog-code-free-20260301",
+ "user_distinct_id": "me",
+ },
+ ),
+ (
+ "upgrade",
+ "PATCH",
+ "/api/seats/me/?product_key=posthog_code",
+ {"plan_key": "posthog-code-pro-200-20260301"},
+ ),
+ (
+ "reactivate",
+ "POST",
+ "/api/seats/me/reactivate/?product_key=posthog_code",
+ {},
+ ),
+ ]
+ )
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ def test_posthog_code_query_param_mutation_is_rejected_locally(
+ self,
+ _name: str,
+ method: str,
+ path: str,
+ payload: dict[str, str],
+ mock_request: MagicMock,
+ ) -> None:
+ self._auth_as_member()
+ request_payload = payload.copy()
+ if request_payload.get("user_distinct_id") == "me":
+ request_payload["user_distinct_id"] = str(self.user.distinct_id)
+ response = self.client.generic(
+ method,
+ path,
+ json.dumps(request_payload),
+ content_type="application/json",
+ )
+
+ self._assert_retired(response)
+ mock_request.assert_not_called()
+
+
@patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
@patch("products.tasks.backend.presentation.views.seat_api.get_cached_instance_license")
class TestSeatAPIBillingUnavailability(BaseSeatAPITest):